Паттерн Стратегия определяет семейство схожих алгоритмов, инкапсулирует каждый из них и обеспечивает их взаимозаменяемость. Он позволяет модифицировать алгоритмы независимо от их использования на стороне клиента. Если простыми словами, то определяются схожие функции помещая их в собственные классы и позволяет их изменять во время работы программы. Из представленного примера ниже, мы видим схожий функционал всех уток, […]
Класс шифрования C#
Этот класс упрощает быстрое шифрование данных паролем с помощью встроенных функций .NET Framework.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
using System.Text; using System.Security.Cryptography; using System.IO; class Encryptor { public static byte[] Encrypt(byte[] input, string password) { try { TripleDESCryptoServiceProvider service = new TripleDESCryptoServiceProvider(); MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] key = md5.ComputeHash(Encoding.ASCII.GetBytes(password)); byte[] iv = md5.ComputeHash(Encoding.ASCII.GetBytes(password)); return Transform(input, service.CreateEncryptor(key, iv)); } catch (Exception) { return new byte[0]; } } public static byte[] Decrypt(byte[] input, string password) { try { TripleDESCryptoServiceProvider service = new TripleDESCryptoServiceProvider(); MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] key = md5.ComputeHash(Encoding.ASCII.GetBytes(password)); byte[] iv = md5.ComputeHash(Encoding.ASCII.GetBytes(password)); return Transform(input, service.CreateDecryptor(key, iv)); } catch (Exception) { return new byte[0]; } } public static string Encrypt(string text, string password) { byte[] input = Encoding.UTF8.GetBytes(text); byte[] output = Encrypt(input, password); return Convert.ToBase64String(output); } public static string Decrypt(string text, string password) { byte[] input = Convert.FromBase64String(text); byte[] output = Decrypt(input, password); return Encoding.UTF8.GetString(output); } private static byte[] Transform(byte[] input, ICryptoTransform CryptoTransform) { MemoryStream memStream = new MemoryStream(); CryptoStream cryptStream = new CryptoStream(memStream, CryptoTransform, CryptoStreamMode.Write); cryptStream.Write(input, 0, input.Length); cryptStream.FlushFinalBlock(); memStream.Position = 0; byte[] result = new byte[Convert.ToInt32(memStream.Length)]; memStream.Read(result, 0, Convert.ToInt32(result.Length)); memStream.Close(); cryptStream.Close(); return result; } } |
Экспорт данные в CSV C#
Простой метод записи данных в формате DataTable или DataView на C# в CSV-файл.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
using System; using System.Data; using System.Windows.Forms; using System.IO; private void ExportDatatviewToCsv(string iFilename, DataView dv) { // Open output stream StreamWriter swFile = new StreamWriter(iFilename); // Header string[] colLbls = new string[dv.Table.Columns.Count]; for (int i = 0; i < dv.Table.Columns.Count; i++) { colLbls[i] = dv.Table.Columns[i].ColumnName; colLbls[i] = GetWriteableValueForCsv(colLbls[i]); } // Write labels swFile.WriteLine(string.Join(",", colLbls)); // Rows of Data foreach (DataRowView rowData in dv) { string[] colData = new string[dv.Table.Columns.Count]; for (int i = 0; i < dv.Table.Columns.Count; i++) { object obj = rowData[i]; colData[i] = GetWriteableValueForCsv(obj); } // Write data in row swFile.WriteLine(string.Join(",", colData)); } // Close output stream swFile.Close(); } private void ExportDatatableToCsv(string iFilename, DataTable dt) { // Open output stream StreamWriter swFile = new StreamWriter(iFilename); // Header string[] colLbls = new string[dt.Columns.Count]; for (int i = 0; i < dt.Columns.Count; i++) { colLbls[i] = dt.Columns[i].ColumnName; colLbls[i] = GetWriteableValueForCsv(colLbls[i]); } // Write labels swFile.WriteLine(string.Join(",", colLbls)); // Rows of Data foreach (DataRow rowData in dt.Rows) { string[] colData = new string[dt.Columns.Count]; for (int i = 0; i < dt.Columns.Count; i++) { object obj = rowData[i]; colData[i] = GetWriteableValueForCsv(obj); } // Write data in row swFile.WriteLine(string.Join(",", colData)); } // Close output stream swFile.Close(); } public static string GetWriteableValueForCsv(object obj) { // Nullable types to blank if (obj == null || obj == Convert.DBNull) return ""; // if string has no ',' if (obj.ToString().IndexOf(",") == -1) return obj.ToString(); // remove backslahes return "\"" + obj.ToString() + "\""; } |
Создание скриншотов с помощью C #
Код использует GDI в C#.NET для рисования основного экрана на растровом изображении.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
public class API { [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)] public static extern IntPtr GetDC(IntPtr hWnd); [DllImport("user32.dll", ExactSpelling = true)] public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC); [DllImport("gdi32.dll", ExactSpelling = true)] public static extern IntPtr BitBlt(IntPtr hDestDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop); [DllImport("user32.dll", EntryPoint = "GetDesktopWindow")] public static extern IntPtr GetDesktopWindow(); } internal class ScreenShot { public static Bitmap Take() { int screenWidth = Screen.PrimaryScreen.Bounds.Width; int screenHeight = Screen.PrimaryScreen.Bounds.Height; Bitmap screenBmp = new Bitmap(screenWidth, screenHeight); Graphics g = Graphics.FromImage(screenBmp); IntPtr dc1 = API.GetDC(API.GetDesktopWindow()); IntPtr dc2 = g.GetHdc(); //Основной эскиз, копирует экран в растровое изображение //последнее число — константа копирования API.BitBlt(dc2, 0, 0, screenWidth, screenHeight, dc1, 0, 0, 13369376); //Clean up API.ReleaseDC(API.GetDesktopWindow(), dc1); g.ReleaseHdc(dc2); g.Dispose(); return screenBmp; } } |
Вычисляет угол, под которым точка находится к началу координат и обратно C#
Используя простую математику, мы можем преобразовать между углами (в градусах) и точками координат XY. Полезно при работе с элементами круга.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/// <summary> /// Вычисляет точку, находящуюся под углом от начала координат (0 справа) /// </summary> private PointF DegreesToXY(float degrees, float radius, Point origin) { PointF xy = new PointF(); double radians = degrees * Math.PI / 180.0; xy.X = (float)Math.Cos(radians) * radius + origin.X; xy.Y = (float)Math.Sin(-radians) * radius + origin.Y; return xy; } /// <summary> /// Вычисляет угол, под которым точка находится к началу координат (0 справа) /// </summary> private float XYToDegrees(Point xy, Point origin) { int deltaX = origin.X - xy.X; int deltaY = origin.Y - xy.Y; double radAngle = Math.Atan2(deltaY, deltaX); double degreeAngle = radAngle * 180.0 / Math.PI; return (float)(180.0 - degreeAngle); } |