С# Хелпер для MSSQL с AutoMapping для выбора по SELECT

Можно использовать когда лень мэпить через ORM. Это всё же лучше, чем через обычные ADO.NET команды работать. Автомэппинг для Select IDataReader точно можно оставить.

Если что то не будет работать то надо замэпить в самом начале запуска приложения. Примерно так
//AutoMapper.Mapper.Reset();
//AutoMapper.Mapper.CreateMap<IDataReader, SubscribeReportLib.Models.QueryCash>();

Если ошибка с System.Core то надо поставить обновление нэт фрэймворк NDP40-KB2468871-v2-x64




using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using AutoMapper;
 
namespace ADO_AutoMapping
{
    class Program
    {
        static void Main(string[] args)
        {
            MSSQL_Helper _helper = new MSSQL_Helper();
 
            var lst = _helper.ReadData<MarkType>("SELECT [id],[name],[inserted] FROM [marktype]");
 
            MarkType o = new MarkType() { id=1, inserted=DateTime.Now, name="as99933"};
            _helper.Insert<MarkType>(o, "id");
 
            _helper.Update<MarkType>(o,"id", new List<MSSQL_Helper.FieldVal>() 
            {
                new MSSQL_Helper.FieldVal 
                {
                    name="id",val=1
                }
            });
 
            _helper.Delete<MarkType>(new List<MSSQL_Helper.FieldVal>() 
            {
                new MSSQL_Helper.FieldVal 
                {
                    name="id",val=12
                }
            });
        }
    }
 
    public class MarkType
    {
        public int id { get; set; }
        public string name { get; set; }
        public DateTime inserted { get; set; }
    }
 
 
 
    class MSSQL_Helper
    {
        public struct FieldVal
        {
            public object val { get; set; }
            public string name { get; set; }
        }
 
        string constr;
 
        public MSSQL_Helper()
        {
            constr = "Data Source=localhost\\sqlexpress;Initial Catalog=MyDataBase;User ID=myuser;Password=mypass";
        }
 
        public MSSQL_Helper(string _constr)
        {
            constr = _constr;
        }
 
        public void SetConnectionString(string _constr)
        {
            constr = _constr;
        }
 
        public object ReadData<T>(string queryString)
        {
            using (var connection =
                       new SqlConnection(constr))
                using (var command =
                    new SqlCommand(queryString, connection))
                {
                    connection.Open();
                    using (var reader = command.ExecuteReader())
                        if (reader.HasRows)
                            return Mapper.DynamicMap<IDataReader, IEnumerable<T>>(reader);
                }
            return null;
        }
 
        public void Insert<T>(object o, string AutoIncFiled)
        {
            var lst = typeof(T).GetProperties().ToList();
            string param = "";
            string fields = "";
            var paramArray = new SqlParameter[lst.Count - 1];
            int i = 0;
            foreach (var prop in lst)
                if (prop.Name != AutoIncFiled)
                {
                    param += "@" + prop.Name + ",";
                    fields += prop.Name + ",";
                    paramArray[i++] = new SqlParameter("@" + prop.Name, prop.GetValue(o, null)?? DBNull.Value);
                }
            ExecuteNonQuery(String.Format("INSERT INTO {0}({1}) VALUES ({2})", typeof(T).Name, fields.Remove(fields.Length - 1), param.Remove(param.Length - 1)), paramArray);
        }
 
        public void Update<T>(object o, string AutoIncFiled, List<FieldVal> WhereFieldVal)
        {
            var lst = typeof(T).GetProperties().ToList();
            string wherestring = "WHERE ";
            string param = "";
            var paramArray = new SqlParameter[lst.Count - 1 + (WhereFieldVal==null?0:WhereFieldVal.Count)];
            int i = 0;
            foreach (var prop in lst)
                if (prop.Name != AutoIncFiled)
                {
                    param += prop.Name+"=@" + prop.Name + ",";
                    paramArray[i++] = new SqlParameter("@" + prop.Name, prop.GetValue(o, null)?? DBNull.Value);
                }
            foreach (FieldVal fv in WhereFieldVal)
            {
                wherestring += fv.name + "=@" + fv.name + ",";
                paramArray[i++] = new SqlParameter("@" + fv.name, fv.val);
            }
            ExecuteNonQuery(String.Format("UPDATE {0} SET {1} {2}", typeof(T).Name, param.Remove(param.Length - 1), wherestring.Remove(wherestring.Length - 1)), paramArray);
        }
 
        public void Delete<T>(List<FieldVal> WhereFieldVal)
        {
            string wherestring = "WHERE ";
            var paramArray = new SqlParameter[WhereFieldVal.Count];
            int i = 0;
            foreach (FieldVal fv in WhereFieldVal)
            {
                wherestring += fv.name + "=@" + fv.name + ",";
                paramArray[i++] = new SqlParameter("@" + fv.name, fv.val);
            }
            ExecuteNonQuery(String.Format("DELETE FROM {0} {1}", typeof(T).Name, wherestring.Remove(wherestring.Length - 1)), paramArray);
        }
 
        private void ExecuteNonQuery(string queryString,SqlParameter[] paramArray)
        {
            using (SqlConnection connection =
                       new SqlConnection(constr))
            using (SqlCommand command =
                new SqlCommand(queryString, connection))
            {
                connection.Open();
                command.Parameters.AddRange(paramArray);
                command.ExecuteNonQuery();
            }
        }

 
        public void ExecuteNonQuery(string queryString)
        {
            using (SqlConnection connection =
                       new SqlConnection(constr))
            using (SqlCommand command =
                new SqlCommand(queryString, connection))
            {
                connection.Open();
                command.ExecuteNonQuery();
            }
        }
    }
}
 

Additional two methods

        public List<T> Select<T>(List<FieldVal> WhereFieldVal, string DBName = "")
        {
            var lst = typeof(T).GetProperties().ToList();
            string wherestring = "WHERE ";
            string param = "";
            var paramArray = new SqlParameter[lst.Count - 1 + (WhereFieldVal == null ? 0 : WhereFieldVal.Count)];
            int i = 0;
            foreach (var prop in lst)
                    param += prop.Name + ",";
            foreach (FieldVal fv in WhereFieldVal)
            {
                wherestring += fv.name + "=@" + fv.name + ",";
                paramArray[i++] = new SqlParameter("@" + fv.name, fv.val);
            }
            string _sql = String.Format("SELECT {1} FROM {0} {2}", DBName == "" ? typeof(T).Name : DBName, param.Remove(param.Length - 1), wherestring.Remove(wherestring.Length - 1));
            return ReadData<T>(_sql);
        }
 
        public List<T> Select<T>(string WhereFieldVal, string DBName = "")
        {
            var lst = typeof(T).GetProperties().ToList();
            string wherestring = "WHERE " + WhereFieldVal;
            string param = "";
            foreach (var prop in lst)
                param += prop.Name + ",";
            string _sql = String.Format("SELECT {1} FROM {0} {2}", DBName == "" ? typeof(T).Name : DBName, param.Remove(param.Length - 1), wherestring);
            return ReadData<T>(_sql);
        }

c# Get all your letters from russian email service mail.ru

OpenPop.NET
using OpenPop.Common.Logging;
using OpenPop.Mime;
using OpenPop.Mime.Decode;
using OpenPop.Mime.Header;
using OpenPop.Pop3;

// FetchAllMessages("pop3.mail.ru", 995, true, "my_mail_ru_user", "mypass");

public static List<OpenPop.Mime.Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password)
        {
            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect(hostname, port, useSsl);

                // Authenticate ourselves towards the server
                client.Authenticate(username, password);

                // Get the number of messages in the inbox
                int messageCount = client.GetMessageCount();

                // We want to download all messages
                List<OpenPop.Mime.Message> allMessages = new List<OpenPop.Mime.Message>(messageCount);

                // Messages are numbered in the interval: [1, messageCount]
                // Ergo: message numbers are 1-based.
                // Most servers give the latest message the highest number
                for (int i = messageCount; i > 0; i--)
                {
                    allMessages.Add(client.GetMessage(i));
                    //client.GetMessage(i).Headers.Subject - так получаем тему письма
                }

                // Now return the fetched messages
                return allMessages;
            }
        }

c# Get a certificate from a container and set a pin / password programmatically


        public static X509Certificate2 GetCertStorePass(string pin, X509Certificate2 certificate2)
        {
            var provider = (Gost3410CryptoServiceProvider)certificate2.PrivateKey;
            var secure = new System.Security.SecureString();

            foreach (char charPass in pin)
                secure.AppendChar(charPass);
            provider.SetContainerPassword(secure);

            return provider.ContainerCertificate;
        }

C# Получаем короткое имя из Subject сертификата


public static string GetSubjectCN(X509Certificate2 cert)
        {
            // вырезаем имя из строки            
            int indexStart = cert.Subject.IndexOf("CN");
            if (indexStart >= 0)
            {
                int indexEnd = cert.Subject.IndexOf(",", indexStart);
                indexStart += 3;
                if (indexStart < indexEnd)
                {
                    return cert.Subject.Substring(indexStart, indexEnd - indexStart);
                }
            }
            return null;
        }

C# How to get all certificates from "My" Store


public static List<string> GetCertNamesFromStore(string search)
        {
            X509Store store = new X509Store("My");
            try
            {
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certCollection = store.Certificates;
                X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
                var res = new List<string>();
                foreach (X509Certificate2 s in certCollection)
                {
                    if (search=="")
                        res.Add(GetSubjectCN(s));
                    else if (s.SubjectName.Name.Contains(search))
                        res.Add(GetSubjectCN(s));
                }
                return res;
            }
            finally
            {
                store.Close();
            }
        }

C# Обработываем событие на Hotkey в приложениях WPF

Способ 1

        public MainWindow()
        {
            InitializeComponent();
            AddHandler(Keyboard.KeyDownEvent, (KeyEventHandler)HandleKeyDownEvent);
        }

        private void HandleKeyDownEvent(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Tab && (Keyboard.Modifiers & (ModifierKeys.Control | ModifierKeys.Shift)) == (ModifierKeys.Control | ModifierKeys.Shift))
            {
                MessageBox.Show("CTRL + SHIFT + TAB trapped");
            }

            if (e.Key == Key.Tab && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                MessageBox.Show("CTRL + TAB trapped");
            }
        }



Способ 2

<Window x:Class="WPFHotkey.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WPFHotkey"
        Title="MainWindow" Height="350" Width="525">
    <Window.CommandBindings>
        <CommandBinding Command="local:MainWindow.Some_Command" Executed="Some_Executed"/>
    </Window.CommandBindings>
    <Window.InputBindings>
        <KeyBinding Key="F4" Modifiers="ALT" Command="local:MainWindow.Some_Command"/>
    </Window.InputBindings>
    <Grid>
        
    </Grid>
</Window>


using System.Windows;
using System.Windows.Input;

namespace WPFHotkey
{
    
    public partial class MainWindow : Window
    {
        public static RoutedCommand Some_Command = new RoutedCommand();


        private void Some_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("Hi!");
        }

        public MainWindow()
        {
            InitializeComponent();
        }

    }
}

c# проверяем xml по xsd схеме

using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;

public class Sample {

  public static void Main() {

    XmlSchemaSet sc = new XmlSchemaSet();
    sc.Add("", "books.xsd");
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas = sc;
    settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
    XmlReader reader = XmlReader.Create("booksSchemaFail.xml", settings);
    while (reader.Read());

  }

  private static void ValidationCallBack(object sender, ValidationEventArgs e) {
    Console.WriteLine("Validation Error: {0}", e.Message);
  }
}