Technology Made Easy

path                                                                                 filter The directory to monitor, in standard or Universal Thetypeoffilestowatch.Forexample,”*.txt”watches for Naming Convention (UNC) notation. changes to all text files. Section101.1:IsFileReady Thetypeoffilestowatch.Forexample,”*.txt”watches for changes to all text files. A common mistake a lot of people starting out with FileSystemWatcher does is not taking into account That the FileWatchereventisraisedassoonasthefileiscreated.However,itmaytakesometimeforthefiletobefinished. Example: Take a file size of […]

Parameter                                                                          Details archiveFileName Thepathtothearchivetoopen,specifiedasarelativeorabsolutepath.Arelativepathis interpreted as relative to the current working directory. Section100.1:Writingtoazipfile Towriteanew.zipfile: System.IO.Compression System.IO.Compression.FileSystem using(FileStreamzipToOpen=newFileStream(@”C:\temp”,FileMode.Open)) { using(ZipArchivearchive=newZipArchive(zipToOpen,ZipArchiveMode.Update)) { ZipArchiveEntryreadmeEntry=archive.CreateEntry(“Readme.txt”); using(StreamWriterwriter=newStreamWriter(readmeEntry.Open())) { writer.WriteLine(“Informationaboutthispackage.”); writer.WriteLine(“========================”); } } } Section100.2:WritingZipFilesin-memory Thefollowingexamplewillreturnthebyte[]dataofazippedfilecontainingthefilesprovidedtoit,without needingaccesstothefilesystem. publicstaticbyte[]ZipFiles(Dictionary<string,byte[]>files) { using(MemoryStreamms=newMemoryStream()) { using(ZipArchivearchive=newZipArchive(ms,ZipArchiveMode.Update)) { foreach(varfileinfiles) { ZipArchiveEntryorderEntry=archive.CreateEntry(file.Key);//createafilewith thisname using(BinaryWriterwriter=newBinaryWriter(orderEntry.Open())) { writer.Write(file.Value);//writethebinarydata } } } //ZipArchivemustbedisposedbeforetheMemoryStreamhasdata returnms.ToArray(); } } Section100.3:GetfilesfromaZipfile Thisexamplegetsalistingoffilesfromtheprovidedziparchivebinary data: publicstaticDictionary<string,byte[]>GetFiles(byte[]zippedFile) […]

Section99.1:CreatingandsendinganHTTPPOSTrequest usingSystem.Net; usingSystem.IO; … stringrequestUrl=”https://www.example.com/submit.html”; HttpWebRequestrequest=HttpWebRequest.CreateHttp(requestUrl); request.Method=”POST”; //Optionally,setpropertiesoftheHttpWebRequest,suchas:request.AutomaticDecompression=DecompressionMethods.Deflate|DecompressionMethods.GZip; request.ContentType=”application/x-www-form-urlencoded”; //CouldalsosetotherHTTPheaderssuchasRequest.UserAgent,Request.Referer, //Request.Accept,orotherheadersviatheRequest.Headerscollection. //SetthePOSTrequestbodydata.Inthisexample,thePOSTdataisin //application/x-www-form-urlencodedformat. stringpostData=”myparam1=myvalue1&myparam2=myvalue2″; using(varwriter=newStreamWriter(request.GetRequestStream())) { writer.Write(postData); } //Submittherequest,andgettheresponsebodyfromtheremoteserver. stringresponseFromRemoteServer; using(HttpWebResponseresponse=(HttpWebResponse)request.GetResponse()) { using(StreamReaderreader=newStreamReader(response.GetResponseStream())) { responseFromRemoteServer=reader.ReadToEnd(); } } Section99.2:CreatingandsendinganHTTPGETrequest usingSystem.Net; usingSystem.IO; … stringrequestUrl=”https://www.example.com/page.html”; HttpWebRequestrequest=HttpWebRequest.CreateHttp(requestUrl); //Optionally,setpropertiesoftheHttpWebRequest,suchas:request.AutomaticDecompression=DecompressionMethods.GZip|DecompressionMethods.Deflate; request.Timeout=2*60*1000;//2minutes,inmilliseconds //Submittherequest,andgettheresponsebody. stringresponseBodyFromRemoteServer; using(HttpWebResponseresponse=(HttpWebResponse)request.GetResponse()) { using(StreamReaderreader=newStreamReader(response.GetResponseStream())) { responseBodyFromRemoteServer=reader.ReadToEnd(); } } Section99.3:ErrorhandlingofspecificHTTPresponsecodes (suchas404NotFound) usingSystem.Net; … stringserverResponse; try { //CallamethodthatperformsanHTTPrequest(pertheaboveexamples). serverResponse=PerformHttpRequest(); } catch(WebExceptionex) […]

Section98.1:BasicTCPCommunicationClient ThiscodeexamplecreatesaTCPclient,sends”HelloWorld”overthesocketconnection,andthenwritestheserver response to the console before closing the connection. //DeclareVariables stringhost=”stackoverflow.com”; intport=9999; inttimeout=5000; //CreateTCPclientandconnect using(var_client=newTcpClient(host,port)) using(var_netStream=_client.GetStream()) { _netStream.ReadTimeout=timeout; //Writeamessageoverthesocket stringmessage=”HelloWorld!”; byte[]dataToSend=System.Text.Encoding.ASCII.GetBytes(message); _netStream.Write(dataToSend,0,dataToSend.Length); //Readserverresponse byte[]recvData=newbyte[256]; intbytes=_netStream.Read(recvData,0,recvData.Length); message=System.Text.Encoding.ASCII.GetString(recvData,0,bytes); Console.WriteLine(string.Format(“Server: {0}”,message)); };//Theclientandstreamwillcloseascontrolexitstheusingblock(Equivilentbutsaferthan callingClose(); Section98.2: Download a file froma web server Downloading a file from the internet is a very common task required by almost every application your […]

Parameter                                                                Details path                The locationof thefile. append           Ifthefileexist,truewilladddatatotheendofthefile(append),falsewilloverwritethefile. text Text to be written or stored. contents        A collection of strings to be written. source            The location of the file you want to use. dest       The location you want a file to go to. Managesfiles. Section97.1:ReadingfromafileusingtheSystem.IO.Fileclass YoucanusetheSystem.IO.File.ReadAllTextfunctiontoreadtheentirecontentsofafileintoastring. stringtext=System.IO.File.ReadAllText(@”C:\MyFolder\MyTextFile.txt”); YoucanalsoreadafileasanarrayoflinesusingtheSystem.IO.File.ReadAllLinesfunction: string[]lines=System.IO.File.ReadAllLines(@”C:\MyFolder\MyTextFile.txt”); Section97.2:Lazilyreadingafileline-by-lineviaan IEnumerable When working with large […]

Section96.1:Declaringadelegatetype ThefollowingsyntaxcreatesadelegatetypewithnameNumberInOutDelegate,representingamethodwhichtakes an intand returns an int. publicdelegateintNumberInOutDelegate(intinput); Thiscanbeusedasfollows: publicstaticclassProgram { staticvoidMain() { NumberInOutDelegatesquare=MathDelegates.Square; intanswer1=square(4); Console.WriteLine(answer1);//Willoutput16 NumberInOutDelegatecube=MathDelegates.Cube; intanswer2=cube(4); Console.WriteLine(answer2);//Willoutput64 } } publicstaticclassMathDelegates { staticintSquare(intx) { returnx*x; } staticintCube(intx) { returnx*x*x; } } TheexampledelegateinstanceisexecutedinthesamewayastheSquaremethod.Adelegateinstanceliterallyacts asadelegateforthecaller:thecallerinvokesthedelegate,andthenthedelegatecallsthetargetmethod.This indirection decouples the caller from the target method. You can declare a generic delegate type, and in that case you may […]

Section95.1:Creatingacustomattribute //1)AllattributesshouldbeinheritedfromSystem.Attribute //2)Youcancustomizeyourattributeusage(e.g.placerestrictions)byusingSystem.AttributeUsage Attribute //3)Youcanusethisattributeonlyviareflectioninthewayitissupposedtobeused //4)MethodMetadataAttributeisjustaname.Youcanuseitwithout”Attribute”postfix-e.g. [MethodMetadata(“Thistextcouldberetrievedviareflection”)]. //5)Youcanoverloadanattributeconstructors [System.AttributeUsage(System.AttributeTargets.Method|System.AttributeTargets.Class)] publicclassMethodMetadataAttribute:System.Attribute { //thisiscustomfieldgivenjustforanexample //youcancreateattributewithoutanyfields //evenanemptyattributecanbeused-asmarker publicstringText{get;set;} //thisconstructorcouldbeusedas[MethodMetadata] publicMethodMetadataAttribute() { } //Thisconstructorcouldbeusedas[MethodMetadata(“String”)] publicMethodMetadataAttribute(stringtext) { Text=text; } } Section95.2:Readinganattribute MethodGetCustomAttributesreturnsanarrayofcustomattributesappliedtothemember.Afterretrievingthis arrayyoucansearchforoneormorespecificattributes. varattribute=typeof(MyClass).GetCustomAttributes().OfType<MyCustomAttribute>().Single(); Oriteratethroughthem foreach(varattributeintypeof(MyClass).GetCustomAttributes()){ Console.WriteLine(attribute.GetType()); } GetCustomAttributeextension method from System.Reflection.CustomAttributeExtensionsretrieves a custom attributeofaspecifiedtype,itcanbeappliedtoanyMemberInfo. varattribute=(MyCustomAttribute)typeof(MyClass).GetCustomAttribute(typeof(MyCustomAttribute)); GetCustomAttributealsohasgenericsignaturetospecifytypeofattributetosearchfor. varattribute=typeof(MyClass).GetCustomAttribute<MyCustomAttribute>(); Booleanargumentinheritcanbepassedtobothofthosemethods.Ifthisvaluesettotruetheancestorsof element would be also to inspected. Section95.3:Usinganattribute [StackDemo(Text=”Hello,World!”)] publicclassMyClass { [StackDemo(“Hello,World!”)] […]

Section94.1:Declaringa struct publicstructVector { publicintX; publicintY; publicintZ; } publicstructPoint { publicdecimalx,y; publicPoint(decimalpointX,decimalpointY) { x=pointX; y=pointY; } } Vectorv1=null;//illegal Vector?v2=null;//OK Nullable<Vector>v3=null//OK //Bothoftheseareacceptable Vectorv1=newVector();v1.X=1; v1.Y=2; v1.Z=3; Vectorv2; v2.X=1; v2.Y=2; v2.Z=3; However,thenewoperatormust be usedin orderto usean initializer: Vectorv1=newMyStruct{X=1,Y=2,Z=3};//OK Vectorv2{X=1,Y=2,Z=3};//illegal Astructcandeclareeverythingaclasscandeclare,withafewexceptions: Section94.2:Structusage Withconstructor: Vectorv1=newVector(); v1.X=1; v1.Y=2; v1.Z=3; Console.WriteLine(“X={0},Y={1},Z={2}”,v1.X,v1.Y,v1.Z); //OutputX=1,Y=2,Z=3 Vectorv1=newVector(); //v1.Xisnotassigned v1.Y=2; v1.Z=3; Console.WriteLine(“X={0},Y={1},Z={2}”,v1.X,v1.Y,v1.Z); //OutputX=0,Y=2,Z=3 Pointpoint1=newPoint(); point1.x=0.5; point1.y=0.6; Pointpoint2=newPoint(0.5,0.6); […]

Section93.1:ConditionalExpressions Whenthefollowingiscompiled,itwillreturnadifferentvaluedependingonwhichdirectivesaredefined. //Compilewith/d:Aor/d:Btoseethedifference stringSomeFunction() { #ifA return”A”; #elifB return”B”; #else return”C”; #endif } Conditionalexpressionsaretypicallyusedtologadditionalinformationfordebugbuilds. voidSomeFunc() { try { SomeRiskyMethod(); } catch(ArgumentExceptionex) { #ifDEBUG log.Error(“SomeFunc”,ex); #endif HandleException(ex); } } Section93.2:OtherCompilerInstructions Line #linecontrolsthelinenumberandfilenamereportedbythecompilerwhenoutputtingwarningsanderrors. voidTest() { #line42″Answer” #linefilename”SomeFile.cs” intlife;//compilerwarningCS0168in”SomeFile.cs”atLine42 #linedefault //compilerwarningsresettodefault } PragmaChecksum #pragmachecksumallowsthespecificationofaspecificchecksumforageneratedprogramdatabase(PDB)for debugging. #pragmachecksum”MyCode.cs””{00000000-0000-0000-0000-000000000000}””{0123456789A}” Section93.3:DefiningandUndefiningSymbols A compiler symbol is a keyword that is defined at compile-time […]

Section92.1:Additemtolist BindingList<string>listOfUIItems=newBindingList<string>(); listOfUIItems.Add(“Alice”); listOfUIItems.Add(“Bob”); Section92.2:AvoidingN*2iteration ThisisplacedinaWindowsFormseventhandler varnameList=newBindingList<string>(); ComboBox1.DataSource=nameList;for(longi=0; i<10000;i++){ nameList.AddRange(new[]{“Alice”,”Bob”,”Carol”}); } Thistakesalongtimetoexecute,tofix,dothebelow: varnameList=newBindingList<string>(); ComboBox1.DataSource=nameList; nameList.RaiseListChangedEvents=false; for(longi=0;i<10000;i++){ nameList.AddRange(new[]{“Alice”,”Bob”,”Carol”}); } nameList.RaiseListChangedEvents=true; nameList.ResetBindings();