4, C # Advanced: MD5 encryption, process, thread, GDI +, XML, delegate

Source: Internet
Author: User
Tags md5 encryption

MD5 encryption

The string is encrypted and cannot be decrypted. The way of decryption on the Internet is also found in the library, can not find nor.

1 protected void Page_Load (object sender, EventArgs e) 2 {3     string s = "123"; 4     Response.Write (GETMD5 (s)); 5} 6 public string GetMd5 (String str) 7 {8     MD5 MD5 = MD5. Create ();//md5 abstract class cannot instantiate the method 9     byte[] buffer = Encoding.Default.GetBytes (str);//convert string to byte array     byte[] Mdbuffer = md5.computehash (buffer); Call the ComputeHash method to pass the array in     //to each element in the byte array tostring ();     StringBuilder result = new StringBuilder ();     int i = 0; I < Mdbuffer. Length; i++),     {         result. Append (Mdbuffer[i]. ToString ("X2")); ToString gets the decimal string tostring ("x") of the hexadecimal string tostring ("x2") aligned with the     }17     return result. ToString (); 18}

In-process

Indicates that a number operation on a position is a one-time X-in. Binary is every two in one, decimal is every ten into one, Hex is every 16 into one, and so on.

So: binary 001010101 only 0 and 1 the data in the computer is a binary representation, and the quaternion represents any real number in 0, 1, 2, 34 digits. Decimal 0~9 digits, hexadecimal 0~9, and ABCEDF (representing decimal numbers) 10~15

The special method of ToString

Time: Now. ToString ("Yyyy-mm-dd hh:mm:ss") year-month-day time: minute: Seconds specific can be custom written separately F y m D t meaning different former can be achieved

Character-type conversions: Int. ToString ("n"); 640,000.00; Int. ToString ("C"); ¥640,000.00;. ToString ("x"); 16 binary

Directory Class

Used to manipulate folders.

1 directory.createdirectory ("d:/ccc/cc"); Create folder 2  3 directory.delete ("D:/CCC", true);//true Delete non-empty folder 4  5 directory.move (@ "D:/CCC", @ "D:/CCCC");//Cut operation  The source directory is gone. Must be the same reel D disk 6  7 string[] s = directory.getfiles (@ "D:\ project \web\images\shiji");//Get the folder directory all files full path 8  9 string[] s = Directory.GetFiles (@ "D:\ project \web\images\shiji", "*.jpg"); Obtain the folder directory under the specified suffix name file full path string[] s = directory.getdirectories (@ "D:\ project \web\images"); Get the full path of the folder under folder directory Directory.Exists (@ "D:\ Project \web\images")//whether there is a folder

Process

We can think of every running application in a computer as a process

1///Get the process running in the current Program 2 process[] Pros = process.getprocesses (); 3 foreach (var item in pros) 4 {
Item. Kill (); Close all processes.
Item. ProcessName; Process Name 5 console.write (item. ToString ()); 6} 7//Open Some programs through the process 8 Process.Start ("Calc"); Open Calculator 9 Process.Start ("Notepad"); Open Notepad 10//Open the specified file one ProcessStartInfo Pro = new ProcessStartInfo (@ "D:\11.txt"); PR = new process (); StartInfo = pro;14 pr. Start ();

Thread

Each process is made up of multiple threads.

Single Thread: Let the program do more things, will trigger the death of the dead state.

Multithreading: Let a program handle multiple things at the same time, run the program in the background, improve the efficiency of the program operation.

Foreground thread: Only all foreground threads are closed to complete the program shutdown. (When WinForm multiple windows)

Background thread: As long as all foreground threads end, the background thread ends automatically.

1//Instantiate the thread class and pass in a method that points to the thread to run. (At this point the thread has been generated, but not yet run) 2//Call the Start method of the thread class, the token thread can be executed by the CPU, but the specific execution event is determined by the CPU. 3 Thread th = new Thread (Test); Create a thread to execute this method. 4th. IsBackground = true; Sets the thread as a background thread, and the thread ends after the foreground is closed. 5th. Start (); The tag is ready and can be executed at will, when execution is determined by the CPU. 6//The cross-thread access is not allowed under. Net. 7//Sometimes it is necessary to manually release the thread when it is closed to determine if the thread is closing  8 if (th = null) 9 {ten     th. Abort (); End this thread can no longer start () one}12 thread.sleep (3000); Sleep 3 seconds after execution 13//thread execution with parameter method Thread.Start ("123"); object type argument after Start bracket write argument

When used in large amounts of data, one thread is searched for data, then stored in the cache, and the page is then asynchronously fetching the data in the cache.

Gdi+

is a drawing device interface that can be used to draw pictures.

Draw a line

Graphics g = this. CreateGraphics (); Create GDI object Pen pen = new Pen (brushes.yellow); Create brush Point p1 = new Point (30, 50); Create two points p2 = new Point (+), G.drawline (pen, p1, p2);

Draw Verification Code

 1//<summary> 2//Character 3//</summary> 4//<param name= "Len" > several </param> 5//<returns&gt ;</returns> 6 public static string validation (int CD) 7 {8 var ran = new Random (); 9 int num, TEM;10 St Ring RTUSTR = ""; one for (int i = 0; I < CD; i++) {num = ran. Next (); if (i% 2 = = 1) tem = num% 10 + ' 0 '; Digital else17 tem = num% + ' A '; The letter is Rtustr + = Convert.tochar (TEM). ToString (); 19}20//write cookie21 HttpCookie cookie = new HttpCookie ("check"); Value = Rtustr.tolower (), HttpContext.Current.Response.Cookies.Add (cookie), return rtustr;25}26//&LT;SU MMARY&GT;28///</summary>30//<param name= "Check" > Characters </param>31 public static byte[] Drawi MG (string check), {Bitmap img = new Bitmap ($), var ht = Graphics.fromimage (IMG), and HT. Clear (Color.White); DrawLine (New Pen (CoLor. Springgreen), 1, 1, (+); PNs font font = new Font ("Microsoft Jas", FontStyle.Bold); var Jianbian = new Lineargradie Ntbrush (New Rectangle (0, 0, IMG). Width, IMG. Height), Color.teal, Color.snow, 2f, true); DrawString (check, font, Jianbian, 0, 0), + HT. DrawRectangle (New Pen (Color.aqua), 0, 0, IMG. Width-1, IMG. HEIGHT-1); MemoryStream ms = new MemoryStream (); Save (MS, Imageformat.jpeg), Ht. Dispose (); Dispose (); return Ms. ToArray (); 46}

Called in MVC

1 public ActionResult Showvalidate () 2 {3     var check = Common.Validate.validation (4); 4     byte[] buffer = COMMON.VALIDATE.DRAWIMG (check); 5     return File (buffer, "image/jpeg"); 6}

Front desk

if ( Validatecode.tolowercase () = = GetCode ()) {    return true;        }        function ChangeCode () {    $ ("#img"). attr ("src", $ ("#img"). attr ("src") + "?"); function GetCode () {    var cookies = Document.cookie.split (";");    for (var i = 0; i < cookies.length; i++) {        var validate = cookies[i].split ("=");        if (Validate[0].replace (/(^\s*) | ( \s*$)/g, "") = = "Check") {            return Validate[1].replace (/(^\s*) | ( \s*$)/g, "");}}    

XML file

Extensible Markup Language for storing lightweight data.

The tags for XML are paired and case-sensitive.

The XML document must contain a root node and only one.

Creating an XML file

 1//Create XML object 2 XmlDocument doc = new XmlDocument (); 3//Create document Description information 4 XmlDeclaration Dec = doc. Createxmldeclaration ("1.0", "Utf-8", null); 5 doc. AppendChild (DEC); 6 7//Create root node 8 XmlElement books = doc. CreateElement ("Books"); 9 Doc. AppendChild (books); 10 11//Create child node XmlElement Book1 = Doc. CreateElement ("book"); books. AppendChild (BOOK1); Add child nodes to BOOKS14 15//Append child nodes to Book1 child nodes XmlElement name1 = doc. CreateElement ("Name"); name1. InnerText = "C #"; Assignment text value Book1. AppendChild (name1), XmlElement Price1 = doc. CreateElement ("price"); Price1. INNERXML = "<b>10.0</b>"; The assignment HTML tag is Book1. AppendChild (Price1); XmlElement items = doc. CreateElement ("Items"); 25//Add attributes to nodes. SetAttribute ("Name", "C #"), and items. SetAttribute ("Price", "10.0"); Book1. AppendChild (items); Doc. Save ("books.xml"); Save 31 32//Create after <?xml version= "1.0" encoding= "Utf-8"? >34 <books>35 <book>36 <name>c#</n ame>37 <price>38 &LT;B&GT;10.0&LT;/B&Gt;39 </price>40 <items name= "C #" price= "10.0"/>41 </book>42 </Books> 

Append to an existing XML file

1 XmlDocument doc = new XmlDocument (), 2 if (file.exists ("books.xml")) 3 {4     doc. Load ("books.xml"); Load XML5     XmlElement books = doc. DocumentElement; Get root node 6     //re-establish element to append 7}

Get XML file

1 XmlDocument doc = new XmlDocument (); 2 Doc. Load ("books.xml"); 3  4 XmlElement books = doc. DocumentElement; 5 XmlNodeList xnl = books. ChildNodes; Get all nodes 6  7 foreach (XmlNode v in XNL)//traversal to get all the node values 8 {9     Console.WriteLine (V.innertext); ten}11 XmlNodeList xnl 1 = doc. SelectNodes ("Books/book/items"); Find a list of nodes (XmlNode node in xnl1) {     Console.WriteLine (node. attributes["Name"]. Value); Gets the value of the name attribute of     Console.WriteLine (node. attributes["Price"]. Value); Get the value of the Price property 17}

Delete an XML file

1 XmlDocument doc = new XmlDocument (); 2 doc. Load ("books.xml"); 3 4 XmlNode xnl = doc. selectSingleNode ("Books/book"); Find single node 5 xnl. RemoveAll (); Delete all 6 doc. Save ("books.xml"); 7 Console.readkey ();

Linqtoxml

 1//compatible with traditional methods to create 2 XDocument xDoc = new XDocument (); 3//xdoc.declaration = new Xdeclaration () default UTF-8 the first row does not need to be built separately 4 XElement xroot = new XElement ("root", "value");  Define element 5 6 XElement xRoot1 = new XElement ("Root1"); Define element 2 7 Xroot1.value = "value 1"; 8 9 XAttribute xattr = new XAttribute ("Id", "1"); Defining attributes of Xdoc.add (Xroot);     Unified Use Add Xroot.add (xattr), Xdoc.save (@ "D:\linqtoxml.xml"); 15 16//Real LINQ syntax-//f# Functional programming language-new XDocument (19 New XElement ("root", new XAttribute ("id", "001"), 21 "value") 22). Save (@ "D:\2.xml"); 23//chain programming, assembly line production F1 (). F2 (). f3 () ... 24 25//Find xml26 XDocument xdoc = new XDocument (New XElement ("root"));//root node Xdoc. Root.add ("Person", XElement new XAttribute ("id", "1"), New XAttribute ("name", "Zhangsan"), New xattr Ibute ("Sex", "1") 31)); Add a child node, Xdoc. Root.add ("Person", XElement new XAttribute ("id", "2"), New XAttribute ("name", "Lisi"), New XAttribute (" Sex "," 2 ")); Panax Notoginseng Xdoc. Save (@ "D:\2.xml"); 38 39<?xml version= "1.0" encoding= "Utf-8"? >40 <root>41 <person id= "1" name= "Zhangsan" sex= "1"/>42 <pe  Rson id= "2" name= "Lisi" sex= "2"/>43 </root>44 45//start to find, modify, delete, XDocument Xdoc = Xdocument.load (@ "D:\2.xml"); Load xml48 foreach (XElement xlt in Xdoc. Root.elements ())//root root node Elements element collection (XLT). Name.localname = = "Person") the node name of//name nodes LocalName without namespace {(XLT). Attribute ("id"). Value = = "1")//Judgment attribute value is 1 o'clock Response.Write (XLT). Attribute ("name"). Value); Output Name55 XLT. Attribute ("name"). Value = "NewName"; Modify the Name56 xlt. Remove (); Delete this node xdoc. Save (@ "D:2.xml");}59}60}61//linq query Syntax//descendants () All child nodes can be added to all nodes under a node. var query = from S in XDOC.D Escendants ()//Find in the collection where s.name.localname = = "Person", select s;67 foreach (XElement xlt in Query) Response.Write (XLT). Value);}71//linq method Syntax (lambda expression)Lement XLT in Xdoc. Descendants ().  Where (s =>74 {s.name.localname = = "Name") {false;80 return true;78}79 return}) 81 {Response.Write (XLT). Value); 83}

Commissioned
Use delegate to define a delegate and pass one method as a parameter to another method.
The function that the delegate points to must return the same value as the parameter

  1//<summary> 2//Delegate Syntax 3///</summary> 4 Class program 5 {6 public delegate void Delsayhi (str ing name);  Define delegate 7 static void Main (string[] args) 8 {9 Delsayhi del = new Delsayhi (Sayhichinese);//Instantiate delegate invocation concrete method Ten del ("San"); Execute one delsayhi del1 = Sayhichinese; Direct assignment method of Del1 ("Si"); 14 15//anonymous function Delsayhi Del2 = delegate (string name) {Console.WriteLine (name + ", think dense");}; Del2 ("Korea"); //lambda expression () No parameters are also written by-= {//Method body} No parameters can be e=> Console.WriteLine (""); If there is only a sentence without {} return returned can be omitted delsayhi del3 = (string name) = {Console.WriteLine (name + ", Savatika");}; Del2 ("Thailand"); Sayhi ("David", Sayhienglish); Call the method of the custom method parameter to invoke the Console.readkey ();     30 public static void Sayhi (string name, Delsayhi del)//define method type Delegate ({) (name); } to public static void Sayhichinese (string name) 33 { Console.WriteLine ("Hello, I call" + name);  Sayhienglish (string name) PNs {Console.WriteLine ("Hello, my name is {0}, Nice to meet you! ", name); +/-<summary> 45//for any array max.///</summary> +/-Class program IC delegate int Delcompre (object O1, Object O2); Define comparison delegate-static void Main (string[] args) 51 {52//comparison int object[] Objs = new object[] {1, 2 , 3, 4, 5, 32, 1, 243,}; The var max = Getmax (Objs, Getintmax); Incoming comparison int method Console.WriteLine (max); The max2 var = getmax (Objs, Delegate (object O1, Object O2). Parse (O1. ToString ())-Int. Parse (O2. ToString ()); 60}); Anonymous functions as compared to int Console.WriteLine (MAX2); 62 63//Compare string object[] STRs = new object[] {"abc", "EFD", "asdf", "SD", "ASDFF"}; The var maxstrs = Getmax (STRs, Delegate (object O1,Object O2) (O1). ToString (). Length-o2. ToString (). Length; 68}); anonymous function Console.WriteLine (maxstrs); The var maxstrs2 = Getmax (STRs, (object O1, object O2) = + O1. ToString (). Length-o2. ToString (). Length; 74}); Lambda expression-Console.WriteLine (Maxstrs2); Console.readkey (); Getintmax (Object O1, Object O2)//Compare int method Bayi {int n1 = Int. Parse (O1. ToString ()); n2 int = Int. Parse (O2. ToString ()); N1-N2 return; *//<summary> 87///to take an arbitrary array of the maximum value of *//</summary>//<param name= "Objs" ; Arrays </param>//<param name= "del" > Delegates </param>//<returns></returns> the PU Blic static Object Getmax (object[] objs, Delcompre del) ({94 Object max = Objs[0]; 0; I < Objs. LengtH i++)//if (Max < objs[i]) object cannot determine what type it is so it cannot be used < 98 if (Del (max, objs[i]) & Lt 0)//If the delegate value is less than 0 the establishment of the incoming how to compare can be objs[i];101 {max =}102}103 retu      RN max;104}105}106 107 108//&LT;SUMMARY&GT;109//Generics <T> Commission//</summary>111 class Program112 {113 public delegate int delcompre<t> (t t1, T T2);         Defines a generic delegate, static void Main (string[] args),//int117 {int[] nums = {1, 2, 3, 4, 5};118 int max = getmax<int> (nums, (int t1, int t2) = = {return t1-t2;}); 119 Console.WriteLine (max), 121//string122 string[] STRs = {"ASD", "SDF", "ZXCVV", "123", "QW E "};123 String maxstr = Getmax (STRs, (string s1, string s2) = = {return S1. Length-s2. Length; }); 124 Console.WriteLine (MAXSTR); 126 Console.readkey (); 127}128 129 public static T getmax< T> (t[] objS, delcompre<t> del)--{131 T max = objs[0];132 for (int i = 0; i < Objs. Length;             i++) 133 {134 if (Del (max, objs[i]) < 0) 135 {136 Max = objs[i];137 }138}139 return max;140}141}

Multicast delegation
Registers multiple methods, which are called to execute the methods sequentially.

1 public delegate void My1 (); 2 3 my1 my = Fun1 (); 4 my+= Fun2 (); + = Implement Multicast delegation 5 6 public static void Fun1 () {7}8 public static void Fun2 () {9}  

4, C # Advanced: MD5 encryption, process, thread, GDI +, XML, delegate

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.