You are on page 1of 141

.

NET Technology: It is a platform or a collection of many small technologies gives integrated as single long technology such that very powerful application can be developed and can be used any time any where.
C# VB.Net VC++.Net Java.Net

CSC

VBC

CL

MJAVAC

Common Language Specification [CLS]

Common Type System [CTS]

Windows Forms

ASP. Net

Web Form

Web Services

Forms

Data Base ADO.NE T

XML

Base Class Library [BCL]

Common Language Runtime [CLR]

Visual Studio.Net

Common Language Specification [CLS]: It is a set of rules or specification which is used to active language interoperability. Language interoperability in which the code written in one language from the application presented in other language.

Before.NET: C Source Code


Compile We Get

COM

VB 6.0Source
Compile We Get

OBJ file exe/.DLL Linker + Definition We get .DLL File Pseudo code
M2 Format

Draw Backs: DLL Hell Versioning

Using .NET:
C# Source Compile We get EXE EXE IL DLL DLL VB.Net Source

Assembly

IL

Code MSIL Format MSIL

M/S Intermediate Language

It is not mandatory for any language to support IL complete specification provided by CLS. 2

Common Type System [CTS]: It is collections of data type definition provided by the .NET frame work which can be by any long that .NET target the .NET technology. It is mandatory that all the entire long has to support the common type system definition.

Windows Forms: It is for designing a desktop application ASP.NET: It is a technology which is used for designing web forms with services and mobile files. 1. Web Forms: It is used for designing web. 2. Web Services: It is a class definition which will be maintained on the web server as a services such that the definitions can be used by any application developed using any languages for any platform or device. 3. Mobile Form: It is used for designing device independent applications.

ADO.NET It is a technology which is used by all the .NET languages to interact with any Data Base or XML documents. Base Class Library: It is a richest of class library definitions provided by the .NET technology that can be used by any language targeting the .NET technology. Common Language Runtime: It is a collection of recourses which is used for executing a .NET assemble with in the .NET environment. First.C

First.exe Executable File I/O

C#
First.CS

CSCfirst.cs

First.exe IL/Assemble

CLR

O/P

Executable File

Meta Data

Code [Machine Dependent]

X86 Inst.set

Meta Data: It maintains the information about the header files that are used with in the application. Code: The code present with in the executable file will be the native code of operating system.

X86 Inst Set: It maintains the information about the platform in which executable file can be executed. Assembly: To compile source code of a .NET application is called as an assembly is of two types: 1. Assembly with Entry point. [Application.exe] 2. Assembly without entry point [class library.dll]

Assembly
P E W R A P P E R

Meta Data Code [MSIL] Machine Independent

CLR

O/P

Resources

Manifest

Meta Data: Meta data maintains the information about the class library and return base class library and dependents files information. First.cs

CL

BCL

Code: The compiled source code of the .NET assembly will be I the format of MSIL instructor and these instructor are machine independent format and hence other than .NET frame work the code cant be used else where. Resource: Whenever .NET assembly uses any images, icons, cursors, audio, or video file or any calculator specific info etc., then theses details will be maintained at resource section of an assembly.

Main Test
First.cs First.exe Author Company name Description

It provides the details about the assembly attributes same as author company version of the assembly product name etc., Common Language Runtime [CLR]: It is a collection of resource which is used to execute a .NET assemble with in the .NET environment.

Base Class Library Support

Type Definitions Debug Manager Thread Support IL to Native JIL Compilation JIT Just In Time

Common Sharing Exception Manager Security Engine Code Manager Garbage Collector

Base Class Library Support: It is reused to load that class definations on the memory based on the information present with in the meta data of an assembly Type of Defination: It is used to map the data types use withy in the application with the data types use with in the application with the data type provided by the common type system. CLR First.cs
int i

type.def System.Int32 [CTS Data Type]

COM Marchaling Resource. It is a resource used by the CLR in order to provide relevant wrappers whenever COM interoperability takes place where can interop means 1. Using COM Components With in .NET Assembly.

COM component

.Net assembly

2. Using .NET Assembly with in COM type Applications.

.Net Assembly

COM type Application

Debug Manager: It is a resource which is used to invoke the debugger whenever any run type error are raised

Exception Manager: It is a resource used by the CLR Inorder to handled the runtime. Error is the exception handling blocks are defined If the exception handling blocks are not defined then resources is used to terminated the process of the application.

Thread Support: Whenever the application is multithread apartment [MTA Thread] application then this resource is used to provide the requirement information to the operating system in order to process the required. Security Engine: It is reused to provide the permisition form the code in order to access the resource of the system. IL to Native: It is a just in time compilation process performed by the CLR in order to generated the native code of the operating system. .NET technology supports two types of just in type compilers. 1. Standard JIT 2. Econo JIT

Code Manager: It is a resource which is used manager the entire code present with in the assembly. Garbage Collector: It is a resource which is used to remove the resources occupied by the unused object on periodical bases.

C#
C++ It is a pure object oriented language VB 6.0 It is an object based programming Java It is a pure object oriented programming language Pointers arent supported It is not component oriented language Interfaces, Multithreading globalization etc are supported Operator over loading is not supported C# It is a pure object oriented programming language. Supports pointers in unsafe mode. It is a component oriented language. Interfaces, Multithreading globalization etc are supported Operator over loading is supported

It supports pointers

Pointers arent support It is a component oriented language. Interfaces, Multithreading globalization etc are supported Operator over loading is not supported

It is not component oriented language. Interfaces, Multithreading globalization etc are not supported Operator over loading is supported

A single language with all the best features and the component oriented is required, in this language greater features all the latest languages such as C++, VB and Java. C# v/s Java. C# is having all the best features of Java. The following features are supported by C# which are not supported by Java. C# support more prematative data type when compare to java. C# considers the data types as a prematative and allocates the memory efficiently where as a java considers all the data types as object and more utilized. Pointers and operators loading are supporting by C# which are not supporting by java. C# supporting jacked arrays which are not supporting by Java. C# supports automatic XML documentation for the application which are not supported by java.

It is a language which is designed based on the test features of all the greatest language such as VB, C++, and Java etc., Types of Applications: That can be developed using C#. Desktop Applications or Client Server Applications: 1. 2. 3. 4. Console Application. Windows Application Windows Control Library. Windows Services.

ASP.NET Technology: 1. 2. 3. 4. ASP.NET Web Applications ASP.NET Web Services. ASP.NET Mobile Application Web Control Library.

Requirements: Operating System WinNT 4.0 Win 2000 Win XP Win 2003

Service Pack 6 4 2 -

.Net Frame Work

Console Application: Whenever the user accepts the input from the console and project the output on the console then such type of application are called as console applications. Structure of Console Application: Class <class name> { Public Static void Main() { //Statement(s) } }

10

C# is the case sensitive and line sensitive language The main method in C# can return either void or an integer in java it must be void only The command line arguments declaration with in the main method in optional in C#. .Net Frame Work: .Net Frame work contains base class libraries common language run time and different long compilers. .Net Platform

.Net Framework

.Net Products

.Net Services

IIS (Internet Intermediate Services): Web services are nothing but a service presented on the web server. Web services are reusable and platform independent In .Net 1.1 visual basic.Net doesnt support unsigned data type but in .Net 2.0 VB.Net also support unsigned data types.

Name Space: Is nothing but the logical container for subname space and set of related classes. System [Base Name Space/Root Name Space] Console Application [Class Name]

To Project Write() WriteLine()

To Accept Read() ReadLine()

Write(): It is used to project the information on the console WriteLine(): It is used to project the information on the console by appending new line character at the end of the string Read(): It is used to read a single character from the console ReadLine(): It is used to accept the input from the console till the user clicks the enter key

11

To Design C# console application using VS.NET IDE: Start Run devenv New Projects

Project Type Visual C# Projects Templates Console Application.

12

class firstprogram { public static void Main() { System.Console.WriteLine("Welcome to C# Project"); } } Execution: Project [Menu] <File name> Properties

13

Then press APPLY next press OK

14

Compile Time Phase: Compile Time Phase: First Program.CS CSC First Program .CS First Program.exe [ILR Assembly] BCL Trege ted Pre JIT Class Loader JIT Compiler Native Code of O/S Security check O/P Access Define Runtime Phase Common Language Runtime [CLR]

The code return with in the C# application can be cartridge into following

Managed Safe Code: Whenever a .NET application has been defined without using the pointers then it is said to managed safe code. Managed Unsafe Code: Whenever a C# application uses pointers on if any instruction are return with in the unsafe block then it is said to be managed unsafe code. Unmanaged Code: Whenever the C# application uses the definations of the COM component then it is said to be unmanaged code. Declaration Variables in C#: Syntax: [modifier] data type variable[=value];

15

Tools and Compilers: .Net frame work contains set of tools for configuration and different on compilers (VB.Net compilers, C#.Net compilers etc)
VB.Net App B C L
Compiler

C#.Net App

Compiler

-----------------------------MSIL --------------------------

C L R

Execute here

VC++.Net App

Compiler

exe/dll

Modifier: it is used specified the access controls for accessing the members of the class.

Modifiers

with in the same class

Derived class Other class X X X

public private[default] protect internal protected internal Data Type:

Other class of other assembly X X X

Derived class of other assembly X X X

Same Program

X Other Program

It is used to specify the value that can be assigned to the variables. Different Data Types: Byte 1 byte Bool 2 bytes Short 2 bytes Int 4 bytes Long 8 bytes Float 4 bytes Double 8 bytes Char 2 bytes String No fixed size Date 8 bytes Decimal 16 bytes 16

Object Ushort Uint Ulong

4 bytes unsigned only for Positive values unsigned only for Positive values unsigned only for Positive values

.NET technology support two types of data types 1. Value by data type. 2. Reference type data type Value Type Data Type When ever a data type has been derived from structure then it is said to be value type data type If a variable has been defined for a value type data type then the variable info and the value will be maintained with in the stack memory Ex int i=10 i 10 Reference Type Data Type Whenever a data type has been derived from a class definitions then it is said to be reference type data type. If a variable has been defined for the reference type data type then the variable information maintained within the stack memory and the value will be maintained with in the heap memory. Ex String s=C#.Net S H10 5 C#.Net H105

Stack Memory Heap Memory Value type data type members doesnt Inheritance is supported by Reference type data type. support inheritance The variable defined for Value type data The default value for the Reference type data type is null value. type will be have a default value. Eg: integer variable int i=0; The memory allocated for the Value type The memory allocated for the reference type members will be released implicitly by data type to be explicitly released the garbage collector on the periodical bases. Value type data type are byte, unbyte, int, Reference type data type object string, Data vint, float, double, character, Boolean, etc., time, enum, class, interface delegate

S 103 Stack Memory

17

Boxing: When ever a value type member has been assigned to the reference type member then it is said to be boxing. Boxing will be performed implicitly. class boxingdemo { public static void Main() { int i=10; object o; o=i; //Boxing System.Console.WriteLine(o.ToString()); } }

In order to convert any object or member as a string then

Syntax: Variable.ToString() Or ObjectName.ToString() UnBoxing: Whenever a reference type member has been assigned to the value type member then it is said to be unboxing. Unboxing has to be performed explicitly Syntax: Variable=(Type)ObjectName; class unboxingdemo { public static void Main() { object o=10; int i; i=(int)o; //Unboxing System.Console.WriteLine(i.ToString()); } } 18

Type Casting: Whenever a lower range data type value as to be converted as a upper range data type value then type casting is used. Eg: converting an integer to a float value. Syntax: variable=(Type) variable; In order to refer the class members present with in the name space directly. To Do: Using Namespace Name; -----------Class Name Members(---); Place Holders: Whenever a value has to be substituted with in a string then place holders should be used. Syntax: {index[:format]} The index value will always starts with O for all the every new statement.

Format to Support Numeric Values: D Projects the value in decimal format. C Projects the value in Currency format. S Projects the value in Scientific notation. E Projects the value in Exponentiation notation P Projects the value in percentiles notation. Format Date Time: D Extracts the long date as string. T Extracts the time value from date time. Formats for String: Syntax: {index, size} If the size is the positive value the text will ne left align the size is the negative value the text will be right align.

19

Here we Give the Class Name.

using System; class employee { public int eno; public string ename; public float sal; 20

public DateTime hiredate; } class company { public static void Main() { employee e=new employee(); Console.Write("Enter Employee No:"); e.eno=int.Parse (Console.ReadLine()); Console.Write("Enter Employee Name:"); e.ename=Console.ReadLine(); Console.Write("Enter Employee Salary:"); e.sal=float.Parse (Console.ReadLine()); Console.Write("Enter Employee Hire Date:"); e.hiredate=DateTime.Parse (Console.ReadLine()); Console.WriteLine (" Number:{0}\n Name:{1}\n Salary:{2:c}\n Hire Date:{3:d}", e.eno, e.ename, e.sal, e.hiredate); } }

Class: It is used to defined a user defined reference type data type with the members. Syntax:[modifier]class <class name> { //member(s); } The members of the class is of two types 1. Static Members. 2. Non-Static Members [Default]

Static Members: These members will be binded to the class defination. Static members will be located on the memory. Whenever the class defination has been loaded on the memory. In order to refer the static member it is mandatory to refer using the class definition only. Static members will be shared among all the objects defined for the class.

Non Static Members: These members are binded to the objects defined for the classes. Non static should be refered using the object reference only

21

Object: Objects occupy the physical memory not the class defination. Objects are always isolated i.e the value assigned for one object members will not be reflected for other object members. Objects are always a non static members and hence the static members cant be accessed using the object reference.

Syntax: Class Name Object Name = new Class Name([--]); Or Class Name Object Name; Object Name=New Class Name([----]); using System; class test { public int ns; // Non Static members public static int s; // Static Memebrs } class usetest { public static void Main() { test t=new test(); t.ns=100; // t.s=200;Error test.s=300; Console.WriteLine("{0},{1}",t.ns,test.s); } } Constructors: It is used to initialize the members of the class If the class is not defination with any constructor the CLR will provide a constructor which is called as default constructor. Constructor is of two types. 1. Static Constructor 2. Non Static Constructor.

Static Constructor: It is used to initialize the static members present with in the class defination. A class defination can have zero or only on e static constructor.

22

Static constructor will be invoked once whenever the class defination loaded on the memory i.e. static constructor will be invoked before the creation of first object. Modifiers should not be used for the static constructor. Static constructor cant accept any parameters.

Syntax: Static ClassName { //initialization statements. } Non Static Constructors: These constructors are used to initialize the non static and the static members of the class. A class can be defined with any number of non static constructor. Non static constructor will be invoked for every new object defined for the class.

Syntax: Modifier ClassName([argInfo]) { //initialization statements. }

using System; class test { public int ns; public static int s; static test(); //ns=100; error; s = 200; public test() { ns=1000; s=2000; } }

class constructordemo { public static void main() { 23

Console.WriteLine ("{0}",test.s); test t=new test(); Console.WriteLine ("{0},{1}",t.ns,test.s); } }

Test t1=new test()

Test ns //non static s //static Public Test() { ns=1000; s=2000; }

Test t2=new test()

t1()[object] ns=1000 S=2000

t2()[object] ns=1000

Whenever the value for the static members has been assigned with constant value with in a non static constructor then for every new object defined for the class the value will be re initialized with same value and hence whenever a constant value has to be initialized for the static members static constructor should be used. Whenever the value for the static members has to be reinitialized with new value for every new object defination for a class then it is advisable to initialize the static members with in the non static constructor.

24

Control Statements: It is used to control the flow of the applications. 1. if Statement: Syntax: if(Condition) { Statements } else { Statements } 2. Switch Statements: Syntax: swith(expression) { case expression1: statements; break; case expression2: statements; break; case expression3: statements; break; default: statements; break; } 3. While loop Syntax: while (condition) { //Statements }

25

4. Do - While loop: Syntax: do { Statements; } while(condition); 5. For loop: Syntax: for(initialization; condition; increment/decrement) { Statements; } 6. For each loop: Syntax: Foreach(variable in collection) { Statements } Method: It is used to modularize the flow of the application. Advantages: Easy debugging Reusability Performance will be improved. Syntax: modifier return DataType method Name([argInfo]) { Statements; } If a function doesnt return in any data type value than the return data type should be defined using void data type. argInfo for any method should be defined using the following Syntax: [mode] Datatype variable

26

The mode for the method argument can be three types. 1. Call by value. 2. Call by reference. 3. Out mode.

C# language doesnt support optional arguments on parameters. In to support optional parameters in C# method overloading should be used. Call By Value: Whenever an argument is passed by call by value mode argument then the value will be passed to the called all the method call by value. If any modifications are performed on the argument with in the called method then the value will not be reflected on the caller.

CALLER
Public static void Main() { int a=10; Display(a); Console.WriteLine({0}a); }

CALLED
Public void Display (int a) { a=100; Console.WriteLine({0}a); }

student

Set Data(rno,name, m,p,c)


Display()

rno,m,p, c sname

Book This:

Get Result

It is a keyword it refers to current class object [In VB]

27

using System; class student { public int rno; public int m,p,c; public string sname; public void setdata(int rno, string name,int m, int p, int c) { this.rno=rno; this.sname=sname; this.m=m; this.p=p; this.c=c; } public void display() { System.Console.WriteLine("Roll Number:{0}\nStudent Name:{1}\nMaths:{2}\nPhysics{3}\nChemistry:{4}\n",rno, sname, m, p, c); } public bool getresult() { if(m>80&&p>80&&c>80) return true; else return false; } } class college { public static void Main() { student s1=new student(); s1.setdata(101,"Chakri",80,90,75 ); s1.display (); if(s1.getresult()==true) Console.WriteLine ("Result:Pass"); else Console.WriteLine("Result:Fail"); } }

28

Call By Reference: Whenever the reference of the member has to be passed from the caller to the called then called by reference mode argument should be used.

CALLER
int a=10; Set A(ref a); Console.WriteLine({0}a);

CALLED
Public void set A (ref int a) { a=100; }

10 0

10 0

Whenever the value for the called by reference mode argument has been modified with in the called method then the value will be reflected at the caller. Employee eno; ename; Salary; Employee (eno, ename,sal); float Get salary (ref sal,Days)

using System; class employee { public int empno; public string ename; private float sal; public employee(int eno,string ename,float sal); { empno=eno; this.ename=ename; this.sal=sal; } 29

public void Getsalary(ref float sal, int days) { Sal=sal*days; } } class company { public static void Main() { employrr e=new employee(101,"Pallavi",54500); Console.WriteLine("Employee No:{0}\nEmployee, Name:{1}\nSalary:{2:c}",e.empno,eename,e.salary); } }

Out mode Argument: It is used to pass the value from the called to the caller.
Out ModeA rgument

Caller

Called

using System; class inst { public int cid; public string cname; public float fees; public inst(int cid, string cname, float fees) { this.cid=cid; this.cname=cname; this.fees=fees; } public void director(out float fee, int discount) { fee=fees; fee=discount; } } 30

class institute { public static void Main() { inst course=new inst (101, "C#" 1800); float finalfees; course.cid rector(out finafees, 300); Console.WriteLine ("courseid:{o}\n Couse Name:{1}\n fees:{2:c}" course.cid, course.cname, final fees); } public void Ref Demo( ref int a) { a=100; } public static void Main() { int a=10; Ref Demo (ref a); Out Demo (out a); }

10 100

1000

public void out Demo(out int a) { a=100; }

} Property: It is used to set or get the value from the private or protected members of the class. Syntax: Public DataType Property Name { set { Variable=value; } get { Return variable; } } 31

A property can be either read only or write only read and write property. To define a read only property then only get block along should defined In order to define the write only property then set block along should defined. In the above syntax value is a key word which will maintain value provided by the user at the run time.

using System; class employee { public int empno; public string ename; private float sal; public employee(int eno,string ename,float sal); { empno=eno; this.ename=ename; this.sal=sal; } public float salary { get { return salary; } } } class company { public static void Main() { employrr e=new employee(101,"Pallavi",54500); Console.WriteLine("Employee No:{0}\nEmployee Name:{1}\nSalary:{2:c}",e.empno,eename,e.salary); } }

32

Indexer: It is used to refer the members of the class like array variable Syntax: Public DataType this [int position] { set { Variable=value; } get { return variable; } }

using System; class indexerclass { public string[] countries=new string[10]; public indexerclass() { for(int i=0;i<10;i++) countries[i]="Unkoown"; } public string this[int position] { set { countries[position]=value; } get { return countries[position]; } } } public class indexerdemo { public static void Main() { indexerclass ic=new indexerclass(); ic[2]="india"; ic[5]="USA"; ic[8]="UK"; 33

for(int i=0;i<10;i++) { Console.WriteLine("{0}",ic[i]); } } }

Object Oriented Programming Features:


Data Abstraction or Data Hiding: It is used to provide the relevant information to the users and used to inside the irrelevant information from the user. To Do: Modifiers are used.

Data Encapsulation or Binding: Identifiers the relevant information and to group the data together is called data encapsulation and binding. To Do: classes and structures are used. Polymorphism (Many forms): When ever an entity can change its definition based on the argument onto passed to that entity then it is said to be supporting polymorphism feature. To Do: overloading concept used. Whenever any language the above three features then the it is said to be object based programming language.

Inheritance:
It is used to reuse or redefine the existing class defination. C# supports only single or multi level inheritance for the class definitions. products Product ID Product Name Price (private) Public Property Price

34

using System; class product { public int productid; public string productname; private float price; public product(int pid,string pname,float price); { productid = pid; productname = pname; this.price=price; } public float Price { get { return Price } } } class company { public static void Main(); { product p1=new product(101,"LG",21000); p1.productnmae="LG Golden Eye 29\"TV" Console.WriteLine({0}\n{1}\n{2:c}";p1.productid, p1.productname,p1.price); } }

35

Single Inheritance: Grand Parent Base Class Parent ---------------------------

Derived Class

Children ---------------

Parent ------------------

Inherited Class Grand Children ---------------------------

Syntax: to inherit a class defination Class Derived class: Base Class { //Statements; }

The members defined using the public, protected internal and protected internal modifiers at the base class can be accessed directly from the derived class. Whenever an object is defined for the derived class the implicitly the base class constructor will always be invoked. If the base class is not defined with no-arguments constructor then if an object is defined for the derived class an error will be raised implicitly.

36

using System; class baseclass { public baseclass() { Console.WriteLine("Base class Constructor Called"); Console.WriteLine("Base class says"+name); } } class Derivedclass:Baseclass { public derivedclass(Chakri) { Console.WriteLine("Derived class constructor"); } } class Inheritancedemo1 { public static Main() { dc=new derivedclass(); } }

Constructor Call Constructor: Whenever the base class is not defined with no-arguments constructor and Inorder to invoke any constructor while defining an object for the derived class then constructor call constructor feature should be used. To Implement: modifier Derived Class ([argInfo]):base([argInfo]) { //statements. }

using System; class BaseClass { public Baseclass(string name) { Console.WriteLine("BaseClass Consstructor say hai:"+name); } } class DerivedClass:BaseClass { 37

public Derivedclass(string name):Base("Chakri") { Console.WriteLine("Derived Class" +name); } } class inheritance2 { public static void Main() { derivedclass dc=new derivedclass("Chakri"); } } using System; class calc { public int add(int a, int b) { return a+b; } public int sub(int a, int b) { return a-b; } } class scalc:calc { public double log10(double d) { return System.Math.Log10(d); } public void display(object o) { Console.WriteLine(o.ToString()); } } class inhertancedemo { public static void Main() { scalc sc=new scalc(); sc.display(sc.add(10,20)); sc.display(sc.sub(100,25)); sc.display(sc.log10(10)); } } 38

Method Overriding: Whenever a base class definition are modified at the derived class then it is said to be method overriding. Employee empno, ename sal Virtual Commission

inherits Clerk -------------

inherits sales man Commission { //---------}

Override

In order to redefined the method definition at the derived class then override keyword should be used it any method is defined using overriding key word at the derived class then it is mandatory that the method should be prefix with virtual keyword at the base class. If any method is developed using the virtual key word at the base class it isnt mandatory is to override the method definition at the derived class.

using System; class Employee { public int empno; public string ename; public virtual double sal; public double commission(double sal) { return sal*0.10; } }

39

class clerk: Employee { } class salesman:Employee { public override double commission(double sal) { return sal*0.25; } } class Company { public static void Main() { clerk c=new clerk(); c.empno=101; c.ename="Chakri"; Console.WriteLine("{0},{1},{2:c},{3:c}",c.empno,c.ename,c.sal, c.commission(c.sal)); s.empno=100; s.ename="Pramod"; s.sal=3500; Console.WriteLine("{0},{1},{2},{3}",s.empno,s.ename,s.sal, s.commission(s.sal)); } } Name Space: It is used to maintain the classes in a hierarchical manner such that the member of the class can be referred easily.
System [Root Namespace/Base Namespace]

Console [class] WriteLine()

IO [SubNamespace] StreamWriter[class] WriterLine()

Windows [Namespce] Forms [SubNamespace] Form [Class Name] ShowDialog()

Name space are also used to avoid class name collocations.

40

Source1.dll
public class c1 { Public void ok1() { // Statements; } }

Source2.dll
public class c1 { Public void ok2() { // Statements; } }

public static void Main() { c1 obj=new c1() } Syntax: namespace <Namespace name> { //namespace defination; //class defination } Whenever a name space is defined within another namespace then the inner namespace is said to be sub namespace. Sub namespace are used to defined the hierarchy within the namespace definition. There is no restriction on the level f defining the sub namespace definition. To refer the classes within the namespace namespaceHierarchy ClassName. To create an object for the class present with in the namespace namespaceHirearchy.ClassName Object = New namespaceHirearchy.ClassName(); in order to refer the classes present with in the namespace directly. using namespaceHirearchy --------------ClassName Object = New ClassName();

41

Interface: It is a collection of members without any definition. In order to use the members of the interface then it is mandatory that the interface has to be inherited by a class. The class which inherit the interface should provide the definition for all the members of the interface. A single class can inherit any number of interface and hence multiple inheritance in C# can be archived for the interface defination. If the class which inherited the interface doesnt provide the defination for all the members of the interface then an object cant be defined for that class. Modifiers should not be provided for the members of the interface. Syntax: Interface <interfaceNmae> { // Members without defination .. } Syntax to Inherit the interface Defination: Class <ClassName>:interfaceName(s) { //members }

iface1
My Method

iface2
My Method

Inherit Derived Class


My Method()

using System; namespace InterfaceDemo1 { interface iface1 { //public void myMethod(); error; void myMethod(); 42

} interface iface2 { void myMethod(); } class Derivedclass:iface1,iface2 { public void myMethod() { Console.Write("Defination for the iface,iface2 member.."); } } class Demo { public static void Main() { Derviedclass dc=new Derivedclass(); dc.myMethod(); } } } A single method presents with in the class can provide the defination for any number of interface members. Whenever the members name of the class and the members of the interface are same then the defination provided for the members of t he class will be implicitly considered as the defination for the members of interface.

Syntax to defined a method to provided the defination for the members of an interface explicitly: return DataType interfaceName.MethodName([argInfo]) { //Statements; } When ever the defination for the members of the interface has been provided explicitly then modifier should not be specified. If the defination for the interface members has been provided explicitly then tat members cant be refered using the derived class object.

Syntax to refer the members of the interface: Define an object for derived class Defined a variable for the interface by binding the defination of the derived class. Syntax: InterfaceName variable=DerivedClass Object as Interface Name; 43

Refer the member using the interface variable name

Syntax: variable members Name([argValues(s)]);

iface1
My Method1

iface2
My Method2

Inherit Derived Class Iface1.myMethod () Iface2.myMethod ()

using System; namespace InterfaceDemo { interface Iface1 { void myMethod(); } interface iface2 { void myMethod(); } class Derivedclass:iface1,iface2 { public void iface1.myMythod() void iface1.myMethod() { Console.WriteLine("Method defination for iface(myMethod()"); } void iface2.myMethod() { Console.WriteLine("Method defination for iface2.myMethod()"); } } 44

class Demo { public static void Main() { Derivedclass DC = new Derivedclass(); iface i1 = DC as Iface1; iface i2 = DC as iface2; i1.myMethod(); i2.myMethod(); } } }

Abstract Class: It is a collection of members with or without any definations. Inorder to use the members of the abstract class it is mandatory that the class has to be inherited by other class. If the abstract class contains any methods without any defination then it is the responsibility of the derived class to provide the defination for the abstract methods. If any abstract class contains all the methods will defined then also an object cant be defined for the abstract class. abstract Base Class P V Method Define() { //Statements } abstract P V Method Undefined() Inherit Derive Class Override P V Method Undefined() { //Statements }

45

using System; namespace AbstractclassDemo { abstract class Baseclass { public void MethodDefined() { Console.WriteLine("Method defoned at the base class"); } public abstract void Methodundefined(); } class Derivedclass:Baseclass { public override Methodundefined(); { Console.WriteLine("Method defined at the derived class..."); } } class Demo { public static void Main() { //Baseclass bc=new Baseclass(); derivedclass dc=new Derivedclass(); dc.Methoddefined(); dc.Methodundeifined(); } } } Interface defination are used to defined listeners and the abstract class defination are used to defined the actions to be performance. A class can inherit any number of interface defination and a class can inherit only single abstract class defination.

Sealed Class: It is to defined a class as the last class in the hierarchy of inheritance i.e. a sealed cant be inherited further and only object can be defined for the sealed class. A sealed class can inherit any no of interface defination or it can inherit a class defination or abstract class defination.

Syntax: Sealed class <Class Name> { //members; } 46

base Class OK( ) inherit final Class ------------inherit [error] other Class -----------------using System; namespace scaledclassdemo { class Baseclass { public void ok() { Console.WriteLine("A Message From Of."); } } sealed class Finalclass:Baseclass { } class Demo { public static void Main() { Finalclass fc = new Finalclass(); fc.ok(); } } }

scaled

47

Windows Application:
Whenever class definitions inherits System.Windows.Forms.Formclass then it is said to be a windows application. To design application using VS.NET. Start Run devenv New Projects

Project type Visual C# projects. Templates Windows Application

48

Press OK

A Container Where all the controls are maintained Alt+Ctrl+X

49

A Container Where the user interface can be designed

Used to set the attributes/properties of the control F4

50

Maintain the information about all the files and the assembles used with in the application Alt+Ctrl+L Ctrl+R

Maintains the information about all the classes used with in the application F2

Control: These are the user interface elements which are used to support interaction between the application and the user.

51

Control

Properties Used to set / get the values from the control

Methods These are the predefined tasks that can be preformed by the control

Events These are the actions that are allowed on the control

A control in .NET application as considered as the class name for which an object has to be defined

Form: It acts like a container control or a contras where other controls can be added or drawn on it.

Height

Scale Width Scale Height Auto Scroll

Width

Accept Button: Bind the button control name which has to be executed whenever the user clicks on the enter key with in the form control.

52

Cancel Button: Specified the name of the button control which has to be executed whenever the user clicks on the Esc Key. Opacity: It is to be used to set the transparency effect for the form control. Start Position: It is used to specify the position where the form has to be displayed on the desktop. Windows State: It is used to specify the mode in which the form has to be displayed on the desktop. Label: It is used to project any state information on the form. Text Box: It is used to accept single, multilane or password characters as the input.

Properties: Multiline: it is to true then the control can accept the input in multiple lines. Password Char: it is used to encrypt the text while displaying by projecting the character specified for the property. Scroll Bars: It is used to bind scrollbars for the text box control. Button: It is used to submit the data.

Common Properties for all the controls Name: Used to provide an unique identifier for the control. Text: It is used set or get the value from any control. Anchor: It is used to increase or decrease of the size with respective to the form control. Dock: It is used to bind the control to the form control based on the direction and filled form control in that relevant direction.

53

Naming Conjunctions for Controls: Label TextBox Button ListBox ComboBox MainMenu lbl txt btn lst cbo mnu

Anchor Name:txtName

Start Position=center screen Properties Accept Button=Button1 Cancel Button=Button2 Opacity=50% [It display light]

//OK(button_click ) string uname; uname = txtname.Text; MessageBox.Show( "Welcome " + uname + " to C# windows Appl.","Alert"); //Cancel( button_click) Application.Exit(); Text Properties Anchor: Top, Left, Right.

54

To design or add windows form:

55

Press OK

The name of the windows form will be implicitly consider as the class name for which an object has to be defined and the form object has to be executed using the following syntax. Application.Run(NewFormName()); With in the main method.

To Execute an Form: Project[Menu]

56

Specify the class Name to be executed

After Press F5

If the name of the form class is not displayed on the startup object list what it indicates the class is not defined with main method. public static void Main() { Application.Run(new From2()); }

Picture Box Control: It is used to project an image on the form Properties: Image: Specify the name of image file which has to be projected on the form. Size mode: It is used to specify the mode in which the image file has to be displayed. Methods: Save: It is used to size the pixels present at the picture box control as an image. Form File: It is used to provide the source for the picture box control. Rotate Flip: It is used to flip or rotate the pixels present with in the picture box based on the method arguments.

57

Radio Button control: It is used to select a single radio button control a collection of radio button controls. Properties: Checked: It returns true if the radio button is selected else the property returns false. Whenever any control has been added to other controls then the control will shared the relationship which is called is containment and hence if the radio button control which belongs to different to are been added on the form control the user can select only one radio button out of all the radio button control placed on the form.

Group Box Control: It is used logically group all the related control together.

// radiobox 90 pictureBox1.Image.RotateFlip(RotateFlipType.Rotate90FlipNone); // radiobox 180 pictureBox1.Image.RotateFlip(RotateFlipType.Rotate180FlipNone);

58

// radiobox 270 pictureBox1.Image.RotateFlip(RotateFlipType.Rotate270FlipNone); // vertical pictureBox1.Image.RotateFlip(RotateFlipType.RotateNoneFlipY); // Horizantal pictureBox1.Image.RotateFlip(RotateFlipType.RotateNoneFlipX); //Refresh pictureBox1.Refresh();

Dialog Control: It is used to project the model common dialog control on the form. Method Properties Open File Dialog File Name Show Dialog() File Save File Dialog Filter Color Dialog Color Color Font Dialog Font Font Print Dialog Printer Copies Open File Dialog: It is used to select a file which is existing with in the system. Save File Dialog: It is used to specify a file which is not existing with in the system. //Save SaveFileDialog.ShowDialog(); pictureBox1.Image.Save(SaveFileDialog.FileName,System.Drawing.Imaging.Ima geFormat.Bmp); MessageBox.Show("File Saved.","Confirm"); //Open OpenFileDialog.Filter="BitmapFiles|*.bmp|imageFiles|*.jpg"; OpenFileDialog.ShowDialog(); pictureBox1.Image = Image.FromFile(OpenFileDialog.FileName);

59

Scroll Bar Control: It is used to provide the scroll bar for the standard controls.

HSCROLLBA R VSCROLLBA R

Thum b

Minimu m Valu e Large Change

Maximu m

Small Change

60

Min-0 Max-255 Small Change-1 Large Change 5 public static void Main() { Application.Run(new Form2()); } private void Form2_Load(object sender, System.EventArgs e) { //Double_Click on form //Form_Load setColor(); } private void vScrollBar1_Scroll(object sender, System.Windows.Forms.ScrollEventArgs e) { //vscrollbar1_scroll setColor(); } private void vScrollBar2_Scroll(object sender, System.Windows.Forms.ScrollEventArgs e) { //vscrollbar2_scroll setColor(); }

61

private void vScrollBar3_Scroll(object sender, System.Windows.Forms.ScrollEventArgs e) { //vscrollbar3_scroll setColor(); } public void setColor() { int r,g,b; r = vScrollBar1.Value; g = vScrollBar2.Value; b = vScrollBar3.Value; lblPreview.BackColor = Color.FromArgb(r,g,b); lblPreview.Text = "Red : " + r.ToString() +"\nGreen : " + g.ToString() + "\nBlue : " + b.ToString(); lblPreview.ForeColor = Color.FromArgb(255-r,255-g,255-b); } Check Box: It is used to select a Boolean value. Properties: Checked: Returns true if the checkbox is selected and returns false. Combo Box Control: It is used to select a single item from a collection of values.

COMBO BOX Drop Down Combo Simple Combo Drop Down List

Drop Down Combo: It is an editable combo where the search will take place if the combo box has been expanded. 62

Simple Combo: It is an editable combo and always the control will support searching. Drop Down List: It is the non editable combo and the search will takes place if the combo box has been expanded Common Properties For The Control Which Supports Single Selection: Item: It is a collection of list items or values. Selected Item: Returns the list item selected with in the items collection of list control. Selected item returns an object.

Selected Index: Return the index number of the selected from the list control. Methods Of List Controls: items.Add(String): It is used to add an item to the items collection of the list control. items.RemoveAt(index): Used to remove an item from the specified index of the items collection. items.Clear(): It is used to clear all the items present with in the list control.

private void Form1_Load(object sender, System.EventArgs e) { //Form_Load 63

for( int i=1;i<=1000;i++ ) { comboBox1.Items.Add(i.ToString()); comboBox2.Items.Add(i.ToString()); comboBox3.Items.Add(i.ToString()); } }

List Box Control: It is used to select a single item or a set of values from the list control. Properties: Select Mode: It is used to specify the mode of selecting the values from the List Box Control. If the value for the selection mode has been set other than single then to retractile the information of t he selected items collections, selected items property should be used. Data Time Picker: It is used to select a data from the calendar control. Properties: Value: Returns the selected Date.

64

//Add_Button_Click string empno,ename,sal,hra,pf,it,hiredate,job,deptno=""; empno = txtEmpno.Text; ename = txtEname.Text; sal = txtSalary.Text; if( radioButton1.Checked == true ) deptno = "10"; if( radioButton2.Checked ) deptno="20"; if( radioButton3.Checked ) deptno="30"; if( checkBox1.Checked ) hra = (double.Parse( sal) * 0.05).ToString(); else hra = "0"; if( checkBox2.Checked ) 65

pf = ( double.Parse(sal) *.02).ToString(); else pf = "0"; if( checkBox3.Checked ) it = (double.Parse(sal)*.01).ToString(); else it = "0"; hiredate = dateTimePicker1.Value.ToString(); job = comboBox1.SelectedItem.ToString(); string str; str = empno + "#" + ename + "#" + sal + "#" + hra + "#" + pf + "#" + it + "#" + deptno + "#" + hiredate + "#" + job; listBox1.Items.Add(str);

//Listbox1_SelectedIndexChanged if( listBox1.SelectedIndex >=0 ) { string []values = System.Text.RegularExpressions.Regex .Split( listBox1.SelectedItem.ToString(),"#"); string msg; msg = "Employee Number : " + values[0] + "\n"; msg += "Employee Name : " + values[1] + "\n"; msg += "Basic Salary : " + values[2] + "\n"; msg += "Department Number : " + values[6] + "\n"; msg += "Hiredate : " + values[7] + "\n"; msg += "Job : " + values[8] + "\n"; double netsalary; netsalary = double.Parse( values[2]) - double.Parse(values[3]) double.Parse(values[4])-double.Parse(values[5]); msg += "Net Salary : " + netsalary.ToString(); MessageBox.Show(msg,"Employee Details");

//Delete(button_click ) if( listBox1.SelectedIndex >=0) { if( MessageBox.Show("Removes item permenently","Delete", MessageBoxButtons.YesNo ) == DialogResult.Yes ) { listBox1.Items.RemoveAt( listBox1.SelectedIndex ); } } else { MessageBox.Show( "Please select an item...","Error"); 66

//Remove All listBox1.Items.Clear();

Using Activex Control In C# Windows Application:

Press Right Click

Press OK

67

//Open(button_click) openFileDialog1.Filter = "AVI Files| *.avi| MP3 Format Files|*.mp3| Video Files| *.dat"; openFileDialog1.ShowDialog(); axMediaPlayer1.FileName = openFileDialog1.FileName;

//Listbox1_selectedindexChanged string fname; fname = "c:\\" + listBox1.SelectedItem.ToString() + ".avi"; axMediaPlayer1.FileName = fname; An application to read the text and to projected the output in speech

Select Text to speech Class.

68

Properties Lip tension

69

//Read(button_click) axTextToSpeech1.Speak( txtMsg.Text );

Visibility=False

Multi line=true Scrool bars=vertical Dock=fill

Select the properties [select control and press F4] //textbox1_keypress axTextToSpeech1.Speak(e.KeyChar.ToString());

70

Properties Event Command

//form_load axAgent1.Characters.Load("Merlin","c:\\winnt\\msagent\\chars\\merlin.acs"); axAgent1.Characters.Character("Merlin").Show(0); foreach( string an in axAgent1.Characters.Character("Merlin").AnimationNames ) { listBox1.Items.Add( an ); } axAgent1.Characters.Character("Merlin").Speak("Welcome to Agents World...Current Time is " + DateTime.Now.ToLongTimeString(),null); axAgent1.Characters.Character("Merlin").Play("Wave"); axAgent1.Characters.Character("Merlin").Commands.Add("cmd1","Sing a Song",1,1,1); axAgent1.Characters.Character("Merlin").Commands.Add("cmd2","Open Internet Explorer",1,1,1);

//listbox1_selectedindexChanged axAgent1.Characters.Character("Merlin").Play( listBox1.SelectedItem.ToString()); private void axAgent1_Command(object sender, //axagent1_command AgentObjects.IAgentCtlUserInput ui = ( AgentObjects.IAgentCtlUserInput ) e.userInput; if( ui.Name == "cmd1" ) { axAgent1.Characters.Character("Merlin").Speak("Ole Ole Ole!.... Howz this!...",null); 71

axAgent1.Characters.Character("Merlin").Play("Congratulate_2"); } if( ui.Name == "cmd2" ) { System.Diagnostics.Process.Start("iexplore"); }

ADO.NET: It is a technology which is used to interact with any database or XML documents ADO.NET supports two types of connectivity. 1. Disconnected Model: 2. Connection oriented Model:

Disconnected Model: It used to interact with the database then the connectivity between the application and the database is not required while performing navigation or manipulations on the data. Disconnected Model Architecture:

Client System Data Set Data View

Application

Data Base

Data Adapter

Connection

Data Provider / Manager Provider Connection Oriented Model: If used to interact with the database then the connectivity application and the database has to be maintained till the application interacts with the database.

72

Application
2

Data Base

Data Reader

Command

Connection

Data Provider / Managed Provider 1 2. If any valid statement other than SELECT statement is used. If SELECT statement is used

ADO.Net

Disconnected Model Connection

Connected Model Connection

Data Adapter

Command

Data Set

Data Reader

Data View

User Interface

User Interface Connection: It is used to establish the physical connection between the application and the data base. Data Adapter: It is a connection of commands which acts like a bridge between the database and the dataset for transferring the data.

73

Data Adapter Select command Table Mapping Insert Command Update Command Delete Command

Read the from Data Set Fill the data in dataset Fill (dataset, data table)

Data Set

Read the data from database Update the database Update (dataset, datatable)

Data Base

Method of Data Adapter: Fill(DataSet, DataTable) It is used to read the data from the database based on the select command of data adapter and used to fill retrieved information in the dataset. Update (DataSet, DataTable): It is used to read the data present with in the data table of data set and used to update that data in the data base. DataSet: It is a in memory representation of the data at the client system in the format if XML. Data Adapter can maintain the information of a single table at a time where as the data set can maintain the information of any number of table irrespective of database.

74

Oracle DB

SQL Server

<tag> -------</tag> XML Document

Data Table DA1 DA2

DS [Data Set] ----------------------------------

Data Member

Since the dataset can maintain the information about any number of tables a data set can be considered as a collection of data tables.

Data Set
Data Table

Data Table
Data Column

Data Reader XML Schema

Data Rows

Constraints

A manipulation performed on the dataset will not be reflected on the database. Dataset supports establishing the relationship between the data members of the dataset. Dataset is of two types. 1. Typed Dataset 2. Untyped Dataset. Typed Dataset: Whenever the dataset has been defined based on XML schema defination(XSD) then it is said to be typed dataset.

75

Untyped Dataset: Whenever the dataset has been defined without the XML schema defination then it is said to be a Untyped dataset. The members of the typed dataset will be binded at the design time and hence to refer data members of the type dataset.

Syntax: DataSetName.TableName Ex: ds.emp; The members of the Untyped dataset will be binded at the runtime and hence Inorder to refer the data members of the untyped dataset. Syntax: DataSetName.Tables[index]; Ex: ds.Tables [0]; or ds.Tables [emp]; Data View: It is a logical representation of the data present at the data members of the dataset Data view should be if the data has to be filtered or if the data has to be projected in page wise.

Command: It is used to provide the source for the connection object. Data Reader: It is a forward and read only record set which will maintain the records retrieve based on the select statement of command object.

76

ADO.Net 1.1 Object Model:


ADO .Net 1.1 Object Model

SQL Server System.Data.sqlclient sql Connect sql Command sql DataReader sql DataAdapter

Oledb Provide System.Data.oledb Oledb Connect Oledb Command Oledb DataReader Oledb DataAdapter

ODBC Drivers System.Data.odbc

Oracle Server System.Data.Oracleclient Oracle Connect Oracle Command Oracle DataReader Oracle DataAdapter

odbc Connect odbc Command odbc DataReader Odbc DataAdapter

DataSet System.Data DataView

Syntax: Connection: xxxConnectionObjectName=New xxxConnection (ConnectionString); Where xxx can be SQL, Oracle, OleDb or Odbc. Connection string to connect SQL server database: Provider=sqloledb.1;user id=sa; password=; database=DbName; dataSource=ServerName; If SQL connection class is used to connect SQL Server database then provider=sqloledb.1 should not be used within the connection string connection

String To Connect Oracle Database: Provider=Oraoledb.Oracle; user id=scott; password=tiger[;data source=ServerName] This will support only oracle 9i. or Provider=msdaora.1; If Oracle Connection class is used to connect the oracle Database then Provider=Provider Name should not be used.

Data Adapter: Syntax: xxxDataAdapter ObjectName= new xxxDataAdapter (select statement, ConnectionObject/Connection String); Data Set: Syntax: DataSet ObjectName =new DataSet(); 77

Data View: Syntax: DataView ObjectName = new DataView(DataSetName.DataTable); Command: Syntax: xxxCommand ObjectName=new xxxCommand([SQL Statement, connection Object) ConnectionString]); Data Reader: Syntax: xxxDataReader ObejectName;
ADO.Net

Disconnected Model CN

Connected Oriented Model Ora CN CN Oledb CN

DA

Ora DA

Cmd

Oledb Cmd

DS

DS

DR

OledbDR

DV

DV

UI

UI

UI

UI

78

Connection Oriented Programming Model Flow: Connection Oriented Programming Model Flow Define a connection Object Open the command the connection Define the command object Connection Connection Type: Command Type Command Text: [Parameter Defination] Text Table Direct Stored Procedure

Select statement (Query) Execute Reader() Execute Scalar()

Any Valid Statement other Than select statement Execute Nonquery()

[Close the connection]

Execute Scalar: It is used to executed a select statement which returns a single column single row value Execute Scalar() method return on object If execute scalar method is used to execute a select statement which returns more than one row or a column then the statement will not raise an error instead the method will return the value present at first row first column of the data retrieved by the statement.

Execute Reader: It is used to execute any valid select statement. Execute Reader() method return a DataReader object.

Execute NonQuery: It is used to execute any valid statement other than the select statement. It is returns an integer which represent the number of records manipulated by the statement. 79

Data Grid Project[Menu ] Add References

80

Press Select after Press OK //Execute (button_click ) try { string stmt; stmt = txtstmt.Text.Substring(0, txtstmt.Text.IndexOf(" ")); // MessageBox.Show(stmt); OracleConnection cn = new OracleConnection("user id=scott;password=tiger"); if( stmt.ToUpper() == "SELECT" ) { OracleDataAdapter da = new OracleDataAdapter( txtstmt.Text , cn ); DataSet ds = new DataSet(); da.Fill(ds,"tmpTable"); dataGrid1.DataSource = ds.Tables[0]; lblmsg.Text = ds.Tables[0].Rows.Count.ToString() + " rows selected..."; } else { cn.Open(); OracleCommand cmd = new OracleCommand(); cmd.Connection = cn; cmd.CommandType = CommandType.Text; cmd.CommandText = txtstmt.Text; cmd.ExecuteNonQuery(); cn.Close(); lblmsg.Text = stmt.ToUpper() + " statement executed successfully..."; } listBox1.Items.Add( txtstmt.Text ); } catch( Exception ex ) { MessageBox.Show( ex.Message , "Error"); } //listbox1_selectedIndexChanged txtstmt.Text = listBox1.SelectedItem.ToString(); //Clear(button_click) txtstmt.Clear();

81

File Stream: It is used to read or write the information on a file. To support FileStream .Net technology has provided a namespace called as System.IO. System.IO

ToWrite (StreamWriter)

ToReader (StreamReader)

Stream Writer: It is a class which is used to write the information on a FileStream. Methods: Writer: It is used to write the information on the buffer. WriteLine: It is used to write the information on the buffer by appending a new line character at the end of the stream. Flush: It is used to read the data present at the buffer and write data permanently on the FileStream. Once the data has been written then the information present at the FileStream is removed.

Close: It is used to close the StreamWriter object. StreamReader: It is used to read the information present at the file and used to return that information. Methods: Read: It is used to read single character from the string. Read() method returns an integer value if the stream is empty than the method return -1. ReadLine: It is used to one single time at a time from the stream. If the stream is empty the method returns a null value.

82

ReadToEnd: It is used to read the entire information present at the stream. Close: It is used to close the StreamReader object.

using System.IO //Before Namespacing //Save(button_click) saveFileDialog1.Filter = "SQL Script Files| *.sql"; saveFileDialog1.ShowDialog(); StreamWriter sw = new StreamWriter( saveFileDialog1.FileName); sw.Write( txtstmt.Text ); sw.Flush(); sw.Close(); MessageBox.Show("Statement Saved.","Save"); //Load(button_click) openFileDialog1.Filter = "SQL Script Files| *.sql"; openFileDialog1.ShowDialog(); StreamReader sr = new StreamReader( openFileDialog1.FileName ); txtstmt.Text = sr.ReadToEnd(); sr.Close(); //Quit(button_click) Application.Exit();

Performance Navigation and Search Using The disconnected Model: Binding Manager Base: It is a class which is used to provide the member for performing the navigation and manipulations on the data. Properties To Support Navigations: Position: It is used to point a DataRow with in the DataRows collection of the Data members finded to the Binding Manager Based Variable. Count: It return the number of records present within the data member binded to the binding manager base variable. Binding Context: It is used to bind the data member of the data set to the binding manager base variable. Syntax: bmb=BindingContext[DataSetName,DataTable]; Methods Of DataSet Members: 83

Contains: It is used to accept a primary key value and used to return a Boolean value true if the record exists else the method returns false. Find: It is used to accept primary column value and used to return the dataraow if the record exists. Contains() and Find() method can be used if and only if the table is defined with primary key. Syntax To Define A Primary Key Constrain For The Datacolumn Of The Datamembers Of Dataset: DataSetName.DataTable.Constraints.Add(ConstraintName,DataColumn,BooleanValue ); If true is passed as the Boolean value then primary key constraint will be defined and if false is passed as the Boolean value then unique constraint will be defined.

//Before Namespace using System.Data.OleDb; BindingManagerBase bmb; DataSet ds = new DataSet(); //Before Form Load //Form_load OleDbConnection cn = new OleDbConnection("provider=oraoledb.oracle;user id=scott;password=tiger"); OleDbDataAdapter da = new OleDbDataAdapter("select * from emp",cn); 84

da.Fill(ds,"EMP"); ds.Tables[0].Constraints.Add("empno_pk", ds.Tables[0].Columns["empno"],true); bmb = BindingContext[ds.Tables[0]]; bmb.Position = 0; showRS( bmb.Position ); //End of the form_load public void showRS( int index) { txtEmpno.Text = ds.Tables[0].Rows[index]["empno"].ToString(); txtEname.Text = ds.Tables[0].Rows[index]["ename"].ToString(); txtSal.Text = ds.Tables[0].Rows[index]["sal"].ToString(); txtDeptno.Text = ds.Tables[0].Rows[index]["deptno"].ToString(); } //First bmb.Position =0; showRS( bmb.Position ); //Prev(button_click) bmb.Position -= 1; showRS(bmb.Position ); //Next bmb.Position += 1; showRS( bmb.Position ); //Last bmb.Position = bmb.Count -1; showRS(bmb.Position ); //Search(button_click) int empno; empno = int.Parse( txtEmpno.Text ); if( ds.Tables[0].Rows.Contains(empno) == true ) { DataRow row; row = ds.Tables[0].Rows.Find(empno ); txtEname.Text = row["ename"].ToString(); txtSal.Text = row["sal"].ToString(); txtDeptno.Text = row["deptno"].ToString(); } else MessageBox.Show( "Employee Record not found...","Error");

85

//Quit Application.Exit();

Find: It is used to scroll a record based on the primary key column value and if the record exists then the method will return the row index value and if the doesnt exists then the method returns. Syntax: DataSetName.DataTables.DefaultView.Find(PrimarykeyColumn.Value); Inorder to used the above find method it is mandatory that the table should be defined with a primary key also the data has to be stored.

//Before Namngspace using System.Data.OracleClient; DataSet ds = new DataSet(); int index,tmpindex; //Form_load OracleConnection cn = new OracleConnection("user id=scott;password=tiger"); OracleDataAdapter da = new OracleDataAdapter("select * from emp", cn ); da.Fill(ds,"EMP"); dataGrid1.DataSource = ds.Tables[0]; ds.Tables[0].Constraints.Add("empno_pk",ds.Tables[0].Columns["empno"],true); ds.Tables[0].DefaultView.Sort = "empno";

86

//Quick Search(button_click) try { dataGrid1.UnSelect(tmpindex); index = ds.Tables[0].DefaultView.Find( int.Parse(txtEmpno.Text)); if( index < 0 ) MessageBox.Show("Record doesnt exists","Error"); else { dataGrid1.Select(index); tmpindex = index; } } catch( Exception ex ) { MessageBox.Show( ex.Message,"Error"); } Select: It is used to search the record based on a condition and return the DataRow Collection if the Condition is satisfied.

DataSet ds = new DataSet(); //Form_load OracleConnection cn = new OracleConnection("user id=scott;password=tiger"); OracleDataAdapter da = new OracleDataAdapter( "select * from emp",cn); da.Fill(ds,"EMP"); //Get Details listBox1.Items.Clear(); DataRow []rows = ds.Tables[0].Select("deptno=" + int.Parse(txtDeptno.Text)); 87

for( int i=0;i<rows.Length;i++) { listBox1.Items.Add( rows[i]["ename"] ); } Inserting A Record Using Disconnected Model: Step1: Define A DataRow. Step2: Assign the New row of the Data members of the dataset to the data row variable. Step3: Assign the vlues to the Data column of the data row. Step4: Add the Data row variable to the data rows collection of the data members of the dataset. Step5: Update the data adapter with the data present at the data members of data set. Tool[Menu]Data

88

Click on NEXT [Button] Use SQL Statements Click on NEXT Button. Write the SQL Query Select * from dept Press NEXT After Press FINISH In SQL to add primary key. After table dept add constraint deptno_pk primary key

89

//Form_load oracleDataAdapter1.Fill(dataSet11,"DEPT");

//Insert Record try { DataRow row; row = dataSet11.DEPT.NewRow(); row[0] = int.Parse(txtDeptno.Text); row[1] = txtDname.Text; row[2] = txtLoc.Text; dataSet11.DEPT.Rows.Add(row); oracleDataAdapter1.Update(dataSet11,"DEPT"); MessageBox.Show("Record Saved","Insert"); } catch( Exception ex) { MessageBox.Show(ex.Message,"Error"); } Steps To Update The Records using Disconnected Model: Step 1: Define a row. Step 2: Assign the data row which has to modified to the datarow variable. Step 3: Start the edit mode. Step 4: Assign the values to the data column of the data row variable which has to be modified. Step 5: End the edit mode. Step 6: Update the data adapter with the data present at the data member of data set.

90

//Browse int dno; dno = int.Parse(txtDeptno.Text); if( dataSet11.DEPT.Rows.Contains(dno) == true ) { DataRow row; row = dataSet11.DEPT.Rows.Find(dno); txtDname.Text = row["dname"].ToString(); txtLoc.Text = row["loc"].ToString(); } else MessageBox.Show( "Record doesnt exist","Error"); //Update Record DataRow row; row=dataSet11.DEPT.Rows.Find( int.Parse(txtDeptno.Text)); row.BeginEdit(); row["dname"] = txtDname.Text; row["loc"] = txtLoc.Text; row.EndEdit(); oracleDataAdapter1.Update(dataSet11,"DEPT"); MessageBox.Show("Record Updated...","Update");

Steps To Delete The Data Row From The Data Table Using Disconnected Model: Step 1: Delete the data row from the data row collection of data member of data set. Step 2: Update the data adapter with the data present at the data members of the data set. //Delete Record if( MessageBox.Show("Are you sure","Delete",MessageBoxButtons.YesNo)= =DialogResult.Yes ) { dataSet11.DEPT.Rows.Find(int.Parse(txtDeptno.Text)).Delete(); oracleDataAdapter1.Update(dataSet11,"DEPT"); MessageBox.Show("Record Deleted","Delete"); }

91

Using Data Forms in C#: Project[Menu]

Select Add New Item

92

Here Press NEXT

93

Here give The Table Name And press NEXT.

Here select the table Name and press NEXT

Here select the table columns and press NEXT

94

Here select the all records or single record and press FINISH.

Here select what we want

95

Assembly: The compiled source code of the .Net application is called as assembly. If an assemble is defined with an empty entry point (Main() method) then it said to be a application. If an assembly is defined without the entry point then is said to be a LIBRARY. Types of Library: 1. Private Assembly. 2. Shared Assembly. Private Assembly: These assembly definitions are binded to a single application.
Source.CS CSC /t :library source.CS Source.dll Class library .Net Component

C:\applicati on1 Bin\debug

C:\applicati on1 Bin\debug

C:\applicati on1 Bin\debug

App1.exe

Source.dll

App1.exe

Source.dll

App1.exe

Source.dll

Usage of Assembly: It is used to achieve language interoperability and reusability of the class definition. Steps To Design A Private Assembly Visual Studio.Net: Step 1: Select the class Library template from VS>Net IDE. Step 2: Specify a valid name for the class library. The name of the class library will be consider as the namespace namespace name within the application. Step 3: Write the code as per the requirement Step 4: Click on build [Menu] Build solution to defined the private assembly.

96

EMP_Info EMPID Photes

Table Created: Create table emp_info [empid number primary key, photo blob]; Blob Binary Large Object; Blobimage[SQL]; Steps To Insert An Image On The Database: Step 1: Import all the namespace required to support the database and the file stream. Step 2: Define an object for the file stream class. Step 3: Define an object for the binary reader class based on the filestream object. Step 4: Define a variable for the byte array. Step 5:Read the data from the binary stream as a byte array and assign that data to the byte array variable. Step 6: Define an object for the connection class and open the connection. Step 7: Define an object for the command class. Step 8: Set the connection, command type, command text properties of the command object. Step 9: Add the parameters for the command object. Step 10: Execute the command object using the execute NonQuery() method. Step 11: close all the objects which are opened. Steps To Design A Private Assembly To Store An Image On The Database: Step 1: Select class library template from VS.Net IDE. Step 2: Specify a valid name for the class library. Ex: Name:PrivateAssembly Step 3: Write the code as per the requirement. using System; using System.Data; using System.Data.OleDb; using System.IO; namespace PrivateAssembly { public class EmployeeInfo { public bool InsertRecord( int empid,string filename ) { try {

97

FileStream fs = new FileStream(filename,FileMode. OpenOrCreate,FileAccess.Read ); BinaryReader br = new BinaryReader(fs); byte []barray; barray = br.ReadBytes( int.Parse(fs.Length.ToString())); OleDbConnection cn = new OleDbConnection( "provider=oraoledb.oracle;user id=scott;password=tiger"); cn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = cn; cmd.CommandType = CommandType.Text; cmd.CommandText = "insert into emp_info values(?,?)"; cmd.Parameters.Add( "empid", empid ); cmd.Parameters.Add("photo",barray); cmd.ExecuteNonQuery(); return true; } catch( Exception ex ) { return false; } } } }

Using The Private Assembly From The VB.Net Windows Application: Step 1: Select the windows application template from VB Project Type. Step 2: Add the references of the private assembly with in the application.

98

The above step will copy the private assembly to the application folder. Step 3: Design the form as per the requirement.

99

Step 4: Define an object for the class present within the private assembly and refer the member using the object reference. Imports PrivateAssembly Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Browse OpenFileDialog1.Filter = "Bitmap Files| *.bmp| Image Files| *.jpg" OpenFileDialog1.ShowDialog() PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName) End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click 'Save Dim obj As New EmployeeInfo If obj.InsertRecord(txtEmpid.Text, OpenFileDialog1.FileName) = True Then MessageBox.Show("Record Inserted", "Save") Else MessageBox.Show("Error while processing the data", "Error") End If End Sub

100

Shared Assembly: These assembly will be shared among all the applications. Strong Name

Source.cs

C:\winnt\assembl y
Global Assembly Cache

Source.dll

C:\app1

C:\app2

C:\app3

Bin\debug
App1.exe

Bin\debug
App2.exe

Bin\debug
App3.exe

The assembles which are register with in the global assemble cache folder is said to be shared assemble. In order to register an assemble to the GAC it is mandatory that an assemble has to be binded with the string name. Global assemble chache maintain the information about any no of assembles with the same name.

Steps For The Design The Shared Assemble: Step 1: Define the strong name key file. Step 2: Select class Library template. Step 3: Specify a valid name for the class library. Step 4: Bind the strong file name information to the assembly and write the code as per the requirement. Step 5: Click ob Build[Menu] Build solution to define the assembly. To above step will define a private assembly. Binding a strong name to an assembly definition doesnt mean an assemble is a shared assemble. Step 6: Register the assemble the defined to the global assemble definition to the global assemble cache [Folder]. 101

Steps To Retrieve The Binary Information Or An Image From An Database: Step 1: Define a connection object and open the connection. Step 2: Defined the command object. Step 3: Set the Connection, Command type and command text property of the command object Step 4: Define a DataReader. Step 5: Execute the statement using the ExecuteReader() method and assign the result to the DataReader object. Step 6: Read the data from the DataReader object Step 7: Define a Byte Array variable. Step 8: Read the data retrieve by the statement as a ByteArray and assign the result to the ByteArray variable. Step 9: Define a file stream object. Step 10: Define a binary Write object base on the file stream object. Step 11: Write the data present at the byte array variable to the binary writer object. Step 12: Close all the objects which are opened. The above steps will prepare an image file dynamically at eh run time based on the information present at the byte array.

Steps To Design The Assembly To Read An Image From The Database: Step 1: Define the strong name file To Do: in .Net Command prompt Sn k demo.snk Step 2: Select class library template from CS.Net IDE Step 3: Specify the valid name for the class library For Eg: Name=SharedAssembly Step 4: Bind the strong name key file information to the assembly and write the code as per the requirement To Do: View Solution Explorer AssembleInfo.cs [assemble:AssembleKeyFile(c:\\demo.snk)] Add References System.Drawing.dll [Add]. using System; using System.Data; using System.Data.OleDb; using System.IO; using System.Drawing; namespace SharedAssembly { public class EmployeeInfo { public Image GetImage( int empid ) 102

{ try { OleDbConnection cn = new OleDbConnection ("provider=oraoledb.oracle; userid=scott;password=tiger"); cn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = cn; cmd.CommandType = CommandType.Text; cmd.CommandText = "select photo from emp_info where empid=" + empid ; OleDbDataReader dreader; dreader = cmd.ExecuteReader(); dreader.Read(); byte []barray = new byte[30000]; dreader.GetBytes(0,0,barray,0,30000); FileStream fs = new FileStream("c:\\tmp.bmp", FileMode.OpenOrCreate,FileAccess.Write ); BinaryWriter bw = new BinaryWriter(fs); bw.Write(barray); bw.Flush(); fs.Close(); bw.Close(); return Image.FromFile("c:\\tmp.bmp"); } catch( Exception ex ) { Image i=null; return i; } } } } Click on Build[Menu] Build Solution Register the assembly definitions with in the global assemble cache folder. VS.Net Command: C:\cs209batch\SharedAssembly\Bin\Debug>gacutil I Shared Assembly.dll; Using Shared Assembly in C#: Windows Application Project Add References SharedAssembly .dll [it is a available in bin folder]

103

using SharedAssembly;

private void button1_Click(object sender, System.EventArgs e) { //Show image(button_click) EmployeeInfo ei = new EmployeeInfo(); pictureBox1.Image = ei.GetImage( int.Parse(textBox1.Text)); }

Satellite Resource Assembly: It is a specified assembly which is used to provided only the resource information. It is used for supporting globalization and localization.

Globalization and localization: Whenever the application supports multiple language or culture then globalization and localization should be used. Steps to achieve Globalization: Step 1: Import the system threading and system globalization namespace. Step 2: Define an object for the culture info class Step 3: Assign the culture into class object to the current culture and current culture property of System.Threading.Thread.Current threading class

104

using System.threading; using System.globalization; string culture="en-US"; switch( comboBox1.SelectedIndex ) { case 0 : //English culture = "en-US"; break; case 1 : //Telugu culture = "te-IN"; break; case 2 : //Tamil culture = "ta-IN"; break; } CultureInfo ci = new CultureInfo( culture ); 105

Thread.CurrentThread.CurrentCulture = ci; Thread.CurrentThread.CurrentUICulture = ci; Form2 f = new Form2(); f.ShowDialog();

COM Interop: 1. using COM components in .Net.

COM Component

Assembly

2. Using .Net Assembly definition from the COM type Application. Assembly COM Type Application

COM [component Object Model]: It is a specification which is used to achieve language interop. Where language interop means using the code written in one language from the application developed using other language. VC++ VB

Plumbering

Component [COM]

Application

Inorder to specify a class definition as a component then it is mandatory that the class has to inherit IUNKNOWN and IDISPATCH interface. Methods of IUNKOWN interface:

106

Query Interface (Query Refer): It is a method which maintaince the information about the address of all the methods which are present at the component in the format of varry table structure. Add References: It is used to increment the reference counter value by one whenever an application uses the definition of a COM Component. Release: It is a method which is used to decrement the reference counter by whenever the application which uses the COM component is closed in a normal manner. Whenever the application has been closed abruptly then the release method will not be invoked. If the references counter value of the component is equal to zero then the resources allocated for the COM component will be released Inorder to use the COM component definitions by any language then it is mandatory that the component should implement IDISPATCH interface. COM component is of two types. 1. In Process COM (.dll) 2. Out Process COM (.exe)

In Process COM (.dll): Operating System COM Server [GUI D] In Process COM [.dll] Private Memory Area [PMA] Whenever a COM type application uses the definition of the COM components request will be given to the COM server where the component will be identifies based on the GUID and then the process of the component will be performed at the private memory area of the operating system and result will be given as a response to the application.

COM Type Application

107

PMA: It is a memory flow where the operating system function calls will be executed Advantage: The performance will be very fast. Limitation: The resource of the operating system will be blocked it is mandatory to use an application in order to use the defination of in process component. Out Process COM (.exe): Operating System COM Server COM Type Application
[GUID]

In Process COM [.dll]

Memory Block

Private Memory Area [PMA]

Whenever a COM type application uses the defination of the out process COM then the request will be given to the COM server where the component is identified and the processing of the component will be performed at a memory block and the result will be given as the response from the PMA. Advantages: 1. The resources of the operating system will not be blocked. 2. out process components can be used independently or it can be used with in other applications. Limitations: Performance will be slow when compared to the inprocess components. COM Assembly Type safe code Used Strong Name Object Based Resilient Building Exception handling.

Type unsafe code Uses GUID Interface Based Immutable Results for handling the exception

108

Using COM Component from .Net Assembly:

Un Managed Environment COM Server

Managed Environment Common Language Runtime [CLR] Runtime Callable Wrapper [RCW]

COM Component

Interop COM Unsafe Code/Unmanaged Code Managed Code .Net Assembly

Whenever a .Net assembly used the definition of the .COM component then a request will be given to the common language Runtime which will identify the request type and defines the runtime callable Wrapper. Once the RCW has been defined then the request will be given to the COM server where the component is identified and the components type library definition are return to the RCW once the RCW collects the type library definition then it will define and interop COM component which will be used by the .Net Assembly.

Using .Net Assembly from COM type Application: Un Managed Environment


COM Server

Managed Environment
Common Language Runtime [CLR]

Interop COM

IUNKNO WN IDISPAT CH OBJECT

COM Callable Wrapper [CCW]

COM Type Application

.Net Assembly

109

`Whenever a COM type application uses the defination of the .Net assembly then the request will given to the COM server which will identify the request type and then sends the request to the CLR. Once CLR collects the request then it will identify the request type and defines the COM callable Wrapper which will read the .Net assembly definition and defines an interop COM components based on the assembly definitions. Design .COM Component using VB6.0: Start programs M.S. Visual Studio 6.0 M.S visual basic 6.0 In templates Activex.DLL Project[Menu] references Available references Select Microsoft Activex Data Object Press Ok Write the code as per the requirement Public function Regsiter(byval user as string, byval pwd as string) as Boolean. Onerror GoTo err dim con As New ADODB.Connection Con.ConnectionString=Provider=OraOledb.Oracle Userid=scott password=tiger Con.open(); Dim sql As String Sql=insert into cs209batch values(&usr&, &Pwd&); Con.executed(sql); Con.close Register User=True ExitFunction Err: RegisterUser=False End Function After Press F4 it open property window In name change name comclass1 Project[MENU] ProjectNameProperties Projectname COMProject$Charp After Press OK

The COM project in the COM type application will be consider as the namespace with in the .Net application.

Built the COM Project. 110

File Make ComProject4

The above steps will define the COM component and register the component within the COM server. Steps To Use COM component from C# windows Application: Project[Menu] Add References COM Project for C# Step 1: Select Windows Application Template The above step will define a interop COM component based on the assembly defination. Interop.COMProjectForCsharp.dll. Design the form as per the requirement.

Create a object for the COM class and refer the member using object reference. //Register( button_Click) comClass1 obj = new comClass1Class(); if( obj.RegisterUser( textBox1.Text , textBox2.Text ) == true ) { MessageBox.Show("User Registered","Register"); } else { MessageBox.Show( "Error while processing the data.","Error"); }

Type Library Import [tlbImp]: It is used to import the COM component type library definition as a .Net Assembly Defination. 111

Syntax: tlbImp typeLibraryFile/out:Assembly. Type Library Export [tlbExp]: It is used to export the .Net Assembly definition as a COM componenet type library definition. Syntax: tlbExp<Assembly>/Out:TypeLIbrary .Net Remoting: Requirement: A technology such that the code within one system should be accessed from the application present in other systems connected with in a network. Solution: [Distributed Technology] Distributed component object [DCOM] Model.

Local System [Client] COM Server Client Register COM Type Application Memory Block

Remote System [Server] COM Server / Com Register DCOM Private Memory Area [PMA]

Other Computer Whenever a COM type application uses the definitions of the DCOM then the request will be given to the COM server of local system which will send a request to the client registration of DCOM and based on that information a request will be given to the COM server of remote system. Once the COM server of remote system can accept the request it will identify the DCOM and the processing of the DCOM will at the memory block of the client system or any specification based on the DCOM completed the result will be provided as a response to the application. Limitation Of DCOM: Huge network infrastructure is required. Use RPC [Remote Procedure Call] protocol for transferring the data an hence DCOM in not internet friendly. Uses binary formatters for transferring the data. 112

If the network is enabled with firewalls or proxy servers then the data will not be passed No security. Drawback of COM model such as DLL hell, versioning etc., are also applicable for DCOM.

Requirement: A technology such that code present in one system should be accessed from the application present in other system connected with in the system by solving the above limitations. .Net Remoting: [.Net .Net]: Communication between .Net assembly present in one system with the .Net assembly present in another system connected with in a network is called as .Net Remoting. .Net Remoting Architecture: Channels to be used for commutating between the system involved in Remoting. How does a client shout send a request to the remote system for accessing the assembly definition How does the server should provided the response to the application present at local system.

.Net Remoting Architecture: Local System [Client] Remoting System Channel Remote System [Server] Remoting System [By Val/ By Ref] Remote Object

Proxy

.Net Assembly

.Net Assembly

Whenever the .Net Remoting is used then all the systems involved in Remoting, Remoting system will be defined. Whenever a .Net assembly uses the definition of .Net assembly uses the defination of .Net assembly present in other system then a request will be given to the Remoting system of the client. 113

Once the Remoting system of the client accepts the request it will define a proxy where the proxy acts like a interfaces between Remoting system and the assembly Once the proxy is defined then it will send a request to the assembly and collects the information will be given to the Remoting system of client. Once the Remoting system of the client receives the information it will send a request to the Remoting system of the server using the channels Remoting system of the server accepts the request and identify the assembly and defines a remote object which will be given as a value or reference to the Remoting system of client from the server using the channels. Then the result will be given as a response to the assembly using the proxy. Channels: These are the physical communication medium used by the .Net Remoting infrastructure the data or information across the system connected with in the network. Inorder to support .Net Remoting it is mandatory to define and register a minimum of one channel in all the systems involved in Remoting. .Net Remoting supports two of channels. 1. TCP Channel. 2. HTTP Channel. TCP Channels It is used to for intranet based application To used define an object for Channels.TCP.TCPChannelsClass formatters Uses binary formatters for formatting the data It is mandatory to define a port explicitly If the network define with firewalls all proxy servers data cant be passed. There is no in built security for TCP Channels and hence user has to provide security for the application programmatically. HTTP Channels It is used for intranet and internet based applications. To use define an object for Sytem.Runtime.Remoting.Channels. Http.HttChannelsClass Uses soap formatters for formatting the data. HttpChannel can use the default port of the Web server and also it will support explicit defining of ports. Data can press through the firewalls all proxy servers http channels can use the default security provided by the web server that is integrated windows athantecation and also it can use secured socket layers [SSL] for transferring the data.

114

Performance of the application will be very fast.

Performance of the application will be slow when compared to the TCP Channel

In order to register the channel object in the system.

ChannelServices.RegisterChannel(ChannelObject); Object defined for TCP channel or HTTP channel. Syntax to Unregister The channel Object: ChannelServices.UnRegisterChannel(ChannelObject); A client application can send a request to the server in two ways. 1. Client Activated Object 2. Server Activated Object. Client Activated Object: Whenever an instance for the remote class is defined within the assembly the request will be given to the server and a remote object will be defined which will be provided as a response either as a value or reference based on the assembly defination.

Server Activated Object: If used to use the defination pf Remote class that the request will be given to the system and defines an object for the remote class whenever the remote method has been used within the application. Server activated object is of two types. 1. Single Call Method. 2. Single Ton Method. Single Call Method: It used then the remote object will serve only the request of a single client i.e once the response is provided then the remote object will be implicitly garbage collected. Single Ton Method: Whenever the first request is given then an object will be defined and the same object will be used to provide the response for any number of future clients request. Server can provide the response in two ways 1. Call By Value Method 2. Call By Reference Method. 115

In order to specify a class definition as a remote class it is mandatory that the class has to inherit Marshal By Value or Marshal By RefObject Class. Marshal By Value Object: If a class inherit Marshal BY Value Object class then the remote class definition will be provide as a value to the client system. Marshal By Ref Object: If a class inherit Marshal By Ref Object class then the reference of the remote object will be given as a response to the client application. The class which inherit Marshal By Ref Object are considered as the true .Net Remoting.

using System; namespace RemoteClassLib { public class RemoteClass : MarshalByRefObject { public RemoteClass() { Console.WriteLine("Object Created..."); } public string Hello( string name ) { Console.WriteLine("Method has been Processed..."); return "Hello " + name; } } } Build Build Solution

Steps To Define The Server Application: Step 1: Import all the namespace required for performing the .Net remoting. Step 2: Define an object for the channel class. Step 3: Register the channel object. Step 4: Create an object for the Remote Class. Step 5: Marshall the Remoting Class Object. The above steps will defined the server and places the Remoting Object at a specific location. Step 6: Disconnect the Remote Object Step 7: Unregister the channel object. The above steps are used to unregister the server. 116

using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Http; using RemoteClassLib; namespace Server { public class ServerApplication { public static void Main() { HttpChannel ch = new HttpChannel(1111); ChannelServices.RegisterChannel(ch); RemoteClass remoteObject = new RemoteClass(); RemotingServices.Marshal( remoteObject , "xyz"); Console.WriteLine("Server Started..."); Console.WriteLine("Clients can access the def. using the following URL :\n http:\\\\localhost:1111\\xyz"); Console.WriteLine( "Press \"Enter\" to stop the server"); Console.ReadLine(); RemotingServices.Disconnect(remoteObject); ChannelServices.UnregisterChannel(ch); } } } Steps To Design a Client Application: Step 1: Import all the namespace required for the .Net remoting. Step 2: Define an object for the channel class. Step 3: Register the channel object. Step 4: Specify the method to be used for accessing the remoting class definition i.e specify weather activated object method or server activated object method should be for accessing the definition. Syntax To Use The Definition Using Client Activated Object Method: RemotingConfiguration.RegisterWellKnownClient Type(typeof(namespaceNameClassName),URL); Syntax To Involve The Remoting Class Definations Using Server Activated Object Method: RemotingConfiguration.RegisterWellKNownServicetype(typeof(namespaceName.Class Name), URL,<single call/singleton>); Step 5: Create an object for the Remote Class and use the member using the object reference. 117

Step 6: [Optional] Unregister the channel object. Add References .NET Browser System.runtime.remoting remoteclass.lib using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Http; using RemoteClassLib; namespace Client { class ClientApplication { public static void Main() { HttpChannel ch = new HttpChannel(0); ChannelServices.RegisterChannel(ch); RemotingConfiguration.RegisterWellKnownClientType( typeof(RemoteClass),"http://localhost:1111/xyz"); RemoteClass obj = new RemoteClass(); Console.WriteLine("Executing Client appl.."); Console.ReadLine(); Console.WriteLine(obj.Hello( "sekhar")); ChannelServices.UnregisterChannel(ch); } } } Remote Class: Select Class Library using System; using System.Data; using System.Data.OleDb; namespace RemoteClassLib { public class RemoteClass : MarshalByRefObject { public int getSalary(int eno) { try { OleDbConnection cn = new OleDbConnection("provider=oraoledb.oracle;user id=scott;password=tiger"); cn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = cn; 118

cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "GETSALARY"; cmd.Parameters.Add("eno", eno ); cmd.Parameters.Add("salary", OleDbType.Integer ); int sal; cmd.ExecuteNonQuery(); sal = int.Parse( cmd.Parameters["salary"].Value.ToString()); return sal; } catch(Exception ex ) { return -1; } } } } Build Build Solution Server Program: using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using RemoteClassLib; namespace Server { public class ServerApplication { public static void Main() { TcpChannel ch = new TcpChannel(2222); ChannelServices.RegisterChannel(ch); RemoteClass obj = new RemoteClass(); RemotingServices.Marshal( obj,"abc"); Console.WriteLine("Server Started...\n Press \"Enter\" to Stop the server..."); Console.ReadLine(); RemotingServices.Disconnect(obj); ChannelServices.UnregisterChannel(ch); } } }

119

using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using System.Data.OleDb; // Before Namespace private void button1_Click(object sender, System.EventArgs e) { //Get(button_click) TcpChannel ch = new TcpChannel(0); ChannelServices.RegisterChannel(ch); RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteClassLib.Remot eClass),"tcp://localhost:2222/abc",WellKnownObjectMode.SingleCall ); RemoteClassLib.RemoteClass obj = new RemoteClassLib.RemoteClass(); int sal; sal = obj.getSalary( int.Parse(txtEmpno.Text )); if( sal > 0 ) txtSal.Text = sal.ToString(); else { MessageBox.Show( "Invalid employee number...","Error"); txtEmpno.Clear(); txtEmpno.Focus(); } ChannelServices.UnregisterChannel(ch);

Multi Threading: It is used to process multiple task at a same time. To Support: .Net frame work has provided a name called a Single Threading

120

STA Thread Application: Caller P S V Main( ) { ------Display( ); --------} Called P V Display( ) { // Statement }

Stack MTA thread Application: ----------Thread 2 -------------------

1 1 2 2

Thread 1 -------------------

-----------

Usage Of Multi Threading: It is used for executing more than one task at same time. Whenever a business logical has to be executed continusally then it is advisable to define the logical as a multi thread. Steps To Design An Application To Support Multi Threading: Step 1: Import the System.Threading namespace. Step 2: Define an object for the Thread. Syntax: Thread <thread name> =new Thread (new threadStart(methodName)); Step 3: Provide the defination for the Thread method which has been dinded. Step 2 and Step 3 can be interchanged. Step 4: Start the processing of the Thread. Syntax: ThreadName.Start(); using System; using System.Threading; namespace ThreadingDemo { 121

class ThreadClass { public void task1() { for( int i=1;i<=3;i++ ) { Console.WriteLine( "From Thread1 : " + i.ToString()); Thread.Sleep(50); } } public void task2() { for( int i=1;i<=3;i++ ) { Console.WriteLine( "From Thread2 : " + i.ToString()); Thread.Sleep(50); } } } class Demo { public static void Main() { ThreadClass tc = new ThreadClass(); Thread t1 = new Thread( new ThreadStart( tc.task1)); Thread t2 = new Thread( new ThreadStart(tc.task2)); t1.Start(); t1.Priority = ThreadPriority.Highest ; t1.Join(); t2.Start(); } } }

Thread execution is not predictable.

In order to execute a specific thread as the initial thread then it is mandatory to specify the priory for the thread. Syntax: ThreadName.Prioritory=ThreadPriority.xxx xxxAbove Normal/Below Normal/Highest/Lowest/Normal. Thread Joining: It is used to halt the processing of other threads while processing the thread which has been joined. 122

Once the processing of the thread which has been joined has been completed then the lock will be released on other threads and then the remaining threads will be processed simultanesly.

Syntax: ThreadName.Join(); Thread1.Join();

Thread 1 ---------------------------------

Thread 2 ---------------------------------

Thread 3 ---------------------------------

Based on above scenario while performing of the process of thread1 the processing of thread2 and thread3 will be halted and once the processing of thread1 is completed then thread2 and thread3 will be executed simultansoly.

Thread1 Reads the data from new student insert the data in old student Thread2 New Student Delete the old student information from new student table

Old Student

123

Thread Monitoring: It is used to block the thread processing of the relevant resources.

P V task1 ( ) { ---------}

P V task2 ( ) { ---------}

Thread 1 -------------------------

Thread 2 -------------------------

Thread 1 -------------------------

using System; using System.Threading; namespace ThreadMonitoring { class ThreadClass1 { public void task1() { Monitor.Enter(this); for(int i=1;i<=3;i++ ) { Console.WriteLine("From Task1 : " + i.ToString() ); Thread.Sleep(50); } Monitor.Exit(this); } } class ThreadClass2 { public void task2() { for( int i=1;i<=3;i++ ) { Console.WriteLine("From Task2 : " + i.ToString()); Thread.Sleep(50); } 124

} } class Demo { public static void Main() { ThreadClass1 tc1 = new ThreadClass1(); ThreadClass2 tc2 = new ThreadClass2(); Thread t1 = new Thread(new ThreadStart( tc1.task1 )); Thread t2 = new Thread(new ThreadStart( tc1.task1 )); Thread t3 = new Thread(new ThreadStart( tc2.task2 )); t1.Start(); //t1.Join(); t2.Start(); t3.Start(); } } }

Thread Synchronization: It is used to lock the other threads while accessing the same thread by one or more threads. Syntax: lock(name) { // Statements } Thread 1 ------------lock (s1); { //Statements; -------} Thread 2 --------------------------------------------------------

using System; using System.Threading; namespace ThreadSyncDemo { public class Address 125

{ public string str1,str2 ; public void Display() { lock( "sl" ) { Console.WriteLine(str1); Thread.Sleep(50); Console.WriteLine(str2); } } } class Demo { public static void Main() { Address addr1 = new Address(); Address addr2 = new Address(); addr1.str1 = "Peers tech."; addr1.str2 = "Huda Complex"; addr2.str1 = "Ameerpet"; addr2.str2 = "Hyd."; Thread t1 = new Thread( new ThreadStart(addr1.Display)); Thread t2 = new Thread(new ThreadStart(addr2.Display)); t1.Start(); t2.Start(); } } }

Multiex Threads: It is used for synchronizing the thread process by locking the thread on the ownership. In order to halt or lock the threads processing MutexObject.Waitone(); In order to release the lock MutexObject.ReleaseMutex();

using System; using System.Threading; namespace MutexThreadDemo { class ThreadClass { static Mutex m; public void Task() 126

{ Console.WriteLine("Task Started..."); m.WaitOne(); Console.WriteLine("Task Ended..."); } public static void Main() { ThreadClass tc = new ThreadClass(); m = new Mutex(true,"demo"); Thread t = new Thread(new ThreadStart(tc.Task)); Console.WriteLine("Before starting the Thread..."); t.Start(); Console.WriteLine("Before setting the Thread to sleep"); Thread.Sleep(10000); Console.WriteLine("After the Thread Sleep."); m.ReleaseMutex(); Console.WriteLine("Program Ends Here..."); } } } Windows Services: It is used for developing the background process for an application. Usage: Windows services is used to provide additional security for the application and also to automatic the task.

127

Programming Mode For The Windows Services: Define a Thread Task (Method) While (true) { ------------} On Start -----------Start the Thread Windows services will be started Windows services will be stopped On Stop Stop the processing of Thread

Steps For Designing The Windows Services: Step 1: Select windows services template from VS.Net IDE. Step 2: Specify a valid name for the windows services application. The name of the windows service application is used to install the sevice in the system service registry. Step 3: Right click any where in the form and con Add Installer. To above step will define the service process installer and service installer. Service Process Installer: It is used to specify the account type to be used by the windows service. Service Installer: It is used to specify the display name sevice name an start up mode for the windows service. Step 4: Set the following properties for services process installer. Account: Specify the account type to be used by the service (Default: User); For Service Installer: Display Name: Specify the description of the windows services to the displayed on the services registry. Service Name: Specify the name to be used by the application for binding the windows services. Start type: specify the mode the start the windows services [Default: Manual]. 128

Step 5: Click on service1.cs[Design] tab and click on Click here to switch to code view link built. Step 6: Write the code as per the requirement. In order to specify a class defination as a windows service than it is mandatory that the class has to inherit System.ServiceProcess.ServiceBox class.

Step 7: Click on Build Build Solution to define the windows service applications. Step 8: Install the windows service application in the system service registry. To Do: [In.Net Command Prompt] Install util i Application .exe SQL ED: Create table todo remainder(msg varchar2(1000)) insert into todoremainder values (&task); Enter values to task: Click on Start Run devnev to start VS.Net; Enter values to task: click on new project button. Enter values to task: Select visual c# project and click on windows application. Enter values to task: Specify the name and location click on OK button. Steps To Design Windows Service To Project Alert Message: New project windows services template name to do remainds right click on form add installer F4 For Service Process Installer Properties: Account: Local System Service Installer F4 Display Name: To Do Task Service Name: To Do Remainder Service1 Start type: Manual.

using System.ServicesProcess; using System.Data.OleDb; using System.Threading; Thread t1; int index; public static string msg=""; public void task() { while( true ) { OleDbConnection cn = new OleDbConnection("provider=oraoledb.oracle;user id=scott;password=tiger"); 129

OleDbDataAdapter da = new OleDbDataAdapter("select * from todoremainder",cn); DataSet ds = new DataSet(); da.Fill(ds,"todoremainder"); if( index >= ds.Tables[0].Rows.Count -1 ) index=0; msg = ds.Tables[0].Rows[index][0].ToString(); index++; Form1 f = new Form1(); f.ShowDialog(); Thread.Sleep(2000); } }

Steps To Start The Service Manually: Start Run Services.msc

130

General Tabclick on Start Click Binding Windows Services To The .Net Application: Select windows application template and design the form as per the requirement.

131

Toolbox componenets Services Controller Property Servicename:toDoRemainderServices1 //Start serviceController1.Start(); //Stop serviceController1.Stop();

Toolbox componentsFile SystemWateher Properties Path<Folder Address> Events //fsw1_Changed string msg; msg = e.FullPath + "\\" + e.Name + " has been modified at " + DateTime.Now.ToString(); 132

insertRecord(msg); //fsw1_Created string msg; msg = e.FullPath + "\\" + e.Name + " has been created at " + DateTime.Now.ToString(); insertRecord(msg); public void insertRecord( string msg ) { OleDbConnection cn = new OleDbConnection("provider=oraoledb.oracle;user id=scott;password=tiger"); cn.Open(); string sql; sql = "insert into cs209spyware values('" + msg + "')"; OleDbCommand cmd = new OleDbCommand(sql,cn); cmd.ExecuteNonQuery(); cn.Close(); } //fsw1_Deleted string msg; msg = e.FullPath + " has been deleted at " + DateTime.Now.ToString(); insertRecord(msg); //Quit Application.Exit(); Delagates: These are the function pointers which are used to point the address of the member function defined within the class. Function pointer in C++ are variables and delegates in .Net are object.

Syntax: public delegate return DataType delagateNmae([argInfo]); using System; namespace DelegateDemo { public class myCalc { public int add(int a,int b) { return a+b; } public int sub(int a, int b ) { return a-b; 133

} } public delegate int fun(int i,int j ); public class Demo { public static void Main() { myCalc mc = new myCalc(); //mc.add(10,20); fun f1 = new fun(mc.add); fun f2 = new fun(mc.sub); Console.WriteLine( f1(10,20).ToString()); Console.WriteLine( f2(200,10).ToString()); } } }

Whenever a delegates is used to point the address of a single member function then it is said to be single cast delegate.

Multi Cast Delegate: Whenever a single delegate is used to point the address of more than one member function then it is said to be multi cast delegate. To Define: Delegate Name d3; D3=d1+d2; Where d1 and d2 are delegate objects. using System; namespace MultiCastDelegateDemo { public delegate void print( string name); class Message { public void Hello( string name) { Console.WriteLine("Hi " + name); } public void Bye( string name ) { Console.WriteLine("Bye " + name ); } } 134

class Demo { public static void Main() { Message obj = new Message(); print p1 = new print(obj.Hello); Console.WriteLine("From Delegate P1 : "); p1("sekhar"); print p2 = new print( obj.Bye); Console.WriteLine("From Delegate P2 : "); p2("srinivas"); print p3; p3 = p1 + p2; Console.WriteLine("From Delegate P3 : "); p3("sri"); } } }

Using Delegates For Event Handling: using System; using System.Windows.Forms; namespace EventHandlingDemo { class FClass : Form { TextBox t = new TextBox(); public FClass() { t.Multiline = true; t.ScrollBars = ScrollBars.Vertical; t.Dock = DockStyle.Fill; t.KeyPress += new KeyPressEventHandler(t_changed); this.Controls.Add(t); this.Text = "My Own Notepad"; } private void t_changed( object sender, KeyPressEventArgs e ) { e.Handled = true; t.Text += "Eat .Net, Sleep .Net, Drink .Net Coz .Net Simply rocks"; } }

135

class Demo { public static void Main() { //FClass fc = new FClass(); // Application.Run(fc); Application.Run(new FClass()); } } } Windows Control Library: It is used to design a reusable windows component such that the control can be used from any .Net windows application development using any .Net language. Steps To Design The Windows Control Library: Step 1: Select windows control library template from the VS.Net IDE. Step 2: Specify a valid name for the control library. Step 3: Design and code the control as per the requirement. Step 4: Click on build[Menu] build solution to define the control library. Select Windows control Library.

136

Step To Design a Numeric Text Box Control: Keys

Normal Keys Key Press 0-9, A-Z Enter Space Back Space From Key Press e.keychar Key Key press Event task Variable 0 9 Back Space Enter ASCII 48 57 8 13 37 38 39 40

Action Keys Key down F1-F12 Home/End

(int) e.keychar

//textBox_keypress int c; c=(int)e.KeyChar; if((c=8)||(c=13)) { } else if(c<48||c>57) e.Handled=true; else e.Handled=false

//Form_keyDown if(e.KeyValue==37) pictureBox1.Left-=10; if(e.KeyValue==38) pictureBox1.Top-=10; if(e.KeyValue==39) pictureBox1.Left+=10; 137

if(e.KeyValue==38) pictureBox1.Top+=10;

Memory Management In .Net: Whenever an object or variables or any members are used within any application then the resources has to be allocated and the memeory in the system is not infinite.

Next Object Pointer Object D Object C Object B Memory Block Object A Managed Heap Block Whenever the manage heap memory block has been occupied by the objects and while creating a new object if the system identifies the memory required for the object is not sufficient then the .Net frame work will give the control the CLR for managing the memory blocks. To achieve memory management in .Net CLR will used garbage collectior. CLR will maintain the complete information about the application root of an assemble wherever application root can be a static member or non static member or CPU register or any member function.

Garbage Collector: It is the resource used by the CLR in order to clear the resources occupied by the unused object. Garbage collector will use Mark and Compact Algorithm in order to clear the resources occupied by the unused objects

Garbage Collector Algorithm: Ist Phase [Mark Phase]: Garbage collector at the first will try to identify the object which are pointed by the application root directly or in directly and graph based on that information. 138

CLR

Next Object Pointer

Application Roots Static Member Non Static Member Pointers CPU Register

Object D Object C Object B Object A Managed Heap Block

Once all the objects which are been used has been marked then the garbage collector will try to prepare graph by pushing the objects which are used to the bottom of the managed heap and places the objects which are non to use above the objects.

CLR

Next Object Pointer

Application Roots Static Member Non Static Member Pointers CPU Register

Object D Object C Object B Object A Managed Heap Block

IInd Phase Compact Phase: In this phase whatever the objects which are not marked will be destroyed and CLR will clear the resources occupied those objects.

139

CLR

Next Object Pointer New Generation Object

Application Roots Static Member Non Static Member Pointers CPU Register

Object E Object D Object C Object B Generation [0] Old Generation Object

If any object is alive after the garbage collection then that object is said to be the old generation object and if any object is created after the garbage collection than it is said to be new generation object. Old generation object will have week relationship and longer life span, new generation object will have strong relationship and short life span.

In order to access the garbage collector using .Net application System.GCClass should be used. Add References System.Windows.Forms.dll; ~ Tilled Symbol using System; using System.Windows.form; namespace garbagecollector { class GarbageCollector { public GarbageCollector() { MessageBox.Show("With in the Constructor Demo"); } public ~GarbageCollector() { MessageBox.Show("with in Destructor"); } } class Demo { public static void Main() { GarbageCollector gcobj = new GarbageCollector(); 140

gcobj=null; System.GC.Collector(); System.GC.WaitForPendingFinalizers(); } } }

Design The Screen Saver Using C#: It is an application which will be design using some animation which is used to increase the life span of the system monitor. Steps to Design Windows Application for Screen Sever: Step 1: Select windows application template from VS.Net IDE and specify a valid name for the application. Step 2: Design the form as per the requirement Programfiles\msvs\vlntdevg8\samples\gallery\context\timeline[image address] Timer collerpropertiesenabled true.

141

You might also like