Архив за месяц: Июнь 2018

c# Ошибка: System.TypeLoadException: Could not load type ‘System.Security.Claims.ClaimsIdentity’ from assembly mscorlib

c# Ошибка: System.TypeLoadException: Could not load type ‘System.Security.Claims.ClaimsIdentity’ from assembly mscorlib

Решение: установить .Net Framework 4.5

C# как узнать, какая вкладка открыта в tabControl

this.tabControl1.SelectedTab – сама выбранная вкладка

this.tabControl1.SelectedTab.Text – её заголовок

tabControl1.SelectTab(1); — выбрать вкладку по номеру

Быстрая настройка тестового https-сервера

Инструкция по бстрому созданию https-сервера. Просто как по быстрому всё поднять без оглядки на безопасность. Использовался Linux Mint 17.3 загруженнй с live-usb флэшки

1. Устанавливаем веб-сервер

mint@mint ~ $ sudo apt-get install nginx php5

2. Создаём самоподписанный сертификат по инструкции https://devcenter.heroku.com/articles/ssl-certificate-self

mint@mint ~ $ which openssl
/usr/bin/openssl
mint@mint ~ $ openssl genrsa -des3 -passout pass:x -out server.pass.key 2048
Generating RSA private key, 2048 bit long modulus
……….+++
…………………………………………………………………………….+++
e is 65537 (0x10001)
mint@mint ~ $ ls
Desktop    Downloads  Pictures  server.pass.key  Videos
Documents  Music      Public    Templates
mint@mint ~ $ openssl rsa -passin pass:x -in server.pass.key -out server.key
writing RSA key
mint@mint ~ $ ls
Desktop    Downloads  Pictures  server.key       Templates
Documents  Music      Public    server.pass.key  Videos
mint@mint ~ $ openssl req -new -key server.key  -out server.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter ‘.’, the field will be left blank.
——
Country Name (2 letter code) [AU]:Russia
string is too long, it needs to be less than  2 bytes long
Country Name (2 letter code) [AU]:RU
State or Province Name (full name) [Some-State]:66
Locality Name (eg, city) []:Ekaterinburg
Organization Name (eg, company) [Internet Widgits Pty Ltd]:PupkinCorp
Organizational Unit Name (eg, section) []:IT
Common Name (e.g. server FQDN or YOUR name) []:localhost
Email Address []:test@localhost

Please enter the following ‘extra’ attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
mint@mint ~ $ ls
Desktop    Downloads  Pictures  server.csr  server.pass.key  Videos
Documents  Music      Public    server.key  Templates
mint@mint ~ $ openssl x509 -req -sha256 -days 365 -in server.csr -signkey server.key -out server.crt
Signature ok
subject=/C=RU/ST=66/L=Ekaterinburg/O=PupkinCorp/OU=IT/CN=localhost/emailAddress=test@localhost
Getting Private key
mint@mint ~ $

3. Копируем сертификат и ключ в папку с конфигами nginx

mint@mint ~ $ sudo cp server.key /etc/nginx/
mint@mint ~ $ sudo cp server.crt /etc/nginx/
mint@mint ~ $ sudo bash
mint ~ # cd /etc/nginx/
mint nginx # ls
conf.d          mime.types           nginx.conf    server.key       win-utf
fastcgi_params  naxsi_core.rules     proxy_params  sites-available
koi-utf         naxsi.rules          scgi_params   sites-enabled
koi-win         naxsi-ui.conf.1.4.1  server.crt    uwsgi_params

4. Правим конфиг веб-сервера — снимаем комментарии с секции про HTTPS и вписываем имена файлов нашего сертификата и ключа (подглядывал в http://nginx.org/en/docs/http/configuring_https_servers.html)

mint nginx # nano sites-enabled/default

# HTTPS server
#
server {
listen 443 ssl;
server_name localhost;

root html;
index index.html index.htm;

ssl on;
ssl_certificate server.crt;
ssl_certificate_key server.key;

ssl_session_timeout 5m;

ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers «HIGH:!aNULL:!MD5 or HIGH:!aNULL:!MD5:!3DES»;
ssl_prefer_server_ciphers on;

location / {
try_files $uri $uri/ =404;
}
}

5. Сохраняемся и перезапускаем веб-сервер

mint sites-available # service nginx stop
mint sites-available # service nginx start

6. В браузере открываем https://localhost/, добавляем исключение (браузер будет ругаться, что сертификат самоподписанный), после этого должны увидеть «Welcome to nginx!» — это будет значить, что успешно через HTTPS открылся файл /usr/share/nginx/html/index.html.

У кого будут замечания и полезне советы, как всё это сделать правильнее — отписывайтесь.

C# Подключение к базе данных MSSQL

using System.Data.SqlClient;
string query = @"select 1";
            using (var connection = new SqlConnection("user id=Vasya;password=P@$w0rd;server=MyServer;database=MyBase;connection timeout=10;")) {
                connection.Open();
                using (var command = new SqlCommand(query, connection)){
                    command.CommandTimeout = 290;
                    using(SqlDataReader reader = command.ExecuteReader()){
                        int rowcounter = -1;
                        while (reader.Read()) {
                            rowcounter++; //счётчик строк в результате запроса
                            //заполняем значения в сохранённой строке
                            if (reader["My_Column"] is int) {
                                int n = (int)reader["My_Column "];
                            }
                            //…
                        }
                        reader.Close();
                    }
               }
          }
//добавить обработчики исключений

Для подключения к базе не под логином и паролем, а через доменную авторизацию под текущей виндовой учёткой строка будет такой:

using (var connection = new SqlConnection("server=MyServer;database=MyBase;connection timeout=10; Integrated Security=True;")) {}