Sie sind auf Seite 1von 145

Source : http://www.visualbuilder.com/csharp/tutorial/ Introduction to C sharp C# (pronounced "C sharp") is a simple, modern, object oriented, and t!

pe sa"e pro#rammin# lan#ua#e. It will immediatel! be "amiliar to C and C$$ pro#rammers. C# combines the hi#h productivit! o" %apid &pplication 'evelopment (%&') lan#ua#es. (he "ollowin# are the advanta#es C# provides : Interactive 'evelopment )nvironment. *isual desi#ners "or buildin# +indows and +eb applications. Compiler. 'ebu##er. Features of C# language: Simple (!pe sa"e *ersionin#: ma,in# new version o" an application "rom e-istin# .ne to wor, . /ollows all ..0s paradi#m &utomatic #arba#e collection /le-ible Application Types in C#

C#

1. Class Library:- Creates a project "or creatin# classes that can be used in
other applications. inter"ace.

2. Console Application:- Creates a *isual C# application with a command line 3. Asp.Net Web Application:- Creates a *isual C# application with a +eb user
inter"ace.

4. Asp.Net Web Service:- Creates an 123 +eb service with *isual C# that
other applications can access.

5. Asp.Net Mobile Web Application:- Creates an application viewable on


0'&s, cell phones, and other mobile devices. Starting C# usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.+indows./orms4

namespace cS6&%0)1&203)S 7 static class 0ro#ram 7 /// 8summar!9 /// (he main entr! point "or the application. /// 8/summar!9 : S(&(hread ; static void 2ain () 7 &pplication .)nable*isualSt!les()4 &pplication .SetCompatible(e-t%enderin#'e"ault( "alse )4 &pplication .%un( new /orm< ())4 = = =

A C# program is divided into 4 parts:

1. Namespace eclaration:- (his speci"ies the namespaces that we are #oin# 2. 3.


to use in the application. ).#. >sin# S!stem4 Class eclaration:- 6ere we mentioned the startin# class "orthis project or we can sa! that this is the entr! point "or ourapplication. Main met!o :- (he main method is the entr! point o" this application and here we can speci"! the "orm that we need to open "irst "rom this application &pplication .%un( new /orm< ())4 // (his line indicates that the control is passed to the instance o" /orm<() in the application once we start with the application. Comments:- (he comments are #iven b! // and /? ?/ bloc, in the C# pro#rams.

4.

Compilation: (his project can be compiled throu#h command prompt usin# the "ollowin# command. (he command will create a "ile called @0ro#ram.e-eA, which we can e-ecute. Csc.e"e #rogram.cs $ypes in C#:C# supports two ,inds o" t!pes: value t!pes and re"erence t!pes. *alue t!pes include simple t!pes (e.#., char, int, and "loat), enum t!pes, and struct t!pes. %e"erence t!pes include class t!pes, inter"ace t!pes, dele#ate t!pes, and arra! t!pes.

Value Types

Reference Types

&llocated on stac,

&llocated on heap

& value t!pe variable contains the data itsel"

%e"erence t!pe variable contains the address o" memor! location where data is actuall! stored

+hen we cop! a value t!pe variable to another one, the actual data is copied and each variable can be independentl! manipulated.

+hen cop!in# a re"erence t!pe variable to another variable, onl! the memor! address is copied. Both variables will still point to the same memor! location, which means, i" we chan#e one variable, the value will be chan#ed "or the other variable too.

Inte#er, "loat, Boolean, double etc are value t!pes.

Strin# and object are re"erence t!pes.

Struct is value t!pe.

Classes and inter"aces are re"erence t!pes.

Control Statement: Selection Statement in C sharp Control statements are used to process some conditional code which onl! runs i" the condition is true otherwise some alternate code ma! be processed. (he "ollowin# are two control statements used in C#.

1. if-else statement 2. s%itc! statement


IF- !S Statement:

I" Statement allows !ou to ta,e di""erent path dependin# on the decision condition. (he condition must return boolean. +hen the condition evaluates to a "oolean true, a bloc, "or that true condition will be e-ecuted.

Synta#:

If (condition) { // Single if statement //execute block if condition, returns true.}

I" (condition) 7 // e-ecute bloc, i" condition, return "alse = else 7 // e-ecute bloc, i" condition, return "alse =

I" (condition<) 7 // e-ecute bloc, i" condition< is true = else i" (conditionC) 7 // e-ecute bloc, i" conditionC is true = else i" (condition D) 7 // e-ecute bloc, i" conditionD is true = else 7 // otherwise i" none condition satis"ied then, this bloc, will e-ecute. = S$itc% Statement: &nother selection statement is the switch statement, which e-ecutes a set o" lo#ic dependin# on the value o" a #iven parameter that is evaluated b! switch statement. (he t!pe o" values a switch statement operates on can be Boolean, )nums, Inte#ral (!pe and Strin#s.

Synta#: Switch (E aluated !alue can be "oolean or Enums or integral t#$e or strings) { //switch with integer t#$e %ase &' // "lock of statement "reak( %ase )' // "lock of statement "reak( %ase *' // "lock of statement

"reak( %ase +' // "lock of statement "reak( ,efault' // "lock of statement "reak( }

Note:- -he switch block follows the switch ex$ression, where one or more choices are e aluated for a $ossible match with the switch ex$ression. Each choice is labeled with the case ke#word, followed b# an exam$le that is of the same t#$e as the switch ex$ression and followed b# a colon ('). .hen the result e aluated in the switch ex$ression matches one of these choices, the statement immediatel# following the matching choice is executed. -he block ends with either break, continue, goto, return or throw statement. &"ample: 'emonstrate Selection Statement

usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4

usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 namespace cS6&%0)1&203)S 7 public partial class /ormC : /orm 7 public /ormC() 7 InitialiEeComponent()4 = private void /ormCF3oad( object sender, )vent&r#s e) 7 Console.+rite3ine( "/.%2 C" )4 = private void button<FClic,( object sender, )vent&r#s e) 7 // 6ere we can #o throu#h the e-ample on I/ int Fvalue G IntDC .0arse(t-t)nter.(e-t)4

i" (Fvalue 9 <HH) 7 2essa#eBo- .Show( "*alue is #reater than <HH" )4 t-t)nter.(e-t G "" 4 = else i" (Fvalue 8 <HH II Fvalue 9 CHH)7 2essa#eBo- .Show( "*alue is #reater than <HH but less than CHH" )4 t-t)nter.(e-t G "" 4 = else 7 2essa#eBo- .Show( "*alue is less than <HH" )4 t-t)nter.(e-t G "" 4 = = private void buttonCFClic,( object sender, )vent&r#s e) 7 // 6ere we can #o throu#h the e-ample on Switch int Fvalue G IntDC .0arse(t-t)nter.(e-t)4 switch (Fvalue) // switch e-ample with inte#er t!pe 7 case <:

case J: case K: //6ere the case < and J has no brea,, this will "alls to this statement 2essa#eBo- .Show( "*alue is < or J or K" )4 t-t)nter.(e-t G "" 4 brea, 4 case C: 2essa#eBo- .Show( "*alue is C" )4 t-t)nter.(e-t G "" 4 brea, 4 case D: 2essa#eBo- .Show( "*alue is D" )4 t-t)nter.(e-t G "" 4 brea, 4 de"ault : 2essa#eBo- .Show( "*alue is #reater than D" )4 brea, 4 = = = =

(utput:

Clic) on: *F &"ample +utton

(his print value is less than <HH Clic) on: s%itc! &"ample +utton

(his print value is #reater than D

!&&'S(( LLLLLLLLL 2ethods 2ethods help !ou to separate code into modules that per"orm a #iven tas,. )ver! pro#ram or application have a startin# entr! point to there application that decide the path e-ecution and all. +e alread! come across di""erent application where the startin# point or entr! point is main ( ) method. 2ethods provide the "le-ibilit! where we can separate the code into modules. (his will ma,e eas! understandin# o"

code, more reusabilit! and increase per"ormance. (he method can pass parameters to another method and return the value that is optional. I" the method contains @voidA ,e!word, this means method will not return an! thin#. Synta": access s$ecifier return/t#$e methodname ($arameter list) { //Statement } )et%od C%aining:- (he method chainin# is the process b! which one method calls another method. (he caller method can pass parameters to the called method and in return the called method return some value (this is optional). #ample -he following exam$le will demonstrate the method conce$ts along with the method chaining. usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.+indows./orms4 namespace cS6&%0)1&203)S 7 static class 0ro#ram 7 /// 8summar!9 /// (he main entr! point "or the application. /// 8/summar!9 : S(&(hread ; static void 2ain () 7

&pplication.)nable*isualSt!les()4 &pplication.SetCompatible(e-t%enderin#'e"ault( "alse )4 &pplication.%un( new /orm< ())4 = = =

Met!o C!aining: 6ere we can add two values to the "orm and >ser can select the options i.e. < &dd, C Subtract, D 2ultipl! and J 'ivide. &nd result will be displa!ed when the user clic, )-ecute. usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4

usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 namespace cS6&%0)1&203)S 7 public partial class /ormJ : /orm 7 public /ormJ() 7 InitialiEeComponent()4 = private void /ormJF3oad( object sender, )vent&r#s e) 7 lbl)nter.(e-t G "" 4 lbl)nter.(e-t G lbl)nter.(e-t $ ")nter < to &dd" $ "Mn" 4 lbl)nter.(e-t G lbl)nter.(e-t $ ")nter C to Sub" $ "Mn" 4 lbl)nter.(e-t G lbl)nter.(e-t $ ")nter D to 2ultipl!" $ "Mn" 4

lbl)nter.(e-t G lbl)nter.(e-t $ ")nter J to 'ivide" $ "Mn" 4 = private void btn)-ecuteFClic,( object sender, )vent&r#s e) 7 int Fval'ec G IntDC .0arse(t-tdecision.(e-t)4 int F"irst*al G IntDC .0arse(te-tBo-<.(e-t)4 int Fsecond*al G IntDC .0arse(te-tBo-C.(e-t)4 switch (Fval'ec) 7 case <: "-add(F"irst*al, Fsecond*al)4 brea, 4 case C: "-subtract(F"irst*al, Fsecond*al)4 brea, 4 case D: "-multipl!(F"irst*al, Fsecond*al)4 brea, 4 case J: "-divide(F"irst*al, Fsecond*al)4 brea, 4 de"ault : 2essa#eBo- .Show( "0lease )nter Speci"ied *alue.." )4 brea, 4 = =

void "-add( int "irstar#, int secondar#) 7 int Fadd G "irstar# $ secondar#4 t-t%esult.(e-t G Fadd.(oStrin#()4 = void "-subtract( int "irstar#, int secondar#) 7 int Fsub G ("irstar# secondar#)4

t-t%esult.(e-t G Fsub.(oStrin#()4 = void "-multipl!( int "irstar#, int secondar#)7 int Fmul G "irstar# ? secondar#4 t-t%esult.(e-t G Fmul.(oStrin#()4 = void "-divide( int "irstar#, int secondar#)7 int Fdiv G "irstar# / secondar#4 t-t%esult.(e-t G Fdiv.(oStrin#()4 = = =

(utput

Namespaces Namespaces are C# pro#ram elements that are used "or lo#ical #roupin# o" the classes. (he! also provide assistance in avoidin# name clashes between two sets o" codes. Namespaces doesnOt corresponds to "ile or director! names. (he usin# directives e.#. ,sing System-his contains number of classes, b# including this names$ace we can access those classes that are there in the S#stem names$ace. &"ample:- 'emonstrate Namespace

usin# S!stem4

usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 using Test * rootnamespace+firstlevelnamespace, namespace cS6&%0)1&203)S 7 public partial class /ormK : /orm 7 public /ormK() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 rootnamespace."irstlevelnamespace. (est'emo ."-(est()4 rootnamespace."irstlevelnamespace. (est'emo<< ."-'ispla!()4

Test+ Test-emo.. +f#-isplay/0, = private void buttonCFClic,( object sender, )vent&r#s e) 7 secondnamespace."irstlevelnamespace. (est'emo< ."-(est<()4 secondnamespace."irstlevelnamespace. (est'emo< ."-(est()4 = = =

namespace rootnamespace 7 // nested namespace namespace "irstlevelnamespace 7 class (est'emo 7 public static void "-(est()

7 2essa#eBo- .Show( "/ire >0 rootnamespace " )4 = = class (est'emo<< 7 public static void "-'ispla!() 7 2essa#eBo- .Show( "'ispla! under rootnamespace " )4 = = = =

namespace secondnamespace 7 // nested namespace namespace "irstlevelnamespace 7

class (est'emo< 7 public static void "-(est<() 7 2essa#eBo- .Show( "/ire >0 secondnamespace" )4 = public static void "-(est() 7 2essa#eBo- .Show( "/ire >0 secondnamespace."irstlevelnamespace."-(est" )4 = = = = &"ample &"planation: In above e-ample we have D namespaces i.e. cS0123E41536ES, rootnames$ace, secondnames$ace.%ootnamespace contains irstlevelnamespace namespace,C classes i.e (est'emo, (est'emo<< and these classes contains methods i.e. "-(est(),"-'ispla!(). Secondnamespace contains nested namespace i.e. "irstlevelnamespace, < class i.e. (est'emo< and the class contains methods i.e "-(est<(),"-(est(). Introduction to Classes Classes are the core o" ..0Os. Classes are declared b! usin# the ,e!word classes. Classes contain data members that represent the class. +e can create object o" the

class, objects are entities and we can create as man! number o" objects o" a #iven class. Synta": %lass classname { //!ariable declaration // 5ethod declaration } Classes can contain t%e follo$ing entities inside its declaration: Constructors 'estructors /ields 2ethods 0roperties Inde-ers 'ele#ates )vents Nested Classes. Constructors:- Constructors are called or initialiEed automaticall! whenever an object o" the class is created. (he purpose o" the constructors is to initialiEe the class members whenever an object o" the class is created. Constructor name is same as o" class name. Constructor doesnOt return an! value, nor even void Constructor initialiEe the class members at the time o" its creation (here are di""erent t!pes o" constructor: 'e"ault Constructor 0arameteriEed Constructor Cop! Constructor 'estructor:- 'estructor is used to deallocate an! memor! that is allocated to the object at the time o" its creation. 'estructor is used "or memor! mana#ement and avoids an! memor! lea,s that occur in the case o" re"erence variables that store on heap memor!. 'estructor ,eeps trac,s o" all the unwanted and unused memor! and "rees it when we are not usin# it. In .net the memor! mana#ement is automaticall! done throu#h 5C i.e. #arba#e collection, this is responsible "or deallocation o" memor!. (he re"erence variable memor! allocated on heap and here the job o" 5C comes into picture, it will deallocate the memor! that is not in used.

(he value t!pe variables allocated memor! on stac,, here the variable doesnOt rePuire an! 5C, the! just "all "rom the stac, i" there are not in used. #ample: -emonstrate Constructor1 -estructor and used of Static met%od .

Test-emo+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace cS6&%0)1&203)S 7 public class (est'emo 7 Strin# str4 static Strin# strC G "de"ault" 4 public (est'emo() 7 //Constructor str G "6i" 4 = public (est'emo( Strin# strde"ault) 7 //0arameteriEed Constructor str G strde"ault4 = public Strin# displa!()7 return str4 =

public static Strin# static"-() 7 return strC $ " (his comes "rom Static "-" 4 = Q(est'emo() 7 // Clean >p Code 6ere. = = = Form2+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 namespace cS6&%0)1&203)S 7 public partial class /ormR : /orm 7 public /ormR() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 //Callin# 'e"ault Constructor (est'emo obj G new (est'emo ()4 2essa#eBo- .Show( "de"ault Constructor :: " $obj.displa!())4 = private void buttonCFClic,( object sender, )vent&r#s e) 7 //Callin# 0arameteriEed Constructor (est'emo obj< G new (est'emo ( "*i,rant" )4 2essa#eBo- .Show( "0arameteriEed Constructor :: " $obj<.displa!())4 =

private void buttonDFClic,( object sender, )vent&r#s e) 7 //Callin# Static method o" the class 2essa#eBo- .Show( "Static method :: " $ (est'emo .static"-())4 = = = (utput: Clic3 on: -efault Constructor 4utton

Clic3 on: 'arameteri5ed Constructor 4utton

Clic3 on: Static met%od 4utton

Inheritance Inheritance is one o" the primar! concepts o" object oriented pro#rammin#. Inheritance is the process b! which we can inherits the properties or methods o" one class into the other class. (he concept behind inheritance, ta,e the base class that contains methods and properties and inherits it into the derived class, that now contains all the members and properties o" the base class as well as its own newl! added members or properties. (he "ollowin# are the advanta#es o" Inheritance:

%euse the e-istence code Save time, we need not do the code veri"ication and testin#. 6ere, we can add and modi"! the methods o" the e-istin# class. 6elp in modulariEation o" code. $ypes of *n!eritance: (he "ollowin# are the t!pes o" inheritance e-ist in C# pro#rammin#. Single *n!eritance: 6ere we have sin#le base class that is inherited b! the derived class. 6ere the derived class has all the "eatures o" the base class and can add new "eatures or modi"! e-istin# "eatures. (he inheritance also depends on the access speci"ier that is used at the time o" base class inheritance. Multi-level *n!eritance: In the multi level inheritance, here we havin# a chain o" inheritance i.e. the base class & is inherited b! derived class B, and it is "urther inherited b! another derived class C. So, the "eature we have in base class &, is also there in 'erived class B, and all the combination "eatures o" class & and class B are there in derived class C. Multiple *n!eritance: In C#, we donOt have multiple inheritance where one class can inherit two base classes. So, the multiple inheritance can be done b! usin# the concept o" inter"aces. 6ere one class can inherit one class and can implements more than one inter"ace. .ybri *n!eritance: (he h!brid inheritance can also be done throu#h with the help o" inter"ace. 6ere the derived class cans implements more than two inter"aces and onl! one class. &"ample: 'emonstrate *n!eritance

-erivedClass6+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace cS6&%0)1&203)S

7 public class parentClassS 7 Strin# str G "0arent:::" 4 public parentClassS() 7 str G "0arent Constructor" 4 = public Strin# displa!() 7 return str4 = public Strin# Show() 7 return "Base Show" 4 = = public class 'erivedClassS : parentClassS 7 Strin# testStr G "'erived::" 4 public 'erivedClassS() 7 testStr G "'erived Constructor" 4 = public Strin# displa!<() 7 return testStr4 = public Strin# Show<() 7 return base.Show()4 = = = Form6+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4

usin# S!stem.+indows./orms4

namespace cS6&%0)1&203)S 7 public partial class /ormS : /orm 7 public /ormS() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 'erivedClassS obj G new 'erivedClassS ()4 2essa#eBo-.Show( "Call to 0arent 2ethod :: " $ obj.displa!())4 2essa#eBo-.Show( "Call to 'erived 2ethod :: " $ obj.displa!<())4 = private void buttonCFClic,( object sender, )vent&r#s e) 7 'erivedClassS obj G new 'erivedClassS ()4 2essa#eBo-.Show( "Call in 'erived method that "urther call Base method GGG9" $ obj.Show<())4 = = = (ut#ut: W!en ,ser Clic)s (n :Simple *n!eritance +utton

W!en ,ser Clic)s (n :Calling +ase Met!o

in 'erive

Met!o

+utton

0ol!morphism 0ol!morphism is the core concept o" ..0Os. 0ol!morphism means one name man! "orms. Types of polymorp%ism <. Compile (ime 0ol!morphism C. %un (ime 0ol!morphism Compile Time 'olymorp%ism (he compile time pol!morphism, here the pol!morphism is implemented durin# compile time, that means at the time o" compilation the compiler ,nows where to bind the method. (he compile time pol!morphism can be implemented throu#h:

2ethod .verloadin# .perator .verloadin# Met!o (verloa ing:

In comple- applications written in C#, we ma! need man! methods which do essentiall! similar "unctions but are just di""erent enou#h to be considered uniPue. So, we can de"ine method overloadin# as i" two or three method in a class has same name but the! di""er b! number o" ar#uments or t!pe o" ar#ument. (perator (verloa ing' (his provides a meanin#"ul understandin# o" the operation b! usin# operator overloadin#. 6ere what we did is we overload an operator and chan#e its meanin#, so that a valuable in"ormation is send to the pro#rammer and this help in reducin# the comple-it!. ).#. I" we need to add two matri- o" D1D

2atri- result G 2atri-.&dd(mat<, matC)4 // this doesnOt #ive an! relevant in"ormation /un $ime #olymorp!ism (he run time pol!morphism, here the compiler doesnOt ,now which method to call at runtime. 6ere we can call the derived method throu#h base class pointer at runtime. (he run time pol!morphism can be implemented throu#h: *irtual T .verride Ue!word. 0itual function: (he virtual "unction is used to implement runtime pol!morphism4 here we have same name method in the base class as well as in the derived class. +e can access the derived method usin# the base pointer. (he virtual ,e!word should be write in "ront o" the base class method and in the derived class we have to write override in "ront o" the method. /or )-ample: %lass "ase%lass { !irtual oid dis$la# () {//statements} } %lass ,eri ed%lass { 7 erride oid dis$la# () {//statements} }

&"ample: 'emonstrate #olymorp!ism

+aseClass1.cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace cS6&%0)1&203)S 7 class BaseClassV 7 Strin# str G "Base" 4 public BaseClassV() 7 = public Strin# displa!() 7 return str $ ": BaseClass 'ispla!" 4 = public virtual Strin# show() 7 return str $ ": BaseClass Show" 4 = = = 'erive Class1.cs usin# S!stem4

usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace cS6&%0)1&203)S 7 class 'erivedClassV : BaseClassV 7 Strin# str G "'erived" 4 public 'erivedClassV() 7 = public new Strin# displa!() 7 //N)+ U)W+.%' is >S) (. 6I') (6) //S&2) 2)(6.' IN (6 B&S) C3&SS return str $ ": 'ispla! 'erived" 4 = public override Strin# show() 7 //.*)%%I') U)W+.%' IS >S)' I/ //(6) 2)(6.' IN (6) B&S) C3&SS IS *I%(>&3 return str $ ": S6.+ 'erived:" 4 = = = Form1.cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 namespace cS6&%0)1&203)S 7 public partial class /ormV : /orm 7 public /ormV() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 //*irtual: 0ol!morphism at %un(ime BaseClassV objBase G new 'erivedClassV ()4

labelK.(e-t G objBase.displa!()4 labelR.(e-t G objBase.show()4 = private void buttonCFClic,( object sender, )vent&r#s e) 7 BaseClassV objBase G new BaseClassV ()4 label<.(e-t G objBase.displa!()4 labelC.(e-t G objBase.show()4 = private void buttonDFClic,( object sender, )vent&r#s e) 7 'erivedClassV obj'er G new 'erivedClassV ()4 labelD.(e-t G obj'er.displa!()4 labelJ.(e-t G obj'er.show()4 = = =

(utput

0roperties 0roperties are used to protect the "ield in a class b! readin# and writin# it throu#h the propert!. 6ere the "ield consists o" one #etter and one setter that are associated with a #iven "ield. +e can access this "ield throu#h this #etter/setter combination. T$o $ays to declare property in t%e class

1. .ne wa! to declare:


class 3ro$ert#,emo { $ri ate String name( //,eclare a field $ublic String get8ame() { //9etter return name( } $ublic oid set8ame( String !alue) {//Setter name : alue( } } 2. Anot!er %ay to eclare:

class 3ro$ert#,emo { $ri ate String name( //,eclare a field

$ublic String 8ame{ get{ return name(} //9etter set{ name : alue(} // Setter } } Read-&nly property: +e can declare a propert! as read onl!4 b! onl! have its #etter. So that the user canOt set the value o" the "ield, because there is no setter "or the "ield. 6ence we restrict the user to chan#e the value o" the "ield at an! #iven time. 7rite-&nly property: +e can declare a propert! as write onl!, b! onl! have its setter. 6ere the user canOt access the value that is there in the "ield. +e can manipulate the value o" the "ield b! usin# its setter, but we canOt #et the value o" this "ield. )-ample: 'emonstarte proper!, %ead .nl! 0ropert!, +rite .nl! 0ropert!+

Cls#roperty3.cs usin# S!stem4 usin#usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace cS6&%0)1&203)S 7 class Cls0ropert!X

7 private int a#e4 private Strin# name4 private Strin# lastName G "'o#ra" 4 private Strin# address4 public int #et&#e() 7 return a#e4 = public void set&#e( int *alue) 7 a#e G *alue4 = public Strin# #etName() 7 return name4 = public void setName( Strin# *alue) 7 name G *alue4 = //%ead .nl! propert!:.nl! 5etter public Strin# #et3astName() 7 return lastName4 = //+rite .nl! 0ropert!: .nl! Setter public void set&ddress( Strin# *alue) 7 address G *alue4 = public Strin# displa!&ddress() 7 return address4 = = = Form3.cs

usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 namespace cS6&%0)1&203)S 7 public partial class /ormX : /orm 7 Cls0ropert!X obj G new Cls0ropert!X ()4 public /ormX() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 //Setters Calls obj.set&#e( Int<R .0arse(te-tBo-<.(e-t))4 obj.setName(te-tBo-C.(e-t)4 obj.set&ddress( " Chandi#arh " )4 //+rite .nl! 0ropert! = private void buttonCFClic,( object sender, )vent&r#s e) 7 //5etters Calls 2essa#eBo- .Show( "Name: " $ obj.#etName())4 2essa#eBo- .Show( "&#e: " $ obj.#et&#e())4 2essa#eBo- .Show( "3ast Name: " $ obj.#et3astName())4//%ead //.nl! propert! 2essa#eBo- .Show( "&ddress: " $ obj.displa!&ddress())4 = = = (utput:

Clic) (n: Set t!e 0alue (his will set the values in the class "ields i.e. name, address Clic) (n: 4et t!e 0alue (his will displa! the values that are set b! the setters.

/irst value that we #et is the name.

Second is the a#e value.

(his "ield onl! has #etter associated to it.

(his "ield onl! has setter associated with it, we can Inde-ers

I" properties are Ovirtual "ieldsO, inde-ers are more li,e 8virtual arrays8 . (he! allow a class to emulate an arra!, where the elements o" this arra! are actuall! d!namicall! #enerated b! "unction calls. (he! allow a class to be used just li,e an arra!. .n the inside o" a class, !ou mana#e a collection o" values an! wa! !ou want. (hese objects could be a "inite set o" class members, another arra!, or some comple- data structure. (he "ollowin# are the advanta#es o" the Inde-ers. %e#ardless o" the internal implementation o" the class, its data can be obtained consistentl! throu#h the use o" inde-ers. Inde-ers arenOt di""erentiated b! name, and a class cannot declare two inde-ers with the same si#nature. 6owever, this does not entail that a class is limited to just one inde-er. 'i""erent inde-ers can have di""erent t!pes and numbers o" inde-in# elements (these bein# ePuivalent to method parameters, e-cept that each inde-er must have at least one inde-in# element, and the Ore"O and OoutO modi"iers cannot be used).

#ample: -emonstrate Inde#ers

ClsInde#ers.9+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace cS6&%0)1&203)S 7 class ClsInde-ers<H 7 private Strin# :; arrStrin#4 private int arrSiEe4 public ClsInde-ers<H( int siEeo"&rra!) 7 //Constructor

arrSiEe G siEeo"&rra!4 arrStrin# G new Strin# :arrSiEe;4 "or ( int iGH4i8arrSiEe4i$$)7 arrStrin#:i; G "No *alue" 4 = = public strin# this : int inde-*alue; 7 #et 7 return arrStrin#:inde-*alue;4 = set 7 arrStrin#:inde-*alue; G value 4 = = public strin# :; this : strin# data; 7 #et 7 "or ( int i G H4 i 8 arrSiEe4 i$$) 7 i" (arrStrin#:i; GG data) 7 arrStrin#:i; G "6i" 4 = = return arrStrin#4 = set 7 "or ( int i G H4 i 8 arrSiEe4 i$$) 7 i" (arrStrin#:i; GG data) 7 arrStrin#:i; G "6i" 4 = =

= = = = Form.9+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 namespace cS6&%0)1&203)S 7 public partial class /orm<H : /orm 7 static int arrSiEe G <H4 ClsInde-ers<H obj G new ClsInde-ers<H (arrSiEe)4 public /orm<H() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 //Inde-ers Implementation : >sin# Inte#er label<.(e-t G "" 4 obj:C; G "666I" 4 obj:K; G "*i,rant" 4 obj:X; G "&mit" 4 "or ( int i G H4 i 8 arrSiEe4 i$$) 7 label<.(e-t G label<.(e-t $ "Inde-er at " $ i $ obj:i; $ "Mn" 4 = = private void buttonCFClic,( object sender, )vent&r#s e) 7 //Inde-ers Implementation : >sin# Strin# label<.(e-t G "" 4 Strin# :; arrStrin# G obj: "No *alue" ;4

"or ( int i G H4 i 8 arrStrin#.3en#th4 i$$) 7 label<.(e-t G label<.(e-t $ "Inde-er at " $ i $ obj:i; $ "Mn" 4 = = = = (utput: Clic) (n: *n e"er *mplementation

Clic) (n: *n e"er 5 Wit! String

Structs Structs is value t!pe user de"ined data t!pe same as int, "loat, bool etc. Structs "eatures: structs are value t!pe In structs memor! allocation can be done on stac,. No #arba#e collector rePuired to remove structs variable because as the! are value t!pe, the memor! allocated is on stac, and so no memor! allocated on heap, when structs variable are not in used the! just "all "rom the stac,. Structs canOt have destructors. Structs canOt inherit another class or structs. (his means there is no concept o" inheritance in structs. Structs ma! inherit multiple inter"aces. Inter"ace is a re"erence t!pe and an! class or structs that implements inter"ace must override all the methods that are there in the inter"ace.

&"ample: 'emonstrate Structs

ClsStruct66.cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace cS6&%0)1&203)S 7 inter"ace I(est 7 strin# (est()4 = struct %ectan#le : I(est 7 public int len#th4 public int breath4 public int hei#ht4 public %ectan#le( int len#th, int breath, int hei#ht) 7 this .len#th G len#th4 this .breath G breath4 this .hei#ht G hei#ht4 = public %ectan#le &dd( %ectan#le rect) 7 %ectan#le new%ect4 new%ect.len#th G len#th $ rect.len#th4

new%ect.breath G breath $ rect.breath4 new%ect.hei#ht G hei#ht $ rect.hei#ht4 return new%ect4 = public strin# (est() 7 return "Implements Inter"ace in structs" 4 = = class ClsStruct<< 7 public Strin# displa!() 7 %ectan#le rect< G new %ectan#le (<H, CH, DH)4 %ectan#le rectC G new %ectan#le (<<H, <CH, <DH)4 %ectan#le rectD4 rectD G rect<.&dd(rectC)4 return "3en#th :: " $ rectD.len#th $ "Mn Breadth :: " $ rectD.breath $ "Mn 6ei#ht :: " $ rectD.hei#ht4 = public strin# print() 7 %ectan#le rect< G new %ectan#le (<H, CH, DH)4 return rect<.(est()4 = = =

Form66.cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4

usin# S!stem.+indows./orms4 namespace cS6&%0)1&203)S 7 public partial class /orm<< : /orm 7 public /orm<<() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 // Structs Implementation label<.(e-t G "" 4 ClsStruct<< obj G new ClsStruct<< ()4 label<.(e-t G obj.displa!()4 = private void buttonCFClic,( object sender, )vent&r#s e) 7 // Structs Implementin# Inter"ace labelC.(e-t G "" 4 ClsStruct<< obj G new ClsStruct<< ()4 labelC.(e-t G obj.print()4 = = =

(utput: Clic)ing (n +ot! t!e +uttons: $!e concept be!in e"ecute an isplaye . t!e structs %ill be

Inter"aces &n interface loo,s li,e a class, but has no implementation. &ninterface is a C# re"erence t!pe with members that do not have implementations. Inter"aces onl! have method si#natures. (he "ollowin# are the properties o" the inter"aces: It contains de"initions o" e ents , indexers , methods and/or$ro$erties . (he reason interfaces onl! provide de"initions is because the! are inherited b! classes and structs , which must provide an implementation "or each inter"ace member de"ined. Inter"aces are li,e protocol or standard that needs to be maintained b! the classes or structs that are implementin# that inter"ace. +e can have "inal variables and abstract methods in inter"ace. (his means the classes or structs that are implementin# inter"aces need to provide the bod! "or all the methods that are there in inter"aces. No need to provide the access speci"ier "or method that is there in inter"ace, all the methods are public.

+e have the concept o" inheritance in inter"ace. .ne inter"ace can e-tends another inter"ace. Synta": Interface Interface8ame { // method signature } Class implementing t!e *nterfaces. %lass cls-est' I-estInterface { // method defined here

} Structs Implementing Interface+ struct str-est' IstructsInterface { // method defined here } *nterfaces may in!erit ot!er interfaces. #ample: -emonstrate Interfaces

ClsInterface.:+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace cS6&%0)1&203)S 7 inter"ace I0arentInterace 7 Strin# displa!()4 = inter"ace IChildInter"ace : I0arentInterace 7 Strin# Show()4 =

class ClsInter"ace<C : IChildInter"ace 7 Strin# str G "6i" 4 public ClsInter"ace<C( Strin# pStr) 7 str G pStr4 = public Strin# (est() 7 return str4 = public Strin# displa!() 7 return str $ " : 'ispla! ." Base Inter"ace" 4 = public Strin# Show() 7 return str $ " : Show ." Child Inter"ace" 4 = = = Form.:+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 namespace cS6&%0)1&203)S 7 public partial class /orm<C : /orm 7 public /orm<C() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e)

7 ClsInter"ace<C obj G new ClsInter"ace<C ( "6ello" )4 label<.(e-t G obj.(est()4 labelC.(e-t G obj.displa!()4 labelD.(e-t G obj.Show()4 = private void /orm<CF3oad( object sender, )vent&r#s e) 7 label<.(e-t G "" 4 labelC.(e-t G "" 4 labelD.(e-t G "" 4 = = = (utput: Clic) (n: *nterface &"ecute +utton

'ele#ates & dele#ate in C# lan#ua#e allows us to re"erence a method. (he other wa! to sa! this dele#ate is a "unction pointer. (he "unction pointer is same as we have pointer to an address now in this case we have pointer to a method address. (here are two t!pes o" dele#ates : Single-Cast 'elegate:- 6ere the dele#ate will re"er to or point to sin#le method or we can Sa! that the pointer is to sin#le method "rom the dele#ate. Multi-Cast 'elegate:-In the multi cast dele#ate, the dele#ate re"er to or point to more than .ne method at runtime. ,elegates features'

'ele#ate is a "unction pointer. 'ele#ate declaration is same as method declaration, e-cept the! have dele#ate modi"ier in "ront o" it. (he method that a dele#ate re"ers or pointin# to must have same si#nature as o" dele#ate method. (o use a dele#ate, we have to create the instance o" the dele#ate and pass the method that it is pointin# too or re"errin# to. Invo,e (), (his method can be used to invo,e the dele#ate. (he dele#ates can be declared b! addin# a dele#ate ,e!word in "ront o" an! method. /or )-ample delegate oid 5#delegate()(

Note'/ -his is declaration of the delegate and it s$ecifies the method signature that it is $ointing or referring. -his means the signature of the method that a delegate $ointing has no $arameter and will not return an# thing. "ut this is an exam$le and we can sa# the delegate can refer to an# t#$e of method. &"ample: 'emonstrate 'elegates

Cls'elegate67.cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace cS6&%0)1&203)S 7 class Cls'ele#ate<D 7 dele#ate void 2!dele#ate ()4 static Strin# str G "" 4 static Strin# sd G "" 4 public Strin# sin#lecast"-()

7 sd G "" 4 sd G "Sin#le Cast 'ele#ate GG9 " 4 2!dele#ate d G null 4 d $G new 2!dele#ate (sin#lecastdele#ate"-)4 d.Invo,e()4 sd G sd $ " :: appender" 4 return sd4 = public Strin# multicast"-() 7 str G "" 4 str G "startin# *alue GG9 " 4 2!dele#ate d G null 4 d $G new 2!dele#ate ("irst"-)4 d $G new 2!dele#ate (second"-)4 d()4 str G str $ " :: appender" 4 return str4 = public void "irst"-() 7 str G str $ " :: "irst"-" 4 = public void second"-() 7 str G str $ " :: second"-" 4 = public void sin#lecastdele#ate"-() 7 sd G sd $ " ::sin#lecastdele#ate"-" 4 = = = Form67.cs usin# S!stem4 usin# S!stem.Collections.5eneric4

usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 namespace cS6&%0)1&203)S 7 public partial class /orm<D : /orm 7 public /orm<D() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 //2ulti cast dele#ate Cls'ele#ate<D obj'ele#ate G new Cls'ele#ate<D ()4 2essa#eBo- .Show(obj'ele#ate.multicast"-())4 = private void buttonCFClic,( object sender, )vent&r#s e) 7 //Sin#le cast dele#ate Cls'ele#ate<D obj'ele#ate G new Cls'ele#ate<D ()4 2essa#eBo- .Show(obj'ele#ate.sin#lecast"-())4 = = = (utput: Clic)ing (n: Single-cast 'elegate +utton

Clic)ing (n: Mutil-cast 'elegate +utton

)-ception 6andlin# #ception )-ceptions are un"oreseen errors that happen in !our pro#rams. 0ro#rammers alwa!s detect and most o" the time writes correct code to avoid all the errors or e-ceptions that can distract the e-ecution o" the code and cause unwanted results. 6owever, there are times when !ou donOt ,now i" an error will occur. /or e-ample, !ou canOt predict when !ouOll receive a "ile I/. error, run out o" s!stem memor!, or encounter a database error. (hese thin#s are #enerall! unli,el!, but the! could still happen and !ou want to be able to deal with them when the! do occur. (his is where e-ception handlin# comes in. +hen e-ceptions occur, the! are said to be "thrown". +hat is actuall! thrown is an object that is derived "rom the @S !stem. )-ceptionA class Try;catc% and Finally 4loc3: (his is a wa! we can handle e-ceptions in C#. (r! Bloc,: In this bloc,, we include all the suspected code. (his means the code that is most li,el! to cause e-ception. Catc! +loc):- In this bloc, we include all handlers that will be ta,e care o" e-ception that occurs. +e can have number o" catch bloc,s associated to sin#le tr! bloc,. Finally 4loc3 : (he "inall! bloc, contains the cleanup code that we needed whether the code is succeed or not. 2ost o" the time we write a code that will deal locate the memor! that we associated in the be#innin# li,e memor! allocated to connection object.

#ample:

#ception <andling

Form.4+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 usin# S!stem.I.4 namespace cS6&%0)1&203)S 7 public partial class /orm<J : /orm 7 public /orm<J() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 //Simple (r!/Catch Bloc, int divideb!Yero G H4 int a G CH4 int b G H4 tr! 7 divideb!Yero G (a / b)4 =catch ( 'ivideB!Yero)-ception e-) 7

2essa#eBo- .Show( "Cnd )1C)0(I.N :: " $ e-.(oStrin#())4 =catch ( )-ception e-) 7 2essa#eBo- .Show( ")1C)0(I.N :: " $e-.(oStrin#())4 = = private void buttonCFClic,( object sender, )vent&r#s e) 7 //(r!,Catch and /inall! Bloc, /ileStream outputStream G null 4 /ileStream inputStream G null 4 tr! 7 outputStream G /ile..pen+rite( "'estination/ile.t-t" )4 inputStream G /ile..pen%ead( "Bo#usInput/ile.t-t" )4 =catch ( )-ception e-) 7 2essa#eBo- .Show(e-.(oStrin#())4 ="inall! 7 i" (outputStream ZG null ) 7 outputStream.Close()4 2essa#eBo- .Show( ".utputStream Closed." )4 = i" (inputStream ZG null ) 7 inputStream.Close()4 2essa#eBo- .Show( "InputStream Closed." )4 = = = = =

(utput: Clic) (n: Simple $ry8catc! +loc) +utton

Clic, .n: (r!/catch and /inall! Bloc, Button

&ttributes &ttributes are elements that allow !ou to add declarative in"ormation to !our pro#rams. (his declarative in"ormation is used "or various purposes durin# runtime and can be used at desi#n time b! application development tools. &ttributes are also used e-tensivel! in securin# .N)( assemblies, "orcin# callin# code to be evaluated a#ainst pre de"ined securit! constraints. &ttribute declared usin# the [:[and [;O brac,ets be"ore an! t!pe declaration. T%e follo$ing are t%e advantages t%e attri"utes provide: 'eclarative in"ormation to !our pro#ram

(his in"ormation can be used at runtime or at compile time b! pro#rammers. 'llImport&ttribute: (his attribute provide in"ormation to communicate with the +inDC libraries. .bsolete&ttribute: (his provides compile time in"ormation to the developer that this method is now deprecated. &ttribute add what is called metadata to !our pro#ram.

&ttributes are classes that can be written in C# and used to decorate !our code with declarative in"ormation. 2an! attributes have parameter lists that allow inclusion o" additional in"ormation that customiEes a pro#ram even "urther. &"amples of Attributes:9 (bsolete : $ublic String first,e$recated;4(){} 9 (bsoleteAttribute : $ublic String second,e$recated;4(){} (bsolete ; <'on=t ,se $!is Met!o .< >: $ublic String third,e$recated;4() 9 S$A$!rea : static oid 5ain () {} Note:- -his attribute declare that this is the entr# $oint for the a$$lication. -his indicates that %< $rogram should communicate with unmanaged %75 code using the single threading a$artment. -he $arameter $ro ide additional information about the attribute #ample To -emonstrate Attri"utes -he following is the screen a$$eared when run the form &= $rogram in the source.

ClsAttri"ute.=+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace cS6&%0)1&203)S 7 class Cls&ttribute<K 7 : .bsolete ; public Strin# "irst'eprecated/1()

7 return "Call "irst'eprecated/1" 4 = : .bsolete&ttribute ; public Strin# second'eprecated/1() 7 return "Call second'eprecated/1" 4 = : .bsolete ( "'onOt >se (his 2ethod." ); public Strin# third'eprecated/1() 7 return "Call third'eprecated/1" 4 = = = Form.=+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 namespace cS6&%0)1&203)S 7 public partial class /orm<K : /orm 7 public /orm<K() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 //&ttribute : use to create method deprecated Cls&ttribute<K obj G new Cls&ttribute<K ()4 obj."irst'eprecated/1()4 //'eprecated 2ethods

obj.second'eprecated/1()4 2essa#eBo- .Show(obj.third'eprecated/1())4 = = = (utput: Clic)ing (n: Attribute fire up +utton

)nums &n enumeration is a special ,ind o" value t!pe limited to a restricted and unchan#eable set o" numerical values. )nums are stron#l! t!ped constants. (he! are essentiall! uniPue t!pes that allow !ou to assi#n s!mbolic names to inte#ral values. A vantages of &nums: In the C# tradition, the! are stron#l! t!ped, meanin# that an enum o" one t!pe ma! not be implicitl! assi#ned to an enum o" another t!pe even thou#h the underl!in# value o" their members are the same. B! de"ault, these numerical values are inte#ers, but the! can also be lon#s, B!tes, etc. +hen !ou de"ine an enumeration !ou provide literals which are then used as Constants "or their correspondin# values. *alues speci"ied in enumeration are static. (hese values are "inal and !ou canOt chan#e the value at runtime. (he S!stem.)num BC3 t!pe is the base class o" enum t!pes and contains methods that allow !ou to wor, with enums in di""erent wa!s, such as wor,in# with a list o" names or values, convertin# "rom value to name, and convertin# "rom name to value. Synta" enum enumname { // alues} Exam$le'/ enum ,a#7f.eek { 5onda#:), -uesda#, .ednesda#, -hursda#:&>, ;rida#, Saturda#,

Sunda# } Note: (he "irst literal, is unassi#ned then it value is set to H. /or an! other literal, i" the value is unassi#ned then the value set is #reater than the value o" the precedin# literal. B! this the value o" 2onda! is set to H and the value o" Sunda! is R. +e can also speci"! the value to the literal in the enums. Note:- 0ere the alue will be 5onda#/), -uesda#/*, .ednesda#/+ and -hursda#/ &>, ;rida#/&&, Saturda#/&), Sunda#/&*.

&"ample: 'emonstrate &nums

Cls&num6?.cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace cS6&%0)1&203)S 7 enum 'a!."+ee, 7 2onda!, (uesda!, +ednesda!, (hursda!, /rida!, Saturda!, Sunda! =

enum *alues)num : b!te 7 .ne G <, two, threeGK, "our, "ive = class Cls)num<R 7 public Strin# 5etvalue)nteredB!>ser( int entered*alue) 7 //user entered value *alues)num values)num G ( *alues)num )entered*alue4 Strin# str G "" 4 switch (values)num) 7 case *alues)num ..ne: str G "/I%S(" 4 brea, 4 case *alues)num .two: str G "S)C.N'" 4 brea, 4 case *alues)num .three: str G "(6I%'" 4 brea, 4 case *alues)num ."our: str G "/.>%(6" 4 brea, 4 case *alues)num ."ive: str G "/I/(6" 4 brea, 4 de"ault : str G "de"ault" 4 brea, 4 = return str4 = public Strin# Create&nd>se)num(!pe()7 'a!."+ee, da!o"+ee, G 'a!."+ee, .(hursda!4 //'a!."+ee, da!o"+ee, G ('a!."+ee,)J4 Strin# str'a! G "" 4 switch (da!o"+ee,) 7 case 'a!."+ee, .2onda!: str'a! G "2onda!" 4

brea, 4 case 'a!."+ee, .(uesda!: str'a! G "(uesda!" 4 brea, 4 case 'a!."+ee, .+ednesda!: str'a! G "+ednesda!" 4 brea, 4 case 'a!."+ee, .(hursda!: str'a! G "(hursda!" 4 brea, 4 case 'a!."+ee, ./rida!: str'a! G "/rida!" 4 brea, 4 case 'a!."+ee, .Saturda!: str'a! G "Saturda!" 4 brea, 4 case 'a!."+ee, .Sunda!: str'a! G "Sunda!" 4 brea, 4 = return str'a!4 = = = Form6?.cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 namespace cS6&%0)1&203)S 7 public partial class /orm<R : /orm 7 public /orm<R() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 //Create and use )nums

Cls)num<R obj G new Cls)num<R ()4 2essa#eBo- .Show(obj.Create&nd>se)num(!pe())4 = private void buttonCFClic,( object sender, )vent&r#s e) 7 //)nter )num *alue /rom >ser int Fuser)nter*alue G IntDC .0arse(te-tBo-<.(e-t)4 Cls)num<R obj G new Cls)num<R ()4 2essa#eBo-.Show(obj.5etvalue)nteredB!>ser(Fuser)nter*alue)4 = = = (utput Clic) (n: &nter &num value from user +utton

Clic) (n: Create an

,se &nums $ype

ncapsulation )ncapsulation is the process o" wrappin# up o" data and members in a class. )ncapsulation provides the wa! to hide data "rom the e-ternal usa#e. (his is important in the scenario when we donOt want our precious data to be used or manipulated b! e-ternal user. )ncapsulation is an object oriented principle o" hidin# the internal state and behavior o" an object, ma,in# !our code more maintainable. A vantages of &ncapsulation 'ata hidin# throu#h the access speci"ier private. %educe couplin# between objects. Increases the maintainabilit! o" code. +rappin# up o" data variables and members inside the class. $!e follo%ing table %ill give t!e available in C#. Access )odifier escription of t!e Access mo ifiers

-escription /$%o can access0

0rivate

0rivate members can be accessed within the class where the! are declared. +e canOt access private members outside the class, not even with the object o" the class. (his basicall! provides the concept o" -ata-<iding+

0rotected

0rotected members scope can be outside the class but onl! limited to the immediate derived class that is inheritin# the base class where the protected members resides. (he protected can be used b! the members o" same class or the members o" derived class.

Internal

6ere the internal members are accessible within the same assembl!. I" !ou donOt speci"! an! modi"ier, b! de"ault it is o" internal t!pe.

0rotected Internal

6ere either accessed in the same assembl! or the derived assembl! also. (his is basicall! a combination o" protected and internal access modi"iers.

0ublic

0ublic members can be accessed an!where. No restriction associated with this access modi"ier.

Seale

Class

(he sealed ,e!word provides the restriction that no other class in the conte-t can inherit this class. B! this, we can ma,e our class not to be inherited b! other class. I" the class tries to inherit the class that is declared as sealed, the compile time error occurs. 6: Class eclare as seale sealed class %lsSealed&? {// 1n# members } Abstract Class (he class declared with abstract ,e!word, this means the class is onl! provide the essential elements and not includin# the bac,#round details. &bstraction is the process o" includin# the essential elements and hidin# the details. In la!man terms, we can sa! that a computer is the abstract "orm, because we are not aware o" the internal technicalit!. I" the class is declared as abstract, we have to #ive the bod! to all the methods that are declared as abstract. 6: Class eclare as abstract abstract class cls1bstract,emo{ // -his can contains abstract or concrete methods. } 2: Abstract Members $ublic abstract string dis$la#name()( Note:- -he abstract methods can onl# include the signature of the method.

&"ample: 'emonstrate &ncapsulation

Cls&ncapsulation6@.cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace cS6&%0)1&203)S 7 class Customer 7 public void Customer%ecord() 7 &ddNew%ecord()4 >pdate)-istin#%ecord()4 'elete%ecord()4 = protected virtual strin# &ddNew%ecord() 7 return "Base: &ddNew%ecord" 4 = //&'' N)+ %)C.%' protected virtual strin# >pdate)-istin#%ecord() 7 return "Base: >pdate)-istin#%ecord" 4 = //>0'&() )1IS(IN5 %)C.%' protected virtual strin# 'elete%ecord() 7 return "Base: 'elete%ecord" 4 = //')3)() )1IS(IN5 %)C.%'

= class Cls)ncapsulation<S : Customer 7 private strin# name G "" 4 //CanOt &ccess .utside the Class private strin# address G "" 4 //CanOt &ccess .utside the Class private strin# priF'ispla!() //CanOt &ccess .utside the Class 7 return "(his method canOt be access outside the class" 4 = public strin# CustomerName 7 //0ublic 0ropert! #et 7 return name4 = set 7 name G value 4 = = public strin# Customer&ddress //0ublic propert! 7 #et 7 return address4 = set 7 address G value 4 = = public strin# Combine'ispla!() //0ublic 2ethod 7 return CustomerName $ " :::" $ Customer&ddress4 = protected override strin# &ddNew%ecord() //0rotected 2ethod 7 return "protected method :: &ddNew%ecord" 4 = protected override strin# >pdate)-istin#%ecord() //0rotected 2ethod 7 return "protected method :: >pdate)-istin#%ecord" 4 = protected override strin# 'elete%ecord() //0rotected 2ethod 7 base .'elete%ecord()4 return "protected method :: 'elete%ecord" 4 = public strin# combineStrin#() 7

strin# cmbStr G "" 4 cmbStr G cmbStr $ &ddNew%ecord() $ "Mn" 4 cmbStr G cmbStr $ >pdate)-istin#%ecord() $ "Mn" 4 cmbStr G cmbStr $ 'elete%ecord()4 return cmbStr4 = = = ClsSeale 6@.cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace cS6&%0)1&203)S 7 sealed class ClsSealed<S 7 private strin# name G "" 4 public strin# CustomerName 7 #et 7 return name4 = set 7 name G value 4 = = public strin# displa!Name() 7 return name4 = = //CanOt inherited a Sealed Class class derivedClass //: ClsSealed<S 7 = = ClsAbstract6@.cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace cS6&%0)1&203)S

7 abstract class cls&bstract'emo 7 private int Fnumber G <H4 public strin# Fname G "" 4 public abstract strin# displa!name()4 // &bstract method public int calc(otal() //Concreate 2ethod 7 return (Fnumber ? <H)4 = = class Cls&bstract<S : cls&bstract'emo 7 public override strin# displa!name() 7 //&bstract 2ethod return "&bstract 2ethod 0rovide Bod! in 'erived Class" 4 = = = (utput Clic) (n: #rivate Members +utton Clic) (n: #ublic Members +utton

Clic) (n: #rotecte

Members +utton

Clic) (n: Seale

Clic) (n: Abstract

'arameter 'assing in C s%arp & methodOs parameters are the t!pes that #et passed to it when the method is called. (he list o" parameters be#ins b! speci"!in# Eero or more O"i-ed parametersO, and it ma! "inish b! speci"!in# a sin#le parameter arra!. (his latter element declared usin# the OparamsO ,e!word means that it is possible to pass an arbitrar! number o" t!pes to a sin#le method. Synta#: 9Mo ifier: parameter-type parameter-i entifier :2odi"ier;: (his is optional and can be either Ore"O or OoutO. 0arameter t!pe: (his declares the t!pe o" the parameter. 0arameter identi"ier: (he name o" the parameter. (here are D t!pe o" parameter that are passed to the method 0assin# b! *alue 0assin# b! %e"erence [.utputO 0arameter. #assing +y 0alue: (he parameter modi"iers Ore"O and OoutO relate to how the parameter is passed into the method. +here neither o" these modi"iers is used, the parameter is passed in Ob! valueO. B! de"ault we are passin# variable b! value. 6ere the new cop! o" the variable is send to the called method. So chan#es done to the variables are not re"lected on the actual parameter. Synta": $ass!alue"#!alue-#$e(@initial!alue)( //%all a method $ri ate oid $ass!alue"#!alue-#$e( int i!) { i! : )>( } 'assing 4y Reference: In C# we can pass variables into methods Ob! re"erenceO. +here a variable is passed b! re"erence, the Ore"O modi"ier must be used both in the method head and the

method invocation (illustrated b! the ne-t code bloc,). (he chan#es made to the "ormal ar#ument will re"lect on the actual ar#ument. Synta": $ass!alue"#2eference-#$e( ref @initial!alue)( //%alling 5ethod $ri ate oid $ass!alue"#2eference-#$e( ref int i!) { i! : )>( } A(utput= parameter: +here a method parameter is de"ined (and invo,ed) usin# the OoutO modi"ier, it is passed b! re"erence. (he di""erence between the OoutO and the Ore"O modi"ier is this: a parameter modi"ied b! the OoutO ,e!word need not be assi#ned a value be"ore bein# passed into the method, but must be assi#ned a value in the method. Synta": $ass!alue"#7ut3arameter( out @initial!alue, out @b!alue)(//%alling >'arams8 )odifier .ne can pass an arbitrar! number o" t!pes to a method b! declarin# a parameter arra! with the OparamsO modi"ier. Synta": $ublic int get-he-otalAsing3aram( $arams int BC int1rr) &"ample: 'emonstrate #arameter #assing in C#

Form61.cs: usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4

usin# S!stem.+indows./orms4 namespace cS6&%0)1&203)S 7 public partial class /orm<V : /orm 7 public /orm<V() 7 InitialiEeComponent()4 = private void btn*alueFClic,( object sender, )vent&r#s e) 7 //*alue int Finitial*alue G Int<R .0arse(te-tBo-<.(e-t)4 2essa#eBo- .Show( "Be"ore Callin# " $ Finitial*alue.(oStrin#())4 pass*alueB!*alue(!pe(Finitial*alue)4 te-tBo-<.(e-t G Finitial*alue.(oStrin#()4 2essa#eBo- .Show( "&"ter Callin# " $ Finitial*alue.(oStrin#())4 = private void btn%e"erenceFClic,( object sender, )vent&r#s e) 7 //%e"erence int Finitial*alue G Int<R .0arse(te-tBo-C.(e-t)4 2essa#eBo- .Show( "Be"ore Callin# " $ Finitial*alue.(oStrin#())4 pass*alueB!%e"erence(!pe( re" Finitial*alue)4 te-tBo-C.(e-t G Finitial*alue.(oStrin#()4 2essa#eBo- .Show( "&"ter Callin# " $ Finitial*alue.(oStrin#())4 = private void btn.utFClic,( object sende 7 //.ut bool Fb*alue4 int Finitial*alue G Int<R .0arse(te-tBo-D.(e-t)4 2essa#eBo- .Show( "Be"ore 0assin# " $ Finitial*alue.(oStrin#())4 pass*alueB!.ut0arameter( out Finitial*alue, out Fb*alue)4 r, )vent&r#s e)

te-tBo-D.(e-t G Finitial*alue.(oStrin#()4 2essa#eBo- .Show( "&"ter #ettin# the value " $ Finitial*alue.(oStrin#())4 = private void pass*alueB!%e"erence(!pe( re" int i*) 7 i* G CH4 = private void pass*alueB!*alue(!pe( int i*) 7 i* G CH4 = private void pass*alueB!.ut0arameter( out int i*, out bool b*alue) 7 b*alue G "alse 4 i* G C4 i" (i* 9 JH) b*alue G true 4 else b*alue G "alse 4 i* G i* ? CH4 = = = (ut#ut:

Clic)ing (n:- #assing #arameter +y 0alue

Clic)ing (n:- #assing #arameter +y /eference

Clic)ing (n:- #assing #arameter +y (ut

)et%od &verloading )ach method has a si#nature. (he si#nature comprises the methodOs name and its parameters (e-ceptin# their names), but not the methodOs return t!pe. 2ethod .verloadin# is one o" the "orms o" pol!morphism. (his is compile time pol!morphism because at compile time the compiler able to distin#uish between the methods that is declared with same name but di""erent number o" ar#uments. Con itions %!ic! s!oul be fulfille for Met!o overloa ing:

2ethod Name should be same "or all the methods that are participatin# in method .verloadin#. (he number o" ar#uments or t!pe o" ar#uments should be di""erent. No class allowed two methods to have same si#nature. Note:- 6ike methods constructors can also be o erloaded.

&"ample: 'emonstrate Met!o

(verloa ing

Cls(verLoa ing63.cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace cS6&%0)1&203)S 7 class Cls.ver3oadin#<X 7 int a4 int b4 //Constructor .ver3oadin# public Cls.ver3oadin#<X() 7 a G <H4 b G CH4 = public Cls.ver3oadin#<X( int a, int b) 7 this .a G a4 this .b G b4= public Cls.ver3oadin#<X( Cls.ver3oadin#<X obj) 7 this .a G obj.a4 this .b G obj.b4 =

public int result() 7 return a $ b4 = //2ethod .ver3oadin# public strin# displa!() 7 return "sin#le method with no parameter" 4 = public strin# displa!( strin# str&) 7 return str&4 = public strin# displa!( strin# str&, strin# strB) 7 return str& $ ":: "$ strB 4 = public strin# displa!( strin# str&, int int&) 7 return str& $ " :: " $ int&.(oStrin#() 4= = = Form63.cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 namespace cS6&%0)1&203)S 7 public partial class /orm<X : /orm 7 public /orm<X() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 // Call Sin#le 0arameter 2ethod Cls.ver3oadin#<X obj G new Cls.ver3oadin#<X ()4 2essa#eBo- .Show(obj.displa!())4 = private void buttonCFClic,( object sender, )vent&r#s e) 7 //Call 0arameteriEed 2ethod Cls.ver3oadin#<X obj G new Cls.ver3oadin#<X ()4 2essa#eBo- .Show(obj.displa!( "vi,rant" ))4 2essa#eBo- .Show(obj.displa!( "*i,rant" , "'o#ra" ))4 2essa#eBo- .Show(obj.displa!( "6i I am " ,CS))4 =

private void buttonDFClic,( object sender, )vent&r#s e) 7 //Constructor overloadin# Cls.ver3oadin#<X obj G new Cls.ver3 Cls.ver3oadin#<X objC G obj<4 2essa#eBo- .Show( "'e"ault Constructor result " $obj.result())4 2essa#eBo- .Show( "0arameteriEed Constructor result " $obj<.result())4 2essa#eBo- .Show( "Cop! Constructor result " $ objC.result())4 = = = (utput: Clic) (n: Calling Single #arameter Met!o oadin#<X ()4 Cls.ver3oadin#<X obj< G new Cls.ver3oadin#<X (DH,JH)4

Clic) (n: Call #arameteriBe

Met!o

Clic) (n: Constructor (verloa ing

-ata"ase Interaction ?sing C s%arp C# is a lan#ua#e. (he classes de"ined in the class libraries are used to communicate with the database and we are usin# C# lan#ua#e to interact with the database. In 1do.8et components we have number o" classes that are responsible to communicate with the database. *ntro ucing A'(.N&$ &do.Net is an .bject oriented set o" libraries that allows !ou to interact with data sources. /ollowin# are the data providers in ado.net.

1. System.'ata.SClClient: contains classes that communicate with 2s 2. 3. 4.


S\3Server. System.'ata.(racleClient:- communicate with .racle. System.'ata.(le b:- communicate to a data source that has an .3)'B provider. System.'ata.( bc:- communicate to a data source that has an .'BC provider

A'(.N&$ (+D&C$S &do.net includes man! objects !ou can use to wor, with data. Some o" the primar! objects are as "ollows:

1. SDl%onnection'/ (o interact with a database, !ou must have a connection to

2. 3.

4.

5.

it. (he connection objects helps identi"!in# the database server, database name, user name and password. (he connection object is used b! command objects. SDl%ommand'/ Wou can use this object to send S\3 statements to the database. (his can represent a S\3 Statement or stored procedure. SDl,ata2eader'/ (he data reader object allows !ou to obtain the results o" a Select statement "rom a command object. (he data returned "rom a data reader is a "ast "orward onl! stream o" data. (his "etch data in a sePuential manner. ,ataSet'/ Wou can ima#ine dataset as a database. (his contain multiple datatable objects, which "urther contains columns and rows objects. +e can also de"ine relationship amon# tables in the dataset. (his is disconnected approach. SDl,ata1da$ter'/ (he SPl'ata&dapter is used to "ill dataset object when readin# the data and writes in a sin#le batch when persistin# chan#es bac, to the database. & data adapter contains a re"erence to the connection object and opens and closes the connection automaticall! when readin# "rom or writin# to the data base. (he data adapter contains J command objects i.e. S)3)C(, >0'&(), ')3)(), and INS)%(

&"ample: 'emonstrate 'atabase *nteraction -his exam$le will $ro ide the interaction with the database. -he user will enter his credentials, if the user is alid and the credentials matched with the database, he is able to iew all the other usersE credentials that are alid.

Form:9+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 usin# S!stem.'ata.SPlClient4 namespace cS6&%0)1&203)S 7 public partial class /ormCH : /orm 7 public /ormCH() 7 InitialiEeComponent()4 = private void btn3o#inFClic,( object sender, )vent&r#s e)

7 //3o#in tr! 7 SPlConnection con G null 4 strin# conStr G "" 4 int F)-ist/la# G H4 conStr G "'ata SourceGlocalhost4initial catalo#G(est'B4uidGsa4pwdGsa"4 con G new SPlConnection (conStr)4 F)-ist/la# G "n>ser)-ists(con,t-tName.(e-t,t-t0assword.(e-t)4 i" (F)-ist/la# GG H) 7 //Not & *alid >ser 2essa#eBo- .Show( "Not & *alid >ser" )4 = else 7 // I" *alid user (han 'ispla! all the *alid >ser that are there in the 'ataBase 2essa#eBo- .Show( "*alid >ser :: 'ispla! &ll the *alid >ser" )4 "ill#rid+ith*alid>ser(con)4 = = catch ( )-ception e-) 7 2essa#eBo- .Show( ")-ception .ccurs.........." $e-.2essa#e)4 = "inall! 7 t-tName.(e-t G "" 4 t-t0assword.(e-t G "" 4 = = /? ? /unction: +hether a *alid >ser or Not ? 'ependin# on the creadentials enter b! user ?/ private int "n>ser)-ists( SPlConnection con, strin# str>serName, strin# str0assword) 7

SPlCommand cmd G null 4 int F)-ist/la# G H4 cmd G new SPlCommand ( "select count(?) "rom tbl3o#in where >serNameG]>serName and passwordG]0assword " , con)4 cmd.0arameters.&dd( "]>serName" ,SPl'b(!pe.N*arChar).*alue G str>serName4 cmd.0arameters.&dd( "]0assword" ,SPl'b(!pe.N*arChar).*alue G str0assword4 cmd.Command(!pe G Command(!pe .(e-t4 con..pen()4 F)-ist/la# G Int<R .0arse(cmd.)-ecuteScalar().(oStrin#())4 con.Close()4 return F)-ist/la#4 =

/*
? i" the Credentials )nter B! user is *alid: ? (hen 'ispla! 3ist ." all (he .ther *alid >sers. ?/ private void "ill#rid+ith*alid>ser( SPlConnection con) 7 SPl'ata&dapter ada G null 4 'ataSet dst G null 4 ada G new SPl'ata&dapter ( "select ? "rom tbl3o#in" , con)4 dst G new 'ataSet ()4 ada./ill(dst, "3o#in" )4 data5rid*iew<.'ataSource G dst.(ables:H;.'e"ault*iew4 = = = (utput: (n Clic): Login +utton

&perator &verloading in C s%arp @. (here are varieties o" operators available "or use in C#. (he C# lan#ua#e de"ines the behavior o" these operators when used in an e-pression with the C# built in data t!pes. C# #ives user the "le-ibilit! to chan#e the de"ault behaviour o" the operators that means, user can de"ine the behavior o" man! o" the standard operators with his own structures and classes. Suppose, "or e-ample, that !ouOre writin# a class that mana#es a set o" records read "rom a database. I" another piece o" code has two objects o" !our class, it ma! want to write an e-pression that joins the records to#ether into a third object. (his sounds li,e an addition operation, and it seems natural "or other pieces o" code to write code li,e the "ollowin#: 2ecords 2ecords&( 2ecords 2ecords)( 2ecords 2ecords*( 2ecords* : 2ecords& F 2ecords)( Wour %ecords class would include a method that speci"ies "how objects o" the class will behave when used in an e-pression with the addition operator. (hese methods

are called user/defined o$erator im$lementations , and the object oriented terminolo#! "or de"inin# operator behavior in a class is called o$erator o erloading . Note: 1ll o$erator o erloading methods must be declared with both the static and $ublic ke#words. &verloading ?nary 'lus ;?nary )inus: I" !ou need to overload the unar! plus operator, the "ollowin# characteristics must be enjo!ed b! the method that is used to overload the unar! plus. & return t!pe o" !our choice (he ,e!word operator (he operator bein# overloaded & parameter list speci"!in# a sin#le parameter o" the t!pe o" class or structure containin# the overloaded operator method &verloading 'refi# Increment and -ecrement &perator: I" !ou need to overload the pre"i- increment or pre"i- decrement operators in !our class or structure, de"ine a method with the "ollowin# characteristics: & return t!pe speci"!in# the t!pe o" class or operator method (he ,e!word operator (he operator bein# overloaded & parameter list speci"!in# a sin#le parameter containin# the overloaded operator method &"ample: 'emonstrate (verloa ing of ,nary #lusE ,nary MinusE #refi" *ncrementE #refi" 'ecrement. &verloading ?nary 'lus usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace FCSharp&pplication 7 class Cls.ver3oad>nar!0lus 7 public int 14 public int W4 public static Cls.ver3oad>nar!0lus operator $(Cls.ver3oad>nar!0lus %*alue) 7 Cls.ver3oad>nar!0lus New.bj G newCls.ver3oad>nar!0lus ()4 i" (%*alue.1 8 H) New.bj.1 G (%*alue.1)4 else New.bj.1 G %*alue.14

i" (%*alue.W 8 H) New.bj.W G (%*alue.W)4 else New.bj.W G %*alue.W4 return New.bj4 = = = &verloading ?nary )inus usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace FCSharp&pplication 7 class Cls.ver3oadin#>nar!2inus 7 public int 14 public int W4 public static Cls.ver3oadin#>nar!2inus operator T (Cls.ver3oadin#>nar!2inus %*alue) 7 Cls.ver3oadin#>nar!2inus objNew G newCls.ver3oadin#>nar!2inus ()4 i" (%*alue.1 9 H) objNew.1 G (%*alue.1)4 else objNew.1 G %*alue.14 i" (%*alue.W 9 H) objNew.W G (%*alue.W)4 else objNew.W G %*alue.W4 return objNew4 = = = &verloading 'refi# Increment usin# S!stem4 usin# S!stem.Collections.5eneric4

usin# S!stem.(e-t4 namespace FCSharp&pplication 7 class Cls.verloadin#Increment 7 public int 14 public int W4 public static Cls.verloadin#Increment operator $$(Cls.verloadin#Increment %*alue) 7 Cls.verloadin#Increment objIncrement G new Cls.verloadin#Increment ()4 objIncrement.1 G %*alue.1 $ <4 objIncrement.W G %*alue.W $ <4 return objIncrement4 = = = &verloading 'refi# -ecrement usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace FCSharp&pplication 7 class Cls.ver3oadin#'ecrement 7 public int 14 public int W4 public static Cls.ver3oadin#'ecrement operator T ( Cls.ver3oadin#'ecrement %*alue) 7 Cls.ver3oadin#'ecrement obj'ecrement G new Cls.ver3oadin#'ecrement ()4 obj'ecrement.1 G %*alue.1 obj'ecrement.W G %*alue.W return obj'ecrement4 = = = Form:+cs <4 <4

usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 namespace FCSharp&pplication 7 public partial class /ormC : /orm 7 public /ormC() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 //.verloadin# >nar! 0lus Cls.ver3oad>nar!0lus obj>nar!0lus G new Cls.ver3oad>nar!0lus ()4 obj>nar!0lus.1 G <HH4 obj>nar!0lus.W G CHH4 2essa#eBo-.Show((obj>nar!0lus.1).(oStrin#())4 2essa#eBo-.Show((obj>nar!0lus.W).(oStrin#())4 obj>nar!0lus G $obj>nar!0lus4 2essa#eBo-.Show((obj>nar!0lus.1).(oStrin#())4 2essa#eBo-.Show((obj>nar!0lus.W).(oStrin#())4 = private void buttonCFClic,( object sender, )vent&r#s e) 7 //.verloadin# >nar! 2inus ()4 Cls.ver3oadin#>nar!2inus obj>nar!2inus G new Cls.ver3oadin#>nar!2inus obj>nar!2inus.1 G <H4 obj>nar!2inus.W G CH4 2essa#eBo-.Show((obj>nar!2inus.1).(oStrin#())4 2essa#eBo-.Show((obj>nar!2inus.W).(oStrin#())4 obj>nar!2inus G obj>nar!2inus4 2essa#eBo-.Show((obj>nar!2inus.1).(oStrin#())4 2essa#eBo-.Show((obj>nar!2inus.W).(oStrin#())4

= private void buttonDFClic,( object sender, )vent&r#s e) 7 //.verladin# 0re"i- Increment Cls.verloadin#Increment objIncrement G new Cls.verloadin#Increment ()4 objIncrement.1 G <HH4 objIncrement.W G CHH4 2essa#eBo-.Show((objIncrement.1).(oStrin#())4 2essa#eBo-.Show((objIncrement.W).(oStrin#())4 objIncrement G $$objIncrement4 2essa#eBo-.Show((objIncrement.1).(oStrin#())4 2essa#eBo-.Show((objIncrement.W).(oStrin#())4 = private void buttonJFClic,( object sender, )vent&r#s e) 7 //.verloadin# 0re"i- 'ecrement Cls.ver3oadin#'ecrement obj'ecrement G new Cls.ver3oadin#'ecrement ()4 obj'ecrement.1 G <HH4 obj'ecrement.W G CHH4 2essa#eBo-.Show((obj'ecrement.1).(oStrin#())4 2essa#eBo-.Show((obj'ecrement.W).(oStrin#())4 obj'ecrement G obj'ecrement4 2essa#eBo-.Show((obj'ecrement.1).(oStrin#())4 2essa#eBo-.Show((obj'ecrement.W).(oStrin#())4 = = = &utput:

Clic) on (verloa ing ,nary #lus:

Clic) on (verloa ing ,nary Minus:

Clic) on #refi" *ncrement:

Clic) on #refi" 'ecrement:

&perator &verloading in C s%arp @: &verloading 4oolean &perator: I" !ou need to overload the true or "alse operators in !our class or structure, de"ine a method with the "ollowin# characteristics: & return t!pe o" bool (he ,e!word operator (he operator bein# overloaded & parameter list speci"!in# a sin#le parameter o" the t!pe o" class or structure containin# the overloaded operator method &verloading Conversion &perator: Wou can also write operator overload methods that convert one t!pe into another t!pe. I" !ou need to de"ine a new conversion operator in !our class or structure, de"ine a method with the "ollowin# characteristics: (he ,e!word implicit i" the conversion is to be treated as an implicit conversion, or the ,e!word e-plicit i" the conversion is to be treated as an e-plicit conversion (he ,e!word operator & t!pe speci"!in# the tar#et t!pe o" the conversion & parameter list speci"!in# the source t!pe o" the conversion &verloading 4inary &perators: (he operators that "all under this cate#or! are : &ddition, Subtraction, 'ivision, 2ultiplication, %emainder, &N', .%, )-clusive .%, Shi"t le"t, Shi"t %i#ht, )Pualit!, InePualit!, 5reater than, less than. I" !ou need to overload an! o" the binar!

operators in !our class or structure, de"ine a method with the "ollowin# characteristics: & return t!pe o" !our choice (he ,e!word operator (he operator bein# overloaded & parameter list speci"!in# two parameters, at least one o" which must be o" the t!pe o" class or structure containin# the overloaded operator method #ample: -emonstrate 4oolean &verloading1 Conversion &verloading and 4inary &perators &verloading Cls&verloading4oolean&pertors+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace FCSharp&pplication 7 class Cls.verloadin#Boolean.pertors 7 public int 14 public int W4 public static bool operator true ( Cls.verloadin#Boolean.pertors %*alue) 7 i" ((%*alue.1 GG H) II (%*alue.W GG H)) return true 4 return "alse 4 = public static bool operator "alse ( Cls.verloadin#Boolean.pertors %*alue) 7 i" ((%*alue.1 GG H) II (%*alue.W GG H)) return "alse 4 return true 4 = = = Cls&verloadingConversion+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4

namespace FCSharp&pplication 7 class Cls.verloadin#Conversion 7 public int 14 public int W4 public static implicit operator double ( Cls.verloadin#Conversion %*alue) 7 double totalF'istance4 double totalFSum4 totalFSum G (%*alue.1 ? %*alue.1) $ (%*alue.W ? %*alue.W)4 totalF'istance G S!stem. 2ath .SPrt(totalFSum)4 return totalF'istance4 = = = Cls&verloading AualityIneAuality+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 namespace FCSharp&pplication 7 class Cls.verloadin#)Pualit!InePualit! 7 public int 14 public int W4 public static bool operator GG( Cls.verloadin#)Pualit!InePualit! obj/irst, Cls.verloadin#)Pualit!InePualit! objSecond) 7 i" (obj/irst.1 ZG objSecond.1) return "alse 4 i" (obj/irst.W ZG objSecond.W) return "alse 4 return true 4 = public override bool )Puals( object o) 7

return true 4 = public override int 5et6ashCode() 7 return H4 = public static bool operator ZG( Cls.verloadin#)Pualit!InePualit! obj/irst, Cls.verloadin#)Pualit!InePualit! objSecond) 7 i" (obj/irst.1 ZG objSecond.1) return true 4 i" (obj/irst.W ZG objSecond.W) return true 4 return "alse 4 = = = FormB+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 namespace FCSharp&pplication 7 public partial class /ormD : /orm 7 public /ormD() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 //.verloadin# (rue and /alse operator Cls.verloadin#Boolean.pertors objBoolean G new Cls.verloadin#Boolean.pertors ()4 objBoolean.1 G CH4

objBoolean.W G DH4 i" (objBoolean) 2essa#eBo-.Show( "(he point is at the ori#in." )4 else 2essa#eBo-.Show( "(he point is not at the ori#in." )4 = private void buttonCFClic,( object sender, )vent&r#s e) 7 //.verloadable Conversion .perator double con'istance4 ()4 Cls.verloadin#Conversion objConversion G new Cls.verloadin#Conversion objConversion.1 G <HH4 objConversion.W G CHH4 con'istance G objConversion4 2essa#eBo-.Show(con'istance.(oStrin#())4 = private void buttonDFClic,( object sender, )vent&r#s e) 7 //.verloadin# )Pualit!/InePualit! .perator Cls.verloadin#)Pualit!InePualit! 2!/irst0oint G new Cls.verloadin#)Pualit!InePualit! ()4 Cls.verloadin#)Pualit!InePualit! 2!Second0oint G new Cls.verloadin#)Pualit!InePualit! ()4 Cls.verloadin#)Pualit!InePualit! 2!(hird0oint G new Cls.verloadin#)Pualit!InePualit! ()4 2!/irst0oint.1 G <HH4 2!/irst0oint.W G CHH4 2!Second0oint.1 G KHH4 2!Second0oint.W G SKH4 2!(hird0oint.1 G <HH4 2!(hird0oint.W G CHH4 i" (2!/irst0oint GG 2!Second0oint) 2essa#eBo-.Show( "2!/irst0oint and 2!Second0oint are at the same coordinates." )4 else 2essa#eBo-.Show( "2!/irst0oint and 2!Second0oint are not at the same coordinates." )4 i" (2!/irst0oint GG 2!(hird0oint) 2essa#eBo-.Show( "2!/irst0oint and 2!(hird0oint are at the same coordinates." )4

else 2essa#eBo-.Show( "2!/irst0oint and 2!(hird0oint are not at the same coordinates." )4 = = = &utput:

Clic)ing on (verloa ing $rue8False (perator

Clic)ing on (verloa ing Conversion (perator

Clic)ing on (verloa ing &Cuality8*neCuality (perator

Soc3ets In soc,et based networ, pro#rammin#, !ou do not directl! access the networ, inter"ace device to send and receive pac,ets. Instead, an intermediar! "ile descriptor is created to handle the pro#rammin# inter"ace to the networ,. (he special "ile descriptors used to re"erence networ, connections are called sockets . (he soc,et de"ines the "ollowin#:

& speci"ic communication domain, such as a networ, connection or a >niInterprocess Communication (I0C) pipe

& speci"ic communication t!pe, such as stream or data#ram & speci"ic protocol, such as (C0 or >'0 &"ter the soc,et is created, it must be bound to either a speci"ic networ, address or port on the s!stem, or to a remote networ, address and port. .nce the soc,et is bound, it can be used to send and receive data "rom the networ,. Cet$or3 Addresses &"ter the soc,et is created, it must be bound to a networ, address/port pair. >NI1 o""ers an I0 speci"ic address structure, soc,addrFin , which uses the "ollowin# elements. >sin# the soc,addrFin structure rePuires placin# the appropriate I0 address and port values in the proper data element.

1. 2. 3. 4.

sinDfamily &n address "amil!, de"ined as a short t!pe sinDport & port number, de"ined as a short t!pe sinDaddr &n address, de"ined as a lon# t!pe (J b!te) I0 address sinDdata V b!tes o" paddin#.

.N)( de"ines two classes in the S#stem.8et namespace to handle various t!pes o" I0 address in"ormation.(he classes are I0&ddress and I0)nd0oint I'Address object is used to represent a sin#le I0 address. (his value can be used in the various soc,et methods to represent the I0 address. I'Address )et%ods:-escription

)et%od

Compares two I0 addresses. )Puals %eturns a hash value "or an I0&ddress object.

5et6ashCode

%eturns the t!pe o" the I0 address instance. 5et(!pe Converts an I0 address "rom host b!te order to networ, b!te 6ost(oNetwor,.rder order. Indicates whether the I0 address is considered the loopbac, address.

Is3oopBac,

Converts an I0 address "rom networ, b!te order to host b!te Networ,(o6ost.rder order. Converts a strin# to an I0&ddress instance. 0arse

(oStrin#

Converts an I0&ddress to a strin# representation o" the dotted decimal "ormat o" the I0 address.

I' nd'oint: object is used when bindin# soc,ets to local addresses, or when connectin# soc,ets to remote addresses. (he "ollowin# two constructors are used to create I0)nd0oint instances: I0)nd0oint (lon# address , int $ort ) I0)nd0oint(I0&ddress address , int $ort ) ' nd'oint )et%ods: -escription

)et%od

Creates an )nd0oint object "rom a Soc,et&ddress object Create %eturns the t!pe o" the I0)nd0oint instance

5et(!pe

Compares two I0)nd0oint objects )Puals Creates a Soc,et&ddress instance o" the I0)nd0oint instance

SerialiEe

Creates a strin# representation o" the I0)nd0oint instance (oStrin# %eturns a hash value "or an I0)nd0oint object

5et6ashCode

&"ample: 'emonstrate Soc)et #rogramming Form4+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 usin# S!stem.Net4 namespace FCSharp&pplication

7 public partial class /ormJ : /orm 7 public /ormJ() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 //Introduction to I0 &ddresses. I0&ddress Faddress< G I0&ddress .0arse( "<XC.<RV.<.<" )4 I0&ddress FaddressC G I0&ddress .Broadcast4 I0&ddress FaddressD G I0&ddress .3oopbac,4 I0&ddress FaddressJ G I0&ddress .None4 I0&ddress FaddressK G I0&ddress .&n!4 I06ost)ntr! FhostName G 'ns .5et6ost)ntr!( 'ns .5et6ostName())4 I0&ddress Fm!2achine G FhostName.&ddress3ist:H;4 i" ( I0&ddress .Is3oopbac,(FaddressD)) lst&ddresses.Items.&dd( "3oopbac, address is: " $ FaddressD.(oStrin#())4 else lst&ddresses.Items.&dd( ")rror obtainin# the 3oopbac,&ddress" )4 lst&ddresses.Items.&dd( "3ocal I0 address is: " $ Fm!2achine.(oStrin#())4 i" (Fm!2achine GG FaddressD) lst&ddresses.Items.&dd( "3oopbac, &ddress Is Same &s3ocal &ddress.Mn" )4 else lst&ddresses.Items.&dd( "(he loopbac, address is not the local address.Mn" )4 lst&ddresses.Items.&dd( "5iven &ddress is: " $ Faddress<.(oStrin#())4 lst&ddresses.Items.&dd( "Broadcast address: " $ FaddressC.(oStrin#())4 lst&ddresses.Items.&dd( "&NW address is: " $ FaddressK.(oStrin#())4 lst&ddresses.Items.&dd( "N.N) address is: " $ FaddressJ.(oStrin#())4 = private void buttonCFClic,( object sender, )vent&r#s e) 7 //Introduction (o I0)nd0oint I0&ddress test< G I0&ddress .0arse( "<XC.<RV.<.<" )4 I0)nd0oint Fend0oint G new I0)nd0oint (test<, VHHH)4 lstI0)nd0oint.Items.&dd( "I0)nd0oint is ::" $Fend0oint.(oStrin#())4 lstI0)nd0oint.Items.&dd( "&ddress/amil! is ::" $Fend0oint.&ddress/amil!)4 lstI0)nd0oint.Items.&dd( "&ddress is :: " $ Fend0oint.&ddress)4

lstI0)nd0oint.Items.&dd( "0ort is :: " $ Fend0oint.0ort)4 lstI0)nd0oint.Items.&dd( "2in port number is :: " $ I0)nd0oint.2in0ort)4 lstI0)nd0oint.Items.&dd( "2a- port number is :: " $I0)nd0oint .2a-0ort)4 Fend0oint.0ort G VH4 lstI0)nd0oint.Items.&dd( "Chan#ed I0)nd0oint is :: " $Fend0oint.(oStrin#())4 Soc,et&ddress Fsoc,et&ddress G Fend0oint.SerialiEe()4 lstI0)nd0oint.Items.&dd( "Soc,et&ddress is :: " $ Fsoc,et&ddress.(oStrin#())4 = == (utput:

-CS E-omain Came SystemF (o simpli"! the unwield! state o" computer namin#, the 'omain Name S!stem ('NS) was created. It allows the master host database to be split up and distributed amon# multiple s!stems on the Internet. 'NS uses a hierarchical database approach, creatin# levels o" in"ormation that can be split and stored on various s!stems throu#hout the Internet. ,8S Structure (he structure o" a hierarchical database is similar to an or#aniEation chart with nodes connected in a treeli,e manner (thatOs the hierarchical part). (he top node is called the root . (he root node does not e-plicitl! show up in Internet host addresses, so it is o"ten re"erred to as the @namelessA node. 2ultiple cate#ories were created under the root level to divide the database into pieces called domains . )ach domain contains 'NS servers that are responsible "or maintainin# the database o" computer names "or that area o" the database (thatOs the distributed part).

(he "irst (or top) level o" distribution is divided into domains based on countr! codes. &dditional top level domains "or speci"ic or#aniEations were created to prevent the countr! domains "rom #ettin# overcrowded.

-omain >.S. militar! sites .mil

-escription

Commercial or#aniEations .com .edu .#ov .net .us .or# .ca .de :other countries; 5erman or#aniEations .r#aniEations "rom other countries Nonpro"it or#aniEations Canadian or#aniEations Internet Service 0roviders (IS0s) .ther >.S. or#aniEations (such as local #overnments) )ducational institutions >.S. #overnment or#aniEations

,sing 'NS (he last wa! to determine s!stem I0 in"ormation is to utiliEe the C# 'NS ('omain Name S!stem) classes. 'NS can be used to obtain Internet hostnames and I0 &ddresses. (he C# S!stem.Net namespace contains the 'NS class, which comprises several methods that allow !ou to obtain 'NS in"ormation about hosts. (he 5et6ostName() method retrieves the hostname o" the local s!stem. (he 5et6ostB!Name() method attempts to "ind the I0 address o" a hostname. 'NS Configuration +hen !our C# application is runnin# on a customerOs s!stem, !ou have no #uarantee that there are an! 'NS servers con"i#ured. Wou can "ind out what (i" an!) 'NS servers are con"i#ured b! usin# the .N)( %e#istr! class methods to e-amine the 'NS %e#istr! values. /ortunatel!, all +indows plat"orms store the 'NS server in"ormation in the same place: 6U32MSWS()2MCurrentControlSetMServicesM(cpipM0arameters %e#istr! 'ata *alues "or 'NS Servers

-ata Value

-escription

-ata"ase'at%

(he location o" the hostOs "ile

-omain

(he name o" the s!stemOs domain

CameServer

(he list o" 'NS servers

<ostname

(he name o" the s!stemOs 'NS host

Searc%!ist

& list o" 'NS domains to append to the end o" hostnames in 'NS name searches

(he value o" most interest here is NameServer . (his should contain a sin#le strin# value representin# all the con"i#ured 'NS servers, separated b! spaces. (he primar! 'NS server will be listed "irst, "ollowed b! the alternate servers. &"ample: 'emonstrate 'NS an usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 usin# S!stem.Net4 usin# 2icroso"t.+inDC4 namespace FCSharp&pplication 7 public partial class /ormR : /orm 7 public /ormR() 7 InitialiEeComponent()4 its Configuration in /egistry

= private void button<FClic,( object sender, )vent&r#s e) 7 //'emonstrate 'NS.. strin# FhostName G 'ns .5et6ostName()4 lst'NS.Items.&dd( "3ocal hostname :: " $ FhostName)4 I06ost)ntr! Fip6ost)ntr! G 'ns .5et6ostB!Name(FhostName)4 "oreach ( I0&ddress Faddress in Fip6ost)ntr!.&ddress3ist) 7 lst'NS.Items.&dd( "I0 &ddress ::" $ Faddress.(oStrin#())4 = = private void buttonCFClic,( object sender, )vent&r#s e) 7 //'NS Con"i#uration in %e#istr! %e#istr!Ue! start G %e#istr! .3ocal2achine4 strin# 'NSservers G ]"SWS()2MCurrentControlSetMServicesM(cpipM0arameters" 4 %e#istr!Ue! 'NSserverUe! G start..penSubUe!('NSservers)4 i" ('NSserverUe! GG null ) 7 lst'NSCon"i#uration.Items.&dd( ">nable to open 'NS servers ,e!" )4 return 4 = strin# serverlist G ( strin# )'NSserverUe!.5et*alue( "NameServer" )4 lst'NSCon"i#uration.Items.&dd( "'NS Servers: " $ serverlist)4 'NSserverUe!.Close()4 start.Close()4 char :; to,en G new char :<;4 to,en:H; G O O 4 strin# :; servers G serverlist.Split(to,en)4 "oreach ( strin# server in servers) 7 lst'NSCon"i#uration.Items.&dd( "'NS server: " $ server)4 = = = = (utput:

Clic) on bot! t!e buttons %ill specifie belo% 7or3ing $it% Files

isplay t!e respective outputs in t!e list bo"

/ile access in .N)( is #enerall! handled with stream objects. In this section, we will discuss about the two classes Binar!+riter and Binar!%eader to demonstrate the "ile handlin# in C#. (he Binar!%eader and Binar!+riter classes support binar! "ile access. (hese classes permit binar! operations to and "rom streams. +inaryWriter (he Binar!+riter class allows primitive data t!pes to be written to streams4 and with the use o" subclassin#, !ou can override the methods o" this class and "ul"ill !our own uniPue character encodin# rePuirements. (he "ollowin# table will summariEe the properties o" the class:

Name

$ype

#urpose

BaseStream

0ropert! &llow access to binar! writer underl!in# stream.

Close

2ethod

Close the Binar! writer class and the underl!in# stream.

/lush

2ethod

/lushes out all data to the underl!in# stream and then

clears bu""ers.

See,

2ethod

Sets the current position within the current stream.

+rite

2ethod

(his overloaded method writes a value out to the current stream.

4inaryReader (he Binar!%eader class, much li,e the Binar!+riter class, relies on a /ileStream object to read "iles . )et%od -escription

Close

Close the binar! reader object and the base stream.

0ee,Char

%eads the ne-t available b!te "rom the stream but does not advance the b!te or character position within the "ile.

%eadBoolean

%eads a Boolean :(rue//alse; value "rom the stream.

%eadB!te

%eads a sin#le b!te "rom the stream. (here is also a readb!tes method "or speci"!in# the number o" b!tes to read.

%eadChar

%eads a sin#le char value "rom the stream. (here is also a readchars method "or speci"!in# the number o" chars to read.

%eadInt<R

%eads an inte#er value (C b!tes).

%eadIntDC

%eads a lon# value (J b!tes).

%eadIntRJ

%eads an ei#ht b!te si#ned inte#er.

&"ample: 'emonstrate %or)ing %it! files usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 usin# S!stem.I.4 namespace FCSharp&pplication 7 public partial class /ormJ : /orm 7 public /ormJ() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 //+ritin# to the "ile /ileStream m!/Stream G new /ileStream ( "5:MMCCSharp&pplicationMM(est.t-t" , /ile2ode ..pen.rCreate, /ile&ccess .%ead+rite)4 Binar!+riter bin+rit G new Binar!+riter (m!/Stream)4 strin# testStrin# G "+ritin# into a /ile..(his is a test *alue." 4 bin+rit.+rite(testStrin#)4 bin+rit.Close()4 m!/Stream.Close()4 = private void buttonCFClic,( object sender, )vent&r#s e) 7 //%eadin# "rom the "ile. lon# ima#e+idth G H4 lon# ima#e6ei#ht G H4 int ima#e0lanes G H4 int ima#eBitCount G H4 strin# :; cma G )nvironment .5etCommand3ine&r#s()4

i" (cma.5et>pperBound(H) 9G <) 7 /ileStream m!/Stream G new /ileStream (cma:<;, /ile2ode ..pen, /ile&ccess .%ead)4 Binar!%eader bin%ead G new Binar!%eader (m!/Stream)4 bin%ead.BaseStream.0ositionGH-<C4 ima#e+idth G bin%ead.%eadIntDC()4 ima#e6ei#htG bin%ead.%eadIntDC()4 ima#es0lanesG bin%ead.%eadInt<R()4 ima#esBitCount G bin%ead.%eadInt<R()4 Console .+rite3ine( ":7H=; 7<=-7C= 7D= bit" ,cma:<;, ima#e+idth, ima#e6ei#ht, ima#eBitCount)4 bin%ead.Close()4 m!/Stream.Close()4 = = private void buttonDFClic,( object sender, )vent&r#s e) 7 //Cop!in# /ile. strin# :; strcla G )nvironment .5etCommand3ine&r#s()4 i" (strcla.5et>pperBound(H) GG C) 7 /ileIn"o cp!"i G new /ileIn"o (strcla:<;)4 cp!"i.Cop!(o(strcla:C;, true )4 2essa#eBo- .Show( "Copied " $ cp!"i.3en#th $ " b!tes." )4 = else 2essa#eBo- .Show( ">sa#e: cp 8input "ile9 8output "ile9" )4 = private void buttonJFClic,( object sender, )vent&r#s e) 7 //'eletin# /ile. strin# :; strcla G )nvironment .5etCommand3ine&r#s()4 i" (strcla.5et>pperBound(H) GG <) 7 /ileIn"o del"i G new /ileIn"o (strcla:<;)4 del"i.'elete()4 2essa#eBo- .Show( "/ile : " $ strcla:<;)4 2essa#eBo- .Show( "&ttributes: " $ del"i.&ttributes.(oStrin#())4 2essa#eBo- .Show( "/ile 'eleted..." )4

= else 2essa#eBo- .Show( ">sa#e: rm 8"ilename9" )4 = private void buttonKFClic,( object sender, )vent&r#s e) 7 //2ovin# /ile. strin# :; strcla G )nvironment .5etCommand3ine&r#s()4 i" (strcla.5et>pperBound(H) GG C) 7 /ileIn"o mov"i G new /ileIn"o (strcla:<;)4 mov"i.2ove(o(strcla:C;)4 2essa#eBo- .Show( "/ile Created : " $mov"i.Creation(ime.(oStrin#())4 2essa#eBo- .Show( "2oved to : " $ strcla:C;)4 = else 2essa#eBo- .Show( ">sa#e: mv 8source "ile9 8destination "ile9" )4 = = = Generating <elp File in C s%arp &n interestin# "eature o" the C# compiler is to #enerate 123 documentation "rom the comments. C# compiler reads speciall! "ormatted comments and #enerates 123 documentation "rom the comments. Wou can then displa!s this 123 on the +eb to provide an e-tra level o" documentation to developers who need to understand the structure o" !our applications. 0re rePuisites to #enerate 123 documentation "rom the comments are:

>se three slashes "or comments(///). (he C# compiler does not #enerate an! 123 'ocumentation "or an! comments that do not be#in with three slashes. Nor does the C# compiler #enerates an! 123 documentation "or re#ular, multi line, comments. >se the /doc option o" the C# compiler to speci"! the name o" the "ile that should contain the #enerated 123 documentation. #ample: -emonstrate H)! documentation from Comments Step.: In the first ste$ we create the %< code file. usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.+indows./orms4 namespace FCSharp&pplication

7 static class 0ro#ram 7 /// 8summar!9 /// (he main entr! point "or the application. /// 'eveloped B! : C# (eam /// 'eveloped .n : C< .ct,HS /// 8/summar!9 : S(&(hread ; static void 2ain () 7 &pplication .)nable*isualSt!les()4 &pplication .SetCompatible(e-t%enderin#'e"ault( "alse )4 S!stem.Console.+rite3ine( "Start>p "or C# +orldZ" )4 = = = Step:: -he following command is used to generate the hel$ file. -he command will create two files i.e. G3rogram.exeH and other is G3rogram0el$;ile.xmlH . Comman : csc 8 oc: .elpFile."ml #rogramFile.cs &utput:-he following xml will be generated b# the abo e command. #rogram.elpFile."ml 8^-ml versionG"<.H"^9 8doc9 8assembl!9 8name90ro#ram8/name9 8/assembl!9 8members9 8member nameG"2:FCSharp&pplication.0ro#ram.2ain"9 8summar!9 (he main entr! point "or the application. 'eveloped B! : C# (eam 'eveloped .n : C< .ct,HS 8/summar!9 8/member9 8/members9

8/doc9 Note: -5ain $ortion of 456 documentation is found in ImemberJ element' -his element contains one ImemberJ tag for each documented item in the source code. -he ImemberJ tag contains one attribute, name, which names the member being documented. -he alue of the name attribute starts with a one/letter $refix describing the t#$e of information being described. 7$tions for the first letter of the name attributeEs alue and its meaning. ImemberJ GnameH : 1ttribute 3refixes J &t%er Important Tags: (he "ollowin# is the list o" more help "ile ta#s which can be used in the C#.

1. FcG:- ( a# to indicate that a small part o" !our comment should be treated
as code. St!le sheets ma! use this element to displa! the code portion o" !our comment ).#. /// (his is the 8c9 2ain ()8/c9 "unction "or the /// 0ro#ram class. Fco eG:- (a# to indicate that multiple lines o" te-t in !our comments should be treated as code: ).#. /// 8code9 /// &r#ument:H;: command line ar#ument < /// &r#ument:<;: command line ar#ument C /// &r#ument:C;: command line ar#ument D /// 8/code9 Fe"ceptionG:- Wou can use the 8e-ception9 ta# to document an! e-ceptions that ma! be raised "rom the memberOs code. (he 8e-ception9 ta# must contain an attribute called cre" whose value speci"ies the t!pe o" e-ception bein# documented. (he cre" attribute value must be enclosed in Puotes. (he te-t o" the element describes the conditions under which the e-ception is thrown: ).#. /// 8e-ception cre"G"S!stem.)-ception"9 /// %aised i" the input is less than H. /// 8/e-ception9 FpermissionG:- >se the 8permission9 ta# to document the permissions available on a #iven "unction or variable. &ccess to a classOs code and data can mean access to all o" the code or it can be restricted to a certain subset o" code. Wou can use the 8permission9 ta# to document the availabilit! o" !our code and data. (he 8permission9 ta# ma,es use o" one attribute: cre". (he value o" the cre" element must name the "unction or variable whose permissions are bein# documented: ).#. /// 8permission nameG"2ain()"9 /// )ver!one can access 2ain (). /// 8/permission9 Fremar)sG:- >se the 8remar,s9 ta# to add in"ormation about an item. (he 8remar,s9 element is #reat "or providin# an overview o" a method or variable and its usa#e. (he 8remar,s9 ta# carries no attributes and its te-t contains the remar,s: ).#. /// 8remar,s9 /// (he 2ain () "unction is the entr! point into the /// application. (he C3% will call 2ain () to start /// the application a"ter the application loads /// 8/remar,s9

2.

3.

4.

5.

Code Access Security

Code access securit! is a "eature o" .N)( that mana#es code, dependent on our level o" trust. I" the C3% trusts the code enou#h to allow it to run, it will be#in e-ecutin# the code. 'ependin# on the permissions provided to the assembl!, however, it mi#ht run within a restricted environment. I" the code is not trusted enou#h to run, or i" it runs but then attempts to per"orm an action, "or which it does not have the relevant permissions, a Securit!)-ception is thrown. (he code access securit! s!stem means that we can stop malicious code runnin#, but we can also allow code to run within a protected environment where we are con"ident that it cannot do an! dama#e. C&S is part o" .Net securit! model that determines whether or not a piece o" code is allowed to run and what resources it can use while runnin#. C&S #rants ri#hts to pro#ram dependin# on the securit! con"i#uration o" the machine. /or e.#. the pro#ram has ri#hts to edit or create a new "ile but the securit! con"i#uration o" machine does not allow the pro#ram to delete a "ile. %ode access securit# is based on two conce$ts %ode 9rou$s and 3ermissions. -he following sections will discuss both in detail. Code Group Code 5roup is the concept o" brin#in# to#ether the code with similar characteristics. (wo e-amples "or code #roups are Internet and Intranet. (he #roup Internet de"ines code that is sourced "rom the Internet, the #roup Intranet de"ines code sourced "rom the 3&N. Code #roups have an entr! rePuirement called membershi$ condition . )ach code #roup has one, and onl! one, membership condition. /ollowin# is the available list o" code #roup memberships: Kone' (he re#ion "rom which the code ori#inated. & Eone is one o" the commonl! used condition. & Eone is the re#ion o" ori#in o" a piece o" code and re"ers to one o" the "ollowin#: 2! Computer, Internet, Intranet, (rusted, or not trusted. Site' (he +eb site "rom which the code ori#inated. Strong 8ame' & uniPue, veri"iable name "or the code. 3ublisher' (he publisher o" the code. A26' (he speci"ic location "rom which the code ori#inated. 0ash !alue' (he hash value "or the assembl!. Ski$ !erification' (his condition rePuests that it b!passes code veri"ication chec,s. 1$$lication ,irector#' (he location o" the assembl! within the application. 1ll %ode' &ll code "ul"ills this condition. %ustom' & user speci"ied condition. Code #roups are arran#ed hierarchicall! with the &ll Code membership condition at the root. 'ermissions 0ermissions are the actions we allow each code #roup to per"orm^ /or e-ample, permissions include @able to access the user inter"aceA and @able to access local stora#e.A (he s!stem administrator usuall! mana#es the permissions at the enterprise, machine, and user levels. )ulti-T%reading & thread is a sePuence o" e-ecution in a pro#ram. &ll our C# pro#rams up to this point have one entr! point_the 2ain () method. )-ecution starts with the "irst statement in the 2ain () method and continues until that method returns. & thread is the basic unit to which the operatin# s!stem allocates processor time.

0rocesses are made up o" one or more threads. & thread is de"ined as a sin#le "low o" operation within a pro#ram. +hen a pro#ram e-ecutes on the C0>, it traverses the pro#ram statements in a sin#le thread until the thread is complete. &multithreaded application distributes "unctions amon# multiple pro#ram "lows, allowin# two or more paths o" e-ecution to occur. )ach path o" e-ecution is a separate thread. Multi-tas)ing' ItOs a "eature o" modern operatin# s!stems with which we can run multiple pro#rams at same time e-ample word, e-cel etc Multi-$!rea ing' 2ulti threadin# "orms subset o" multi tas,in# instead o" havin# to switch between pro#rams this "eature switches between di""erent parts o" the same pro#ram. )-ample we are writin# a word document and at the same time word is doin# a spell chec, in bac,#round. 2ultithreaded pro#rams create their own threads that can be e-ecuted separatel! "rom the main thread o" the pro#ram. &ll threads created b! the primar! thread share the same memor! address space as the primar! thread. ."ten the secondar! threads are used to per"orm computationall! intensive "unctions, allowin# the main thread to continue respondin# to +indows events. +ithout the secondar! threads, the user could not select an!thin# "rom the menu or clic, an! buttons while an application computed a mathematical "unction System+T%reading: (his namespace has all the classes that are related to implement threadin#. &n! .Net application who wants to implements threadin# has to import this namespace. Note: In .Net pro#ram, there are alwa!s at least two threads runnin#, i.e. one is the main pro#ram and other is the #arba#e collector. States: (hreads have several operational states, which are enumerated usin# the .N)( (hread State enumeration, "ound in the S!stem.(hreadin# namespace. Initiali5ed: (he thread has been initialiEed but not started. /ea y: (he thread is waitin# "or a processor. /unning: (he thread is currentl! usin# the processor. Stan by: (he thread is about to use the processor. $erminate : (he thread is "inished and is read! to e-it. $ransition: (he thread is waitin# "or a resource other than the processor. ,n)no%n: (he s!stem is unable to determine the thread state. Wait: (he thread is not read! to use the processor T%e T%read Class >se the (hread class to create a new (hread object, which produces a new thread within the current process. (he "ormat o" the (hread constructor is as "ollows, where start is a (hreadStart dele#ate: $!rea ;$!rea Start start> (he (hreadStart dele#ate points to the method that will be per"ormed within the new thread. +g+ (hread newthreadG new (hread (new (hreadStart (an!2ethod))4 *oid an!2ethod () 7=

&"ter the (hread object is created, it can be controlled usin# various (hread class methods, which are as under: Abort ;>: (erminate the thread. &Cuals ;>: 'etermines whether two thread objects are same. 4et.as!Co e ;>: 5et a uniPue representation "or the thread. 4et$ype ;>: 5et the t!pe o" the current thread. *nterrupt ;>: Interrupts a thread that is in a wait state. Doin ;>: Bloc,s the callin# thread until the thread terminates. /esume ;>: %esumes a thread that has been suspended. Start ;>: Chan#e the state o" the thread to runnin#. Suspen ;>: Suspend the e-ecution o" the thread. $oString ;>: #ets a strin# representation o" the (hread object. T%read priority: (he thread priorit! determines the order in which thread has to e-ecute. (he thread priorit! can be chan#ed b! usin# (hreadname.0riorit! G (hread0riorit!.6i#hest. 'i""erent levels o" priorit! provided b! .Net: (hread0riorit!.6i#hest (hread0riorit!.&boveNormal (hread0riorit!.Normal (hread0riorit!.BelowNormal (hread0riorit!.3owest $!rea .Sleep ;>: (hread e-ecution can be paused b! callin# the (hread.Sleep method. (his method ta,es an inte#er value that determines how lon# the thread should sleep. &"ample: 'emonstrate $!rea ing usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 usin# S!stem.%untime.%emotin#4 usin# S!stem.(hreadin#4 namespace Console&pplication< 7 class 0ro#ram< 7 static void 2ain ( strin# :; ar#s) 7 0ro#ram< ts G new 0ro#ram< ()4 = public 0ro#ram<() 7

int i4 (hread "irst(hread G new (hread ( new (hreadStart (/irst2ethod))4 (hread second(hread G new (hread ( new (hreadStart (Second2ethod))4 "irst(hread.Start()4 second(hread.Start()4 "or (i G H4 i 8 <H4 i$$) 7 Console.+rite3ine( "2ain: 7H=" , i)4 (hread .Sleep(<HHH)4 = = void /irst2ethod() 7 int i4 "or (i G H4 i 8 <H4 i$$) 7 Console.+rite3ine( " /irst thread: 7H=" , i)4 (hread .Sleep(CHHH)4 = = void Second2ethod() 7 int i4 "or (i G H4 i 8 <H4 i$$) 7 Console.+rite3ine( " Second threadC: 7H=" , i)4 (hread .Sleep(DHHH)4 = = = = (utput: 2ain : H /irst thread: H Second threadC: H 2ain : < /irst thread: < 2ain : C Second threadC: < 2ain : D /irst thread: C 2ain : J 2ain : K Second threadC: C /irst thread: D 2ain : R 2ain : S /irst thread: J 2ain : V Second threadC: D 2ain : X /irst thread: K Second threadC: J /irst thread: R /irst thread: S Second threadC: K /irst thread: V Second threadC: R /irst thread: X Second threadC: S Second threadC: V Second threadC: X Glo"ali5ation and !ocali5ation @.

+hen writin# applications "or international distribution, di""erent cultures and re#ions must be ,ept in mind. 'i""erent cultures have diver#in# calendars and use di""erent number and date "ormats, and also the sort order with the letters & Y ma! lead to various results. (o ma,e applications "it "or #lobal mar,ets !ou have to #lobaliEe and localiEe them. 9lobaliLation is about internationaliEin# applications: preparin# applications "or international mar,ets. +ith #lobaliEation, the application supports number and date "ormats dependin# on the culture, di""erent calendars, and so on. 6ocaliLation is about translatin# applications "or speci"ic cultures. /or translations o" strin#s, !ou can use resources. .N)( supports #lobaliEation and localiEation o" +indows and +eb applications. (o #lobaliEe an application !ou can use classes "rom the namespace S#stem.9lobaliLationS#stem.2esources. whereas to localiEe an application !ou can use resources that are supported b! the namespace System+Glo"ali5ation (he S#stem.9lobaliLation namespace holds all culture and re#ion classes to support di""erent date "ormats, di""erent number "ormats, and even di""erent calendars that are represented in classes such as 5re#orian calendar, 6ebrew Calendar, `apanese Calendar, and so on. >sin# these classes !ou can displa! di""erent representations dependin# on the userOs locale. Cultures and Regions (he world is divided into multiple cultures and re#ions, and applications have to be aware o" these cultural and re#ional di""erences. %/C <SRR de"ines culture names that are used worldwide dependin# on a lan#ua#e and a countr! or re#ion. Some e-amples are en &>, en C&, en 5B, and en >S "or the )n#lish lan#ua#e in &ustralia , Canada , >nited Uin#dom , and the >nited States . Note:- 5ost Im$ortant class in S#stem.9lobaliation names$ace isCulture*nfo B2e$resents a %ultureC #ample: -emonstrate CultureInfo usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 usin# S!stem.%untime.%emotin#4 usin# S!stem.(hreadin#4 usin# S!stem.5lobaliEation4 namespace Console&pplication< 7 class 0ro#ram< 7 static void 2ain ( strin# :; ar#s) 7 int val G <CDJKRSVXH4

strin# name G "visualbuilder" 4 //Culture o" the Current (hread Console .+rite3ine(val.(oStrin#( "N" ))4 //use I/ormat0rovider Console .+rite3ine(val.(oStrin#( "N" , new CultureIn"o ( ""r /%" )))4 //Chan#e the culture o" the thread (hread .Current(hread.CurrentCulture G new CultureIn"o ( "de ')" )4 Console .+rite3ine(val.(oStrin#( "N" ))4 = = = &utput: -he following out$ut will be dis$la#ed on console. 'ispla! in Current Culture: <,CDJ,KRS,VXH.HH 'ispla! in /rench Culture: < CDJ KRS VXH, HH 'ispla! in ') Culture: <.CDJ.KRS.VXH, HH 7or3ing $it% Registry in C s%arp +indows %e#istr! is a central database "or application con"i#uration settin#s and other in"ormation rePuired b! the applications. (he +indows %e#istr! is a data repositor! that e-ists on each computer in +indows .peratin# s!stems. Both the s!stem and application pro#rams use this repositor! to store in"ormation needed at runtime. /or e-ample, the s!stem stores "ile associations (the applications or command lines associated with each ,nown "ile e-tension) in the %e#istr!. &pplications o"ten use the %e#istr! to store in"ormation such as usersO option settin#s and data "ile pathnames. Note:- I" !ouOve never open +indows re#istr!, !ou can see it b! runnin# regedit "rom command line .N)( /ramewor, 3ibrar! provides two classes 2egistr# and 2egistr#Me# to wor, with the windows re#istr!. (hese classes are de"ined in 5icrosoft..in*) namespace. So be"ore usin# these classes, !ou need to add re"erence to this namespace. Registry Class: (he %e#istr! class contains members to provides access to re#istr! ,e!s. +e can de"ine re#istr! ,e!s in the "ollowin# order. Current,ser - Stores in"ormation about user pre"erences. LocalMac!ine - Stores con"i#uration in"ormation "or the local machine. Classes/oot - Stores in"ormation about t!pes (and classes) and their properties. ,sers - Stores in"ormation about the de"ault user con"i#uration. #erformance'ata - Stores per"ormance in"ormation "or so"tware components. CurrentConfig - Stores non user speci"ic hardware in"ormation.

'yn'ata - Stores d!namic data. (he %e#istr! class members are described in the "ollowin# table. %eturns a %e#istr!Ue! t!pe which provides access to 6U)WFC3&SS)SF%..( ,e!.

Classes%oot

3ocal2achine

%eturns a %e#istr!Ue! t!pe which provides access to 6U)WF3.C&3F2&C6IN) ,e!.

CurrentCon"i#

%eturns a %e#istr!Ue! t!pe which provides access to 6U)WFC>%%)N(FC.N/I5 ,e!.

'!n'ata

%eturns a %e#istr!Ue! t!pe which provides access to 6U)WF'WNF'&(& ,e!.

Current>ser

%eturns a %e#istr!Ue! t!pe which provides access to 6U)WFC>%%)N(F>S)% ,e!

0er"ormance'ata %eturns a %e#istr!Ue! t!pe which provides access to 6U)WF0)%/.%2&NC)F'&(& ,e!.

>sers

%eturns a %e#istr!Ue! t!pe which provides access to 6U)WF>S)%S ,e!.

RegistryIey Class : (he %e#istr!Ue! class contains members to add, remove, replace, and read re#istr! data. Some o" its common methods and properties are de"ined in the "ollowin# table. #roperties: Came - %epresents the name o" the ,e!. Su"IeyCount - %epresents the count o" sub,e!s at the base level, "or theCurrent ,e!. ValueCount - %epresents the count o" values in the ,e!. Met!o s:

5et*alueNames

%etrieves an arra! o" strin#s that contains all the value names associated with this ,e!.

5et*alue

%eturns the speci"ied value.

.penSubUe!

.pens a sub,e!.

5etSubUe!Names %eturns an arra! o" strin#s that contains all the sub,e! names.

'eleteSubUe!(ree 'eletes a sub,e! and an! children.

'eleteSubUe!

'eletes the speci"ied sub,e!.

CreateSubUe!

Creates a new sub,e! i" not e-ists, otherwise opens an e-istin# sub,e!.

Set*alue

Sets the speci"ied value.

'elete*alue

'eletes the speci"ied value "rom a ,e!.

Close

Closes the ,e!.

&"ample:- Wor)ing %it! Win o%s /egistry. Form.+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4

usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 usin# 2icroso"t.+inDC4 namespace +indows&pplication< 7 public partial class /orm< : /orm 7 public /orm<() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 //&ddin# a Ue! and *alue in %e#istr! %e#istr!Ue! ,e! G %e#istr! .3ocal2achine..penSubUe!( "So"tware" , true )4 //Create Ue! inside the so"tware "older %e#istr!Ue! new,e! G ,e!.CreateSubUe!( "New(estUe!&dded" )4 //>ser Can also set the value "or this Ue! new,e!.Set*alue( "New(estUe!&dded" , "*alue/or(his(estUe!" )4 2essa#eBo-.Show( "Ue!/*alue is added in the %e#istr!..." )4 = private void buttonCFClic,( object sender, )vent&r#s e) 7 //%etrievin# 'ata /rom %e#istr! %e#istr!Ue! p%e#Ue! G %e#istr! .3ocal2achine4 p%e#Ue! G p%e#Ue!..penSubUe!( "6&%'+&%)MM ')SC%I0(I.NMMS!stemMM/loatin#0oint0rocessorMMH" )4 .bject value."Ue! G p%e#Ue!.5et*alue( "Identi"ier" )4 2essa#eBo-.Show( "Ue! *alue is :: " $ value."Ue!)4 = private void buttonDFClic,( object sender, )vent&r#s e) 7 //'eletin# Ue!/*alue "rom %e#istr! %e#istr!Ue! delUe!*alue G %e#istr! .3ocal2achine..penSubUe!( "So"twareMM" )4 delUe!*alue.'elete*alue( "*alue/or(his(estUe!" )4 // 'elete the ,e! "rom the re#istr!. true )4 %e#istr!Ue! delSubUe! G %e#istr! .3ocal2achine..penSubUe!( "So"tware" ,

delSubUe!.'eleteSubUe!( "New(estUe!&dded" )4 2essa#eBo-.Show( "'eletin# Ue!/*alue in the %e#istr!" )4

= = = &utput: A ing a Hey80alue in t!e /egistry /etrieving 0alue from t!e /egistry Glo"ali5ation and !ocali5ation @: (he comin# section will discuss about some more classes used "or 5lobaliEation in C#. Resources and Resource7riter %esources such as pictures or strin# tables can be put into resource "iles or satellite assemblies. Such resources can be ver! help"ul when localiEin# applications, and .N)( has built in support to search "or localiEed resources. & resource "ile can be a te-t "ile or a .res- "ile or 123 "ile. (his "ile contains the ,e!/value pairs. +here the ,e!s are used in the pro#ram and at run time the! are replaced with the values that is correspondin# to each ,e!. /or e-ample: Name G `im (ire &ddress G >S& &uthor G 0uppet 0ublisher G `im (oe Note:-/es4en.e"e utilit# is used to create a resource file out of this Gtest.txtH file. the command /esgen test.txt will create the text.txt resource file and /esgen test.txt test.resx will createtthe 456 file from the test.txt file. Resource7riter (his class under the S!stem.%esources namespace is used to create the resource "ile throu#h the pro#rammin#. (he below e-ample will create the object o" the2esource.riter1dd2esource() method. and then we can use the same object to add upto C5B o" resources. +e have to just suppl! the ,e!/value pair to the objectOs &"ample: 'emonstrate /esourceWriter usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.(e-t4 usin# S!stem.%untime.%emotin#4 usin# S!stem.(hreadin#4 usin# S!stem.5lobaliEation4 usin# S!stem.%esources4 namespace Console&pplication< 7 class 0ro#ram<

7 static void 2ain ( strin# :; ar#s) 7 %esource+riter rw G new %esource+riter ( "%+'emo.resources" )4 rw.&dd%esource( "Name " , "*isualBuilder" )4 rw.&dd%esource( "&dress" , " >U " )4 rw.&dd%esource( "6obb!" , "Cric,et" )4 rw.&dd%esource( "/avourite Countr!" , " &ustralia " )4 rw.&dd%esource( "0la!er" , "Sunn!" )4 rw.Close()4 = = = (utput: -his will create 2.,emo.resources file, which contains the ke#/ alue $airs. -he %lose() method of the 2esource.riter class automaticall# calls 2esource.riter.9enerate() to finall# write the resources to the file 2.,emo.resources. ?sing Resource File in an Application +e can add resource "iles to assemblies usin# the assembl! #eneration tool al+e#e, usin# the /embed option or usin# the c# compiler with /resource option or directl! usin# the *S.Net. (he "ollowin# are the steps to use the resource "iles in C# application. <. C. D. J. K. R. S. V. .pen the application >se the conte-t menu o" the solution e-plorer (&dd 99 &dd )-istin# Item) 3ocate the path where the resource "ile is situated. I" !ou chec, the %esource a"ter addin# it to the projects, its Build&ction is @)mbedded %esourceA, this means the resource is embedded to the output assembl!. Wou can view the resource "ile usin# the I3'asm.e-e utilit! b! chec,in# it in the assembl! mani"est. (o access the embedded resources, use the %esource 2ana#er class "rom the S!stem.%esources namespace. Wou can pass the assembl! that has the resources as an ar#ument to the constructor o" the %esource 2ana#er class .nce !ou include the resource "ile in the application use the %esource 2ana#er and load the resource "ile into this.

&"ample: 'emonstrate ,sage of /esource File usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4

usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 usin# S!stem.%e"lection4 usin# S!stem.%esources4 namespace cS6&%0)1&203)S 7 public partial class /ormCC : /orm 7 public /ormCC() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 //>sin# %esource /ile S!stem.%esources. %esource2ana#er rm4 &ssembl! assembl! G &ssembl! .5et)-ecutin#&ssembl!()4 rm G new %esource2ana#er ( "cS6&%0)1&203)S.%+'emo" , assembl!)4 t-tName.(e-t G rm.5etStrin#( "Name " )4 t-t&ddress.(e-tGrm.5etStrin#( "&dress" )4 t-t6obb!.(e-t G rm.5etStrin#( "6obb!" )4 t-t/Countr!.(e-t G rm.5etStrin#( "/avourite Countr!" )4 t-t0la!er.(e-t G rm.5etStrin#( "0la!er" )4 = = = 7indo$s Service (he core "unction o" a +indows Service is to run an application in the bac,#round. .ne o" the wa!s that it di""ers "rom an windows application in that a +indows Service starts be"ore an! user lo#s in to the s!stem (i" it has been setup to start at boot up), althou#h it can also be setup in such a wa! that it rePuires user to start it manuall!. & +indows Service also has its own process hence it runs ver! e""icientl!. Normall! a +indows Service will not have a user inter"ace "or a simple reason it can be run even i" no one is lo##ed on to the s!stem but this is not a rule, !ou can still have a +indows Service with a user inter"ace. Creating a Win o%s Service: Step 6:- .pen *S CHHK, Clic, on /ile 9 0rojects.

Step 2:- (his will open up a project and clic,in# on the h!perlin, that is there on the pa#e, !ou will be able to open the code behind pa#e where !ou can code "or the web service. Step 7:- &dd /unctionalit! to the web service that !ou have created. (here are two overridden "unction i.e. @.nStartA and @.nStopA. (he .nStart "unction e-ecutes when !ou start !our service and the .nStop "unction #ets e-ecute when !ou stop a service. //.nStart protected override void .nStart( strin# :; ar#s) 7= //.nStop protected override void .nStop() 7= Step I:- Install and %un the Service: /or Installation o" the service on the computer, one need to have the administrator ri#hts to install the service on the computer. (he install>til tool is provided b! with the .Net "ramewor, to install the application. Note:- -he use should ha e administrator rights to install the utilit#. If the utilit# is not installed then it will dis$la# a $o$u$ when #ou run the $rogram. &"ample: 'emonstrate Win o%s Services. usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'ia#nostics4 usin# S!stem.Service0rocess4 usin# S!stem.(e-t4 usin# S!stem.I.4 namespace winService/irst 7 public partial class .(estService : ServiceBase 7 public .(estService() 7 InitialiEeComponent()4 = protected override void .nStart( strin# :; ar#s) 7 //(his will be printed at the start o" the service....

/ileStream "s G new /ileStream ( ]"C:MwindowService(estMtrac,er/or+ebService.t-t" , ..pen.rCreate, /ile&ccess .+rite)4 mFstream+riter.BaseStream.See,(H, See,.ri#in .)nd)4

/ile2ode

Stream+riter mFstream+riter G new Stream+riter ("s)4 mFstream+riter.+rite3ine( " ?????????????????????????? Mn" )4 mFstream+riter.+rite3ine( " mc+indowsService: Service Started Mn" )4 mFstream+riter.+rite3ine( " ?????????????????????????? Mn" )4 mFstream+riter./lush()4 mFstream+riter.Close()4 = protected override void .nStop() 7 // (.'.: &dd code here to per"orm an! tear down necessar! to stop !our service. //(his will be printed at the end o" the service... /ileStream "s G new /ileStream ( ]"C:MwindowService(estMtrac,er/or+ebService.t-t" , /ile2ode ..pen.rCreate, /ile&ccess .+rite)4 Stream+riter mFstream+riter G new Stream+riter ("s)4 mFstream+riter.BaseStream.See,(H, See,.ri#in .)nd)4 mFstream+riter.+rite3ine( " ??????????????????????????? Mn" )4 mFstream+riter.+rite3ine( " mc+indowsService: Service Stopped Mn" )4 mFstream+riter.+rite3ine( " ??????????????????????????? Mn" )4 mFstream+riter./lush()4 mFstream+riter.Close()4 = = = (utput: Note:- -hr $rogram will write the content in the text file that we s$ecified. -he following lines gets $rinted in the text file.

?????????????????????????? mc+indowsService: Service Started

?????????????????????????? ??????????????????????????? mc+indowsService: Service Stopped ??????????????????????????? 7e" Service (he term "web service" re"ers to a "orm o" a component that can be used remotel!. +eb services are invo,ed remotel! usin# S.&0 or 6((0 5)( and 6((0 0.S( protocols. +eb services are based on 123 and return an "answer" to the client in 123 "ormat. +eb services have all the advanta#es o" components plus man! more. T%e most significant "enefits include:

1. #latform an Language *n epen ence : +eb services can be built and 2.


consumed on an! operatin# s!stem just as lon# as that operatin# s!stem supports the S.&0 protocol and 123. Automatic ,pgra e : >nli,e components, i" a web service rePuires an update, that update is propa#ated to all applications consumin# that web service immediatel!. (his is because the actual methods and properties "or the web service are invo,ed "rom the web server remotel!, meanin# that each "unction contained within a web service appears as a "blac, bo-" to a client: the! arenOt concerned with the wa! the "unction does its job, just as lon# as it returns the e-pected result.

Some Important Terms in 7e" Services:

1. ,''* : >''I (>niversal 'escription, 'iscover! and Inte#ration) is a re#istr!

2.

3. 4.

that provides a place "or a compan! to re#ister its business and the services that it o""ers. 0eople or businesses that need a service can use this re#istr! to "ind a business that provides the service. +hen !ou search "or a web service usin# >''IOs web service or web browser, >''I returns a listin# o" web services that matched !our criteria. (his list is returned in the "orm o" a 'ISC. or +S'3 document. WS'L: +S'3 (+eb Services 'escription 3an#ua#e) is a lan#ua#e that describes a web service. It contains in"ormation such as where !ou can "ind the web service, methods and properties that it supports, its data t!pes, and the protocol used to communicate with the web service. +S'3 is based on the 123 "ormat and itOs used to create pro-! objects. Basicall!, without a +S'3 document, developers wouldnOt be able to use web services simpl! because the! wouldnOt ,now which methods and properties the! support and also which communication method an! particular web service supports. '*SC( : 'ISC. (&bbreviated "rom disco ver!) is a list o" +S'3 documents. 'ISC. is used to #roup common web services to#ether. 'ISC. documents are also in 123 "ormat. S(A#: S.&0 (Simple .bject &ccess 0rotocol) is a protocol to transport data to and "rom the web server. It is in 123 "ormat and allows !ou to transport a

variet! o" data t!pes used in .N)(. &s an alternative to S.&0, we can use 6((0 5)( and 6((0 0.S(, which will be covered later in the article. (hese protocols return the output in a non S.&0 "ormat4 however this output is still in 123 "ormat. #ample: -emonstrate 7e" Service usin# S!stem4 usin# S!stem.+eb4 usin# S!stem.+eb.Services4 usin# S!stem.+eb.Services.0rotocols4 : +ebService (Namespace G "http://tempuri.or#/" , 'escription G "New +)B Service 'eveloped b! *.'" ); : +ebServiceBindin# (Con"orms(o G +si0ro"iles .Basic0ro"ile<F<); public class Service : S!stem.+eb.Services. +ebService 7 public Service () 7 //>ncomment the "ollowin# line i" usin# desi#ned components //InitialiEeComponent()4 = : +eb2ethod ('escriptionG "5et)mplo!eeName: (his will return the )mplo!ee Name." ); public strin# #et)mplo!eeName() 7 return "`ames (ube" 4 = : +eb2ethod ('escription G "5et)mplo!ee&#e: (his will return the )mplo!ee &#e." ); public strin# #et)mplo!ee&#e() 7 return "CD" 4 = = (utput: /un t!is Web Service or FJ Note: &C. -here are ) methods that are associated with this web ser ice. )C. -he web ser ice us under the default names$ace that is htt$'//tem$uri.org. . *C. Each 456 .eb ser ice needs a uniDue names$ace in order for client a$$lications to distinguish it from other ser ices on the .eb.htt$'//tem$uri.org/ is a ailable for 456 .eb ser ices that are under de elo$ment, but $ublished 456 .eb ser ices should use a more $ermanent names$ace .

(utput: *f user clic)s on t!e get&mployeeAge lin) Clic) on t!e *nvo)e +utton %ill Consuming 7e" Services & +eb Service is an e-ternal inter"ace provided b! a +eb site that can be called "rom other +eb sites. /or e-ample, a "inancial compan! ma! ma,e up to the minute stoc, Puotes available via +eb Service "or those who do their tradin# with that compan!. (his in"ormation could be read "rom a +eb pa#e and displa!ed, or read "rom a stand alone application on a customerOs des,top computer. Client Communicate t%roug% $e" service: S.&0 over 6((0 S.&0 over 6((0 123 123 !ocation . !ocation : isplay t!e value.

Soap calls are remote "unction calls that invo,e methods e-ecutions on +eb Service components at 3ocation C. (he output is render as 123 and pass bac, to the 3ocation < where the user wants to access the +eb Service. &t 3ocation <, the user need to consume some o" the "unctions o" the web service that is available on the internet, to ma,e the remote "unction calls (%/C). &ll the processin# canOt be done on the remote machine, there"ore, we have to create the pro-! o" the web service "rom where we can process our data. (his whole process is also called as marshalling o" data. 'ue to securit! threats, we create the pro-! o" the server object here it is web service. (hat means we are creatin# a " pro#y o"Ject " to act on behal" o" the ori#inal +eb service. (he pro-! object will have all the public available data inter"aces as the ori#inal +eb service. Consuming a 7e" Service (he "ollowin# are the steps to call/consume a webservice. Step 6: Create a +eb Service project and run it so that no compilation error e-ists. Step 2: Create new +eb Site that will consume this web site that is there in !our s!stem usin# the *S.Net. Create New +eb Site with the name: +eb Site Name that will consume web service:.ebSer ice@%onsume. Step 7: .nce !ou are done with the creation o" the new site that will consume the web Service. 3et e-ample the web service run as this >%3:!ttp:88local!ost:6JK18WebServiceLNe%8MyWebService.asm"

Step I: %i#ht clic, on the solution, Clic, on @&dd +eb %e"erenceA. (his will open up a new pop up window where !ou can speci"! the?R! name of your $e" service .

6ere we speci"! the web service >%3 and i" !ou loo, at the ri#ht panel there is +eb %e"erence Name: localhost B-his the default name that is thereC.

StepJ: +e speci"! @localhostFm!+ebServiceA name "or the web re"erence. (his will include D "iles under this "older. 2!+ebService.disco 2!+ebService.discomap 2!+ebService.wsdl Step?: 3oo, Inside the contents o" the @discoA "ile 8^-ml versionG"<.H" encodin#G"ut" V" ^9 8discover! -mlns:-siG"http://www.wD.or#/CHH</123Schema instance" -mlns:-sdG"http://www.wD.or#/CHH</123Schema"-mlnsG"http://schema s.-mlsoap.or#/disco/"9 8contract%e"re"G"http://localhost:<KHV/+ebServiceFNew/2!+ebService.asm-^wsdl "doc%e"G"http://localhost:<KHV/+ebServiceFNew/2!+ebService.asm-" -mlnsG"htt p://schemas.-mlsoap.or#/disco/scl/" /9 8soapaddressG"http://localhost:<KHV/+ebServiceFNew/2!+ebService.asm-" -mlns :P<G"http://tempuri.or#/" bindin#G"P<:ServiceSoap"-mlnsG"http://schemas.-mlso ap.or#/disco/soap/" /9 8soapaddressG"http://localhost:<KHV/+ebServiceFNew/2!+ebService.asm-" -mlns :PCG"http://tempuri.or#/" bindin#G"PC:ServiceSoap<C" -mlnsG"http://schemas.-mlsoap.or#/disco/soap/" /9 8/discover!9 Step@: 3oo, Inside the contents o" the @discomapA "ile 8^-ml versionG"<.H" encodin#G"ut" V" ^9 8'iscover!Client%esults/ile-mlns:-siG"http://www.wD.or#/CHH</123Schema instance"-mlns:-sdG"http://www.wD.or#/CHH</123Schema"9 8%esults9 8'iscover!Client%esultre"erence(!peG"S!stem.+eb.Services.'iscover!.'iscover!'o cument%e"erence"urlG"http://localhost:<KHV/+ebServiceFNew/2!+ebService.asm^disco" "ilenameG"2!+ebService.disco" /9 8'iscover!Client%esultre"erence(!peG"S!stem.+eb.Services.'iscover!.Contract%e"e rence"urlG"http://localhost:<KHV/+ebServiceFNew/2!+ebService.asm-^wsdl" "ilena meG"2!+ebService.wsdl" /9 8/%esults9 8/'iscover!Client%esults/ile9 &"ample: 'emonstrate t!e Consumption of t!e Web Service in t!e Web Site usin# S!stem4 usin# S!stem.'ata4 usin# S!stem.Con"i#uration4 usin# S!stem.+eb4 usin# S!stem.+eb.Securit!4 usin# S!stem.+eb.>I4 usin# S!stem.+eb.>I.+ebControls4

usin# S!stem.+eb.>I.+ebControls.+eb0arts4 usin# S!stem.+eb.>I.6tmlControls4 public partial class F'e"ault : S!stem.+eb.>I. 0a#e 7 protected void 0a#eF3oad( object sender, )vent&r#s e) 7 = protected void Button<FClic,( object sender, )vent&r#s e) 7 //Consumin# the +ebServices throu#h &dd +eb %e"erence ///etchin# the *alue "rom the +eb Services localhostFm!+ebService. Service objServiceConsume G newlocalhostFm!+ebService. Service ()4 t-tName.(e-t G objServiceConsume.#et)mplo!eeName()4 t-t&#e.(e-t G objServiceConsume.#et)mplo!ee&#e()4 = = (utput:

Clic) on t!e Fetc!er button: $!is %ill fetc! t!e value from t!e Web Service.

Creating 'ro#y &"Ject of 7e" Service (here are man! wa!s to consume +eb Services. <. (he "irst wa! is to use a S.&0 0ro-! Client .bject #enerated b! the +S'3 utilit!, and it provides pro#rammers with their "amiliar object model that the! can use to call methods provided b! the #enerated 0ro-! Inter"ace. C. (he second wa! is to use 6((0 0.S( and 6((0 5)( protocols. D. (he third wa! is to use a S.&0 standard %ePuest messa#e that parses S.&0 response messa#es with the help o" the 1236((0 C.2 object that is installed b! the 2icroso"t 123 0arser. WS'L: +eb Services 'escription 3an#ua#e (+S'3) is an 123 based protocol "or in"ormation e-chan#e in decentraliEed and distributed environments. & +S'3 document de"ines services as collections o" networ, endpoints, or ports. & +S'3 document uses the "ollowin# elements in the de"inition o" networ, services: $ypes 5 a container "or data t!pe de"initions usin# some t!pe s!stem (such as 1S'). Message 5 an abstract, t!ped de"inition o" the data bein# communicated. (peration 5 an abstract description o" an action supported b! the service. #ort $ype 5an abstract set o" operations supported b! one or more endpoints.

+in ing 5 a concrete protocol and data "ormat speci"ication "or a particular port t!pe. #ort 5 a sin#le endpoint de"ined as a combination o" a bindin# and a networ, address. Service 5 a collection o" related endpoints. 'ro#y Class: (his pro-! class serves as an intermediate between the &S0.N)( +eb pa#e and the +eb service

Consuming Web Service obMect: <. (he &sp.Net pa#e instantiates an instance o" the pro-! class. /or e.#. 0ro-!ClassName objpro-! G new 0ro-!ClassName()4 C. .nce the object is instantiated, then with the help o" pro-! object, this will ma,e a call to the web service method. /or e.#. objpro-!.+eb2ethodName(an! 0arameter that has to send)4 D. (he pro-! class marshals the parameter list and ma,es an 6((0 rePuest to the +eb service sittin# on +eb Server C. J. (he +eb service unmarshals the incomin# parameters, runs the method, and marshals the output parameters. (hese are sent bac, in an 6((0 response. K. (he pro-! class unmarshals the return parameters and passes bac, the result to the &S0.N)( +eb pa#e. Creating a #ro"y Class: Creatin# a 0ro-! class involves three steps: tep 6:- /irst create the pro-! class o" the web service usin# the +S'3 tool. wsdl.exe'/>tilit! to #enerate code "or -ml web service clients and -ml web services usin# &S0.N)( "rom +S'3 contract "iles, 1S' schemas and discomap discover! documents. (his tool can be used in conjunction with disco.e-e. Run t%is from t%e Command 'rompt: C:M0ro#ram /ilesM2icroso"t *isual Studio VM*C9 $sdl%ttp:;;local%ost:.=9K;7e"ServiceDCe$;)y7e"Service+asm# 2icroso"t (%) +eb Services 'escription 3an#ua#e >tilit! :2icroso"t (%) .N)( /ramewor,, *ersion C.H.KHSCS.JC; Cop!ri#ht (C) 2icroso"t Corporation. &ll ri#hts reserved. +ritin# "ile OC:M0ro#ram /ilesM2icroso"t *isual Studio VM*CMService.csO. Step 2:- (his will create the @Service.csA "ile on the speci"ied location. &"ter this compile this 0ro-! Class to #enerate the compiled pro-!

Class i.e. @Service.dllA %un this "rom the command 0rompt: C:M0ro#ram /ilesM2icroso"t *isual Studio VM*C9 csc ;t:li"raryService+cs 2icroso"t (%) *isual C# CHHK Compiler version V.HH.KHSCS.JC "or 2icroso"t (%) +indows (%) CHHK /ramewor, version C.H.KHSCS Cop!ri#ht (C) 2icroso"t Corporation CHH< CHHK. &ll ri#hts %eserved. Step 7:-0lace this compiled pro-! class in the dll o" the +eb Site "rom where !ou want to access the +eb Service. 7S-!+ H : a +sdl.e-e contains onl! one reDuired parameter, a >%3 or path to the +S'3 "or the +eb service. (he "ollowin# optional parameters can be speci"ied: a /lan#ua#e: language T speci"ies what lan#ua#e the 0ro-! class should be created in (vb/cs/js). a /protocol: $rotocol T speci"ies the pa!load protocol to be used (S.&0, 6ttp5et, 6ttp0ost) a /namespace: names$ace T the namespace o" the #enerated 0ro-! class. a /out: filename T the "ilename o" the 0ro-! class. 'ro#y Class inclusion <. &dd the pro-! class to the newl! created +eb Site C. 5o to Solution )-plorer4 ri#ht clic, on that solution b clic, on @&dd %e"erenceA. Below pop up window appears

1. Clic,in# @.,A will include the pro-! class to the solution under @Bin "olderA.
C. Now we can use this pro-! class and the methods that are there in the web services. Note: & pro-! class is a class containin# all o" the methods and objects e-posed b! the +eb service. (hese methods handle the marshallin# o" the parameters into S.&0, sendin# the S.&0 rePuest over 6((0, receivin# the response "rom the +eb service, and unmarshallin# the return value. (he pro-! class allows the client pro#ram to call a +eb service as i" the +eb service was a local component. .nce !ou create a pro-! class usin# the .N)( command line toolwsdl.exe , a +eb service client ma! invo,e pro-! class methods, which communicate with a +eb service over the networ, b! processin# the S.&0 messa#es sent to and "rom the +eb service.

#ample: -emonstrate t%e Creation of 'ro#y Class and its ?sage usin# S!stem4 usin# S!stem.'ata4 usin# S!stem.Con"i#uration4 usin# S!stem.+eb4 usin# S!stem.+eb.Securit!4 usin# S!stem.+eb.>I4 usin# S!stem.+eb.>I.+ebControls4 usin# S!stem.+eb.>I.+ebControls.+eb0arts4 usin# S!stem.+eb.>I.6tmlControls4 public partial class F'e"ault : S!stem.+eb.>I. 0a#e 7 protected void 0a#eF3oad( object sender, )vent&r#s e) 7 = protected void btnCustomerFClic,( object sender, )vent&r#s e) 7 ///etchin# the Customer 'ata "rom the 0ro-! Class. tr! 7 Service objService G new Service ()4 t-tCustomer&#e.(e-t G objService.#et)mplo!ee&#e()4 t-tCustomerName.(e-t G objService.#et)mplo!eeName()4 = catch ( )-ception e-) 7 %esponse.+rite(e-.Source)4 = = = &utput:

Clic) (n t!e NCustomer 'ataO +utton:

Creating an H)! document (he .N)( #ives us "le-ibilit! to wor, with the 123 "iles easil!. .N)( provides "ollowin# "ive namespaces "or 123 manipulation.

1. System.Pml:- Contains major 123 classes.(his namespace contains man!


classes to read and write 123 documents.Some classes under this namespace are 1ml%eader, 1ml(e-t%eader, 1ml*alidatin#%eader, 1mlNode%eader, 1ml+riter, and 1ml(e-t+riter. System.Pml.Sc!ema:- Contains classes which wor, with 123 schemas. 1mlSchema, 1mlSchema&ll, 1mlSchema10ath, and 1mlSchema(!pe are the classes comes under this namespace.. System.Pml.SerialiBation:- Contains classes that are used to serialiEe objects into 123 "ormat documents or streams. System.Pml.P#at!:- Contains 10ath related classes to use 10ath speci"ications. 10ath'ocument, 10ath)-ression, 10athNavi#ator, and 10athNodeIterator classes comes under this namespace.. System.Pml.Psl :- Contains classes to wor, with 1S3( trans"ormations.

2. 3. 4. 5.

#ample: -emonstrate Creation of H)! -ocument usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 usin# S!stem.1ml4 namespace FCSharp&pplication 7 public partial class /orm<H : /orm 7 public /orm<H() 7

InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 1ml'ocument -mldoc4 1mlNode -mlnode4 1ml)lement -mlelem4 1ml)lement -mlelemC4 1ml)lement -mlelemD4 1ml(e-t -mlte-t4 -mldocG new 1ml'ocument ()4 //123 ')C3&%&(I.N S)C(I.N -mlnodeG-mldoc.CreateNode( 1mlNode(!pe .1ml'eclaration, "" , "" )4 -mldoc.&ppendChild(-mlnode)4 //S(&%(IN5 N.') -mlelemG-mldoc.Create)lement( "" ,t-t%oot.(e-t, "" )4 -mlte-tG-mldoc.Create(e-tNode(t-t%oot'esc.(e-t)4 -mlelem.&ppendChild(-mlte-t)4 -mldoc.&ppendChild(-mlelem)4 //&'' C6I3' )3)2)N( (. (6IS N.') -mlelemCG-mldoc.Create)lement( "" ,t-t/irstChild.(e-t, "" )4 -mlte-tG-mldoc.Create(e-tNode(t-t/irstChild'esc.(e-t)4 -mlelemC.&ppendChild(-mlte-t)4 -mldoc.ChildNodes.Item(<).&ppendChild(-mlelemC)4 //&'' C6I3' )3)2)N( (. (6IS N.') -mlelemD G -mldoc.Create)lement( "" ,t-tSecondChild.(e-t, "" )4 -mlte-t G -mldoc.Create(e-tNode(t-tSecondChild'esc.(e-t)4 -mlelemD.&ppendChild(-mlte-t)4 -mldoc.ChildNodes.Item(<).&ppendChild(-mlelemD)4 //S&*) (6) 123 '.C>2)N( IN & /I3) "C:MC%)&()123.123" tr! 7 -mldoc.Save( "c:MMC%)&()123'ocument.-ml" )4 = catch ( )-ception e-) 7 Console.+rite3ine(e-.Source)4 = 2essa#eBo-.Show( "???????????123 '.C>2)N( C%)&()'????????????" )4 =

= = (utput:

Clic)ing on t!e NCreate PML 'ocumentO after filling all t!e fiel s.

4enerate

PML files loo)s li)e:

8^-ml versionG"<.H" ^9 8%ootName9 8/irstChildName9 /irstChild'esc 8//irstChildName9 8SecondChildName9 SecondChild'esc 8/SecondChildName9 8/%ootName9 Reading H)! document in C s%arp (he 1ml%eader and 1ml(e-t%eader classes are de"ined in the S!stem.123 namespace.(he 1ml(e-t%eader class is derived "rom 1ml%eader class. (he 1ml(e-t%eader class can be used to read the 123 documents. (he read "unction o" this document reads the document until end o" its nodes. #ample: -he following exam$le will show how the %< $rogram will read the xml file. usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 usin# S!stem.1ml4 namespace FCSharp&pplication 7 public partial class /orm<< : /orm 7 public /orm<<() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 //%ead 123 'ocument

tr! 7 // .pen an 123 "ile : %ead &n! 123 that !ou have 1ml(e-t%eader reader G new 1ml(e-t%eader ( "C:MMC%)&()123'ocument.-ml" )4 while (reader.%ead()) 7 // 2ove to "irst element reader.2ove(o)lement()4 lst%ead123.Items.&dd( "1ml(e-t%eader 0roperties (est" )4 lst%ead123.Items.&dd( "GGGGGGGGGGGGGGGGGGG" )4 // %ead )lementOs 0roperties lst%ead123.Items.&dd( "Name:" $ reader.Name)4 lst%ead123.Items.&dd( "Base >%I:" $ reader.Base>%I)4 lst%ead123.Items.&dd( "3ocal Name:" $ reader.3ocalName)4 lst%ead123.Items.&dd( "&ttribute Count:" $ reader.&ttributeCount.(oStrin#())4 lst%ead123.Items.&dd( "'epth:" $reader.'epth.(oStrin#())4 lst%ead123.Items.&dd( "3ine Number:" $ reader.3ineNumber.(oStrin#())4 lst%ead123.Items.&dd( "Node (!pe:" $ reader.Node(!pe.(oStrin#())4 lst%ead123.Items.&dd( "&ttribute Count:" $ reader.*alue.(oStrin#())4 = = catch ( )-ception e-) 7 2essa#eBo- .Show ( ")-ception: 7H=" , e-.(oStrin#())4 = = = = (utput: $!e follo%ing screen %ill be program. isplaye %!en run t!e above

Clic)ing (n t!e A /ea

PML N button t!e follo%ing screen %ill be

isplaye .

?sing H)!7riter class to 7rite H)! document in C s%arp (he 1ml+riter class contains the "unctionalit! to write to 123 documents. 1ml+riter is an abstract base class and is a super class o" 1ml(e-t+riter and 1mlNode+riter

classes which are used to write the 123 documents. (his class has man! +rite111 methods to write paired, unpaired and empt! 123 elements. Some o" these methods are used in a start and end pair. /or e-ample, to write an element, !ou need to call +riteStart)lement then write a strin# "ollowed b! +rite)nd)lement. #ample: -emonstrate 7riting to H)! file usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 usin# S!stem.1ml4 namespace FCSharp&pplication 7 public partial class /orm<C : /orm 7 public /orm<C() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 //+ritin# 123 '.C>2)N( tr! 7 //C%)&() N)+ /I3) 1ml(e-t+riter -ml+%I()% G new 1ml(e-t+riter ( "C:MMwrite)mplo!ee%ecordIn123<.-ml" , null )4 //.0)N '.C>2)N( /.% +%I(IN5 -ml+%I()%.+riteStart'ocument()4 //+%I() C.22)N(S -ml+%I()%.+riteComment( "Commentss: S(&%( '&() : C< .C( HS" )4 -ml+%I()%.+riteComment( "Commentss: +%I() 123 '.C>2)N(" )4 //+%I() /I%S( )3)2)N( -ml+%I()%.+riteStart)lement( ")203.W))" )4 -ml+%I()%.+riteStart)lement( "r" , "%)C.%'" , "urn:record" )4 //+%I() N)1( )3)2)N(

-ml+%I()%.+riteStart)lement( ")203.W)) N&2)" , "" )4 -ml+%I()%.+riteStrin#(t-tName.(e-t)4 -ml+%I()%.+rite)nd)lement()4 //+%I() &N.(6)% )3)2)N( -ml+%I()%.+riteStart)lement( ")203.W)) &''%)SS" , "" )4 -ml+%I()%.+riteStrin#(t-t&ddress.(e-t)4 -ml+%I()%.+rite)nd)lement()4 //+%I() &N.(6)% )3)2)N( -ml+%I()%.+riteStart)lement( ")203.W)) 'ate ." Birth" , "" )4 -ml+%I()%.+riteStrin#(t-t'.B.(e-t)4 -ml+%I()%.+rite)nd)lement()4 //+%I() &N.(6)% )3)2)N( -ml+%I()%.+riteStart)lement( ")203.W)) \uali"ication" ,"" )4 -ml+%I()%.+riteStrin#(t-t\ual.(e-t)4 -ml+%I()%.+rite)nd)lement()4 //+%I() C6&%&C()%S char :; ch G new char :D;4 ch:H; G O1O 4 ch:<; G O2O 4 ch:C; G O3O 4 -ml+%I()%.+riteStart)lement( "+%I(IN5 C6&%&C()% IN 123 '.C>2)N(" )4 -ml+%I()%.+riteChars(ch, H, ch.3en#th)4 -ml+%I()%.+rite)nd)lement()4 // )N' ./ '.C>2)N( -ml+%I()%.+rite)nd'ocument()4 // C3.S) +%I()% -ml+%I()%.Close()4 2essa#eBo-.Show( "?????????'.N)???????????" )4 = catch ( )-ception e-) 7 2essa#eBo- .Show(e-.Source)4 = = ==

%licking on the G.riting 456 ,ocumentH

(his will #enerate a 1ml "ile that contains the contents as #iven below: L$rite mployeeRecordInH)!+#mlM 8^-ml versionG"<.H"^9 8Z Commentss: S(&%( '&() : C< .C( HS 9 8Z Commentss: +%I() 123 '.C>2)N( 9 8)203.W))9 8r:%)C.%' -mlns:rG"urn:record"9 8)203.W)) N&2)9`oseph8/)203.W)) N&2)9 8)203.W)) &''%)SS9(err!8/)203.W)) &''%)SS9 8)203.W)) 'ate ." Birth9<S S <XV<8/)203.W)) 'ate ." Birth9 8)203.W)) \uali"ication92B&8/)203.W)) \uali"ication9 8+%I(IN5 C6&%&C()% IN 123 '.C>2)N(91238/+%I(IN5 C6&%&C()% IN 123 '.C>2)N(9 8/r:%)C.%'9 8/)203.W))9 Assem"ly Information : Getting 'ermission set of t%e assem"ly (he basics o" C&S is whenever an! code is bein# e-ecuted in mana#ed world the .N)( runtime veri"ies whether that code is allowed or not based on evidence and set o" permissions. (wo important thin#s that are ver! much importance to the "ramewor, is: &vi ence:- /rom where the code comes^ Is the code mana#ed or unmana#ed. #ermissions:- (he permission set on which the code e-ecutes. 'ermissions and 'ermission Sets 0ermission is what a code can do with particular resource li,e /ile, %e#istr! etc., and 0ermission Set is collection o" permission. 'olicy !evels N)( S!stem comes up with J 0olicies that are )nterprise , 2achine >ser, and &pp'omain (which can be done throu#h pro#rammaticall!). )ach polic! has multiple code #roups and multiple permission sets.(he! have the hierarch! #iven below.

Enter$rise ' 1ll managed code in an enter$rise setting.

5achine' 1ll managed code on the com$uter. Aser' %ode in all $rocesses associated with the current user. 1$$lication ,omain' 5anaged code in the hostEs a$$lication domain. &"ample:- $o get t!e permission set of Current Assembly. Form.B+cs usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 usin# S!stem.(hreadin#4 usin# S!stem.'ia#nostics4 usin# S!stem.%e"lection4 usin# S!stem.Securit!4 usin# S!stem.Securit!.0olic!4 usin# S!stem.Securit!.0ermissions4 usin# S!stem.Collections4 namespace FCSharp&pplication 7 public partial class /orm<D : /orm 7 //N&2) ./ (6) B>I3'FIN N&2)' 0)%2ISSI.N S)( /.% />33(%>S(. const strin# s/ull(rust G "/ull(rust" 4 static 0ermissionSet "inalSet G new Named0ermissionSet ( "/inal&ssembl!Set" )4 static 0ermissionSet permSet G null 4 ///IN' .>( +6)(6)% (6IS &SS)2B3W IS />33(%>S( 0)%2ISSI.NS. static bool "ull(rust G true 4 public /orm<D() 7 InitialiEeComponent()4 = private void /orm<DF3oad( object sender, )vent&r#s e) 7 = ///I5>%) .>( (6) C.')5%.>0 &N' (6) 0.3ICW 3)*)3 ./ (6) &SS)2B3W.

static bool is%es5roups( Code5roup Fcode5roupparent, 0olic!3evel Fpolic!3evel) 7 Named0ermissionSet Fnamed0ermissionSet G Fpolic!3evel.5etNamed0ermissionSet( Fcode5roupparent.0ermissionSetName)4 i" (is/ull(rust(Fnamed0ermissionSet)) return true 4 i" (permSet GG null ) permSet G ( 0ermissionSet )Fnamed0ermissionSet4 else permSet G permSet.>nion(Fnamed0ermissionSet)4 i" (Fcode5roupparent.Children.Count 9 H) 7 "oreach ( Code5roup cp in Fcode5roupparent.Children) 7 i" (cp.Children.Count 9 H) is%es5roups(cp, Fpolic!3evel)4 else 7 Named0ermissionSet npsC G Fpolic!3evel.5etNamed0ermissionSet( cp.0ermissionSetName)4 i" (is/ull(rust(npsC)) return true 4 permSet G permSet.>nion(npsC)4 = = = ///>33 (%>S( C.') N.( /.>N' return "alse 4 = //C6)CU +6)(6)% (6) 0)%2ISSI.N S)( I/ />33(%>S( .% N.( /.% (6) C>%%)N( &SS)2B3W. static bool is/ull(rust( Named0ermissionSet Fnamed0ermissionSet) 7 i" (Fnamed0ermissionSet.Name.)Puals( "/ull(rust" )) return true 4 return "alse 4 = //0&SS (6) 0)%2ISSI.N S)( &N' 3IS(B.1 &S &%5>2)N( (. (6) />NC(I.N. static void #et.utput( 0ermissionSet FpermissionSet, 3istBo- FlistBo-) 7 I)numerator ps)numerator G FpermissionSet.5et)numerator()4

while (ps)numerator.2oveNe-t()) FlistBo-.Items.&dd(ps)numerator.Current)4 = private void button<FClic,( object sender, )vent&r#s e) 7 ///etchin# the 0ermission Set o" the &ssembl! lst0ermission.Items.&dd( "3ist o" permissions assi#n to current assembl!" )4 I)numerator polic! G Securit!2ana#er .0olic!6ierarch!()4 while (polic!.2oveNe-t()) 7 0olic!3evel current3evel G ( 0olic!3evel )polic!.Current4 Code5roup #roup Gcurrent3evel.%esolve2atchin#Code5roups ( &ssembl! .5et)-ecutin#&ssembl!().)vidence)4 "ull(rust IG is%es5roups(#roup, current3evel)4 i" (Z"ull(rust) 7 i" ("inalSet GG null ) "inalSet G permSet4 else "inalSet G "inalSet.Intersect(permSet)4 permSet G null 4 = else 7 lst0ermission.Items.&dd( "Current 3evel " $current3evel.3abel $ " cc " $ "5roup " $ #roup.Name $ " cc " $ "5roup 0olic! " $ #roup.0ermissionSetName)4 = = i" ("ull(rust) lbl2ode.(e-t G "&ssembl! is runnin# in "ull trust mode." 4 else #et.utput("inalSet, lst0ermission)4 = = = &utput:

Clic,in# on the @&ssembl! In"ormationA button.

Creating your o$n 'ermission Set >ser can also create their own permission sets and code #roups in the C#. (he "ollowin# are the steps needs to "ollow to create !our own permission sets and code #roups: Steps to create your o$n permission set and Code group <. 5o to Control 0anel 9 &dministrative (ools 9 2icroso"t .N)( /ramewor, C.H Con"i#uration b 'ouble clic, on this a popup windows appear

C. Creatin# a new 0ermission Set b )-pand @%untime Securit! 0olic!A. (here are D securit! polic! levels i.e. )nterprise , 2achine and >ser. +e are creatin# the permission set "or the machine securit! level.

D. &ssi#n the permission to the permission set: )ach permission set is a collection o" much di""erent permission to various resources on the computer. Select the permission that !ou need in the permission set.

J. 6ere I am selectin# the @/ile I.A permission "rom the pool o" permission set. &nd then chan#e the settin#s "or this permission. 6ere speci"! the @C:MA in the "ile path and assi#n onl! readin# permission to this.

K. 6ere we assi#n D permission to the newl! create permission set i.e. /ile I., Securit! and >ser Inter"ace.

Create Ce$ Code Group Create new code #roup and assi#n the permission that !ou create to this code #roup so that !our assembl! will wor, under the speci"ied permission set. %i#ht clic, on the &llFCode node and this will open a pop up window i.e. Create Code 5roup wiEard. Speci"! the name "or !our code #roup.

6. C!oose a con ition type for t!e co e group: (he membership condition determines whether or not an assembl! meets speci"ic rePuirements to #et the permission associated with a code #roup. Condition t!pe in the speci"ied conte-t: Stron# Name. Wou have to just clic, on the Import button b Select the assembl! "rom the pop up and this will e-tract the in"ormation that we needed.

2. Assign a #ermission Set to t!e co e group: 6ere throu#h this window we can assi#n the permission set to this code #roup that we are #oin# to create. Select the permission set that we created earlier. (hou#h this window either we can create new permission set or reuse the e-istin# one.

7. 4o t!roug! t!e properties of t!e ne%ly create

Co e 4roup

%i#ht clic, on the code #roup that !ou just created and !ou can view the @Code 5roup A properties li,e the Code 5roup Name, its membership conditions and permission set that is associated to it.

Create an Application: (hat will per"orm read and write operations on "ile. usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 usin# S!stem.I.4 namespace winCreatin#0S)( 7 public partial class /orm< : /orm 7 public /orm<() 7 InitialiEeComponent()4 = private void buttonCFClic,( object sender, )vent&r#s e) 7 //+ritin# to the 'ocument Stream+riter Fstream+riter G new Stream+riter ( "c:MM(est0ermission.t-t" )4 Fstream+riter.+rite3ine( " Securit! is Important" )4 Fstream+riter.+rite3ine( " Securit! can provide &uthentication " )4 Fstream+riter.Close()4 = private void button<FClic,( object sender, )vent&r#s e) 7 //%eadin# "rom the 'ocument

Stream%eader Fstream+riter G new Stream%eader ( "c:MM(est0ermission.t-t" )4 lst0S)(.Items.&dd(Fstream+riter.%ead3ine())4 lst0S)(.Items.&dd(Fstream+riter.%ead3ine())4 Fstream+riter.Close()4 = = = (utput: 8ow run the a$$lication and tr# to click on the GwriteH button the screen, this will gi e #ou following exce$tion.'/

?sing C s%arp Soc3et (he S!stem.Net.Soc,ets namespace contains the classes that provide the actual .N)( inter"ace to the low level +insoc, &0Is. (his section #ives a brie" overview o" the C# Soc,et class. (he core o" the S!stem.Net.Soc,ets namespace is the Soc,et class. It provides the C# mana#ed code implementation o" the +insoc, &0I. (he Soc,et class constructor is as "ollows: Soc,et(&ddress/amil! af , Soc,et(!pe st , 0rotocol(!pe $t ) &s !ou can see, the basic "ormat o" the Soc,et constructor mimics the ori#inal >nisoc,et() "unction. It uses three parameters to de"ine the t!pe o" soc,et to create: &n 1ddress;amil# to de"ine the networ, t!pe & Socket-#$e to de"ine the t!pe o" data connection & 3rotocol-#$e to de"ine a speci"ic networ, protocol )ach o" these parameters is represented b! a separate enumeration within the S!stem.NetF.Soc,ets namespace. )ach enumeration contains the values that can be used. /or normal I0 communications on networ,s, the &ddress/amil!.InterNetwor, value should alwa!s be used "or the &ddress/amil!. +ith the Inter8etwork 1ddress;amil#, the Socket-#$e parameter must match a particular 3rotocol-#$eparameter. Wou are not allowed to mi- and match Socket-#$esand 3rotocol-#$es. Soc3et 'roperties: Several properties o" the Soc,et class can be used to retrieve in"ormation "rom a created Soc,et object -escription 'roperty

&ddress/amil!

5ets the address "amil! o" the Soc,et

Bloc,in#

5ets or sets whether the Soc,et is in bloc,in# mode

3ocal)nd0oint

5ets the local )nd0oint object "or the Soc,et

Connected

5ets a value that indicates i" the Soc,et is connected to a remote device

%emote)nd0oint

5ets the remote )nd0oint in"ormation "or the Soc,et

Soc,et(!pe

5ets the t!pe o" the Soc,et

6andle

5ets the operatin# s!stem handle "or the Soc,et

0rotocol(!pe

5ets the protocol t!pe o" the Soc,et

&vailable

5ets the amount o" data that is read! to be read

*ntro uction to Soc)et &"ceptions: .ne "eature o" soc,et pro#rammin# included in .N)( /ramewor, is neither used b! >ni- nor the +insoc, &0I is socket exce$tions. &ll o" the Soc,et class methods use the Soc,et)-ception e-ception. &n! soc,et pro#rammin# !ou do should alwa!s chec, "or Soc,et)-ception e-ceptions and then attempt to recover "rom the error, or at least warn the user o" the problem. &"ample: 'emonstrate Soc)et #roperties an usin# S!stem4 usin# S!stem.Collections.5eneric4 usin# S!stem.Component2odel4 usin# S!stem.'ata4 usin# S!stem.'rawin#4 usin# S!stem.(e-t4 usin# S!stem.+indows./orms4 Soc)et &"ception .an ling

usin# S!stem.Net4 usin# S!stem.Net.Soc,ets4 namespace FCSharp&pplication 7 public partial class /ormK : /orm 7 public /ormK() 7 InitialiEeComponent()4 = private void button<FClic,( object sender, )vent&r#s e) 7 // 'emonstrate Soc,et 0roperties I0&ddress Fip&ddress G I0&ddress .0arse( "<CS.H.H.<" )4 I0)nd0oint Fip)nd0oint G new I0)nd0oint (Fip&ddress, VHHH)4 Soc,et Fsoc,et(est G new Soc,et ( &ddress/amil! .InterNetwor,, Soc,et(!pe .Stream, 0rotocol(!pe .(cp)4 lstSoc,et0roperties.Items.&dd( "&ddress/amil! :: " $ Fsoc,et(est.&ddress/amil!)4 lstSoc,et0roperties.Items.&dd( "Soc,et(!pe :: " $ Fsoc,et(est.Soc,et(!pe)4 lstSoc,et0roperties.Items.&dd( "0rotocol(!pe :: " $ Fsoc,et(est.0rotocol(!pe)4 lstSoc,et0roperties.Items.&dd( "Bloc,in# :: " $Fsoc,et(est.Bloc,in#)4 Fsoc,et(est.Bloc,in# G "alse 4 lstSoc,et0roperties.Items.&dd( "new Bloc,in# :: " $ Fsoc,et(est.Bloc,in#)4 lstSoc,et0roperties.Items.&dd( "Connected :: " $ Fsoc,et(est.Connected)4 Fsoc,et(est.Bind(Fip)nd0oint)4 I0)nd0oint FnewIp)nd0oint G ( I0)nd0oint )Fsoc,et(est.3ocal)nd0oint4 lstSoc,et0roperties.Items.&dd( "3ocal )nd0oint :: " $ FnewIp)nd0oint.(oStrin#())4 Fsoc,et(est.Close()4 = private void buttonCFClic,( object sender, )vent&r#s e) 7 //Soc,et )-ceptions I0&ddress FhostI0&ddress G I0&ddress .0arse( "<XC.<RV.<.<" )4 I0)nd0oint FhostI0)nd0oint G new I0)nd0oint (FhostI0&ddress, VHHH)4 Soc,et Fsoc,et G new Soc,et ( &ddress/amil! .InterNetwor,, Soc,et(!pe .Stream, 0rotocol(!pe .(cp)4 tr! 7

Fsoc,et.Connect(FhostI0)nd0oint)4 = catch ( Soc,et)-ception e<) 7 lstSoc,et)-ceptions.Items.&dd( "0roblem Connectin# (o 6ost ........" )4 lstSoc,et)-ceptions.Items.&dd(e<.(oStrin#())4 Fsoc,et.Close()4 return 4 = tr! 7 Fsoc,et.Send( )ncodin# .&SCII.5etB!tes( "testin#" ))4 = catch ( Soc,et)-ception e-) 7 lstSoc,et)-ceptions.Items.&dd( "0roblem Sendin# 'ata" )4 lstSoc,et)-ceptions.Items.&dd(e-.(oStrin#())4 Fsoc,et.Close()4 return 4 = Fsoc,et.Close()4 = = = (utput:

Clic)ing (n bot! t!e +uttons %ill listbo"

isplay t!e respective outputs in t!e

Das könnte Ihnen auch gefallen