Паттерн Шаблонный Метода задает скелет алгоритма в методе, оставляя определение реализации некоторых шагов субклассам. Субклассы могут переопределять некоторые части алгоритма без изменения его структуры. Основной задаче паттерна является создание шаблона алгоритма, то есть метод определяющий алгоритм в виде последовательности шагов. Один или несколько шагов определяются ввиде абстрактных методов, реализуемых субклассами. Таким образом гарантируется неизменность структуры […]
Как рассчитать возраст по дате рождения на C#?
Приведу небольшой фрагмент кода, который позволяет по вводу даты, рассчитать ваш возраст.
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 |
using System; using System.Collections.Generic; using System.Linq; using System.Net; namespace Work { class Program { static void Main(string[] args) { var date= CalculateAge(new DateTime(1980, 12, 22)); Console.WriteLine($"Ваш возраст: {date}"); Console.ReadKey(); } public static int CalculateAge(DateTime BirthDate) { int YearsPassed = DateTime.Now.Year - BirthDate.Year; if (DateTime.Now.Month < BirthDate.Month || (DateTime.Now.Month == BirthDate.Month && DateTime.Now.Day < BirthDate.Day)) { YearsPassed--; } return YearsPassed; } } } |
Как проверить подключение к интернету на C#?
Проверка интернет-соединения не такая уж тривиальная задача как может показаться, и для этого существует много способов, но рассмотрим самый простой. Мы отправим запрос к сайту google и, если он вернет ответ, соответственно подключение к интернету имеется, в обратном случаи интернет отсутствует.
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 |
using System; using System.Collections.Generic; using System.Linq; using System.Net; namespace Work { class Program { static void Main(string[] args) { ConnectionAvailable("http://www.google.com").ToString(); Console.ReadKey(); } public static bool ConnectionAvailable(string strServer) { try { HttpWebRequest httpReq = (HttpWebRequest)HttpWebRequest.Create(strServer); HttpWebResponse httpWeb = (HttpWebResponse)httpReq.GetResponse(); if (HttpStatusCode.OK == httpWeb.StatusCode) { // HTTP = 200 - Интернет безусловно есть! httpWeb.Close(); Console.WriteLine("Соединения с интернетом присутствует"); return true; } else { // сервер вернул отрицательный ответ, возможно что инета нет httpWeb.Close(); Console.WriteLine("Соединения с интернетом отсутствует, либо трафик сети перегружен"); return false; } } catch (WebException) { Console.WriteLine("Соединения с интернетом отсутствует"); return false; } } } } |
Криптография и защита на C#
В этом примере мы зашифруем сообщение с помощью RSA, и проверим его на соответствие вводимого сообщения, путем сверки цифровой подписи. Для этого создадим вспомогательные классы для работы:
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 |
using System; using System.Security.Cryptography; using System.Text; public class MD5HashHelper { public byte[] GetHash(string message) { byte[] data; data = UTF8Encoding.ASCII.GetBytes(message); MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); return md5.ComputeHash(data, 0, data.Length); } public bool VerifyHash(string message, byte[] hash) { byte[] data; data = UTF8Encoding.ASCII.GetBytes(message); MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] hashTemp = md5.ComputeHash(data, 0, data.Length); for (Int32 counter = 0; counter <= hash.Length - 1; counter += 1) { if (hash[counter] != hashTemp[counter]) { return false; } } return true; } } public class DigitalSignatureHelper { private RSAParameters m_public; public byte[] CreateSignature(byte[] hash) { RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(RSA); RSAFormatter.SetHashAlgorithm("MD5"); m_public = RSA.ExportParameters(false); return RSAFormatter.CreateSignature(hash); } public bool VerifySignature(byte[] hash, byte[] signedhash) { RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAParameters RSAKeyInfo = new RSAParameters(); RSAKeyInfo.Modulus = m_public.Modulus; RSAKeyInfo.Exponent = m_public.Exponent; RSA.ImportParameters(RSAKeyInfo); RSAPKCS1SignatureDeformatter RSADeformatter = new RSAPKCS1SignatureDeformatter(RSA); RSADeformatter.SetHashAlgorithm("MD5"); return RSADeformatter.VerifySignature(hash, signedhash); } } |
И код формы:
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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 |
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace DigitalSignature_Example { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { internal System.Windows.Forms.Button Button2; internal System.Windows.Forms.Button Button1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Button2 = new System.Windows.Forms.Button(); this.Button1 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // Button2 // this.Button2.Location = new System.Drawing.Point(224, 24); this.Button2.Name = "Button2"; this.Button2.Size = new System.Drawing.Size(112, 23); this.Button2.TabIndex = 5; this.Button2.Text = "Generate Signature"; this.Button2.Click += new System.EventHandler(this.Button2_Click); // // Button1 // this.Button1.Location = new System.Drawing.Point(224, 64); this.Button1.Name = "Button1"; this.Button1.Size = new System.Drawing.Size(112, 23); this.Button1.TabIndex = 4; this.Button1.Text = "Verify Signature"; this.Button1.Click += new System.EventHandler(this.Button1_Click); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(120, 24); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(96, 20); this.textBox1.TabIndex = 6; this.textBox1.Text = "My Signature"; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(120, 64); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(96, 20); this.textBox2.TabIndex = 7; this.textBox2.Text = "My Signature"; // // label1 // this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(178))); this.label1.Location = new System.Drawing.Point(8, 24); this.label1.Name = "label1"; this.label1.TabIndex = 8; this.label1.Text = "Set Signature"; // // label2 // this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(178))); this.label2.Location = new System.Drawing.Point(8, 64); this.label2.Name = "label2"; this.label2.TabIndex = 9; this.label2.Text = "Verify Signature"; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(344, 110); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.textBox2); this.Controls.Add(this.textBox1); this.Controls.Add(this.Button2); this.Controls.Add(this.Button1); this.MaximizeBox = false; this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Digital Signature - By Fadi Abdel-qader"; this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } DigitalSignatureHelper ds = new DigitalSignatureHelper(); byte[] hash1; byte[] hash2; byte[] signedhash; private void Button2_Click(object sender, System.EventArgs e) { try { MD5HashHelper md5 = new MD5HashHelper(); hash1 = md5.GetHash(textBox1.Text); signedhash = ds.CreateSignature(hash1); MessageBox.Show("Подпись создана успешно!"); } catch(Exception ex){MessageBox.Show(ex.Message);} } private void Button1_Click(object sender, System.EventArgs e) { try { MD5HashHelper md5 = new MD5HashHelper(); hash2 = md5.GetHash(textBox2.Text); if (ds.VerifySignature(hash2, signedhash)) { MessageBox.Show("Подписи проверены Успешно!"); } else { MessageBox.Show("Не удалось проверить подписи!"); } } catch(Exception ex){MessageBox.Show(ex.Message);} } } } |
Пример приема и передачи файла по сети C#
Вы этой статье я покажу как можно создать клиентско серверное приложение для передачи файлов по сети. Для начала напишем проект для передачи файла:
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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Runtime.Serialization.Formatters.Binary; using System.IO; using System.Net; using System.Net.Sockets; namespace File_Sender { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.TextBox text_IP; private System.Windows.Forms.OpenFileDialog openFileDialog1; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.textBox1 = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.text_IP = new System.Windows.Forms.TextBox(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.SuspendLayout(); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(48, 56); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(240, 20); this.textBox1.TabIndex = 0; this.textBox1.Text = ""; this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged); // // button1 // this.button1.Location = new System.Drawing.Point(296, 56); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(48, 23); this.button1.TabIndex = 1; this.button1.Text = "::"; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Enabled = false; this.button2.Location = new System.Drawing.Point(16, 152); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(128, 23); this.button2.TabIndex = 2; this.button2.Text = "Send The File To:"; this.button2.Click += new System.EventHandler(this.button2_Click); // // text_IP // this.text_IP.Location = new System.Drawing.Point(152, 152); this.text_IP.Name = "text_IP"; this.text_IP.Size = new System.Drawing.Size(208, 20); this.text_IP.TabIndex = 3; this.text_IP.Text = "127.0.0.1"; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(400, 266); this.Controls.Add(this.text_IP); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.textBox1); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "File Sender - By Fadi Abdel-qader fadidotnet.org"; this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } private void button2_Click(object sender, System.EventArgs e) { FileStream fs = new FileStream(textBox1.Text,FileMode.Open); byte[] buffer = new byte[fs.Length]; int len = (int)fs.Length; fs.Read(buffer,0,len); fs.Close(); BinaryFormatter br = new BinaryFormatter (); TcpClient myclient = new TcpClient (text_IP.Text,7000); NetworkStream myns = myclient.GetStream (); br.Serialize (myns,FileName); BinaryWriter mysw = new BinaryWriter (myns); mysw.Write(buffer); mysw.Close (); myns.Close (); myclient.Close (); } string FileName; private void button1_Click(object sender, System.EventArgs e) { openFileDialog1.ShowDialog(); textBox1.Text = openFileDialog1.FileName; FileInfo TheFile = new FileInfo(textBox1.Text); // Get The File Name FileName = TheFile.Name; } private void textBox1_TextChanged(object sender, System.EventArgs e) { if (textBox1.Text.Length > 3) button2.Enabled = true; else button2.Enabled = false; } } } |
Теперь создадим проект для приема данный:
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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Threading; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters; using System.IO; using System.Net; using System.Net.Sockets; namespace File_Receiver { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.ListBox listBox1; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.listBox1 = new System.Windows.Forms.ListBox(); this.SuspendLayout(); // // label1 // this.label1.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(224)), ((System.Byte)(224)), ((System.Byte)(224))); this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(178))); this.label1.Location = new System.Drawing.Point(8, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(160, 23); this.label1.TabIndex = 0; this.label1.Text = "Automatically Save to"; // // textBox1 // this.textBox1.Location = new System.Drawing.Point(176, 8); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(176, 20); this.textBox1.TabIndex = 1; this.textBox1.Text = "C:\\"; // // listBox1 // this.listBox1.Dock = System.Windows.Forms.DockStyle.Bottom; this.listBox1.Location = new System.Drawing.Point(0, 48); this.listBox1.Name = "listBox1"; this.listBox1.Size = new System.Drawing.Size(408, 134); this.listBox1.TabIndex = 2; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(408, 182); this.Controls.Add(this.listBox1); this.Controls.Add(this.textBox1); this.Controls.Add(this.label1); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "File Receiver By Fadi Abdel-qader fadidotnet.org"; this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing); this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } NetworkStream myns; TcpListener mytcpl; Socket mysocket; Thread myth; BinaryReader bb; void File_Receiver() { mytcpl = new TcpListener (7000); mytcpl.Start (); mysocket = mytcpl.AcceptSocket (); myns = new NetworkStream (mysocket); BinaryFormatter br = new BinaryFormatter (); object op; op= br.Deserialize (myns); // Deserialize the Object from Stream bb = new BinaryReader (myns); byte[] buffer = bb.ReadBytes(5000000); FileStream fss = new FileStream(@textBox1.Text + (string) op, FileMode.CreateNew, FileAccess.Write); fss.Write(buffer,0,buffer.Length); fss.Close(); mytcpl.Stop(); listBox1.Items.Add ("Successfully Saved to: " + textBox1.Text + (string) op); if (mysocket.Connected ==true) { while (true) { File_Receiver(); } } } private void Form1_Load(object sender, System.EventArgs e) { myth= new Thread (new System.Threading .ThreadStart(File_Receiver)); // Start Thread Session myth.Start (); } private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) { myth.Abort (); mytcpl.Stop (); } } } |
N