Technology Made Easy

Section110.1:MultithreadedTimersSystem.Threading.Timer-Simplestmultithreadedtimer.Containstwomethodsandoneconstructor. Example: A timer calls the DataWrite method, which writes “multithread executed…” after five seconds have elapsed, and then every second after that until the user presses Enter: usingSystem; usingSystem.Threading; classProgram { staticvoidMain() { //Firstinterval=5000ms;subsequentintervals=1000ms Timertimer=newTimer(DataWrite,”multithreadexecuted…”,5000,1000); Console.ReadLine(); timer.Dispose();//Thisbothstopsthetimerandcleansup. } staticvoidDataWrite(objectdata) { //Thisrunsonapooledthread Console.WriteLine(data);//Writes”multithreadexecuted…” } } Note:Willpostaseparatesectionfordisposingmultithreadedtimers. Change-Thismethodcanbecalledwhenyouwouldlikechangethetimerinterval. Timeout.Infinite- If youwant to firejust once. Specifythis in […]

Section109.1:UsingStreams Astreamisanobjectthatprovidesalow-levelmeanstotransferdata.Theythemselvesdonotactasdata containers. Thedatathatwedealwithisinformofbytearray(byte[]).Thefunctionsforreadingandwritingareallbyte orientated, e.g. WriteByte(). Therearenofunctionsfordealingwithintegers,stringsetc.Thismakesthestreamverygeneral-purpose,butless simpletoworkwithif,say,youjustwanttotransfertext.Streamscanbeparticularlyveryhelpfulwhenyouare dealing with large amount of data. WewillneedtousedifferenttypeofStreambasedwhereitneedstobewritten/readfrom(i.e.thebackingstore). Forexample,ifthesourceisafile,weneedtouseFileStream: stringfilePath=@”c:\Users\exampleuser\Documents\userinputlog.txt”; using(FileStreamfs=newFileStream(filePath,FileMode.Open,FileAccess.Read, FileShare.ReadWrite)) { //dostuffhere… fs.Close(); } Similarly,MemoryStreamisusedifthebackingstoreismemory: //Readallbytesinfromafileonthedisk. byte[]file=File.ReadAllBytes(“C:\\file.txt”); //Createamemorystreamfromthosebytes. using(MemoryStreammemory=newMemoryStream(file)) { //dostuffhere… } Similarly,System.Net.Sockets.NetworkStreamisusedfornetworkaccess. AllStreamsarederivedfromthegenericclassSystem.IO.Stream.Datacannotbedirectlyreadorwrittenfrom streams.The.NETFrameworkprovideshelperclassessuchasStreamReader,StreamWriter,BinaryReaderand BinaryWriterthatconvertbetweennativetypesandthelow-levelstreaminterface,andtransferthedatatoor from the stream for you. ReadingandwritingtostreamscanbedoneviaStreamReaderandStreamWriter.Oneshouldbecarefulwhen closingthese.Bydefault,closingwillalsoclosecontainedstreamaswellandmakeitunusableforfurtheruses.This defaultbehaviourcanbechangebyusingaconstructorwhichhasboolleaveOpenparameterandsettingitsvalue as true. StreamWriter: FileStreamfs=newFileStream(“sample.txt”,FileMode.Create); StreamWritersw=newStreamWriter(fs); stringNextLine=”Thisistheappendedline.”; sw.Write(NextLine); sw.Close(); //fs.Close();Thereisnoneedtoclosefs.Closingswwillalsoclosethestreamitcontains. StreamReader: using(varms=newMemoryStream()) […]

Section108.1:CheckedandUnchecked C#statementsexecutesineithercheckedoruncheckedcontext.Inacheckedcontext,arithmeticoverflowraisesan exception. In an unchecked context, arithmetic overflow is ignored and the result is truncated. shortm=32767; shortn=32767; intresult1=              checked((short)(m+n));                //willthrowanOverflowException intresult2=              unchecked((short)(m+n));//willreturn-2 Ifneitherofthesearespecifiedthenthedefaultcontextwillrelyonotherfactors,suchascompileroptions. Section108.2: Checkedand Uncheckedas a scope Thekeywordscanalsocreatescopesinorderto(un)checkmultipleoperations. shortm =32767; shortn=32767; checked { intresult1=(short)(m+n);//willthrowanOverflowException } unchecked { intresult2=(short)(m+n);//willreturn-2 }

Section107.1:Asimpleindexer classFoo { privatestring[]cities=new[]{“Paris”,”London”,”Berlin”}; publicstringthis[intindex] { get{ returncities[index]; } set{ cities[index]=value; } } } Usage: varfoo=newFoo(); //accessavalue stringberlin=foo[2]; //assignavalue foo[0]=”Rome”; ViewDemo Section107.2:Overloadingtheindexertocreatea SparseArray Byoverloadingtheindexeryoucancreateaclassthatlooksandfeelslikeanarraybutisn’t.ItwillhaveO(1)getand set methods, can access an element at index 100, and yet still have the size of the elements inside of it. The SparseArray class classSparseArray { Dictionary<int,string>array=newDictionary<int,string>(); publicstringthis[inti] { get { […]

Section106.1:System.Stringclass InC#(and.NET)astringisrepresentedbyclassSystem.String.Thestringkeywordisanaliasforthisclass. The System.String class is immutable, i.e once created its state cannot be altered. SoalltheoperationsyouperformonastringlikeSubstring,Remove,Replace,concatenationusing+operatoretc will create a new string and return it. Seethefollowingprogramfordemonstration- stringstr=”mystring”; stringnewString=str.Substring(3); Console.WriteLine(newString); Console.WriteLine(str); Thiswillprintstringandmystringrespectively. Section106.2:Stringsandimmutability Immutabletypesaretypesthatwhenchangedcreateanewversionoftheobjectinmemory,ratherthanchanging theexistingobjectinmemory.Thesimplestexampleofthisisthebuilt-instringtype. Takingthefollowingcode,thatappends”world”ontotheword”Hello” stringmyString=”hello”; myString+=”world”; Whatishappeninginmemoryinthiscaseisthatanewobjectiscreatedwhenyouappendtothestringinthe secondline.Ifyoudothisaspartofalargeloop,thereisthepotentialforthistocauseperformanceissuesinyour application. ThemutableequivalentforastringisaStringBuilder Takingthefollowingcode StringBuildermyStringBuilder=newStringBuilder(“hello”);myStringBuild er.append(“world”); When you run this, youare modifying the StringBuilderobjectitself in memory.

Section105.1:TypesofPolymorphism Polymorphism means that a operation can also be applied to values of some other types. There are multiple types of Polymorphism: containsfunctionoverloading.ThetargetisthataMethodcanbeusedwithdifferenttypeswithoutthe needofbeinggeneric. istheuseofgenerictypes.SeeGenerics hasthetargetinheritofaclasstogeneralizeasimilarfunctionality Adhocpolymorphism ThetargetofAdhocpolymorphismistocreateamethod,thatcanbecalledbydifferentdatatypeswithoutaneed oftype-conversioninthefunctioncallorgenerics.Thefollowingmethod(s)sumInt(par1,par2)canbecalledwith differentdatatypesandhasforeachcombinationoftypesaownimplementation: publicstaticintsumInt(inta,intb) { returna+b; } publicstaticintsumInt(stringa,stringb) { int_a,_b; if(!Int32.TryParse(a,out_a)) _a=0; if(!Int32.TryParse(b,out_b)) _b=0; return_a+_b; } publicstaticintsumInt(stringa,intb) { int_a; if(!Int32.TryParse(a,out_a)) _a=0; return_a+b; } publicstaticintsumInt(inta,stringb) { returnsumInt(b,a); } publicstaticvoidMain() […]

Section104.1:CustomActionFilters We write custom action filters for various reasons. We may have a custom action filter for logging, or for saving data to database before any action execution. We could also have one for fetching data from the database and setting it as the global values of the application. Tocreateacustomactionfilter,weneedtoperformthefollowingtasks: Overrideatleastoneofthefollowingmethods: OnActionExecuting–Thismethodiscalledbeforeacontrolleractionisexecuted. OnActionExecuted–This method is […]

Byusingasynchronoussocketsaservercanlisteningforincomingconnectionsanddosomeotherlogicinthe mean time in contrast to synchronous socket when they are listening they block the main thread and the application is becoming unresponsive an will freeze until a client connects. Section103.1:AsynchronousSocket(Client/Server)example ServerSideexample CreateListenerforserver Start of with creating an server that will handle clients that connect, and requests that will be send. So create an Listener […]

AccessingnetworksharefileusingPInvoke. Section102.1:Codetoaccessnetworksharedfile publicclassNetworkConnection:IDisposable { string_networkName; publicNetworkConnection(stringnetworkName, NetworkCredentialcredentials) { _networkName=networkName; varnetResource=newNetResource() { Scope=ResourceScope.GlobalNetwork, ResourceType=ResourceType.Disk, DisplayType=ResourceDisplaytype.Share,RemoteNa me=networkName }; varuserName=string.IsNullOrEmpty(credentials.Domain) ?credentials.UserName :string.Format(@”{0}\{1}”,credentials.Domain,credentials.UserName); varresult=WNetAddConnection2( netResource, credentials.Password, userName, 0); if(result!=0) { thrownewWin32Exception(result); } } ~NetworkConnection() { Dispose(false); } publicvoidDispose() { Dispose(true); GC.SuppressFinalize(this); } protectedvirtualvoidDispose(booldisposing) { WNetCancelConnection2(_networkName,0,true); } [DllImport(“mpr.dll”)] privatestaticexternintWNetAddConnection2(NetResourcenetResource, stringpassword,stringusername,intflags); [DllImport(“mpr.dll”)] privatestaticexternintWNetCancelConnection2(stringname,intflags, boolforce); } [StructLayout(LayoutKind.Sequential)] publicclassNetResource { publicResourceScopeScope;publicResource TypeResourceType; publicResourceDisplaytypeDisplayType; […]

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 […]