Category Archives: C# Programming

Chapter99: PerformingHTTP requests

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()))…
Continue reading

Chapter98:Networking

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);…
Continue reading

Chapter97:FileandStreamI/O

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.…
Continue reading

Chapter96:Delegates

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 {…
Continue reading

Chapter95:Attributes

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;…
Continue reading

Chapter94:Structs

Section94.1:Declaringa struct publicstructVector { publicintX; publicintY; publicintZ; } publicstructPoint { publicdecimalx,y; publicPoint(decimalpointX,decimalpointY) { x=pointX; y=pointY; } } structinstancefieldscanbesetviaaparametrizedconstructororindividuallyafterstructconstruction. Privatememberscanonlybeinitializedbytheconstructor. structdefines a sealed type…
Continue reading

Chapter93:Preprocessordirectives

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…
Continue reading

Chapter92:BindingList

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();
Continue reading

Chapter91:OverloadResolution

Section91.1:BasicOverloadingExampleThiscodecontainsanoverloadedmethodnamedHello: classExample { publicstaticvoidHello(intarg) { Console.WriteLine("int"); } publicstaticvoidHello(doublearg) { Console.WriteLine("double"); } publicstaticvoidMain(string[]args) { Hello(0); Hello(0.0); } } WhentheMainmethodiscalled,itwillprint int double Atcompile-time,whenthecompilerfindsthemethodcallHello(0),itfindsallmethodswiththenameHello.In thiscase,itfindstwoofthem.Itthentriestodeterminewhichofthemethodsisbetter.Thealgorithmfor determiningwhichmethodisbetteriscomplex,butitusuallyboilsdownto"makeasfewimplicitconversionsas…
Continue reading

Chapter90:ExpressionTrees

Parameter                                     Details TDelegate                    Thedelegatetypetobeusedfortheexpression lambdaExpression Thelambdaexpression(ex.num=>num<5) ExpressionTreesareExpressionsarrangedinatreelikedatastructure.Eachnodeinthetreeisarepresentationof an expression, an expression being code. An In-Memory representation of a Lambda expression would be an…
Continue reading