You are on page 1of 367

C# 2010 with Microsoft.Net Framework 4.

0
Pragati Software Pvt. Ltd. www.pragatisoftware.com

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

Index
Module Module 1 Module 2 Module 3 Module 4 Module 5 Module 6 Module 7 Module 8 Module 9 Module 10 Module 11 Module 12 Particulars Getting Started Basic Language Constructs Class and Object Class Library Inheritance Exception Handling Other C# Features String, StringBuilder and Dateformats Collection classes Generics and Nullable Types Windows Form Control I File I/O Page 4 15 37 47 59 75 85 99 117 129 137 159
2

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

Index

(Contd)
Working with DB Data Bound Controls DotNet Framework and Assembly Delegate Thread Introduction to Web Services Windows Form Control II Advance Thread Reflection Serialization Iterators
SQL BULK copy Database Operations

Module 13 Module 14 Module 15 Module 16 Module 17 Module 18 APPENDIX APPENDIX APPENDIX APPENDIX APPENDIX APPENDIX APPENDIX

181 226 239 244 253 273 290 306 320 324 332 351 353
3

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

Module 1: Getting Started


Overview
Introduction to C# Types of applications Understanding some terms: solution, project, Visual Studio IDE Writing, compiling and running a simple program

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

Framework Version
DLR C# 4.0 VB 10 Code Contracts PLINQ MEF

.Net Framework 4.0


Enhancement for WCF, WPF, WF C# 3.0 VB 9 LINQ AJAX

.Net Framework 3.5


WCF

.Net Framework 3.0


C# 2.0 VB 8.0

WPF

WF

Card Space

.Net Framework 2.0 CLR 4.0


Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

MEF : The Managed Extensibility Framework or MEF is a library for creating lightweight, extensible applications. It allows application developers to discover and use extensions with no configuration required. It also lets extension developers easily encapsulate code and avoid fragile hard dependencies. MEF not only allows extensions to be reused within applications, but across applications as well. DLR : The dynamic language runtime (DLR) is a runtime environment that adds a set of services for dynamic languages to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages.

.Net Framework

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

.NET Framework is a common platform for designing, developing and deploying the various types of applications such as: Console Application, Windows Application, Web Based Application, Class Library Application, Web services, WCF, WPF, WF etc.. A developer can develop application by using any of the language which is compatible with .NET Framework. The languages compatible with .NET Framework are such as C#, VB, J#, VC++, F# etc. The Base class library provides a comprehensive set of facilities for application development. The .NET Framework provides a run-time environment called the Common Language Runtime. It runs the code and provides the services which makes the development process easier. Microsoft provides IDE as a Visual Studio to implement the .NET Framework. .NET Framework comes with redistributable installer that contains the Common Language Runtime and .NET Framework components which are necessary to run .NET Framework applications. The .NET Framework is available as a stand-alone executable file, Dotnetfx.exe. NOTE:Prior to .NET Framework for developing different types of applications different technologies were used. E.g. : For developing Console applications languages such as C/C++ was used. For developing Windows based applications VB was introduced by the Microsoft. For developing and designing web based applications, technologies such as HTML, DHTML, JavaScript, classic ASP were used. It means for developing specific type of application, one has to use different technologies.

Types of Applications
Console applications. Windows applications ASP.NET Web applications Class libraries Custom controls (User defined controls). Windows service Web Service

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

We can create multiple kinds of applications such as: Console Applications: Applications that run on command prompt. Windows Applications: Desktop application using windows forms. ASP. Net Web Applications: Browser based applications i.e. Web sites. Class Library: Components basically are reusable piece of code that contains some business logic. Custom Controls: We can create our own controls from the existing controls either in windows or in web. Windows Services: We can create services that run in the background. Web Services: Web Services are web components. We can have a business logic available on the web that can be shared by people across the world.

Features of C#
Object-oriented features Structured exception handling Powerful Windows based applications Building Web based applications Simple data access Multithreading Simplified deployment XML Web Services

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

Features of C# C# is a very powerful language. It implements Rapid Application Development Tools for developing various kinds of application. Full Support for Object Oriented Programming. Structured Exception Handling helps create and maintain the program with robust error handlers. In this technique, we write a code which detects and traps the errors during execution and prevents application from inconsistent state. .NET provides an IDE to develop all kinds of applications such as Windows, Web, Console, AJAX based, Mobile etc into one environment using the languages that are supported by framework. Multithreading Capabilities.

Creating a New Project


2. Language

(Contd...)
1. Framework Version

3. Application Template

4. Project Name 5. Project Location 6. Solution Name


Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

Start Microsoft Visual Studio 2010. Click on File > New > Projects 1.Select from the drop down appropriate version of .NET Framework. 2.Choose the language C# from Left hand side project type.. 3.On the right hand side from the templates available, select Console Application. 4.Specify the project name. 5.Select the location to save the project. 6.Specify the name for solution.

Solutions and Projects


1. Solution name

A solution usually acts as a container for one or more projects A project typically contains all the files required for the application.

2. Project name

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

10

1. Solutions: A Visual Studio solution can include just one project or several projects built jointly by a development team. A complex application might require multiple solutions. 2. Projects: Visual Studio projects are used as containers within a solution to logically manage, build, and debug the items that comprise your application. The output of a project is usually an executable program (.exe) or a dynamic-link library (.dll) which known as Assembly.

10

Writing the First Program


namespace Module01 { class Program { static void Main(string[] args) { Console.WriteLine("Hello World..."); Console.ReadLine(); } } }

Click on Debug -> Start to view the output.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

11

(Source code: C:\Training\Module01\Module01\Module01\Program.cs)


Namespace is a logical collection of the types such as: class interface struct enum delegate In class Program we have Main() method which is known as entry point. Console is a class under System namespace which has a WriteLine() and ReadLine() as a method.

11

Compilation Process in .NET


Visual Basic C# J#

Compiler

Compiler

Compiler

Windows CLR

MAC CLR

JIT
Managed code

JIT

CPU

CPU
12

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

.Net framework supports various languages to develop the applications. A developer may write a code by using any of the language (VB, C#, J#, VC++, F#) which is compatible with .Net Framework. What happens when the code is written and compiled in .Net framework? Every language has its own language compiler. Very first the code is compiled by the language compiler and it produces a MSIL (Microsoft Intermediate Language) code. It is also known as IL code. This MSIL code is now sent to the CLR (Common Language Runtime). Once the MSIL code is sent to the CLR, only the code which is required during runtime is getting compiled into native machine code. This process is known as JITing and it is performed by a component known as JITer (Just in Time Compiler). Once the native machine code is produced it goes through under tight security policy which is known as CASPOL (Code-Access-Security-Policy). If this code is safe then only it is executed on CPU. This code is also known as managed code.
Same process happens for the other OS also.

12

Location of .exe file.


1. Location of .exe 2. Exe file

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

13

.Exe is always stored at location : project folder\bin\debug.

13

Components of CLR

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

14

Class Loader : It loads all the Base Class Libraries required during execution of code. Type Verifier : Type verifier checks for the type compatibility. It is also known as CTS(Common Type System). The specification for the types are specified by CLS (Common Language Specification). Exception Manager : Exception manager manages the exception during runtime. JIT : Just-In-Time compiler produces native machine code which is required while runtime. Garbage Collector : It is also known as Heap Manager or Auto memory manager. It releases the memory by removing unused/out of scope objects. In invokes automatically. One can not predict about its invocation. Security Manager : Once the native machine code is produced, it is sent to the CPU for execution. This native machine code goes under tight security policy. This security policy is known as CASPOL . It is categorized into : 1) Code based Interface 2) Role based Interface. Thread Manager : Thread manager manages the multi-threading envt. COM Marshaller : While migrating from old COM application to .NET application ,the type compatibilty of COM applications with .NET types is marshalled by this component.

14

Module 2. Basic Language Constructs


Overview
Variables and data types Operators (arithmetic, relational, logical, assignment, conditional, etc.) Conditional statements

if else switch
Looping Constructs

while do.loop while() for


Arrays

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

15

15

Data Types

(Contd)

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

16

The .NET platform provides Common Type System to all the supported languages. This means that all the languages must support the same data types as enforced by common language runtime. Data Types object string sbyte short int Description The ultimate base type of all other types String type; a string is a sequence of Unicode characters 8-bit signed integral type 16-bit signed integral type 32-bit signed integral type object o = null; string s = "hello"; sbyte val = 12; short val =12; int val=12; long val1=12; byte val1=12; ushort val1=12; uint val1=12; unit val2=34U; ulong val1=12; float val = 1.23f; double val1=1.23; bool val1=true; char val1=h; decimal val = 1.23M; Example

long 64-bit signed integral type long val2=34L; byte ushort uint ulong float 8-bit unsigned integral type 16-bit unsigned integral 32-bit unsigned integral type 64-bit unsigned integral type Single=precision floating point

double Double-precision floating point type double val2=4.56D; bool char decimal Boolean type; a bool value is either true or false Character type; a char value is a Unicode character Precise decimal type with 28 significant digits

Formatting Numeric Data C or c Currency format D or d double M or m decimal F or f float L or l - long

16

Variable and Data type Program


static void Main(string[ ] args) { double centigrade; double fahrenheit; centigrade = 33.3; fahrenheit = (centigrade * 9 / 5) + 32; Console.WriteLine("33.3 Centigrade = " + fahrenheit + " Fahrenheit."); Console.ReadLine(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

17

(Source code: Module02\Module02\01variable.cs)


Variable Declaration int num; double salary, balance; string name;

17

Common Type System (CTS)

CommonTypeSystem

C# CLS VisualBasic.NET

VC++

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

18

The Common Type System , is a part of the .net framework describes how the various data types must be declared, managed and used at runtime and plays a very crucial role for supporting cross language integration. Some of the most common functions it conducts are : 1.Type Safety, Cross language integration and high performance execution of code. 2.It has a set of rules that all .net compliant languages must follow so that the objects created in those languages can interact with each other . It supports the complete implementation of the programming languages. Common Language Specification (CLS) :

When you write code in one language and this code is then used by other programs that were developed in different languages, then that code should be CLS compliant, which simply means that it should abide by the rules specified in the CLS. The CLS describes features such as common data types for different languages. CLS compliance is important when software components that are created in one language will be used by other languages. The CLS is called as a subset of the CTS because it defines those set of rules that are a part of the CTS itself.

18

CLS
C# int i; string str; double dbl; VB.NET Dim i as Integer Dim str as String Dim dbl as double

.NET Type System.Int32 i; System.String str; System.Double dbl;

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

19

If one application written in C# and one application written in VB.NET wants to communicate with each other, how the communication will happen? In .NET if C# uses int to store numeric value which has a storage size 32 bits and VB.NET uses Integer to store numeric value which also has a storage size 32 bits. Then Common language specification specifies the common type compatible with both the types and produces a result as Int32.

19

Named Constant
static void Main(string[ ] args) { const float Pi = 3.14f; float radius, area; radius = 10.0f; area = Pi * radius * radius; Console.WriteLine("Area of circle = " + area.ToString()); Console.ReadLine(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

20

(Source code: Module02\Module02\02constant.cs) Named constants are created by declaring a variable with keyword const. Using a named constant can improve the readability of your code, as it becomes a form of documentation. Besides, since a named constant is defined in only one place in a program, if the value of the constant needs to be changed, it needs to be changed only in one place. Thus, use of named constants improves program maintenance also.

20

Writing comments
static void Main(string[ ] args) { /* variable declaration */ const float Pi = 3.14f; float Radius, Area; Radius = 10.0f; /* Calculation */ Area = Pi * Radius * Radius; //Printing Result Console.WriteLine("Area of circle = " + Area.ToString()); Console.ReadLine(); }

Comment

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

21

comments can improve the readability (and thereby, maintainability) of source code. Single Line comment // text following // up to the end of the line is treated as a single line comment, and is ignored by the compiler. /* */ Similarly, any text between /* and the next */ is known as multi line comment, and is also ignored by the compiler. In C# you can add the contents by using short-cut keys (ctrl+E, C). And for uncommenting short-cut key used is (ctrl_E, U).

21

Taking Input from the User


static void Main(string[ ] args) { const float Pi = 3.14f; float Radius, Area; Console.Write("Enter the value for radius : "); Radius = float.Parse (Console.ReadLine()); Area = Pi * Radius * Radius; Console.WriteLine("Area = " + Area.ToString()); Console.ReadLine(); } Output window Input window

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

22

(Source code: (Source code: Module02\Module02\03userinput.cs) To take input from the user at the runtime we use Console.ReadLine() method and assigning the value to the variable Radius. When we take the input from the command line it is always taken as string type. The data type of the Radius variable is float, so we require to convert string type to float type. For that we are using the method Parse of the float type to convert string value to the float value.

When we print the value we are giving message and then we display the value. So every part of the Console.WriteLine() method has to be of a string type. So for printing we are converting the decimal value of area into string by using ToString() method.

22

Operators
Operator Arithmetic Unary Assignment Comparison Concatenation Logical operations Language Element +, , *, /, % ++ , -=, +=, -=, *=, /=

==, !=, <, >, <=, >= + &&, ||


23

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

e.g. int num1=5, num2=10, num3; Arithmetic Operators : num1 + num2; num1 num2; num1 * num2 ; num1 / num2; num1 % num2; Unary : pre-Increment/pre-decrement : ++num1 / --num1; post-Increment/post-decrement : num2++/num2 -Assignment : num3=num1 + num2; num1+=num2; Comparison : num3= num1==num2; It will return 1 (true) if both the numbers are equal or 0 (false) if numbers not equal. Concatenation : string str1 = Hello , str2 = World; Console.WriteLine(str1 + str2); Logical operations : && (Logical and) :num3=(num1 >5 && num2<=10); It will match both the expression. If both the expressions are true it will return 1 otherwise 0 for false. || (Logical or) : num3=(num1 > 5 || num2<=10); It will return 1 (true) if any one of the expression is matched.

23

The if...else Structure


if (expression) statement; if (expression) statement1; else statement2;

if (expression) statement1; else if (expression) statement2; else statement3;

if (expression) { statement1; if (expression) statement2; } else statement3;

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

24

If-else is a decision making statement. Returns true if the condition is true or returns false in else part.

24

The if...else Structure Example


static void Main(string[ ] args) { int Num1 = 10, Num2=15; if (Num1 > Num2) Console.WriteLine("Num1 is greater the Num2"); else Console.WriteLine("Num2 is greater then Num1"); Console.ReadLine(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

25

The multiple if Structure Example


static void Main(string[] args) { int a = 5, b = 6, c = 7, min, max; if (a >= b) { if (a >= c) { max = a; if (b >= c) { min = c; } else { min = b; } } else { max = c; min = b; } } else if (b >= c) { max = b; if (a >= c) { min = c; } else { min = a; } } else { max = c; if (a >= b) { min = b; } else { min = a; } } Console.WriteLine("max={0} min={1}", max, min); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

26

(Source code: Module02\Module02\04if.cs)

26

The switch statement


switch (expression) { case value: statements; break; case value: statements; break; default: statements; break; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

27

To choose one option among the multiple choices switch-case statement is used.

27

The switch statement Example


case 7: static void Main(string[] args) case 8: { case 9: int month = 1; case 10: switch (month) Console.WriteLine("Monsoon { season"); case 11: break; case 12: default: case 1: Console.WriteLine(Invalid month); case 2: Console.WriteLine("Winter Season"); } break; } case 3: case 4: case 5: case 6: Console.WriteLine("Summer season"); break;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

28

(Source code: Module02\Module02\06switch.cs)

28

while loop
while (condition) { statements; increment / decrement statement }
static void Main(string[ ] args) { int num = 1; while (num <= 5) { Console.WriteLine("Number = " + num.ToString()); num++; } Console.ReadLine(); }
29

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

(Source code: Module02\Module02\07while.cs) While loop: The boolean expression is evaluated, and if true, the following statement (which can be a block) is executed. Thereafter the boolean expression is evaluated again, and once again, if true, the following statement is executed. This process continues until the boolean expression evaluates to false. A while loop does not execute at all if the boolean - expression is false the first time itself. If you want a loop to be executed at least once before checking the boolean - expression, you should use the do...while loop.

29

dowhile Example
do { statements; increment / decrement statement } while (condition);
static void Main(string[ ] args) { int num = 0; do{ Console.WriteLine("Number = " + num.ToString()); num+=2; } while(num<=10); Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

30

(Source code: Module02\Module02\08doloop.cs)


Here the boolean expression is evaluated after executing the statement. While the expression is true, the statement is executed repeatedly.

30

For Loop
for (initialize; condition; increment/decrement) { statements; }
static void Main(string[ ] args) { for (int number = 101; number <= 105; number++) { Console.WriteLine("Number = " + number); } Console.ReadLine(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

31

(Source code: Module02\Module02\09for.cs) For loop is used for fixed iteration.

31

Array
Array is a group of elements having same name, same data type and different index.

heap

stack

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

32

An array is an ordered collection of elements. Elements of an array can be of primitive types or references to objects. The value defined in the square bracket is the size of the array. Lower limit start with zero (0) Upper limit is whatever is the size -1. The first element of the array has index zero, and the index of the last element is one less than the length of the array. Thus, the first element of the above array is referred to as numbers [0], while the last element is numbers [4]. The length of an array is available with the length field. Stack memory : All value types are primarily stored on stack area. Heap memory : All reference types are stored on heap area.

32

Array (continued)

Syntax:Datatype [ ] arrayname = new Datatype [size];

int [ ] numbers = new int[5]; Or int [ ] numbers = new int [ ] {10,20,30,40,50}; 1-D Array Reference Or int [ ] numbers ={1,2,3,4,5};
33

Array Object 10 20 30 40 50

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

Memory Map of array

(contd)

String [ ] zones = { "East", "West", "North", "South } ;

1-D Array Reference Array Object

North

East

South

West

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

34

As every string itself is an object, array of strings is nothing but array of references to string objects.

34

34

Array class and methods


Array class is the base class for all the arrays in CLR.
Method Reverse() Explaination Revereses the order of array elements. Sorts array in ascending order. Syntax Array.Reverse(array); Example int [] numbers =new int {24,12,3,43,43}; Array.Reverse(numbers); Array.Sort(numbers); Array.Clear(numbers,0,5);

Sort() Clear()

Array.Sort(array);

Sets the range of Clear(Arrayname,int,int) elements in the array to zero, or to false, or to Nothing depending on the type of array

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

35

(Source code: Module02\Module02\10Array.cs)

35

Multidimensional Array
Syntax Datatype [,] arrayname = new Datatype [rows, columns];
int[,] number = new int[3,3]; number [0,0]= 10; number[0,1] = 20; Or int[,] num = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

2-D Array Reference 1 2 3 Array Object 4 5 6


36

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

(Source code: Module02\Module02\11MultidimensionArray.cs) Multi dimensional arrays are always the collection of One dimensional arrays. One 1-D array for each row and one 1-D array of references to preserve references to the 1-D arrays which are carrying values.

36

Module 3: Classes and Objects


Overview
Classes and Objects Fields and Methods Access Control The this reference Constructors Overloading Properties Static Methods and Fields

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

37

37

Classes and Objects


Object An object is an instance of the class. It is a real time entity. A class does not have its own existence (memory allocation), objects created for those classes do. For this reason, objects are said to be an instance of a class. For e.g. Apple is an object of fruit class or car is an object of vehicle class. Each object has an attribute and behaviour. Attribute defines physical presentation of object and behaviour defines the tasks which the object can perform. Class A class can be considered as a generalized description of one or more objects that share the same set of attributes and responsibilities. A class is known as a user defined data type.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

38

38

Classes and Objects Continued


Object car john (Emp) Class Vehicle Employee Attributes Wheels, Engine, Headlights Empid, Empname, Salary Accno, Accname, Balance Name, Address, Semester ProductId, Productname, Quanity, Price Behaviour Speed(), CalcBonus()

bankAccoutntObj

BankAccount

Deposit(), Withdraw() Get Result()

smith

Student

coffee

Product

CalcTotalPrice()

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

39

An object is anything that is of some interest to an application under development. An object may represent some real-life entity, or an event, or some aspect of the solution strategy to a given business problem. In a banking application, an accountholder (or its data representation within the system) is an object. In a sales information system, a product is an object. In a library management system, students, faculty members, books are all objects. Objects have attributes; these are characteristics that describe the objects. For example, a student object may have the attributes such as name, address, semester, etc. A book object may have the attributes such as book ID, title, author, publisher, etc. While talking about objects, we cannot ignore talking about classes. A class can be considered as a generalized description of one or more objects that share the same set of attributes and responsibilities. For example, all employees belong to an Employee class.

39

Classes and Objects


Rectangle Class

CalcArea()

CalcPerimeter()

length=5

width=8

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

40

40

Creating a Rectangle Class


class Rectangle { float length=5; float breadth=8; public float CalcArea() { return length * breadth; } public float CalcPerimeter() { return 2 * (length + breadth); } } static void Main(string[] args) { //Class Instantiation Rectangle rectangleObject = new Rectangle(); Console.WriteLine(Area={0},rectangleObject.CalcArea().ToString()); Console.WriteLine(Perimeter={0},rectangleObject.CalcPerimeter().ToString()); Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

41

(Source code: Module03\SimpleClassObjectDemo\Rectangle.cs) A class may have zero, one or more fields; these are variables that hold data for an object of that class. The Rectangle class above has two fields: length, breadth. Every object of this class has its own specific instances of these variables. A class's methods contain the code that understands and manipulates the state of an object. The Rectangle class has various methods, such as CalcArea(), CalcPerimeter(). These methods modify or return some fields of the class. The code has one more class called Program, in the main method of which one object of the Rectangle class is created and used. All these aspects are explained in subsequently. In the above example the Rectangle class is instantiated using the new" keyword. The "rectangleObject" is the object reference which holds the Rectangles object. Using this reference the CalcArea() and CalcPerimeter() method is invoked through which the data is set.

41

Properties
In the previous example the values are assigned in the class itself. What if one wants to get input from the user?
Its not possible at this point of time. Because in C# by default class members are private. Hence the fields length and breadth are private. Private fields are not accessible from outside of the class.

C#.NET provides us solution for this as Properties.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

42

(Source code: Module03\SimpleClassObjectDemo\RectangleVersion3.cs) You can use both fields and properties to store information in an object. Although public fields and properties are almost indistinguishable from a client-application perspective, they are declared differently within a class. Whereas fields are simply public variables that a class exposes, properties use methods to control how values are set or returned. Properties have get and set accessor. Get accessor is used to return the value of a property Set accessor is used to set the value of a property; they have a parameter, usually called Value, with the same data type as the property itself. Property can be declare as ReadOnly or WriteOnly which help us to keep check on the variable. ReadOnly property allows only reading value of the variable. We can not change the value of the variable. Only have get accessor. WriteOnly property allows only setting value for the variable. We can not able to read the value from the variable. Only have set accessor.

42

Properties

(continued)
static void Main(string[] args){ Rectangle rectangleObject1 = new Rectangle(); rectangleObject1.Length = 5; rectangleObject1.Breadth = 8; Console.WriteLine(Area={0},rectangleObject1 .CalcArea().ToString()); Console.WriteLine(Perimeter={0}, rectangleObject1.CalcPerimeter().ToString()); Console.ReadLine(); }

Private //property field private float length; public float Length { get { return length; } set { length = value; } Private } field private float breadth; public float Breadth { }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

43

In the above code length and breadth are the private fields, hence can not be access from outside. Therefore public properties are defined for those private fields. It has get and set access specifiers. get returns the value and set assigns the to a field.

43

Constructors
Constructor is a special method which has same name as class. Constructor is invoked when the class is instantiated. Constructor method does not have any return type.
class Rectangle { float length; float breadth; //constructor public Rectangle() { length = 0; breadth = 0; } Constructor } invoked static void Main(string[] args){ Rectangle rectangleObject1 = new Rectangle(); ; } Instance creation

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

44

Constructors is a special method that is executed when an object of the class is to be created. A constructor is typically used to initialize the state of an object. A constructor is a special method that must be present in a class for the class to get instantiated. Constructor is having the same name as of the class. When there is no constructor present, .NET Framework will create one for you. When you instantiate an object by using the new keyword, the class's constructor is called. You can provide initialization code that is guaranteed to run when the object is instantiated. If you write a constructor explicitly in your class, .NET Framework won't create it anymore. Like other methods, a constructor can take parameters, but cannot return a value. The constructor of a class can never be explicitly called; it is automatically called when an object of the class is created by you. For every new instance the constructor is going to be called.

44

Constructor Overloading
class RectangleVersion2{ float length; float breadth; //constructor public RectangleVersion2() { this.length = 0; this.breadth = 0; } public RectangleVersion2(float _length, float _breadth) { this.length = _length; this.breadth = _breadth; } } static void Main(string[ ] args) { RectangleVersion2 rectangleObject1 = new RectangleVersion2(); RectangleVersion2 rectangleObject2 = new RectangleVersion2(8, 6); Console.ReadLine(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

45

(Source code: Module03\SimpleClassObjectDemo\RectangleVersion2.cs) A class can have two or more different methods (constructor, methods) with the same name, provided their signature is different. The signature of a method is The Name of the method Number of Parameters Types of Parameters Order of Parameter

This feature of having multiple methods with the same name but different signatures is known as overloading. When you call a method, the compiler determines the actual method to invoke based on the number and types of parameters supplied by you. However it is not overloaded by varying only one or more of the following items The modifiers such as public, shared, static The Parameter name The Parameter modifiers, such as ref and out The data type of the return value

Static constructor cannot be overloaded. We can only overload instance constructor.

45

The this Reference


public RectangleVersion2() { this.length = 0; this.breadth = 0; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

46

(Source code: Module03\SimpleClassObjectDemo\RectangleVersion2.cs) A method of an object can refer to itself by using the this reference. One common use of the this reference is when you need to pass a reference to the current object to some other method. The this reference is also often used when the name of some parameter is the same as the name of a data member.

46

Module 4: Class Library


Overview
Overview of Class Library Create Class Library. Create a Test Application.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

47

Overview of Class Library


The .NET framework is a collection of Base Class Libraries. E.g :- System, System.IO etc. As per business requirement you can create your own library and use it in one or more applications. A library is a reusable component which has an extension .dll which needs to be referenced from the executables.

UIApplication

.dll
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

48

Create Class Library

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

49

1. Start Microsoft Visual studio 2010 3. Name it as HRSystem.

New Project.

2. From the project types select Class Library.

49

Create Class Library


public class Employee { private int empId; private string empName; private double salary; //properties ....

public double CalcBonus(double percentage) { return salary * percentage; public Employee() { } } public Employee(int id,string Name, double sal) } { this.empId = id; this.empName = Name; this.salary = sal; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

50

50

Creating Class Library continued


Build EmployeeLibrary. It will generate .DLL file.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

51

Menu options for building project: 1. Click on Build Menu -> Build EmployeeLibrary.

51

Create a Test Application

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

52

1. Add a new Console Application in the same solution. 2. Save it as ABCCorporation. 3. Add reference to ABCCorporation project.

Menu option for adding the project: 1. File -> New Project -> Console Application. 2. Save as ABCCorporation. 3. From the solutions drop-down list select -> Add to Solution.

52

Adding reference of dll to Application

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

53

Menu options: 1.Click on Project -> Add reference . 2.From the dialogue box select projects tab -> select EmployeeLibrary.dll. (It the dll and application is in the same solution otherwise click on browse tab and select the required dll from the path).

53

Creating a Test Application


using EmployeeLibrary; class Program { static void Main(string[] args) { Employee employee = new Employee(1,"Trupti", 25000); double bonus=employee.CalcBonus(0.3); Console.WriteLine(Bonus={0},bonus); Console.ReadLine(); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

54

(Source code : C:\Training\Module04\EmployeeLibrary\ABCCorporation\Program.cs)

54

Set startup project

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

55

55

Static field
Static field is used when we want to have values that are shared across all instances of a particular class. Static fields and static constants enable this to happen by belonging to the class and not to the actual objects. In your application, you can declare a variable and refer to it regardless of which instance of an object you are using. Such a variable is called static.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

56

56

Static field
public class Employee { private static int Id=0; public Employee() { empId = 0; empName =unknown; salary = 0; } public Employee(int id,string Name, double sal) { ++id; this.empId = id; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

57

Assignment
Create a class library project. Add Product class with following members: Product
-productId ; -productName ; -unitPrice ; -Quantity + GetProducts(productname,unitprice,Quantity);

productId must me auto incremented. Display totalprice of product available


Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

58

Module 5. Inheritance
Overview Object Oriented Concepts Bank Case Study Inheritance Constructor in extended classes Overriding methods Polymorphism Use of Sealed keyword Abstract class and method Declaring Interface Implementing Interface

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

59

59

Object Oriented Concepts


Abstraction Encapsulation Inheritance Polymorphism

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

60

Abstraction refers to the description of externally visible behavior of an object. Abstraction is used to describe what an object does, rather than how it does it. Encapsulation is a description of the internal data structures and internal implementation that give rise to this externally visible behavior. Encapsulation deals with how the object does it. Inheritance facilitates reusability of code. A new class can inherit all the properties and methods of another existing class. Polymorphism refers to the ability to hide many implementations behind the common interface. Using polymorphism, a single name may denote objects of many different classes.

60

Bank Application
Create a class library project. Save it as BankLibrary. It will provide Business Logic of Banking Services.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

61

61

A BankAccount Class the Super Class


public class BankAccount { . ; public BankAccount() { .; } public BankAccount (string AccName, double Balance) { . ; } public int AccNumber { get ; } public string AccName { get ; set ; } public double Balance { get ; set ; } public double Withdraw(double amount) { ..; } public double Deposit(double amount) { .. ; } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

62

(Source code: C:\Training\Module05\BankLibrary\BankLibrary\BankAccount.cs)

62

Inheritance
Inheritance is a powerful feature of OOP. It provides following features: Reusability Easy maintenance of code. Extendibility

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

63

Inheritance Inheritance is a powerful feature of object-oriented programming languages. This refers to the ability of a class to inherit the fields and operations of another class, and extend these further. Inheritance can also be useful when two or more classes have some fields and operations in common. Instead of duplicating these common aspects in various classes, we can keep them in a base class, that other classes inherit from. For example, in a banking application, we may have a SavingsAccount class as well as a CurrentAccount class. Both these classes may have some common operations and fields, in addition to having their own specific fields and operations. Such common fields and operations can be kept in a common base class called BankAccount. The SavingsAccount and CurrentAccount classes can then inherit from the BankAccount class. In .NET, there is a class called Object. Every other class explicitly or implicitly inherits from the Object class. .Net allows single inheritance of the class.

63

Access Specifiers
Visibility / Access Specifier Same class Derived class in same assembly Other class Other class in other assembly Derived class in other assembly private protected internal public protected internal Yes Yes Yes No No

Yes No No No No

Yes Yes No No No

Yes Yes Yes No No

Yes Yes Yes Yes Yes

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

64

The SavingsAccount Class the Sub Class


public class SavingsAccount : BankAccount { .; static SavingsAccount() { . ; } public SavingsAccount(string AccName,double Balance,bool IsSalaryAccount) :base(AccName,Balance) { .. ; } public double CalculateInterest() { . ; } }

Using Derived class object


static void Main(string[ ] args) { SavingsAccount savingobject = new SavingsAccount(); . ; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

65

(Source code: Module04\Inheritance\SavingAccount.cs) An object of the SavingsAccount class would have all the fields other then private of its base class as well as the ones additionally defined within that class. Similarly, on an object of the SavingsAccount class, all the public and internal operations of the BankAccount class can be applied. In this program we have created the instance of SavingsAccount class, which is the derived class of the BankAccount class. All the members of the BankAccount class are created inside the memory of the SavingsAccount instance. It is calling the methods inherited from its base as well as of its own.

65

Calling parent class constructor


class BankAccount { public BankAccount(float balance) { . ; } } class SavingsAccount : BankAccount { public SavingsAccount(float balance, bool IsSalaryAccount) : base(balance) { .. } }

Object

BankAccount

SavingsAccount

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

66

(Source code: Module04\Inheritance\BankAccount.cs) (Source code: Module04\Inheritance\SavingAccount.cs) (Source code: Module04\Inheritance\Program.cs) A derived class must choose one of its super class constructors to invoke. The part of the object that is inherited from a super class must be initialized properly by the super class itself. The constructor of a derived class can invoke a base class's constructor using base keyword

66

Overriding Methods
A method in sub class with the same signature as a super class has but with different implementation is known as method overriding. Same signature means methods must have same name. same number of arguments same type of arguments. same access specifier Keyword virtual is used in base class method definition. Virtual indicates that this method can be overriden by sub class.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

67

A subclass can replace its super class's implementation of a method with one of its own. This is known as overriding a method. Both the signature and return type must be the same as the super class. In .Net by default method of super class cannot be overridden by sub class. For this sub class require permission from the super class Super class method should have keyword virtual and sub class method should have keyword override. virtual indicates that this method can be overridden by an identically named method in a derived class. virtual is the default setting for a method that itself overrides a base class method. Override keyword specifies that a property or method overrides a member inherited from a base class. This keyword indicates that method overrides an identically named method in a base class. The number and data types of the arguments, and the data type of the return value, must exactly match those of the base class procedure.

67

Overriding Methods continued


class BankAccount { public virtual void Withdraw(float amount) { . ; } } class SavingsAccount : BankAccount { public override void Withdraw(float amount) { .. ; } public override ToString() { . ; } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

68

(Source code: Module04\Inheritance\BankAccount.cs) (Source code: Module04\Inheritance\SavingAccount.cs) (Source code: Module04\Inheritance\Program.cs)

68

Polymorphism
Polymorphism is a Greek word which means many-shaped. It has two distinct aspects:
At run time object of inherited class may be treated as object of base class . Base classes may define and implement virtual methods and inherited classes may override these methods , which means inherited classes provide its own definition and implementation.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

69

Polymorphism
class BankAccount { .. ; public int AccountNumber { .. ; } public float Balance { .. ; } public BankAccount() { .. ; } public BankAccount(float _balance) { .. ; } public void Deposit(float amount) { .. ; } public virtual void Withdraw(float amount) { ; } } class SavingsAccount : BankAccount { .. ; static SavingsAccount() { . ;} public SavingsAccount() { .. ; } public SavingsAccount(float balance, bool IsSalaryAccount) : base(balance) { .. ; } public float CalculateInterest() { .. ; } public override void Withdraw(float amount) { . ; } } class CurrentAccount : BankAccount { ; public CurrentAccount(float balance, float overdraftlimit) : base(balance) { .. ; } public override void Withdraw(float amount) { .. ; } } static void Main(string[ ] args) { BankAccount Bankref; Bankref = new SavingsAccount(7000,true); Bankref = new CurrentAccount(4000, 2000); }
70

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

70

Preventing Overriding
class BankAccount { public virtual void Withdraw(float amount) { . ; } } class SavingsAccount : BankAccount { public sealed override void Withdraw(float amount) { .. ; } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

71

(Source code: Module04\SealedExample\BankAccount.cs) (Source code: Module04\SealedExample\SavingAccount.cs) (Source code: Module04\SealedExample\SubSavingAccount.cs) You can prevent subclasses from overriding the implementation of a method of a super class, by making it sealed. You can even make an entire class sealed, thereby preventing any extension of that class. All the methods of a sealed class are implicitly sealed. It can improve security. If a class is sealed, you know that nobody can extend it, and therefore, nobody can violate its contract. Similarly, if a method is sealed, you can rely on its implementation details. sealed is the default setting for a method that does not itself override a base class method.

71

Preventing Inheritance
sealed class SavingsAccount : BankAccount { } class SubSaving : SavingsAccount // compile time error { }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

72

Sealed classes are primarily used to prevent the inheritance. A sealed class can not be a base class. But it can be instantiated.

72

Abstract Class
The abstract keyword enables you to create classes and class members solely for the purpose of inheritance. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. An abstract class can not be instantiated. Abstract class public abstract class BankAccount { public abstract void Withdraw(float amount); } Abstract method

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

73

You can mark a class as abstract, which means that the class cannot be instantiated. This way you can create a class that cannot have objects, but serves as a base for other subclasses. For example in a bank we can have account as either saving or current but we cannot have account type as a bank. The use of this class would be only to extend it to SavingsAccount and BankAccount class for reducing duplication of work and maintenance. The opposite of abstract is concrete; a concrete class can be instantiated. For example, Clerk, Executive and Manager would be concrete classes, extending the Employee class. For example, SavingsAccount and CurrentAccount would be concrete classes, extending the BankAccount.

73

Interface
An interface contains only the signature of methods, delegates and events. The implementation of the methods is done in the class which implements the interface. An interface can inherit from one or more base interface.
public interface Iinterest { float CaclulateInterest(float irate); }

Method signature Interface implementation

class SavingAccount : BankAccount, Iinterest { public float CaclulateInterest(float irate) { . ; } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

74

An interface is a way to declare a type consisting only of abstract methods, Events or Properties. An interface provides a protocol binding to the classes that implement it. An interface cannot be instantiated. It consists of abstract methods, Events or Properties, i.e., it does not contain any implementation. An interface also cannot contain any variables.

74

Module 6. Exceptions Handling


Overview
What is Exception Handling? The try-catch Structure The finally Clause The throw Cause User Defined Exception

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

75

75

What is an Exception Handling?


Error which occurs during runtime is known as Exception. The mechanism to handle such errors during runtime is called as Exception Handling.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

76

try-catch-finally
C# provides 3 keywords to handle an Exception.
try :- The try keyword is required. It lets the compiler know that you are attempting a normal flow of a program. catch :-During runtime if any exception occurs instead of letting the program crash the flow of the program can be transferred to cache section. catch block is always followed by try. finally :- This block executes always. It is optional to use finally.

Syntax for try-catch-finally try { error prone code; } catch { statement for exception handling ; } finally { statement for clean up ; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

77

Structured Exception Handling concept is introduced in .NET Framework. The System.Exception is the base class for all the exceptions in .NET. C# provides three keywords try, catch and finally to do exception handling. The try keyword encloses the statements that might throw an exception whereas the catch keyword is used to handle an exception if one exists. The finally clause can be used for doing any clean up process

77

Understanding Exceptions
static void Main(string[ ] args) { int num1, num2, ans; Exception occurs here num1 = 10; num2 = 0; ans = num1 / num2; Console.WriteLine("Answer = " + ans); Console.ReadLine(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

78

There are three types of errors which occurs in program, Syntax errors, run-time errors and logical errors. Exception handling is mechanism to detect and handle run time errors. .NET provides us Exception Handling techniques to overcome such situations. There are two types of exceptions: System Exception - Exceptions generated by CLR. Application Exception - Exceptions generated in application When we run the above code, it will get compile but at run time when control come to the line ans = num1 \ num2", it will throw an exception. We require to manage this type of error which is known as Exception Handling

78

Exception Handling Mechanism


static void Main(string[ ] args) { . ; try { int num1, num2, ans; num1 = 10; num2 = 0; ans = num1 / num2; Console.WriteLine("Answer = " + ans); } catch (DivideByZeroException ex) { Console.WriteLine(ex.Message); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

79

(Source code: Module05\ExceptionHandling\ExceptionHandling\Program1.cs) If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks. If there is no exception occurred inside the try block, the control directly transfers to finally block. The statements inside the finally block is executed always.

79

Multiple Catch Block


int num1, ans; int[ ] numarray = new int[1]; try { num1 = 10; numarray[0] = 5; ans = num1 / numarray[1]; Console.WriteLine("Answer = " + ans); } catch (DivideByZeroException ex) { . ; } catch (IndexOutOfRangeException ex) { Console.WriteLine(ex.Message); } catch (Exception ex) { } finally { }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

80

(Source code: Module05\ExceptionHandling\ExceptionHandling\Program2.cs) A try block can throw multiple exceptions, which can be handled by using multiple catch blocks. We can use generalized Exception class to handle any type of runtime exception. Add the generalize catch block as the last catch block in the hierarchy otherwise at the compile time it will give an error. A previous catch clause already catches all exceptions of this or of a super type ('System.Exception') Some of the Exception classes are System.Exception System.DevideByZeroException System.NullReferenceException Syste.InvalidCastException System.IndexOutOfRangeException etc.

80

finally
finally : Code in finally block is always executed. It contain clean up code to release the resources.
int num1, ans; int[ ] numarray = new int[1]; try { ; } catch (DivideByZeroException ex) { . ; } catch (IndexOutOfRangeException ex) { ; } finally { Console.WriteLine(End of Main Block); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

81

Finally can be used in such cases where its needed to free-up the resources always. Finally block is optional.

81

throw
throw : Exceptions can be explicitly generated by using a throw keyword.
int num1, num2, ans; num1 = 10, num2 = 0; if(num1/num2) { throw new DivideByZeroException(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

82

We can create our own exception by creating a class and inheriting it from the Exception base class. To throw the exception throw keyword is used throw keyword is used to raise an Exception. Sometimes it may happen that a method that is called might be getting an exception which is handled by the caller of that method. In such situation the throw keyword is used.

82

User defined Exceptions


It is possible to create our own exception (user defined exception) classes. System.Exception must be base class for all the exception classes. In the constructor needs to define the steps which you want to perform.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

83

83

User Defined Exceptions


class BalanceException : Exception { public BalanceException(string msg) :base(msg) { } } class SavingsAccount { .. ; public SavingsAccount() { . ; } public void Withdraw(float amount) { if ((balance - amount) > 500) balance -= amount; throw exception else throw new BalanceException("Not enough balance"); } } User defined exception class static void Main() { SavingsAccount saving = new SavingsAccount(); try { saving.Withdraw(3000); } catch (BalanceException ex) { Console.WriteLine(ex.Message); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

84

(Source code: Module05\ExceptionHandling\ExceptionHandling\BalanceException.cs)

84

Module 7. Other C# Features


Overview
Structure enum Type casting Boxing Unboxing ref and out parameter Operator overloading Partial class Static class

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

85

85

Structure
Structure is a generalization of the user defined data type. Used when a single variable is required to hold multiple types of data Structure is a value type.
struct Employee { .. ; public Employee(int id, string name, string add, float sal) { .. ; } public float AnnualSalary() { . ; } } static void Main() { Employee emp1 = new Employee(101, Smith", "Mumbai", 2000.00f); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

86

(Source code: Module06\Module06\StructureExample.cs) Structure is a type like a class which we can define within the namespace. The members of a structure cannot be initialized within the structure declaration A structure can have instance constructors only if they take parameters A structure can have property or method Structure procedures cannot handle events A structure is not inheritable A structure can implement interface Structure Structure is Value Types. (Stack memory) By default all elements declared in structure are public. Can have instance constructor only if they take parameters. Unlike classes, structure can be instantiated without using a new operator. Structure can not inherit from other structure or classes Structure can implement interface

86

enum
enum is a set of symbolic names that map to known numerical values. enum is a set of named constant collection of integer value.
enum Months { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec } class enumExample { static void Main() { Console.WriteLine(Months.Apr); Console.WriteLine((int)Months.Apr); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

87

(Source code: Module06\Module06\enumExample.cs)

By default first enumerator value start from 0 and the value of each successive enumerator is increased by 1. enum Months { Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec } You can assign integer value to the individual enumerator and the value of each successive enumerator is increased by 1. enum Months { Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }

87

Type Casting
Converting value type to another value type
OR

Convert reference type to another reference type


static void Main() { decimal number = 3.14M; int i = (int)number; Console.WriteLine("decimal value = {0}", number); Console.WriteLine("int i = {0}", i); Console.ReadLine(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

88

(Source code: Module06\Module06\TypecastingExample.cs)

88

Boxing - Unboxing
Boxing is an implicit conversion of a value type to the reference type. Unboxing is an explicit conversion from the reference type to a value type.
static void Main() { int i = 10; //value type object obj = i; //boxing int j = (int)obj; //unboxing Console.WriteLine(i.ToString()); Console.WriteLine(obj.ToString()); Console.WriteLine(j.ToString()); Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

89

Value types are stored on the stack memory and Reference types are stored on the Heap memory.

89

Ref Parameter
class RefExample { static void Methodref(ref int i) { i = 100; } static void Main() { int number = 0; Console.WriteLine("Value of number = " + number.ToString()); Methodref(ref number); Console.WriteLine("Value of number = " + number.ToString()); Console.ReadLine(); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

90

(Source code: Module06\Module06\RefExample.cs) Ref parameter means argument passing by reference. Any changes to the parameter in the method will be applied to the variable when the control passes back to the calling method. To use the ref parameter, both the method and the calling method must explicitly use the ref keyword. An argument passed to a ref parameter must first be initialized.

90

Out Parameter
class OutExample { static void methodout(out int i, out string str) { i = 100; str="assigned value to out parameter"; } static void Main() { int number; string line; methodout(out number, out line); Console.WriteLine("number = " + number.ToString()); Console.WriteLine("line = " + line); Console.ReadLine(); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

91

(Source code: Module06\Module06\OutExample.cs) out parameter means argument passing by reference. Any changes to the parameter in the method will be applied to the variable when the control passes back to the calling method. To use the out parameter, both the method and the calling method must explicitly use the out keyword. An argument passed to an out parameter do not require to be initialized first. Although variable passed as out arguments do not have to be initialized before being passed, the calling method is required to assign a value before the method returns.

91

Operator Overloading
class OrderItem { private string productid; private Int32 quantity; private decimal unitprice; public string ProductID { get { return productid; } set { productid = value; } } public Int32 Quantity { get { return quantity; } set { quantity = value; } } public decimal UnitPrice { get { return unitprice; } set { unitprice = value; } } public decimal Total { get { return UnitPrice * Quantity; } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

92

(Source code: Module06\Module06\OperatorOverloadingExample.cs) Operator overloading means use of operator with an object. It gives better readability Operator overloading method always have public static access specifiers. Operator overloading always return a type and never be void. At least one operand must be of user defined type. Relational operators are overloaded in pairs only. The ref and out parameters are not allowed as arguments. Syntax public static return_type operator op ( argument list ) {}

92

Operator Overloading

(Contd)

public static OrderItem operator +(OrderItem Item1, OrderItem Item2) { if (Item1.ProductID != Item2.ProductID) { throw new Exception("You can only add OrderItems where the ProductID is the same for both objects"); } else if (Item1.UnitPrice != Item2.UnitPrice) { throw new Exception("You can only add OrderItems where the UnitPrice is the same for both objects"); } else { OrderItem item = new OrderItem(); item.ProductID = Item1.ProductID; item.Quantity = Item1.Quantity + Item2.Quantity; item.UnitPrice = Item1.UnitPrice; return item; } } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

93

(Source code: Module06\Module06\OperatorOverloadingExample.cs) Operators All binary operators can be overloaded +, -, *, /, %, &, | etc. All unary operators can be overloaded +, -, !, ~, ++, --, true, false All relational operators can be overloaded, but only in pairs ==, !=, > , <, >=, <= Operators cannot be overloaded &&, ||, () (conversion operator), =, ., ?:, ->, new, is, as, sizeof, Following operators are automatically overloaded when the respective binary operator is overloaded +=, -=, *=, /=

93

Operator Overloading

(Contd)

static void Main() { OrderItem Item1 = new OrderItem(); OrderItem Item2 = new OrderItem(); OrderItem Item3; try { Item1.ProductID = "1"; Item1.Quantity = 5; Item1.UnitPrice = 10; Item2.ProductID = "1"; Item2.Quantity = 4; Item2.UnitPrice = 10; Item3 = Item1 + Item2; Console.WriteLine(Item3.Total); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

94

(Source code: Module06\Module06\OperatorOverloadingExample.cs)

94

Partial Type
partial class PartialTest { public void Method2(int i) { number = i; Console.WriteLine("number = " + number); } } partial class PartialTest { private int number; public int Method1(int i) { return i++; } } class PartialExample { static void Main() { PartialTest obj = new PartialTest(); Console.WriteLine(obj.Method1(100).ToString()); obj.Method2(10); Console.ReadLine(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

95

(Source code: Module06\Module06\PartialExample.cs) Partial class means class or structure definition can be split into multiple physical files. And all files are combined when the application is compiled. Can be used when working on a large project, allow multiple programmer to work on it simultaneously. Separate the business logic( user defined code) and system generated code in separate file. For example Windows Form Rules of partial class All parts require to be define in same namespace. Each part require to be available at compile time. Must use the same access specifiers. (public, private,) If any single part is defined as abstract, then the whole class is abstract. If any single part is sealed, then the whole class is sealed. If any part declare a base type, then the whole class inherits that base class. Parts can specify different interface, but the whole class implements all interfaces.

95

Static class
static class Temperature { public static double CelsiusToFahrenheit(double celsius) { //convert celsius to fahrenheit double Fahrenheit = (celsius * 9 / 5) + 32; return Fahrenheit; } public static double FahrenheitToCelsius(double fahrenheit) { double Celsius = (fahrenheit - 32) * 5 / 9; return Celsius; } } class StaticExample { static void Main(){ double F, C; F= 100; C = 35; Console.WriteLine("{0} degree Celsius temperature in Fahrenheit: {1:F2}",C, Temperature.CelsiusToFahrenheit(C)); Console.WriteLine("{0} degree Fahrenhit temperature in Celsius: {1:F2}",F, Temperature.FahrenheitToCelsius(F)); Console.ReadLine(); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

96

(Source code: Module06\Module06\StaticExample.cs) Static class means class cannot be instantiated. It can contain only static members. And the class is sealed means cannot be inherited.

96

Auto - Implemented Property


class Person { public string Name { get; set; } public int Age { get; set; } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

97

(Source code: Module06\Module06\ObjectInitializerExample.cs)

Auto implemented Property Auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessor. Automatic properties allow you to avoid declaring manually a private field and write the get/set accessor -- instead the compiler create the private field and the default get/set accessor. You cannot write any validation for auto implemented properties. Auto-implemented properties must declare both a get and a set accessor. To create a readonly auto-implemented property, give it a private set accessor.

97

Object Initializer
class ObjectInitializerExample { static void Main() { Person pobj = new Person { Name = "Bhavana", Age = 18 }; Console.WriteLine("Name = " + pobj.Name); Console.WriteLine("Age = " + pobj.Age); Console.ReadLine(); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

98

(Source code: Module06\Module06\ObjectInitializerExample.cs) Object initializer allow you to include an initializer that specifies the initial values of the members of a newly created object. This enables you to combine declaration and initialization in one step.

98

Module 8. String, StringBuilder, Dateformat


Overview
Useful method of string class. StringBuilder class. Dateformats. Output formats.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

99

99

String Class methods


Various property and methods of string class Property of string class Length Gets the number of characters.
string s= "welcome"; Console.WriteLine(s.Length);

//7

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

100

(Source code: Module07\StringExample\StringExample\Program.cs) String is an immutable, means data cannot be changed. Whenever we try to change the data of string type, it is returning or creating brand new string object Escape Characters \ Single quote \ double quote \\ - file paths \a triggers system alert(beep) \n new line \t horizontal tab

100

String class methods

(Contd)

Comparing Strings The compare method compares two strings and returns an integer value
string s = "welcome"; string s1 = "Welcome"; int i; i = string.Compare(s, s1); Console.WriteLine(i); //-1 s = "welcome"; s1 = "welcome"; i = string.Compare(s, s1); Console.WriteLine(i); //0 s = "Welcome"; s1 = "welcome"; i = string.Compare(s, s1); Console.WriteLine(i); //+1
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

101

(Source code: Module07\StringExample\StringExample\Program.cs)

101

String class methods

(Contd)

Concat the concat method concatenate two strings and returns a new string
string s = "Hello"; string s1 = "World"; Console.WriteLine(string.Concat(s, s1));

//HelloWorid

Copy Creates a new instance of string with the same value as a specified string
string s = "Hello"; string s1; s1 = string.Copy(s); Console.WriteLine(s1);
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

102

(Source code: Module07\StringExample\StringExample\Program.cs)

102

String class methods

(Contd)

Ends with Determines whether the end of the string matches the specified string. Returns boolean result true or false.
string s = "Welcome"; Console.WriteLine (s.EndsWith ("me")); // true

Equals Determines whether two String objects have the same value. Returns Boolean result true or false.
string s = "Welcome"; string s1= "welcome"; Console.WriteLine(s.Equals(s1)); //false

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

103

(Source code: Module07\StringExample\StringExample\Program.cs)

103

String class methods

(Contd)

IndexOf Return the index of the given String parameter in a Searched String.
string s= "Welcome"; int i = s.IndexOf ("e"); //1 Console.WriteLine(i); i = s.IndexOf ("e", 2); //6 Console.WriteLine(i);

LastIndexOf Returns the index position of the last occurrence of a specified String within the Searched String.
string s= "Welcome"; int i = s.LastIndexOf ("e"); //6 Console.WriteLine(i);
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

104

(Source code: Module07\StringExample\StringExample\Program.cs)

104

String class methods

(Contd)

PadLeft Right-aligns the String, padding on the left with spaces or a specified character for a specified total length. PadRight Left-aligns the String, padding on the right with spaces or a specified character, for a specified total length.
string s= "Welcome"; Console.WriteLine(s.PadLeft(10, '*')); //***Welcome Console.WriteLine(s.PadRight(10, '*')); //Welcome***

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

105

(Source code: Module07\StringExample\StringExample\Program.cs)

105

String class methods

(Contd)

Remove Remove the characters from specified position in a given String.


string s= "Welcome"; Console.WriteLine(s.Remove(3, 4)) ; // Wel

Replace Replaces all occurrences of a specified character or String, with another specified character or string.
string s = "Welcome"; Console.WriteLine (s.Replace ("e", "a")); // Walcoma

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

106

(Source code: Module07\StringExample\StringExample\Program.cs)

106

String class methods


StartWith

(Contd)

Determines whether the beginning of the String matches the specified String parameter. Returns Boolean value true or false.
string s = "Welcome"; Console.WriteLine (s.StartsWith ("We")); // true

Substring Returns part of a string


string s = "Welcome"; Console.WriteLine(s.Substring(3)); // come Console.WriteLine(s.Substring(3, 3)); // com

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

107

(Source code: Module07\StringExample\StringExample\Program.cs)

107

String class methods

(Contd)

ToLower Returns a String in lowercase ToUpper Returns a copy of the String in uppercase.
string s= "WELCOME"; Console.WriteLine (s.ToLower()); // welcome string s1 = "welcome"; Console.WriteLine (s1.ToUpper()); //WELCOME

ToString Converts the value to a String type.


Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

108

(Source code: Module07\StringExample\StringExample\Program.cs)

108

String class methods


Trim

(Contd)

Removes all occurrences of a set of specified character from the beginning and end of the String.

TrimEnd
Removes all occurrences of a set of specified character from the end of the String.

TrimStart
Removes all occurrences of a set of specified character from the beginning of the String. String s= "-----------WELCOME-----------"; Console.WriteLine (s); Console.WriteLine (s.Trim('-')); //WELCOME Console.WriteLine (s.TrimEnd('-')); //-----------WELCOME Console.WriteLine (s.TrimStart('-')); //WELCOME---------Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

109

(Source code: Module07\StringExample\StringExample\Program.cs)

109

StringBuilder Class
The StringBuilder class represents a mutable string of characters. static void Main(string[ ] args) { StringBuilder builder = new StringBuilder("Hello wrold. "); Console.WriteLine(builder); builder.Append("This is class test."); Console.WriteLine(builder); builder.Insert(21, "StringBuilder "); Console.WriteLine(builder); builder.Remove(5, 6); Console.WriteLine(builder); builder.Replace(".", "!"); Console.WriteLine(builder); Console.WriteLine("Length = " + builder.Length); Console.ReadLine(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

110

(Source code: Module07\StringBuilderExample\StringBuilderExample\Program.cs) A string is a sequential collection of Unicode characters used to represent text. It is immutable because once specified the text can not be changed. There are methods to modify string but they will return a new string object with the changes made. These changes will not happen to the existing string object. The StringBuilder class represents a mutable string of characters. It's called mutable because it can be modified once it has been created by using Append, Insert, Remove, and Replace methods. The changes will happen to the existing StringBuilder object The StringBuilder class is defined in the System.Text namespace.

110

Date formats
Specifier d D t T f F g G Description Short Date Long Date Short Time Long Time Full date and time Full date and time (long) Default date and time 8/4/2012 8-Apr-12 21:08 21:08:59 4/8/2012 21:08 4/8/2012 21:08 8/4/2012 21:08 Output

Default date and time (long) 8/4/2012 21:08


111

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

Date formats continued


Specifier M r s u Y dd ddd dddd Description Day / Month RFC1123 date Sortable date/time Output 8-Apr Sun, 08 Apr 2012 21:08:59 GMT 2012-04-08T21:08:59

Universal time, local timezone 2012-04-08 21:08:59Z Month / Year Day Short Day Name Full Day Name Apr-12 8 Sun Sunday
112

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

Date formats continued


Specifier hh HH mm MM MMM MMMM ss tt Description 2 digit hour 2 digit hour (24 hour) 2 digit minute Month Short Month name Month name seconds AM/PM 9 21 8 4 Apr April 59 PM
113

Output

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

Date formats continued


Specifier yy yyyy Description 2 digit year 4 digit year seperator, e.g. {0:hh:mm:ss} seperator, e.g. {0:dd/MM/yyyy} Output 7 2012 9:08:59 8/4/2012

: /

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

114

Date formats continued


DateTime time = DateTime.Now; string format = "ddd"+" "+"dd-MMM-yyyy"; Console.WriteLine(time.ToString(format)); Console.ReadLine();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

115

Output formats
Character C or c D or d E or e F or f G or g N or n X or x Description Currency Decimal Scientific Fixed-point General Number Examples Console.Write("{0:C}", 2.5); Console.Write("{0:C}", -2.5); Console.Write("{0:D5}", 25); Console.Write("{0:E}", 250000); Console.Write("{0:F2}", 25); Console.Write("{0:F0}", 25); Output $2.50 ($2.50) 25 2.50E+05 25 25

Console.Write("{0:G}", 2.5); 2.5 Console.Write("{0:N}", 2500000); 2,500,000.00 FA FFFF

Hexadecimal Console.Write("{0:X}", 250); Console.Write("{0:X}", 0xffff);

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

116

116

Module 9. Collections
Overview
System.Collections Namespace. ArrayList HashTable Collection Initializer

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

117

117

Collection Classes
A collection is a set of objects. Using collection we can organize and manipulate the objects. Can keep the track of objects. The System.Collection namespace contains the different types of collection classes, such as Stack, Queue, ArrayList, HashTable, etc.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

118

118

ArrayList
ArrayList is a collection of element of different types. It increases the size of the storage location as required. It stores the value as object. It represents dynamically sized array of objects. It is contained in the namespace System.Collections;

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

119

ArrayList Example
Using System.Collection; static void Main(string[ ] args) { ArrayList countryList = new ArrayList(); countryList.Add("India"); Console.WriteLine("Total items = " + countryList.Count.ToString()); for (int i = 0; i < countryList.Count; i++) { Console.WriteLine(countryList[i].ToString()); } //insert value countryList.Insert(1, "France"); Console.WriteLine("\n-------print specific item form the arraylist object-------\n"); Console.WriteLine(countryList[2].ToString()); } //reverse countryList.Reverse(); //sort countryList.Sort(); //RemoveAt() countryList.RemoveAt(2); //Clear() countryList.Clear(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

120

(Source code: Module07\CollectionExample\CollectionExample\ArrayListExample.cs) ArrayList is the collection of elements of different type Elements in this collection can be accessed using an integer index. Indexes in this collection are zerobased.

120

HashTable
HashTable object contains Items in key and value pair. Keys are used as indexes. Values can be searched by using keys.

MH GA GJ TN AP RJ

Maharashtra Goa Gujrat Tamilnadu Andra pradesh Rajasthan

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

121

HashTable Example
static void Main() { Hashtable hashlist = new Hashtable(); hashlist.Add("txt", "notepad.exe"); hashlist.Add("bmp", "paint.exe"); hashlist.Add("rtf", "wrodpad.exe"); // The Add method throws an exception if the new key is already in the hash table. try { hashlist.Add("txt", "winword.exe"); } catch { Console.WriteLine("An element with Key txt already exists."); } Console.WriteLine("\n------------------------------\n"); //DictionaryEntry - Defines a dictionary key/value pair that can be set or retrieved. foreach (DictionaryEntry de in hashlist) { Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value); } Console.WriteLine("\n------------------------------\n"); //Printing the value of the specific key Console.WriteLine("For key = rtf, value = {0}.", hashlist["rtf"]); Console.ReadLine(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

122

(Source code: Module07\CollectionExample\CollectionExample\HashTableExample.cs) HashTable represents a collection of key/value pairs that are organized based on the hash code of the key.

122

Stack
Stack represents last-in-first-out (LIFO) . You may assume kitchen dish stack. You can pull out a top most dish which is kept in stack very last. It simply consists of non-generic collection of objects. pop push

5 4 3 2 1 0

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

123

Stack Example
static void Main() { Stack stackobj = new Stack(); stackobj.Push("Hello"); stackobj.Push("Stack"); stackobj.Push("class"); stackobj.Push("example"); Console.WriteLine("Count = " + stackobj.Count.ToString()); Console.WriteLine("\n------------------\n"); foreach (Object obj in stackobj) { Console.WriteLine(obj.ToString()); } Console.WriteLine("\n---------Top Element- peek method---------\n"); Console.WriteLine(stackobj.Peek()); Console.WriteLine("\n---------Top Element- pop method---------\n"); Console.WriteLine(stackobj.Pop()); Console.WriteLine("\n---------count---------\n"); Console.WriteLine("Count = " + stackobj.Count.ToString()); foreach (Object obj in stackobj) { Console.WriteLine(obj.ToString()); } Console.ReadLine(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

124

124

Queue
Queue represents first-in-first-out (FIFO) . We can Enqueue (add) items in queue. We can Dequeue (remove) items from queue.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

125

Queue Class
static void Main() { Queue queueobj = new Queue(); queueobj.Enqueue("Hello"); queueobj.Enqueue("Queue"); queueobj.Enqueue("class"); queueobj.Enqueue("example"); Console.WriteLine("Count = " + queueobj.Count.ToString()); foreach (Object obj in queueobj) { Console.WriteLine(obj.ToString()); } Console.WriteLine("\n---------Top Element- ---------\n, queueobj.Dequeue()); Console.WriteLine("\n---------count----------\n, queueobj.Count.ToString()); foreach (Object obj in queueobj) { Console.WriteLine(obj.ToString()); } Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

126

(Source code: Module07\CollectionExample\CollectionExample\QueueExample.cs)

126

Linked List
A Linked list is a data structure consisting of group nodes which together represents a sequence.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

127

Collection Initializer
Able to give values to collections in a concise and compact manner
static void Main() { ArrayList countryList = new ArrayList { "India", "Usa", "Japan" }; for (int i = 0; i < countryList.Count; i++) { Console.WriteLine(countryList[i].ToString()); } Console.ReadLine(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

128

(Source code: Module07\CollectionExample\CollectionExample\CollectionInitializerExample.cs)

128

Module 10. Generics and Nullable Types


Overview
Limitations of Collection Classes Understanding Generics Advantages of generics over collection Nullable Types

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

129

129

Limitation of Collection Classes


class Person { for (int i = 0; i < list.Count; i++) { list[i]. //error 1 string name, address; public Person(string name, string address) { this.name = name; this.address = address; } //error 2 public void Display(){ ((Person)list[i]).Display(); } Console.WriteLine ("Name = " + name); Console.WriteLine("Address = " + address); } } static void Main(string[] args) { ArrayList list = new ArrayList(); //error 3 list.Add(new Person("Bhavana", "Mumbai")); int temp =int.Parse( list[0].ToString()); } list.Add(new Person("Vishal", "Mumbai")); list.Add("Krishna");

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

130

Whenever we store any data to the collection class object they are always maintained as Object type. Because of this it is possible that we can store different type of data in collection object. This feature one way is advantageous that we can store different types of value in collection, but this feature also have some disadvantages Error 1 We are storing different type of values in the ArrayList object We have added the object of Person class which is user defined type. While retrieving the members of the list object we typed list[i]. Which gives public member of the Object class only and it will not give the public member which you have defined in Person class. Error 2 You require to explicitly typecast the member. After typecasting it will give the public member of the Person class. But it will give an error at the run time when in the for loop when we try to retrieve the third item which is not of the Person type. Error 3 At the compilation time it allows us to convent any member of the ArrayList to int type or any other type. But at the run time when it require to assign the value of user defined type to an int type it will give an error.

130

Why Generics?
In the earlier code example two major issues were faced as follows:
Boxing and unboxing overhead : Boxing and unboxing operations lead to performance overhead since it involves dynamic memory allocation and runtime type check. No strong type data at compilation time : The earlier code is technically correct. Error will be not be thrown at compile time. But when the code is executed it will throw an exception InvalidCastException.

Generics has solution for these limitations.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

131

Generics
Type Safety -- Generic types enforce type compliance at compile-time, and not run-time (as in the case of using Object). This reduces the chances of data-type conflict during run-time Performance -- The data types to be used in a Generic class are determined at compile-time, hence there is no need to perform type casting during run-time, which is a computationally costly process. Code reuse -- Since you only need to write the class once and customize it to use with the various data types, there is a substantial amount of code-reuse.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

132

Comparison between Generic, Collection and Array To define an array, we have to give the fix size. The size cant be dynamically increased. Every time reallocation of memory happens. Collections are dynamic. To store or retrieve a value, it performs boxing and un-boxing which affects performance considerably. Whereas generics are type safe. While defining it we have to provide a type. No other type value can be stored.

132

Generics List<T> Collection


static void Main() { List<string> liststr = new List<string>(); liststr.Add("Vishal"); liststr.Add("Amit"); //liststr.Add(new Person("Pankaj", "Mumbai")); //compile time error for (int i = 0; i < liststr.Count; i++) { Console.WriteLine(liststr[i]); } Console.WriteLine("\n-------------------------------\n"); List<Person> listperson = new List<Person>(); listperson.Add(new Person("Bhavana", "Mumbai")); listperson.Add(new Person("Pankaj", "Mumbai")); for (int i = 0; i < listperson.Count; i++) { listperson[i].Display(); } Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

133

133

Generic Dictionary<key,value> collection


class Customers { . public Customers(string Name, string Location) { .. } public int CustId { get ; } public string CustName { get; set; } public string CustLocation {get; set; } public void displayCust() { } } static void Main(string[] args) { Dictionary<int, Customers> customerDictionary = new Dictionary<int,Customers>(); Customers customer3 = new Customers("Anju", "Borivali"); Customers customer4 = new Customers(Amit", "Kalyan"); foreach (KeyValuePair<int, Customers> custKeyValue in customerDictionary) { Console.WriteLine( custKeyValue.Key, custKeyValue.Value.CustName, custKeyValue.Value.CustLocation); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

134

Generic Dictionary collection stores information into key/value pair. There is a non generic collection HashTable which also stores the information into key/value pair. But it stores data of type object.

134

Creating our own Generic Classes


class GenericClass<T> { T value1, value2; public UserdefinedGeneric(T val1, T val2) { value1 = val1; value2 = val2; } public void Swap() { T temp = value1; value1 = value2; value2 = temp; Console.WriteLine(value1 + " + value2); } } static void Main(string[] args) { UserdefinedGeneric<string> obj1 = new UserdefinedGeneric<string>("Trupti", Hello"); obj1.Swap(); UserdefinedGeneric<int> obj2 = new UserdefinedGeneric<int>(25", 50"); obj2.Swap();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

135

Generic is a technique with which you can delay the specification of the type of one or more programming elements in a class or a method ,until the time of the usage of that class or method. With generics instead of specifying the data type of the parameters, you define labels, which can later be replaced by the data type that the user specifies at the time of using the generic method or class Generic is a type parameter, which allows to design a class or method where the value of the type is specified at the time of instantiating class or usage of a method.

135

Nullable Type
static void Main() { int number1 = 10; Nullable<int> number2 = null; int? number3 = null; try { Console.WriteLine("number1 = " + number1.ToString()); Console.WriteLine("number2 = " + number2.Value); Console.WriteLine("number3 = " + number3.ToString()); Console.WriteLine("\n------------------------------\n"); if (number2.HasValue == true) Console.WriteLine("number2 = " + number2.Value); else Console.WriteLine("Null value"); Console.WriteLine("\n------arithmatic operation with nullable type--------\n"); Console.WriteLine(number1 + number2.GetValueOrDefault(0)); number2 = 100; Console.WriteLine(number1 + number2.GetValueOrDefault(0)); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine();
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

136

Nullable type One of the primary differences between value types such as int or structures and reference types such as string is that reference types support a null value. That is to say, a reference type variable can contain the value null, which means that the variable doesn't actually refer to a value. In contrast, a value type variable always contains a value. An int variable always contains a value, even if that number is zero. Nullable type adds nullability to any value type.

136

Module 11. Windows Form - I


Overview
Introduction to Window Forms IDE Creating forms with controls Responding to form events Using basic controls (e.g. Label, TextBox, Button, etc.) Anchor and Dock Properties

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

137

137

Visual Studio IDE


ToolBox Form Design View Solution Explorer Property Window

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

138

GUI application helps us to create user interface. A well designed interface makes the application more users friendly. In a windows based application, user interface is accomplished with windows Forms and controls. Windows form is a base container for user interface. A control is an object that can be drawn on to the Form to enable or enhance user interaction with the application. Examples of these control, TextBox, Button, Label, Radio Button etc. All these Windows Controls are based on the Control class, which is the base class for all controls. To create GUI application, Start Visual Studio .Net, from Project Window select Template type as Windows Application. System will open visual studio .net IDE which include Form Designer, Solution Explorer, Property window, toolbox etc.

138

Introduction to Controls
Label TextBox MultiLine TextBox ListBox CheckBox

RadioButton ComboBox

Button

GroupBox
139

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

Form is a base unit on which we can place the controls. Every controls including Form will have properties, methods and events. Forms properties Text Value to be display in the title bar WindowState Initial visual state of a form

139

Label Example
Display dynamic time.

private void timer1_Tick(object sender, EventArgs e) { lbldatetime.Text = DateTime.Now.ToString(); } private void DynamicTime_Load(object sender, EventArgs e) { lbldatetime.Text = DateTime.Now.ToString(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

140

(Source code: Module10\WinForm1\WinForm1\DynamicTime.cs) Label Properties Name lbldatetime Text empty Timer control from the component tab Properties Enable True Interval 1000

140

MessageBox Class
Use to display informative message to the user and can take user confirmation.
MessageBox.Show("Welcome to GUI Application");

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

141

(Source code: Module10\WinForm1\WinForm1\Form1.cs) Static method MessageBox.show() is used to accept the message, title, buttons and icon as parameters. Only message is the compulsory parameter.

141

Login Form Example

public partial class LoginForm : Form { int count = 0; public LoginForm() { InitializeComponent(); } private void btncancel_Click(object sender, EventArgs e) { this.Close(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

142

(Source code: Module10\WinForm1\WinForm1\LoginForm.cs) Design a form which accept user name and password. Check username as pragati and password as admin. If username and password are correct then show the Win Form welcome else display the proper error message in the message box. Give three chance to write the correct username and password else display appropriate message and close the application. Label Display static text from providing information. Properties Name - Control Name Text Value to be displayed AutoSize Allow automatic resizing according to the txt length

142

Login Form Example

(Contd)

private void btnsubmit_Click(object sender, EventArgs e) { if (txtusername.Text == "pragati" && txtpwd.Text == "admin") { Welcome frm = new Welcome(); this.Hide(); frm.Show(); } else { MessageBox.Show("Invalid username or password. Please provide the correct value", "Login"); count = count + 1; txtusername.Clear(); txtpwd.Clear(); txtusername.Focus(); } if (count == 3) { MessageBox.Show("Sorry! Please try again", "Login"); this.Close(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

143

(Source code: Module10\WinForm1\WinForm1\LoginForm.cs) TextBox Display text to the user and accept the input from the user. Properties Name Control Name Text Display or accept the text Multiline convert single line textbox into multi line textbox PasswordChar set a character that acts as a placeholder for the characters. Button Perform an action Properties Name - Control name Text Value to be displayed AutoSize Controls automatically size itself to fit its content. Image Image to be displayed

143

Welcome Form

private void btnclose_Click(object sender, EventArgs e) { Application.Exit(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

144

(Source code: Module10\WinForm1\WinForm1\Welcome.cs) This.Close() will close the individual form while Application.Exit() method will close all the form which are loaded in memory for that application.

144

ComboBox Example

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

145

(Source code: Module10\WinForm1\WinForm1\ComboBoxExample.cs) Select your qualification and computer skills from the list given below. Select the country from the combo dropdown. If users want he/she can add the country name in the combo dropdown. While adding the new data keep check that no duplication allowed. Same time if user wants he/she can delete the country name from the list. ComboBox Display a drop down list of items, from which user can select any one item. Properties Name Control name Text Selected text from the list Items Collection of the items to be displayed in drop down DropdownStyle Appearance and functionality of combo box Add some country name in combo box at design time by using Items property. We can also add data dynamically.

145

ComboBox Example

(Contd)

private void btnadd_Click(object sender, EventArgs e) { int i, flag =0; for( i=0;i<cmbcountry.Items.Count;i++) { if (cmbcountry.Items[i].ToString() == (txtcountry.Text).ToUpper()) { flag=0; break; } else flag=1; } if (flag==1) { cmbcountry.Items.Add(txtcountry.Text.ToUpper()); txtcountry.Clear(); MessageBox.Show("Country added"); } else { txtcountry.Clear(); MessageBox.Show("Country present cannot add duplicate"); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

146

(Source code: Module10\WinForm1\WinForm1\ComboBoxExample.cs)

146

ComboBox Example

(Contd)

private void btnremove_Click(object sender, EventArgs e) { txtcountry.Text = ""; cmbcountry.Items.RemoveAt(cmbcountry.SelectedIndex); } private void cmbcountry_SelectedIndexChanged(object sender, EventArgs e) { int itemno = cmbcountry.SelectedIndex; txtcountry.Text = cmbcountry.Items[itemno].ToString(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

147

(Source code: Module10\WinForm1\WinForm1\ComboBoxExample.cs)

147

ListBox Example

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

148

(Source code: Module10\WinForm1\WinForm1\ListBoxExample.cs) ListBox Display a list of items, from which user can select one or more items Properties Name Control name Items Collection of the items to be displayed in list box SelectionMode Method in which items are selected. One, MultiSingle, MultiExtended. Difference between Combo box and List box Listbox support multiple selection from the given options, while ListBox allows only single selection.

148

ListBox Example

(Contd)

private void btnlist_Click(object sender, EventArgs e) { int i; string str = "Qualification"; for (i = 0; i <= lstqualification.Items.Count - 1; i++) { if (lstqualification.GetSelected(i) == true) { str += "\n"; str += lstqualification.Items[i]; } } Label3.Text = str; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

149

(Source code: Module10\WinForm1\WinForm1\ListBoxExample.cs)

149

ListBox Example

(Contd)

private void btnmultiselect_Click(object sender, EventArgs e) { ListBox.SelectedIndexCollection listboxcollection = lstqualification.SelectedIndices; MessageBox.Show(listboxcollection.Count.ToString()); string str = null; for (int i = 0; i < listboxcollection.Count; i++) { int index = listboxcollection[i]; str += lstqualification.Items[index].ToString()+ " "; } MessageBox.Show (str); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

150

(Source code: Module10\WinForm1\WinForm1\ListBoxExample.cs)

150

ListBox Example

(Contd)

private void btnchecklist_Click(object sender, EventArgs e) { string str = "Computer Skill"; for (int i = 0; i <= clstskill.Items.Count - 1; i++) { if (clstskill.GetItemChecked(i) == true) { str += "\n"; str += clstskill.Items[i]; } } Label4.Text = str; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

151

(Source code: Module10\WinForm1\WinForm1\ListBoxExample.cs)

151

RadioButton Example

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

152

(Source code: Module10\WinForm1\WinForm1\RadioButtonExample.cs) Create an application which accept the amount and convert into rupee. The amount can be converted from dollar or pound to rupee. For creating a group of Radio Buttons we require to use either GroupBox or Panel, which will work as a base container for the RadioButtons. GroupBox The GroupBox displays a frame around a group of controls with or without a caption. Use a GroupBox to logically group a collection of controls on a form. The GroupBox is a container control. Properties Name Control Name Text Get or Set the Caption Value.

152

RadioButton Example

(Contd)

private void rbdollar_CheckedChanged(object sender, EventArgs e) { if (rbdollar.Checked==true) { decimal amount= decimal.Parse(txtamount.Text)*45; lblresult.Text = "Converted amount = " + amount.ToString(); } else lblresult.Text=""; } private void rbpound_CheckedChanged(object sender, EventArgs e) { if (rbpound.Checked==true) { decimal amount= decimal.Parse(txtamount.Text)*70; lblresult.Text = "Converted amount = " + amount.ToString(); } else lblresult.Text=""; }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

153

(Source code: Module10\WinForm1\WinForm1\RadioButtonExample.cs) Panel contains other controls. Properties Name Control Name AutoScroll Gets or sets a value indicating whether the container will allow the user to scroll to any controls placed outside of its visible boundaries. Border Style - Indicates the border style for the control RadioButton From a given choice user can select any one option. Name Control Name Text Get or Set the text associated with the control. Checked Gets or Sets a value indicating whether the control is checked.

153

CheckBox Example

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

154

(Source code: Module10\WinForm1\WinForm1\CheckBoxExample.cs) CheckBox From a given choice user can select one, multiple, all or none. Properties Name Control Name Text Get or set the text associated with the control Checked Indicates whether the check box is checked or unchecked

154

CheckBox Example

(Contd)

private void CheckSkill() { string skills = "Skills = "; for (int i=0;i<Controls.Count ;i++) { string cnt = Controls[i].GetType().ToString(); if (cnt == "System.Windows.Forms.CheckBox") { CheckBox cb= (CheckBox) Controls[i]; if (cb.Checked==true) skills += " " + cb.Text; } } txtresult.Text=skills; } private void chkoffice_CheckedChanged(object sender, EventArgs e) { CheckSkill(); } private void chkprg_CheckedChanged(object sender, EventArgs e) { CheckSkill(); } private void chkdb_CheckedChanged(object sender, EventArgs e) { CheckSkill(); } private void chkweb_CheckedChanged(object sender, EventArgs e) { CheckSkill(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

155

(Source code: Module10\WinForm1\WinForm1\CheckBoxExample.cs)

155

MessageBox Example
private void btnStart_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show ("Do you want to start an Excel Application? , "MessageBox Example", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes ) System.Diagnostics.Process.Start("excel.exe"); else this.Close(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

156

When user click the Ms excel Button take the conformation from the user, if user click yes button start excel application else close the current application. MessageBox.Show ( Message, Title, MessageBoxButtons, MessageBoxIcon); MessageBoxButtons Enumeration Combination of buttons OK OKCancel AbortRetryIgnore YesNoCancel YesNo RetryCancel Integer values of the individual member Ok Cancel Abort Retry Ignore Yes No MessageBoxIcon enumeration Question Stop Exclamation Warning 1 2 3 4 5 6 7

156

Anchor Property
When a control is anchored to an edge of its container the distance between the control and specified edge remains constant when container resizes.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

157

A control can be anchored to one or more edges of its parent container. Anchoring a control to its parent ensures that the anchored edges remain in the same position relative to the edges of the parent container when the parent container is resized.

157

Dock Property
Align control to the edges of the form by setting the Dock property. Top

Left

Fill

Right

Bottom

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

158

Control Location of the dock property

Setting

Effects

DockStyle.Top

Dock to the top of the form

DockStyle.Bottom DockStyle.Left

Dock to the bottom of the form Dock to the left of the form

DockStyle.Right

Dock to the right of the form

DockStyle.Fill

Fill remaining space in the form

DockStyle.None

Does not dock anywhere

158

Module 12. File I/O


Overview
System.IO Namespace The Directory and File Classes The FileStream Class Reading and Writing to File using StreamReader and StreamWriter.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

159

159

Input and Output


Input means reading Output means writing Standard input keyboard and mouse Standard output Monitor and printer Import System.IO namespace

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

160

160

File IO
Stream

Stream Reader/ Stream Writer

File Stream

File

Binary Reader/ Binary Writer


Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

161

File is a persistent storage where data is stored in bytes, known as a stream and we can perform input / output operations i.e. we can read and write to a file. In C# to use file handling we required to use System.IO namespace with a class library that supports string, character and file manipulation. These classes contain properties, methods and events for creating, copying, moving, and deleting files and directories. The parent class of file processing is Stream. With Stream, you can store data to a stream or you can retrieve data from a stream. Stream is an abstract class, which means that you cannot use it to declare an object in your application. The most commonly used classes are FileStream, StreamReader and StreamWriter. The Directory class in C# allows us to create and work with Folders/Directories. With this class you can create, edit and delete folders and also maintain drives on the machine.

161

File IO classes
Stream
File Stream

Text Reader

Text Writer

Binary Reader

Binary Writer Stream Reader Stream Writer Network Stream

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

162

Base class in File IO operations is Stream class which is present in System.IO namespace. File IO provides various stream classes such as StreamWriter, StreamWriter, File Stream, BinaryReader, BinaryWriter, NetworkStream etc

162

The Directory Class


Method of the Directory class Method CreateDirecotry Exists Use Create a directory at a specified path location Directory.CreateDirectory(c:\\examples) Checked whether the directory exist at the specified location if exists return true else false. Messagebox.show(Directory.Exists(c:\\examples)) Remove the directory and its contents. Directory.Delete(c:\\examples)

Delete

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

163

The Directory class in C# allows us to create and work with Folders/Directories. With this class you can create, edit and delete folders and also maintain drives on the machine.

The Directory Class


GetDirectories

(Contd)

Returns the names of all sub directory available under specified path Add textbox and button On click event of the button write the following code. Int I; String[ ] dir; dir = Directory.GetDirectories("c:\\") For (i=0;i<dir.Length;i++) { TextBox1.AppendText(dir[i] + \n); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

164

The Directory Class


GetDirectoryRoot

(Contd)

Return the root information about the specified path Directory. GetDirectoryRoot (Messagebox.show(c:\\examples) ) Returns the parent directory of the specified path DirectoryInfo di; di = Directory.GetParent("c:\\examples") MessageBox.Show(di.ToString()) Returns the names of all files available under specified path int i; String[ ] file; file = Directory.GetFiles("c:\\") For (i=0;i<file.Length;i++) { TextBox1.AppendText(file[i] + \n); }
165

GetParent

GetFiles

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

The Directory Class


Move getLogicalDrives

(Contd)

Move a file or a directory to a new location Directory.move(c:\\sample\data, c:\\examples\data) Retruns the name of the logical drives of the computer Int I; String[ ] drive; drive = Directory.GetLogicalDrives(); for (i=0;i<drive.length;i++) { TextBox1.AppendText(drive[i] + \n); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

166

FileStream Class
This class provides access to standard input and output files. FileStream fs = new FileStream(path, FileMode);

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

167

This class provides access to standard input and output files. We use the members of FileMode enumerations with the constructors of this class to create or open a file. After a file is opened it's FileStream object can be passed to the StreamReader and StreamWriter classes to work with the data in the file. File Modes Append - Open the file if it exists and seek to the end of the file, or create a new file. Create - Create a new file. If file exists, it will be overwritten. CreateNew - Create a new file. If file exists, throw an exception. Open - Open an existing file. OpenOrCreate - Open a file if it exists, otherwise create a new file Truncate - Open an existing file, once opened the file should be truncated so that its size is zero. If file does not exist, throw an exception.

167

StreamReader and StreamWriter Class

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

168

168

Save Button Code


using System.IO; savefiledialog = new SaveFileDialog(); savefiledialog.CheckPathExists = true; savefiledialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"; savefiledialog.Title = "Save File as "; savefiledialog.FilterIndex = 2; savefiledialog.InitialDirectory = @"C:\"; savefiledialog.RestoreDirectory = true; if (savefiledialog.ShowDialog() == DialogResult.OK){ FileStream file = new FileStream(savefiledialog.FileName, FileMode.Create); StreamWriter writer = new StreamWriter(file); writer.WriteLine(rtbData.Text); MessageBox.Show("File created successfully"); writer.Close(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

169

169

Open Button Code


Open button Click Event
OpenFileDialog openfiledialog = new OpenFileDialog(); openfiledialog.Title = "Open file.."; openfiledialog.InitialDirectory = @"C:\"; openfiledialog.RestoreDirectory = true; if (openfiledialog.ShowDialog() == DialogResult.OK) { FileStream file = new FileStream(openfiledialog.FileName, FileMode.Open); StreamReader reader = new StreamReader(file); rtbData.AppendText(reader.ReadToEnd()); reader.Close(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

170

170

Write and Read using same stream


Write&Read button click event
FileStream stream = new FileStream("c:\\data.txt", FileMode.OpenOrCreate ); StreamWriter writer = new StreamWriter(stream); StreamReader reader = new StreamReader(stream); writer.WriteLine("Testing writing and reading from the same file"); writer.WriteLine("This concept is interesting \n"); writer.Flush(); reader.BaseStream.Seek(0, SeekOrigin.Begin); WorkArea.Text = reader.ReadToEnd(); writer.Close(); reader.Close(); stream.Close();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

171

171

Binary Reading and Writing

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

172

Binary is basically used to read primitive data.

172

BinaryWriter and BinaryReader Code


FileStream stream = new FileStream ("c:\\binary.txt", FileMode.Create); BinaryWriter writer = new BinaryWriter (stream); writer.Write(WorkArea.Text); WorkArea.Clear(); writer.Close(); stream.Close(); FileStream stream = new FileStream("c:\\binary.txt", FileMode.Open ); BinaryReader reader = new BinaryReader(stream); while (reader.PeekChar() != -1) { char c = reader.ReadChar(); WorkArea.AppendText(c.ToString()); if (c == ' ) { WorkArea.AppendText("\n"); }} reader.Close(); stream.Close();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

173

173

Split method
Use as a string tokenize

string str = textBox1.Text; int count =str.Split(new char[] {' '}).Length ; MessageBox.Show(count.ToString());

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

174

Input Form

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

175

Create the registration form which takes the input from the user. When user click on Save button it will store the information to the file.. When user click on Clear button it will clear information form the input controls. When user click on Display existing users checkbox, it will display all the files available in c:\Users folder in ListBox. By selecting any of the file you can view the information in the Rich Text Box.

175

Input Form Code


private void Registration_Load(object sender, EventArgs e){ List<string> country = new List<string> {"India","Usa","Japan","Uk","France"}; cmbcountry.DataSource = country; List<string> qualification = new List<string> { "Graduate", "Post graduate", "CA", "MBA", "Doctor", "Engineer", "MCA" }; lstqualification.DataSource = qualification; } private void chktel_CheckedChanged(object sender, EventArgs e) { if (chktel.Checked == true) txttel.Enabled = true; else txttel.Enabled = false; } private void chkmobile_CheckedChanged(object sender, EventArgs e) { if (chkmobile.Checked == true) txtmobile.Enabled = true; else txtmobile.Enabled = false; } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

176

176

Input Form Code

(Contd)

if (rdbmale.Checked == true) private void btnsave_Click(object sender, gender = "Male"; EventArgs e) { if (rdbfemale.Checked == true) string tel = null, mobile = null, gender = null, gender = "Female"; status = null, qualification = null, message = null; if (rdbsingle.Checked == true) string name = txtuname.Text; status = "Single"; string pwd = txtpwd.Text; if (rdbmarried.Checked == true) string address = txtaddress.Text; status = "Married"; int itemno = cmbcountry.SelectedIndex; for (int i = 0; i <= string country = lstqualification.Items.Count - 1; i++) { cmbcountry.Items[itemno].ToString(); if (lstqualification.GetSelected(i) == if (txttel.Text != "") true) { tel = txttel.Text; qualification += lstqualification.Items[i]; else qualification += " ;} tel = "No Telephone"; } if (txtmobile.Text != "") mobile = txtmobile.Text; else mobile = "No Mobile";
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

177

177

Input Form Code

(Contd)

message = "User Name = " + name + "\nPassword = " + pwd + "\nAddress = " + address + "\nCountry = " + country + "\nTelephone = " + tel + "\nMobile = " + mobile + "\nGender = " + gender + "\nStatus = " + status + "\nQualification = " + qualification; try { if (!Directory.Exists(@C:\Users")) { Directory.CreateDirectory(@"c:\Users"); } string path = @C:\Users\" + name + ".txt"; FileStream fs = new FileStream(path, FileMode.Create); StreamWriter writer = new StreamWriter(fs); writer.WriteLine(message); writer.Close(); fs.Close(); MessageBox.Show("Data added in file"); fs = new FileStream(path, FileMode.Open); StreamReader reader = new StreamReader(fs); rtbdisplay.Text = reader.ReadToEnd(); rtbdisplay.Visible = true;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

178

178

Input Form Code

(Contd)
txttel.Enabled = false; txtmobile.Clear(); txtmobile.Enabled = false; lstqualification.Refresh(); rtbdisplay.Clear(); rtbdisplay.Visible = false; chkusers.Checked = false; } private void chkusers_CheckedChanged (object sender, EventArgs e) { if (chkusers.Checked == true) { lstusers.Items.Clear(); lstusers.Visible = true; string path = @"c:\users"; string[] users = Directory.GetFiles(path); for (int i = 0; i < users.Length; i++) { lstusers.Items.Add(users[i]); } } else lstusers.Visible = false; }
179

reader.Close(); fs.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnclear_Click(object sender, EventArgs e) { txtuname.Clear(); txtpwd.Clear(); txtaddress.Clear(); cmbcountry.Text = ""; rdbmale.Checked = false; rdbfemale.Checked = false; rdbsingle.Checked = false; rdbmarried.Checked = false; chktel.Checked = false; chkmobile.Checked = false; txttel.Clear();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

179

Input Form Code

(Contd)

private void lstusers_SelectedIndexChanged(object sender, EventArgs e) { try { string filename = lstusers.Text; FileStream fs = new FileStream(filename, FileMode.Open); StreamReader reader = new StreamReader(fs); rtbdisplay.Text = reader.ReadToEnd(); rtbdisplay.Visible = true; reader.Close(); fs.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

180

(Source code: Module11\FileIO\FileIO\Registration.cs)

180

Module 13. Working with Databases


Overview
Introduction to Ado.Net Ado.Net disconnected model Ado.Net connected Model Data Providers Disconnected Database Connectivity Configuring Connection String in Config file Connected Database Connectivity Filter Insert data using connected architecture Command Builder Data Navigation Master Detail Relationship Stored Procedure
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

181

181

Overview

(Contd)

Transaction Data Relation SQL Bulk Copy Batch Update Multiple Active Result Set Reading and writing data to XML Data Independent Provider

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

182

Introduction to Ado.Net
ADO.NET is a set of classes, interfaces for working with data A system designed for disconnected environments A programming model with XML support Use XML as the format for transmitting data from a data source to DataSet

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

183

183

ADO.NET Disconnected Model


Provider Client Application
Connection

Database
Data Adapter
DataSet

Select Command Insert Command Update Command Delete Command

DataSet
XML

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

184

Connection object which provides a connection to the Data source. ADO.Net introduces the concept of disconnected data architecture. In traditional data access components, you make a connection to the database system and then interact with it through SQL queries using the connection. The application stays connected to the DB system even when it is not using DB services. This commonly wastes the valuable and expensive database resource as most of the time applications only query and view the persistent data. ADO.Net solves this problem by managing a local buffer of persistent data called data set. Your application connects to the database server when it needs to pass some query and then disconnects immediately after getting the result back and storing it in dataset. This design of ADO.Net is called disconnected data architecture. DataAdapter is the bridge between data source and the DataSet. It fills the data to the DataSet and performs the update. The dataset is a in-memory representation of data. It can be considered as a local copy of the relevant portions of the database. DataAdapeter class take care of when to open the connection and when to close it. We do not require to explicitly maintain the connection object. For select command we have to call the Fill() method of the DataAdapter class. And for insert, update and delete command we have to call Update() method of the DataAdapter class. These methods internally maintain connection object.

184

ADO.NET Connected Model

Provider Client Application


Connection Command DataReader

Database

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

185

Connection object which provides a connection to the Data Source. In the connected environment, it is your responsibility to open and close the database connection. You first establish the database connection, perform the interested operations to the database and when you are done, close the database connection. All the changes are done directly to the database and no local (memory) buffer is maintained. Command takes any SQL statement or Stored Procedure Data Reader provides Read Only, Forward Only stream of rows from a Data Source. Three methods to execute the command ExecuteNonQuery() Use for executing query which is not going to return record. E.g. Insert, update, delete, create, drop, stored procedure etc. (returns number of rows affected) ExecuteReader() Execute the query, and returns one row at a time. Return type is DataReader. ExecuteScalar() Returns single value Execute the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored. Return type is Object. In the connected model in our code we have to maintain the connection object. Before executing any query, first we require to open the connection and after executing the query we have to close the connection. Till the time you will not close the connection the resource is in use and you cannot execute another query using the same connection object.

185

Date Providers (NameSpaces)


System.Data System.Data.OleDb System.Data.SqlClient System.Data.OracleClient System.Data.Common

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

186

System.Data DataSet, DataTable, DataColumn, DataRow, DataRelation, DataView etc. System.Data.OleDb Can be used with all the databases like Ms Access, Ms SQL Server, Oracle, Sybase, DB2 etc. System.Data.SqlClient Used only with Ms SQL Server 7.0 and above version Will give the support foe the features of Ms SQL Server database like SQL Bulk Copy etc. Support the Data Type of Ms SQL Server Database System.Data.OracleClient Used only with Oracle database Support the Data Type of Oracle Database like CLOB, BLOB, BFILE etc. System.Data.Common It support a;; the data providers mention above. The classes in this provider are integrated to give a support to write the code that will work with all .Net Framework data providers.

186

Disconnected Database Connectivity with Different Databases

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

187

187

Disconnected Connectivity with Ms SQL Server


Add the following namespace in the program using System.Data.SqlClient; Write code for Ms SQL Server Button Click Event
try { SqlConnection conn = new SqlConnection(@"server=.\sa1; database=Northwind; integrated security=true;"); string sql = "select * from products"; SqlDataAdapter adp = new SqlDataAdapter(sql, conn); DataSet ds = new DataSet(); adp.Fill(ds, "products"); dataGridView1.DataSource = ds.Tables["products"]; } catch (Exception ex) { MessageBox.Show(ex.Message); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

188

Disconnected connectivity with MS Access Add the following namespace in the program using System.Data.OleDb; Write code for Ms Access Button Click Event try { OleDbConnection conn = new OleDbConnection ( @"provider=Microsoft.Jet.OLEDB.4.0; data source = C:\Northwind.mdb"); string sql = "select * from customers"; OleDbDataAdapter adp = new OleDbDataAdapter(sql, conn); DataSet ds = new DataSet(); adp.Fill(ds, "customers"); dataGridView1.DataSource = ds.Tables["customers"]; } catch (Exception ex) { MessageBox.Show(ex.Message); } Disconnected connectivity with MS Access Add the following namespace in the program using System.Data.OracleClient; Write code for Oracle button Click Event try { OracleConnection conn = new OracleConnection("data source=<oracelservicename>; user id=<username>; password=<password>;"); string sql = "select * from emp"; OracleDataAdapter adp = new OracleDataAdapter(sql, conn); DataSet ds = new DataSet(); adp.Fill(ds, "emp"); dataGridView1.DataSource = ds.Tables["emp"]; } catch (Exception ex) { MessageBox.Show(ex.Message); }

188

Configuring Connection String in .config File


To add the App.config file in your project click menu Project -> Add New Item From left hand side select General option and from the write hand side select Application Configuration File. Do not change the name of this file. Click on Add button to add the file in your project.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

189

Config is a XML file. if you have to change server name ,database name etc in connection string then you have to make changes in only .config file and not on each and every Forms. you can also add more than one connection string in config file. To access the connection string from the config file, first you have to add the reference to the System.Configuration namespace in your project. use the System.Configuration namespace in every C# files, where you want to use the connection string from the config file.

189

Configuring Connection String in .config File (contd)


Write the connection string in the confilg file within connectionStrings element
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="NorthwindConnStr" connectionString="server=.\sa1;database=Northwind;integrated security=true" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration>

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

190

190

Using Connection String in C# file


using System.Data.SqlClient; using System.Configuration; string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr);

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

191

191

Display Data using Connected Architecture

string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr); string sql = "select * from categories"; SqlCommand cmd = new SqlCommand(sql, conn); conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); DataTable table = new DataTable(); table.Load(reader); conn.Close(); dataGridView1.DataSource = table;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

192

(Source code: Module12\DatabaseApplication\DatabaseApplication\02Connected.cs)

192

Apply Filter on DataSet

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

193

(Source code: Module12\DatabaseApplication\DatabaseApplication\03Filter.cs) DataSet data is the in memory data. After we retrive the data in dataset, we can apply the filter on it and display the specific data to the users. For this there are 2 methods 1] Select() method of the DataTable class and 2] DataView class object with RowFilter Property

193

Apply Filter on DataSet


Declare the 2 class level variable
int catid = 0; DataSet ds;

(Contd)

Form Load Event string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr); SqlDataAdapter adp = new SqlDataAdapter("select * from Categories", conn); ds = new DataSet(); adp.Fill(ds, "Categories"); adp = new SqlDataAdapter("Select * from Products", conn); adp.Fill(ds, "Products"); lstcategory.DisplayMember = ds.Tables["Categories"].Columns["CategoryName"].ToString(); lstcategory.ValueMember = ds.Tables["Categories"].Columns["CategoryID"].ToString(); lstcategory.DataSource = ds.Tables["Categories"];
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

194

(Source code: Module12\DatabaseApplication\DatabaseApplication\03Filter.cs)

194

Apply Filter on DataSet

(Contd)

ListBox SelectedIndexChanged Event

if (lstcategory.SelectedIndex >0 && lstcategory.SelectedValue != null) { catid = (int) lstcategory.SelectedValue ; }

View Button Click Event

DataView view = ds.Tables["Products"].DefaultView; view.RowFilter="categoryid=" + catid; dataGridView1.DataSource = view;

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

195

195

Apply Filter on DataSet DataTable Select() Method


select button click event
lstselect.Items.Clear(); DataRow[] row = ds.Tables["Products"].Select("categoryid=" + catid); if (row.Length > 0) { for (int i = 0; i < row.Length; i++) { lstselect.Items.Add(row[i]["productName"]); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

196

(Source code: Module12\DatabaseApplication\DatabaseApplication\03Filter.cs)

196

Insert data using Connected Architecture

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

197

197

Insert data using Connected Architecture Code


string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr); string sql = "Insert into products (productname, unitprice) values (@pname, @price)"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@pname", txtpname.Text); cmd.Parameters.AddWithValue("price", decimal.Parse(txtup.Text)); conn.Open(); int feedback = cmd.ExecuteNonQuery(); conn.Close(); MessageBox.Show(feedback + " record inserted"); cmd.CommandText = "select productid, productname, unitprice from products where productid >77"; conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); DataTable table = new DataTable(); table.Load(reader); conn.Close(); dataGridView1.DataSource = table;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

198

198

Stored Procedure

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

199

(Source code: Module12\DatabaseApplication\DatabaseApplication\08spin.cs)

199

Stored Procedure

(Contd)

Write the following stored procedure in the MS SQL Server


create proc InsertData (@prodname varchar(20), @unitprice numeric(10,2)) as begin transaction insert into products (productname, unitprice) values (@prodname, @unitprice) Commit transaction

Code for the Insert Button Click


string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr);

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

200

(Source code: Module12\DatabaseApplication\DatabaseApplication\08spin.cs)

200

Stored Procedure

(Contd)

SqlCommand cmd = new SqlCommand ("Insertdata", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@prodname", txtpname.Text ); cmd.Parameters.AddWithValue("@unitprice", txtup.Text); conn.Open(); int feedback = cmd.ExecuteNonQuery(); conn.Close(); MessageBox.Show(feedback + " record inserted"); txtpname.Clear(); txtup.Clear(); conn.Open(); cmd = new SqlCommand("select * from products where productid>77",conn); SqlDataReader reader = cmd.ExecuteReader(); DataTable table = new DataTable(); table.Load(reader); conn.Close(); dataGridView1.DataSource = table;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

201

(Source code: Module12\DatabaseApplication\DatabaseApplication\08spin.cs)

201

CommandBuilder for Update Data in Disconnected Architecture

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

202

(Source code: Module12\DatabaseApplication\DatabaseApplication\05CommandBuilder.cs) CommandBuilder - Automatically generates single-table commands that are used to

reconcile changes made to a DataSet with the associated database. Minimum requirement to pass the select command (select query) with command builder object. When associated with a DataAdapter, the DbCommandBuilder automatically generates the InsertCommand, UpdateCommand, and DeleteCommand properties of the DataAdapter The SelectCommand must also return at least one primary key or unique column. If none are present, an InvalidOperation exception is generated, and the commands are not generated.

202

Code for update data using CommandBuilder


Declare Class level members
SqlConnection conn; SqlDataAdapter adp; SqlCommandBuilder cb; DataTable table;

Write the following code in load event


conn = new SqlConnection(connstr); string sql = "select * from products"; adp = new SqlDataAdapter(sql, conn); cb = new SqlCommandBuilder(adp); table = new DataTable(); adp.Fill(table); DataColumn[] pk = new DataColumn [1]; pk[0] = table.Columns["productid"]; table.PrimaryKey = pk; dataGridView1.DataSource = table;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

203

(Source code: Module12\DatabaseApplication\DatabaseApplication\05CommandBuilder.cs)

203

Code for update data using CommandBuilder


Write the following code for the Update button click event
try { table = (DataTable )dataGridView1.DataSource; adp.Update(table ); MessageBox.Show("Data modified in the Database"); } catch (Exception ex) { MessageBox.Show(ex.Message); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

204

(Source code: Module12\DatabaseApplication\DatabaseApplication\05CommandBuilder.cs)

204

Data Navigation

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

205

(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)

205

Data Navigation

(Contd)

Declare class level member


SqlConnection conn; SqlDataAdapter adp; SqlCommandBuilder cb; DataSet ds; BindingManagerBase bm; int pid, flag; void Display() { txtpid.Text = ds.Tables["products"].Rows[bm.Position]["productid"].ToString(); txtpname.Text = ds.Tables["products"].Rows[bm.Position]["productname"].ToString(); txtup.Text = ds.Tables["products"].Rows[bm.Position]["unitprice"].ToString(); lblrecno.Text = bm.Position + 1 + " / " + bm.Count; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

206

(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)

206

Data Navigation

(Contd)

Code for load event


string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; conn = new SqlConnection(connstr); string sql = "select productid, productname,unitprice from products"; adp = new SqlDataAdapter(sql, conn); cb = new SqlCommandBuilder(adp); ds = new DataSet(); adp.Fill(ds, "products"); DataColumn[] pk = new DataColumn[1]; pk[0] = ds.Tables["products"].Columns["productid"]; ds.Tables["products"].PrimaryKey = pk; bm = this.BindingContext[ds, "products"]; bm.Position = 0; Display();
207

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)

207

Data Navigation
First Button
bm.Position = 0 Display()

(Contd)

Next Button
bm.Position += 1 Display()

Prior Button
bm.Position -= 1 Display()

Last Button
bm.Position = bm.Count - 1 Display()

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

208

(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)

208

Data Navigation
Add Button
txtpid.Clear(); txtpname.Clear(); txtup.Clear(); flag = 1; btnsave.Enabled = true;

(Contd) Delete Button


DialogResult result = MessageBox.Show("Are you sure, you want to delete the record?", "Delete Box", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.Yes) { MessageBox.Show("Click save button to delete the record"); pid = int.Parse(txtpid.Text); flag = 3; btnsave.Enabled = true; }

Edit Button
pid =int.Parse ( txtpid.Text); flag = 2; btnsave.Enabled = true;

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

209

(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)

209

Data Navigation
Save Button

(Contd)
else if (flag == 3) { //Delete dr = ds.Tables["products"].Rows.Find(pid); if (dr != null) { dr.Delete(); } }

DataRow dr; if (flag == 1) { //Add dr = ds.Tables["products"].NewRow(); dr["productid"] = 0; dr["productname"] = txtpname.Text; dr["unitprice"] = decimal.Parse(txtup.Text); ds.Tables["products"].Rows.Add(dr); } else if (flag == 2) { //Edit dr = ds.Tables["products"].Rows.Find(pid); if (dr != null) { dr.BeginEdit(); dr["productid"] = pid; dr["productname"] = txtpname.Text; dr["unitprice"] = decimal.Parse(txtup.Text); dr.EndEdit(); } }

adp.Update(ds, "products"); MessageBox.Show("Data modified"); ds.Clear(); adp.Fill(ds, "products"); bm.Position = 0; Display(); flag = 0; btnsave.Enabled = false;
210

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)

210

Data Navigation

(Contd)

Concurrency Check
catch (Exception ex) { MessageBox.Show(ex.Message); if (ds.HasErrors) { foreach(DataTable table in ds.Tables) { if (table.HasErrors) { foreach (DataRow row in table.Rows) { if (row.HasErrors) { MessageBox.Show("Table : " + table.TableName + "\n Row : " + row["productid"].ToString() + "\n" + row.RowError, "Error Box"); row.ClearErrors(); row.RejectChanges(); } } } } } Pragati Software Pvt. Ltd., 312, } Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com Lok 211

(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)

211

Data Navigation
Exit Button
Application.Exit();

(Contd)

Find Button
_06FindProduct frm = new _06FindProduct(); frm.ShowDialog(); int productid = frm.prodid; //MessageBox.Show(productid.ToString()); if (productid > 0) { DataRow dr = ds.Tables["products"].Rows.Find(productid); if (dr != null) MessageBox.Show("Product ID : " + dr["productid"] + "\nProduct Name : " + dr["productname"] + "\nUnit Price : " + dr["unitprice"], "Display Box"); else MessageBox.Show("Record not found", "Display Box");

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

212

(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)

212

Data Navigation

(Contd)

public _06FindProduct() { InitializeComponent(); } public int prodid; private void btnsubmit_Click(object sender, EventArgs e) { if (txtprodid.Text == "") prodid = 0; else prodid = int.Parse (txtprodid.Text); this.Close(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

213

(Source code: Module12\DatabaseApplication\DatabaseApplication\06FindProduct.cs)

213

Master Detail Relationship

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

214

(Source code: Module12\DatabaseApplication\DatabaseApplication\07MasterDetail.cs)

214

Master Detail Relationship


Class level declaration SqlConnection conn; SqlDataAdapter adp; SqlCommandBuilder cb; DataSet ds; BindingManagerBase bm;

(Contd)

void Display() { txtcatid.Text = ds.Tables["categories"].Rows[bm.Position]["categoryid"].ToString(); txtcatname.Text = ds.Tables["categories"].Rows[bm.Position]["categoryname"].ToString(); lblrecno.Text = bm.Position + 1 + " / " + bm.Count; int catid = int.Parse(txtcatid.Text); DataView view = ds.Tables["products"].DefaultView; view.RowFilter = "categoryid=" + catid; dataGridView1.DataSource = view; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

215

(Source code: Module12\DatabaseApplication\DatabaseApplication\07MasterDetail.cs)

215

Master Detail Relationship


Form Load Event

(Contd)

string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; conn = new SqlConnection(connstr); string sqlcategory = "select categoryid, categoryname from categories order by categoryid"; string sqlproduct = "select productid, productname,unitprice, categoryid from products"; adp = new SqlDataAdapter(sqlcategory, conn); ds = new DataSet(); adp.Fill(ds, "categories"); SqlCommand selectcmd = new SqlCommand(sqlproduct, conn); adp.SelectCommand = selectcmd ; adp.Fill(ds, "products"); bm = this.BindingContext[ds, "categories"]; bm.Position = 0; Display();
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

216

(Source code: Module12\DatabaseApplication\DatabaseApplication\07MasterDetail.cs)

216

Master Detail Relationship


First Button
bm.Position = 0; Display();

(Contd)

Previous Button
bm.Position = bm.Position + 1; Display();

Next Button
bm.Position = bm.Position + 1; Display();

Last Button
bm.Position = bm.Count - 1; Display();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

217

(Source code: Module12\DatabaseApplication\DatabaseApplication\07MasterDetail.cs)

217

Stored Procedure with Out Parameter

Write the following stored procedure in the MS SQL Server


create proc TotalProduct (@catid int, @count int output) as select @count=count(productid) from products where Categoryid = @catid
218

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

(Source code: Module12\DatabaseApplication\DatabaseApplication\09spout.cs)

218

Stored Procedure with Out Parameter


Form Load event populate the list box

(Contd)

string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr); string sql = "select categoryid, categoryname from categories order by categoryid"; SqlDataAdapter adp = new SqlDataAdapter(sql,conn); DataSet ds = new DataSet(); adp.Fill(ds,"categories"); lstcategory.DisplayMember = ds.Tables["categories"].Columns["categoryname"].ToString(); lstcategory.ValueMember = ds.Tables["categories"].Columns["categoryid"].ToString(); lstcategory.DataSource = ds.Tables["categories"];

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

219

(Source code: Module12\DatabaseApplication\DatabaseApplication\09spout.cs)

219

Stored Procedure with Out Parameter


Type the following code in the ListBox SelectedIndexChanged event

(Contd)

string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr); SqlCommand cmd = new SqlCommand("TotalProduct", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@catid", int.Parse(lstcategory.SelectedValue.ToString() )); cmd.Parameters.Add("@count", SqlDbType.Int); cmd.Parameters[1].Direction = ParameterDirection.Output; conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); lblresult.Text = "Total Product for catgory " + lstcategory.SelectedValue.ToString() + " = " + cmd.Parameters[1].Value.ToString();
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

220

(Source code: Module12\DatabaseApplication\DatabaseApplication\09spout.cs)

220

Transaction

int result1, result2; string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr); conn.Open();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

221

(Source code: Module12\DatabaseApplication\DatabaseApplication\10Transaction.cs)

221

Transaction

(Contd)

cmd = conn.CreateCommand(); cmd.Connection = conn; cmd.CommandText = "insert into products (productname, unitprice) values ('Ipod',25000)"; MyTransaction = conn.BeginTransaction(); cmd.Transaction = MyTransaction; result1 = cmd.ExecuteNonQuery(); cmd.CommandText = "update products set unitprice=0 where productid=80"; result2 = cmd.ExecuteNonQuery(); if (result1 > 0 && result2 > 0) { MyTransaction.Commit(); MessageBox.Show("Transaction saved, Data modified"); } else { MyTransaction.Rollback(); MessageBox.Show("Transaction Rollback"); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

222

(Source code: Module12\DatabaseApplication\DatabaseApplication\10Transaction.cs)

222

DataRelation

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

223

(Source code: Module12\DatabaseApplication\DatabaseApplication\11DataRelation.cs)

223

DataRelation

(Contd)

Form Load Event


decimal total; string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr); SqlDataAdapter adpcategory = new SqlDataAdapter("select * from Categories", conn); SqlDataAdapter adpprod = new SqlDataAdapter("select * from products", conn); DataSet ds = new DataSet(); adpcategory.Fill(ds, "categories"); adpprod.Fill(ds, "products"); ds.Relations.Add("category", ds.Tables["categories"].Columns["categoryid"], ds.Tables["products"].Columns["categoryid"]);

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

224

(Source code: Module12\DatabaseApplication\DatabaseApplication\11DataRelation.cs)

224

DataRelation

(Contd)

foreach (DataRow catrow in ds.Tables["categories"].Rows) { total = 0; lstrelation.Items.Add("CategoryID = " + catrow["categoryid"] + " " + "Category Name = " + catrow["categoryName"]); lstrelation.Items.Add("-------------------------------"); foreach (DataRow prodrow in catrow.GetChildRows("category")) { lstrelation.Items.Add("Productname = " + prodrow["productname"] + " " + "unitPrice = " + prodrow["unitprice"]); total += decimal.Parse(prodrow["unitprice"].ToString()); } lstrelation.Items.Add("-------------------------------------------------"); lstrelation.Items.Add("Total = " + total); lstrelation.Items.Add("-------------------------------------------------"); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

225

(Source code: Module12\DatabaseApplication\DatabaseApplication\11DataRelation.cs)

225

Module 14. Data Bound Control


Overview
Populating DataGridView Control using Wizard Populating ListBox Control using Wizard Binding Navigator

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

226

226

Populating DataGridView Control using Wizard


Add DataGridView Control from the data menu Click on the smart tag Click on Choose Data Source Drop Down arrow

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

227

(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)

227

Populating DataGridView Control using Wizard


Click on Add Project Data Source

(Contd)

Select Database and click Next option

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

228

(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)

228

Populating DataGridView Control using Wizard

(Contd)

Click New Connection Button and specify the name of the SQL Server, Authentication and Database. Click on Test Connection button. If you get the message Test Connection Succeeded then click on OK button.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

229

(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)

229

Populating DataGridView Control using Wizard

(Contd)

Save the connection String in Application Configuration file Click Next Button

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

230

(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)

230

Populating DataGridView Control using Wizard

(Contd)

Select Categories table from the list and click Finish button

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

231

(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)

231

Populating DataGridView Control using Wizard


Display the data in grid

(Contd)

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

232

(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)

232

Populating ListBox Control using Wizard


Add ListBox from the Common Controls Click on smart option Check Use data bound items

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

233

(Source code: Module 13\DataBoundControl\DataBoundControl\02ListBoxControl.cs)

233

Populating ListBox using Wizard (Contd)


Select Data Source option Specify Display Member and Value Member options

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

234

(Source code: Module 13\DataBoundControl\DataBoundControl\02ListBoxControl.cs)

234

Populating ListBox using Wizard (Contd)


Add the Label and name the label as lblcatid. Write the following code in the listbox SelectedIndexChanged event
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { if (listBox1.SelectedValue != null) lblcatid.Text = listBox1.SelectedValue.ToString(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

235

(Source code: Module 13\DataBoundControl\DataBoundControl\02ListBoxControl.cs)

235

Populating ListBox using Wizard (Contd)


Run the Form Display Member property is used for display the column in the ListBox. When we select the option from the ListBox it will display the Value Member.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

236

(Source code: Module 13\DataBoundControl\DataBoundControl\02ListBoxControl.cs)

236

Binding Navigator
Add Binding Source Control from the Data Tab. Go to Property window and specify DataSource Property. Add 2 Labels and 2 Textboxes Add Binding Navigator Control from Data Tab. Go to Property window and specify BindingSource Property as BindingSource1 DataMember Property as Categories Select the txtcatid TextBox and assign the DataBinding Text property as Categoryid Select the txtcatname TextBox and assign the DataBinding Text property as CategoryName

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

237

(Source code: Module 13\DataBoundControl\DataBoundControl\03Navigator.cs)

237

Binding Navigator

(Contd)

Run and Test the Program

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

238

(Source code: Module 13\DataBoundControl\DataBoundControl\03Navigator.cs)

238

Module 15. DotNet Framework & Assembly


Overview
.Net Framework Assembly Type of Assembly Create Class Library Create Test Application Creating Shared Assembly Viewing the Manifest File Process of compiling and executing managed code

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

239

239

Assembly

Assembly
Manifest Module Metadata MSIL Types Types Types Types

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

240

An assembly is a single deployable unit that contains all the information about the implementation of classes, structure, interfaces, enum and delegates. An assembly stores all the information about itself. The information is called metadata, which includes the name and version number of the assembly, security information, information about the dependencies, and a list of the files that constitute the assembly. Assembly is a logical EXE or DLL. An assembly consists of manifest, module and type. Manifest is the descriptor of the assembly. Module is either a DLL or EXE. Type can be a class, interface, structure, enum, delegates that contains data and logic.

240

Types of Assembly
Private Assembly Shared Assembly

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

241

Private Assembly A private assembly is deployed and used exclusively with a single name. A private assembly is referenced by its simple name The simple name is defined in the assemblys metadata. When you refer to private assembly , it get copied into the project which is referring to this assembly. Shared Assembly Shared assembly is also known as Strong Named Assembly It gives support to versioning and security of assembly Strong named assembly will have unique identification When you refer to shared assembly , it will not create the local copy of this assembly. It always refer to the location from where you have included the reference. Identity consist of Simple Text Name Version Number Culture Information Public Key Digital Signature

241

Creating Shared Assembly


Adding the dll file in GAC folder

(Contd)

(C:\WINDOWS\Microsoft.NET\assembly\GAC_MSIL)

Start MS Visual Studio Command Prompt and go to the folder where you have stored your dll file.
(Start Program Microsoft Visual Studio 2010 Visual Studio Tools Visual Studio 2010 Command Prompt )

Generate strong name key.


Sn -k key.snk calc.snk

Type the following command at the command prompt gacutil i calculatorlib.dll This command will register the assembly in GAC Now when you add the reference of the assembly into your application, it will not create the local copy of assembly, it will maintain the reference to the folder from where you are adding the assembly.
242

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

242

Viewing Manifest File

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

243

Intermediate Language Disassembler (ILDASM) ILDASM is a tool for viewing the contents of assembly. Each assembly has a single manifest file which contains metadata. Go to Microsoft Visual Studio command Prompt and type ILDASM or go to start program Microsoft Windows SDK V6.OA Tools IL Disassembler Select File menu Click Open Select exe or dll file for which you want to see IL code

243

Module 16. Delegate


Overview Understanding Delegate SingleCast Delegate MultiCast Delegate Anonymous Method

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

244

244

Understanding Delegate
Declaring and invoking Delegate involves 4 steps
Delegate declaration delegate returntype Name ([parameters]) Declare Delegate method Returntype Name ([parameters]) Delegate instantiation delegatename instancename = new delegatename(methodname) Delegate invocation Instancename(parameters value)

Use of Delegate
Events Threads Asynchronous Application
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

245

Features of Delegate Delegate is one of the type which we can declare within the Namespace. Delegates are termed as function pointers. Delegates contain the address of the method that is to be executed. Signature of delegate and method signature should be identical. Delegates act as middle layer to communicate the event occurred to the system. There are two types of delegates Singlecast and multicast. Singlecase delegate can hold and invoke single method Multicast delegate can hold and invoke multiple methods.

245

SingleCast Delegate
//Declare Delegate delegate void DelegateString(string s); delegate int DelegateCube(int number); class _01SingleCastDelegate { //method public static void Greet(string Name) { Console.WriteLine("Hello..." + Name); } //method public static void Wish(string Name) { int Hour = System.DateTime.Now.Hour; if (Hour >= 5 && Hour < 12) Console.WriteLine("Good Morning..." + Name); else if (Hour >= 12 && Hour < 16) Console.WriteLine("Good Afternoon..." + Name); else if (Hour >= 16 && Hour < 22) Console.WriteLine("Good Evening..." + Name); else Console.WriteLine("Good Night..." + Name); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

246

(Source code: Module 15\DelegateExample\DelegateExample\01SingleCastDelegate.cs)

246

SingleCast Delegate

(Contd)

//method public static int NumberCube(int number) { return number * number * number; } public static void Main() { //instantiate delegate DelegateString delegateobj1 = new DelegateString(Greet); DelegateString delegateobj2 = new DelegateString(Wish ); //Invoke delegate delegateobj1("Bhavana"); Console.WriteLine("-----------------------------------"); delegateobj2("Bhavana"); Console.WriteLine("====================================="); DelegateCube delegatecubeobj = new DelegateCube(NumberCube); Console.WriteLine("Cube of Number 3 = " + delegatecubeobj(3)); Console.ReadLine(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

247

(Source code: Module 15\DelegateExample\DelegateExample\01SingleCastDelegate.cs)

247

MultiCast Delegate
delegate void DelegateMultiCast (int value1, int value2); class _02MultiCastDelegate { public static void AddNumbers(int number1, int number2) { int total = number1 + number2; Console.WriteLine("Addition of 2 numbers {0}, {1} = {2}", number1, number2,total); } public static void MultiplyNumbers(int number1, int number2) { int total = number1 * number2; Console.WriteLine("Multiplication of 2 numbers {0}, {1} = {2}", number1, number2, total); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

248

(Source code: Module 15\DelegateExample\DelegateExample\02MultiCastDelegate.cs) Using multicast delegate you can call more then one method through single delegate instance. It will successively call each method in order. The delegate signature should return a void, otherwise, you would only get the result of the last invoked method. If one of the method invoked by the delegate throws an exception, the execution stops.

248

MultiCast Delegate

(Contd)

public static void Power(int number1, int number2) { int total=1; for (int i = 1; i <= number2; i++) { total = total * number1; } Console.WriteLine("Power of number {0}, {1} = {2}", number1, number2, total); } public static void Main() { DelegateMultiCast Multicastobj=null; Multicastobj += new DelegateMultiCast(AddNumbers); Multicastobj += new DelegateMultiCast(MultiplyNumbers); Multicastobj += new DelegateMultiCast(Power); Multicastobj(5,3); Console.ReadLine(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

249

(Source code: Module 15\DelegateExample\DelegateExample\02MultiCastDelegate.cs)

249

Event
Provides notifications to clients when something interesting happens. Events are declared using delegates.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

250

Events continued
delegate void MyEventHandler(); class MyEvent { public event MyEventHandler SomeEvent; public void OnSomeEvent() { if (SomeEvent != null) SomeEvent(); } } class Program { static void handler() { Console.WriteLine("Event occurred"); } static void Main(string[] args) { MyEvent evt = new MyEvent(); evt.SomeEvent += handler; evt.OnSomeEvent(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

251

Anonymous Method
delegate void DelegateAnonymous(int value1, int value2); class _03AnonymousMethod { public static void Main() { DelegateAnonymous obj = delegate(int number1, int number2) { try { int Total = number1 / number2; Console.WriteLine("Division of {0} / {1} = {2}", number1, number2, Total); } catch (DivideByZeroException ex) { Console.WriteLine(ex.Message); } }; obj(10, 2); Console.ReadLine(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

252

(Source code: Module 15\DelegateExample\DelegateExample\03AnonymousMethod.cs) A method must exist for the delegate to work. However, another way to use the delegate is Anonymous Method. An anonymous method is a block of code that is used as the parameter for the delegate. The benefit of the anonymous method is to reduce the code. You do not have to define a method just ot use it with delegate. With anonymous method code does not perform faster. The compiler will defines a method, which has an automatically assigned name, which we do not need to know.

252

Module 17. Threads


Overview
Understanding Threads Creating, executing and terminating threads ParametizeThreadStart Delegate Thread Priorities Synchronization among threads

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

253

253

Understanding Thread
Thread is a line of execution. Series of steps executed at a time is known as a Thread. Import System.Threading namespace for all the Thread Program. Initialize Balance Call Deposit Method Increment Balance Print Balance
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

254

Each stream of execution is called a thread. Multithreading is used to divide lengthy tasks into different segments that would otherwise abort programs. Threads are mainly used to utilize the processor to a maximum extent by avoiding it's idle time. Threads in DotNet are based on the namespace System.Threading.

254

MultiThreading
Execution of such steps by different tellers can be considered as multi-threading in a computer jargon. Initialize Balance Call Deposit Method Increment Balance Print Balance Initialize Balance Call Deposit Method Increment Balance Print Balance

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

255

255

Thread State
Wait/Sleep/Join Thread Blocks Unstarted Start Running Thread Unblocks Abort Abort

Abort Requested

Thread Ends

Thread Ends Stopped

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

256

Specifies the execution states of a thread. Unstarted The Start() method has not been invoked on the thread Running The thread has been started, it is not blocked. Wait / Sleep / Join The thread is blocked. This could be the result of calling Sleep() or Join() or requesting a lock Monitor.Enter() or Monitor.Wait() Abort Requested the Abort() method has been invoked on the thread. Stopped the thread has stopped.

Creating Thread
void Runthread_Task() { for (int i = 1; i <= 10; i++) { Console.WriteLine("\tMsg #{0} from secondary thread", i); } } void RunThread() { Thread t = new Thread(new ThreadStart(Runthread_Task)); //run the new thread t.Start(); //print some message to the console window for (int i = 1; i <= 10; i++) { Console.WriteLine("Msg #{0} from Main Thread", i); } //t.Abort(); //t.Join(); Console.WriteLine("End of Main Thread Program"); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

257

(Source code: Module 16\ThreadApplication\ThreadApplication\01Thread.cs) Methods of Thread Start Start the Thread Change the ThreadState to Running mode ThreadState specifies the execution states of a Thread Sleep Block the current Thread for the specified number of milliseconds. Abort Terminate the Thread Join Block the calling Thread until a thread terminates or complete the task.

257

Creating Thread

(Contd)

static void Main(string[ ] args) { _01Thread obj = new _01Thread(); obj.RunThread(); Console.ReadLine(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

258

(Source code: Module 16\ThreadApplication\ThreadApplication\01Thread.cs)

258

ParameterizedThreadStart Delegate
void RunParameterizedThread_Task(Object obj) { for (int i = 1; i <= (int)obj; i++) { Console.WriteLine("Msg #{0} from secondary thread", i); } } void RunparametizedThread() { Thread t = new Thread(new ParameterizedThreadStart (RunParameterizedThread_Task )); t.Start(20); for (int i = 1; i <= 20; i++) { Console.WriteLine("Msg #{0} from Main Thread", i); } t.Join(); }
259

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

259

ParameterizedThreadStart Delegate
static void Main(string[ ] args) { _02ThreadParameter obj = new _02ThreadParameter(); obj.RunparametizedThread(); Console.WriteLine("Thread Program over"); Console.ReadLine(); }

(Contd)

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

260

(Source code: Module 16\ThreadApplication\ThreadApplication\02ThreadParameter.cs)

260

Thread Priority
ThreadPriority Enumeration
Above Normal Below Normal Highest Lowest Normal

Default priority for all thread is Normal

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

261

Threads are scheduled for execution based on their priority. It determines the order of thread execution. It can be very with each Operating System.

261

Thread Priority
public long count;

(Contd)

public void StartCount() { while (true) { count += 1; } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

262

(Source code: Module 16\ThreadApplication\ThreadApplication\03Priority.cs)

262

Thread Priority

(Contd)

public static void Main() { _03Priority obj1 = new _03Priority(); Thread t1 = new Thread(new ThreadStart(obj1.StartCount)); t1.Priority = ThreadPriority.Lowest; _03Priority obj2 = new _03Priority(); Thread t2 = new Thread(new ThreadStart(obj2.StartCount)); t2.Priority = ThreadPriority.Highest; t1.Start(); Thread.Sleep(1); t2.Start(); Thread.Sleep(1); t1.Abort(); t2.Abort(); Console.WriteLine("High Priority Thread Clicks : " + obj2.count); Console.WriteLine("Low Priority Thread Clicks : " + obj1.count); Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

263

(Source code: Module 16\ThreadApplication\ThreadApplication\03Priority.cs)

263

Creating Multiple Thread


In this process the last recorded transaction updates the balance.

File cabinets

Teller2

Teller1

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

264

264

Multiple Thread
int AccNo; string Name; float Bal; public float Balance { get { return Bal; } private set { Bal = value; } } public _04SavingMultiThread(int AccNo, string Name, float Bal) { this.AccNo = AccNo; this.Name = Name; this.Bal = Bal; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

265

(Source code: Module 16\ThreadApplication\ThreadApplication\04SavingMultiThread.cs)

265

Multiple Thread

(Contd)

public void Deposit(float amt) { Bal = Bal + amt; Console.WriteLine("Balance after deposit = " + Bal.ToString()); } public void Withdraw(float amt) { Bal = Bal - amt; Console.WriteLine("Balance after withdraw = " + Bal.ToString()); } public void Transaction(object amt) { string ThreadName = Thread.CurrentThread.Name; Console.WriteLine("Depositing amount by " + ThreadName); Deposit((float)amt); Withdraw((float)amt); Console.WriteLine("=================================="); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

266

(Source code: Module 16\ThreadApplication\ThreadApplication\04SavingMultiThread.cs)

266

Multiple Thread

(Contd)

public static void Main() { _04SavingMultiThread s1 = new _04SavingMultiThread (101, "Bhavana", 1000f); Thread thread1 = new Thread(new ParameterizedThreadStart(s1.Transaction)); Thread thread2 = new Thread(new ParameterizedThreadStart(s1.Transaction)); Thread thread3 = new Thread(new ParameterizedThreadStart(s1.Transaction)); thread1.Name = "Thread 1"; thread2.Name = "Thread 2"; thread3.Name = "Thread 3"; thread1.Start(500f); thread2.Start(500f); thread3.Start(500f); Console.ReadLine(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

267

(Source code: Module 16\ThreadApplication\ThreadApplication\04SavingMultiThread.cs)

267

Thread Synchronization
This type of locking tells when to use that filing cabinet and when not to.

Wait until I am Finished !!!

File cabinets

Teller2

Teller1

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

268

Synchronized specifies that the method can be executed by only one thread at a time. We can either use method synchronization or object synchronization (Block synchronization) For method synchronization we can use the attribute [MethodImpl(MethodImplOptions.Synchronized )] before the method declaration which is coming from the namespace System.Runtime.ComillerServices For object synchronization we can use either the lock() method or Monitor class. The Monitor class grant a lock for an object. Lock() method internally use the Monitor class only. Best practice is to minimize the code inside synchronized blocks because they prevent concurrent threads from executing - losing any advantage of multi-threaded applications. Synchronized blocks help let those portions of a method that do not access shared resources to be run simultaneously while still keeping those parts that need to be shared thread-safe.

268

Thread Synchronization

(Contd)

synchronization provides a lock on the resource that is shared among threads and makes a thread wait until the other thread finishes the job with the resource.

Balance = 5000 Sub Deposit (byval amt as Decimal)

Object lock

A synchronized transaction

Thread@1

Thread@2

Thread@3

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

269

269

Thread Synchronization

(Contd)

public void Transaction(object amt) { Monitor.Enter(this); string ThreadName = Thread.CurrentThread.Name; Console.WriteLine("Depositing amount by " + ThreadName); Console.WriteLine("Intial Balance = " + Balance); Deposit((float)amt); Withdraw((float)amt); Console.WriteLine("=================================="); Monitor.Exit(this); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

270

(Source code: Module 16\ThreadApplication\ThreadApplication\05SavingSynchronizee.cs)

270

Thread Synchronization

(Contd)

public static void Main() { _05SavingSynchronize s1 = new _05SavingSynchronize(101, "Bhavana", 1000f); Thread thread1 = new Thread(new ParameterizedThreadStart(s1.Transaction)); Thread thread2 = new Thread(new ParameterizedThreadStart(s1.Transaction)); Thread thread3 = new Thread(new ParameterizedThreadStart(s1.Transaction)); thread1.Name = "Thread 1"; thread2.Name = "Thread 2"; thread3.Name = "Thread 3"; thread1.Start(500f); thread2.Start(500f); thread3.Start(500f); Console.ReadLine(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

271

(Source code: Module 16\ThreadApplication\ThreadApplication\05SavingSynchronizee.cs)

271

Thread pool
Collection of threads Performs a number of tasks in background process. Primary thread leaves free to perform other tasks asynchronously.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

272

Thread pools are often employed in server applications. Each incoming request is assigned to a thread from the thread pool, so the request can be processed asynchronously, without tying up the primary thread or delaying the processing of subsequent requests. Once a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task. Thread pools typically have a maximum number of threads. If all the threads are busy, additional tasks are placed in queue until they can be serviced as threads become available. You can implement your own thread pool, but it is easier to use the thread pool provided by the .NET Framework through the ThreadPool class.

272

Module 18. Introduction to Web Services


Overview
Overview of Web Services Creating and Testing Web Service Consuming Web Service

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

273

273

Definition
XML Web Service is a programmable logic accessible by standard web protocols
Allow applications to send and receive information across the internet Language and Platform independent

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

274

A web service exposes a number of methods that provide functionality that can be used by one or more applications, regardless of the programming languages, operating systems and hardware platforms used to develop them. The methods that provide such functionality are called web methods. Some of the use of XML Web Service Authentication Services Weather Reports Exchange Rate Stock Quotes Etc.

274

Components of Web Services


Communication through SOAP messages Client Application
Locate a Web Service

Web Service

Describes

UDDI Registry

WSDL Document

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

275

Web service is comprised of five fundamental components Delivery Medium Internet Delivery Protocol HTTP Message Formatting SOAP (Simple Access Object Protocol) Service Description WSDL (Web Service Description Language) Web Service Publication UDDI (Universal Description, Discovery and Integration)

275

Creating Web Services


Select File New Web Site

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

276

276

Code for Web Services


public class ServiceHello : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

277

(Source code: Module 18\WebServiceHello\App_Code\ServiceHello.cs)

277

Test Web Services

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

278

278

Consuming Web Services


Start Windows Application

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

279

279

Add Web Service Reference


Click on Project Menu Add Web Reference Click Web Service on the local machine

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

280

280

Select the Web Service from the List

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

281

281

Create Proxy
Will display the Web methods available in the web service Click on Add Reference button, which creates the proxy. Default name is localhost

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

282

282

Design Windows Form and write the code


Add one Button and one Label Write the following code on button click event Create the object of proxy class and call the method using proxy object
localhost.ServiceHello obj = new WebServiceHelloTest.localhost.ServiceHello(); lblmsg.Text = obj.HelloWorld();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

283

(Source code: Module 18\WebServiceHelloTest\WebServiceHelloTest\Form1.cs)

283

Exchange Rate Web Service Example

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

284

(Source code: Module 18\WebServiceExchangeRateTest\WebServiceExchangeRateTest\Form1.cs)

284

XML File for Exchange Rate


<?xml version="1.0" encoding="utf-8" ?> <ExchangeRate> <ERate> <Country>Usa</Country> <Rate>41</Rate> </ERate> <ERate> <Country>Uk</Country> <Rate>70</Rate> </ERate> <ERate> <Country>Japan</Country> <Rate>120</Rate> </ERate> </ExchangeRate>
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

285

(Source code: Module 18\WebServiceExchangeRate\ExchangeRate.XML)

285

Code foe Exchange Rate Web Service


Web method for getting the names of the country
[WebMethod] public string[] GetCountries() { DataSet ds = new DataSet(); List<string> CountryList = new List<string>(); ds.ReadXml(Server.MapPath("Exchangerate.xml")); //DataRow[] row = ds.Tables[0].Select("Country"); foreach (DataRow dr in ds.Tables[0].Rows ) { CountryList.Add(dr["Country"].ToString()); } return CountryList.ToArray(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

286

(Source code: Module 18\WebServiceExchangeRate\App_Code\ServiceExchangeRate.cs)

286

Code for Exchange Rate Web Service

(Contd)

Web method return the exchange rate for the country name passed as parameter
[WebMethod] public decimal GetExchangeRate(string Country) { DataSet ds = new DataSet(); decimal rate; ds.ReadXml(Server.MapPath("Exchangerate.xml")); DataRow[] row =ds.Tables[0].Select("Country='" + Country + "'"); if (row != null) rate =decimal.Parse( row[0]["Rate"].ToString()); else rate = 0; return rate; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

287

(Source code: Module 18\WebServiceExchangeRate\App_Code\ServiceExchangeRate.cs)

287

Consume Exchange Rate Web Service


Design Windows Form with List Box and Label controls Write the code in form load event to populate list box with the name of the countries.
localhost.ServiceExchangeRate obj = new WebServiceExchangeRateTest.localhost.ServiceExchangeRate(); private void Form1_Load(object sender, EventArgs e) { obj = new WebServiceExchangeRateTest.localhost.ServiceExchangeRate(); string[] countries = obj.GetCountries(); foreach (string str in countries) { lstcountry.Items.Add(str); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

288

(Source code: Module 18\WebServiceExchangeRateTest\WebServiceExchangeRateTest\Form1.cs)

288

List Box SelectedIndexChanged Event


private void lstcountry_SelectedIndexChanged(object sender, EventArgs e) { int count = lstcountry.SelectedIndex; string country = lstcountry.Items[count].ToString(); lblmsg.Text = obj.GetExchangeRate(country).ToString(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

289

(Source code: Module 18\WebServiceExchangeRateTest\WebServiceExchangeRateTest\Form1.cs)

289

APPENDIX: Windows Form - II


OverView
MenuStip Control ContextMenuStrip Control ToolStrip Control StatusStrip Control Dialog Controls MDI Application

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

290

Notepad Example
Menu Strip Tool Strip RichTextBox ContextMenu Strip

Status Strip

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

291

(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs) Example where we cover the controls like Menu Strip Tool Strip Status Strip ContextMenu Strip - is a short cut menu which get activated when user click with Right Mouse Button on a specific control Rich Text Box

291

Notepad Example
FileStream fs; StreamReader reader; StreamWriter writer; string FileName = null;

(Contd)

private void Form1_Load(object sender, EventArgs e) { statusStrip1.Items[1].Text = DateTime.Now.ToString(); } private void timer1_Tick(object sender, EventArgs e) { statusStrip1.Items[1].Text = DateTime.Now.ToString(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

292

(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs) MenuItem Strip The strip is to show menu at the top of the form. Properties Name Menu Control Name Text Short Cut Key Board short cut

292

Notepad Example

(Contd)

private void newToolStripMenuItem_Click(object sender, EventArgs e) { WorkArea.Text = ""; FileName = null; WorkArea.Focus(); } private void openToolStripMenuItem_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { try { FileName = openFileDialog1.FileName; fs = new FileStream(FileName, FileMode.Open); reader = new StreamReader(fs); WorkArea.Text = reader.ReadToEnd(); reader.Close(); fs.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

293

(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs) ToolBar Strip It shows toolbar within the space provided below menu strip. It facilitates accessing menu items through short cuts. Properties Name Items Select type as Button and click add Name Text Image

293

Notepad Example

(Contd)

private void saveToolStripMenuItem_Click(object sender, EventArgs e) { if (FileName == null) { saToolStripMenuItem_Click(sender, e); } else { fs = new FileStream(FileName, FileMode.Create); writer = new StreamWriter(fs); writer.WriteLine(WorkArea.Text); writer.Close(); fs.Close(); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

294

(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs) Status Strip Provides status menu strip at the bottom of the form. It gives meta information/messages/properties about the task. Properties Name Items

294

Notepad Example

(Contd)

private void saveasToolStripMenuItem_Click(object sender, EventArgs e) { if (saveFileDialog1.ShowDialog() == DialogResult.OK) { try { FileName = saveFileDialog1.FileName; fs = new FileStream(FileName, FileMode.Create); writer = new StreamWriter(fs); writer.WriteLine(WorkArea.Text); writer.Close(); fs.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

295

(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs)

295

Notepad Example

(Contd)

private void clearToolStripMenuItem_Click(object sender, EventArgs e) { WorkArea.Text = ""; FileName = null; } private void CuttoolStripMenuItem_Click(object sender, EventArgs e) { WorkArea.Cut(); } private void copyToolStripMenuItem_Click(object sender, EventArgs e) { WorkArea.Copy(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

296

(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs) SaveDialog Box Shows dialog box for saving the information. Properties Name Control Name DefaultExt Default extension txt Filter File filter to display in a dialog box e.g. txt files|*.txt|all files|*.* FilterIndex The index of the file filter selected in the dialog 1 for the first item InitialDirectory The initial directory for the dialog RestoreDirectory Dialog restore the current directory before closing True / False FontDialog Box Show dialog box for selecting fonts from the list of installed fonts on the platform. Properties Name ShowColor ShowApply Control Name Show Color Choice True Show the Apply Button True

296

Notepad Example

(Contd)

private void pasteToolStripMenuItem_Click(object sender, EventArgs e) { WorkArea.Paste(); } private void undoToolStripMenuItem_Click(object sender, EventArgs e) { WorkArea.Undo(); } private void redoToolStripMenuItem_Click(object sender, EventArgs e) { WorkArea.Redo(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

297

(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs) Color Dialog Box Shows dialog box to select color. Properties Name FullOpen Control Name Show the custom color section True

297

Notepad Example

(Contd)

private void fontToolStripMenuItem_Click(object sender, EventArgs e) { try { if (fontDialog1.ShowDialog() == DialogResult.OK) { WorkArea.SelectionFont = fontDialog1.Font; WorkArea.SelectionColor = fontDialog1.Color; } } catch (Exception ex) { MessageBox.Show(ex.Message); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

298

(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs)

298

Notepad Example

(Contd)

private void backgroundColorToolStripMenuItem_Click(object sender, EventArgs e) { try { if (colorDialog1.ShowDialog() == DialogResult.OK) WorkArea.BackColor = colorDialog1.Color; } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

299

(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs)

299

Notepad Example

(Contd)

private void toolStripButtonNew_Click(object sender, EventArgs e) { newToolStripMenuItem_Click(sender, e); } private void toolStripButtonOpen_Click(object sender, EventArgs e) { openToolStripMenuItem_Click(sender, e); } private void toolStripButtonSave_Click(object sender, EventArgs e) { saveToolStripMenuItem_Click(sender, e); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

300

(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs)

300

Notepad Example

(Contd)

private void toolStripButtonCut_Click(object sender, EventArgs e) { CuttoolStripMenuItem_Click(sender, e); } private void toolStripButtonCopy_Click(object sender, EventArgs e) { copyToolStripMenuItem_Click(sender, e); } private void toolStripButtonPaste_Click(object sender, EventArgs e) { pasteToolStripMenuItem_Click(sender, e); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

301

(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs)

301

MDI Application
Three steps for creating MDI Application Create a Parent Form Create a Child Form Call Child Form from a Parent Form

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

302

Single Document Interface (SDI) only one document is visible at a time, e.g., Notepad. Multiple Document Interface Application (MDI) allows to display multiple document at the same time, with each document displayed in its own window, e.g., Microsoft Word.

302

MDI Application Example

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

303

(Source code: APPENDIX\MdiApplication\MdiAppliation)

303

MDI Application Example


(Contd)

Start New Project Create Parent Form Set IsMdiContainer Property of the Parent Form to True Add Menu Item Add Child Form Add RichTextBox on Child Form

Parent Form class level declaration int count=0;

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

304

304

MDI Application Example


New Menu Item count = count + 1; ChildForm frmchild = new ChildForm(); ; frmchild.MdiParent = this; frmchild.Text = "Form " + count.ToString(); frmchild.Show(); Cascade Menu Item this.LayoutMdi(MdiLayout.Cascade) Horizontal Menu Item this.LayoutMdi(MdiLayout.TileHorizontal) Vertical Menu Item this.LayoutMdi(MdiLayout.TileVertical)

(Contd)

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

305

(Source code: APPENDIX\MDIApplication\MDIApplication\MDIParent.cs)

305

Appendix: Advance Threads


Overview
Thread Safe class Singleton Pattern Thread Safe

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

306

Thread Safe class


Thread safety is a computer Programming concept applicable in the context of multi threaded programs. To make the class as thread safe we have to mark all the member as static

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

307

Thread-safe programming is only necessary if you have data that can be modified by more than one thread at a time. In a client/server situation, usually the server has multiple clients. If all those clients can change shared data on the server, they must not be allowed to conflict with one another. Normally, if two clients try to change shared data, you have to hope that the first client is able to finish with the data before the second client begins to modify it. This situation is called racing. A class is called thread safe when all the members of the class declared as synchronized.

Error Log Program


Add the following namespaces in your program
using System.IO; using System.Threading; using System.Runtime.CompilerServices; We will keep only one instance of the StreamWriter class which is going to be used by all the threads. So we will keep this instance as static. class LogFile { static StreamWriter ErrorLog;

We will write LogStart() and Trace() method also as static. LogStart() method will open the file and Trace() method will write the error message in the Error Log file.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

308

(Source code: Appendix Thread\SynchronizedThreadEx\SynchronizedThreadEx\Logfile.cs) Example: You have created a multi threaded application. While executing the program if there is any error comes we want to register those errors in log file. Multiple thread is running this application, but on server you will have only one error log file where you have to register the error. So we will male this error log program as thread safe, where only one thread is allowed to write its error at a time. Other threads have to wait for the first thread to complete it task.

Error Log Program (Contd)


[MethodImpl(MethodImplOptions.Synchronized)] public static void LogStart(string sFile) { //open Trace Log file ErrorLog = new StreamWriter(File.Open(sFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

309

(Source code: Appendix Thread\SynchronizedThreadEx\SynchronizedThreadEx\Logfile.cs)

Error Log Program (Contd)


[MethodImpl(MethodImplOptions.Synchronized )] public static void Trace() { string str = Thread.CurrentThread.Name; Console.WriteLine(str + " - Writing error into log file \n"); ErrorLog.WriteLine(str); ErrorLog.WriteLine("----------------------"); for (int i = 0; i < 25; i++) { ErrorLog.WriteLine(str + ",count : " + i); Console.WriteLine(str + ",count : " + i); } ErrorLog.WriteLine("============================="); Console.WriteLine("------------------------------"); Thread.Sleep(5000); ErrorLog.Flush(); Console.WriteLine(str + " - Error writing into log file Complete......"); Console.WriteLine("=============================="); Console.WriteLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

310

(Source code: Appendix Thread\SynchronizedThreadEx\SynchronizedThreadEx\Logfile.cs)

Test Program
static void Main(string[] args) { LogFile.LogStart("C:\\LOGFILE.txt"); Thread t1 = new Thread(new ThreadStart(LogFile.Trace)); Thread t2 = new Thread(new ThreadStart(LogFile.Trace)); Thread t3 = new Thread(new ThreadStart(LogFile.Trace)); Thread t4 = new Thread(new ThreadStart(LogFile.Trace)); t1.Name = "Thread 1"; t2.Name = "Thread 2"; t3.Name = "Thread 3"; t4.Name = "Thread 4"; t1.Start(); t2.Start(); t3.Start(); t4.Start(); t1.Join(); t2.Join(); t3.Join(); t4.Join(); Console.WriteLine("\nMain Ends............."); Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

311

(Source code: Appendix Thread\SynchronizedThreadEx\SynchronizedThreadEx\Program.cs)

Write a test program where we will create multiple thread and each thread will write some message to this log file.

Singleton Pattern using Thread safe


a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

312

Basic characteristics of the singleton class A single constructor, which is private and parameter less The class is sealed. This is optional, but may help the CLR to optimize A static variable which holds a reference to the single created instance, if any. A public static read only property means getting the reference to the single created instance.

Bad code which is not thread safe


Bad code which is not thread safe public sealed class Singleton { static Singleton instance = null; Singleton() {} public static Singleton Instance() { if (instance == null) { Console.WriteLine("Creating instance..."); System.Threading.Thread.Sleep(2000); instance = new Singleton(); } return instance; } public static void RunThread() { Instance(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

313

(Source code: Appendix Thread\SingletonThreadSafe\SingletonThreadSafe\Singleton.cs)

Testing Program
static void Main(string[] args) { Thread t1 = new Thread(new ThreadStart(Singleton.RunThread)); Thread t2 = new Thread(new ThreadStart(Singleton.RunThread)); Thread t3 = new Thread(new ThreadStart(Singleton.RunThread)); Thread t4 = new Thread(new ThreadStart(Singleton.RunThread)); t1.Start(); t2.Start(); t3.Start(); t4.Start(); t1.Join(); t2.Join(); t3.Join(); t4.Join(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

314

(Source code: Appendix Thread\SingletonThreadSafe\SingletonThreadSafe\Program.cs) When you run this program, though it is a singleton program, it will create the multiple instance of the class. Different threads could have evaluated the test if (instance==null) and found it to be true, then all thread created instances, which violates the singleton pattern.

Simple Thread Safe Singleton Pattern


public sealed class SingleTonSafeThread { static SingleTonSafeThread instance = null; SingleTonSafeThread() {} [MethodImpl(MethodImplOptions.Synchronized)] private static SingleTonSafeThread Instance() { if (instance == null) { Console.WriteLine("Creating instance..."); System.Threading.Thread.Sleep(2000); instance = new SingleTonSafeThread(); } return instance; } [public static void RunThread() { Instance(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

315

(Source code: Appendix Thread\SingletonThreadSafe\SingletonThreadSafe\SingletonThreadSafe.cs) Mark the method as thread safe.

Test Program
static void Main(string[] args) { Thread t1 = new Thread(new ThreadStart(SingleTonSafeThread.RunThread)); Thread t2 = new Thread(new ThreadStart(SingleTonSafeThread.RunThread)); Thread t3 = new Thread(new ThreadStart(SingleTonSafeThread.RunThread)); Thread t4 = new Thread(new ThreadStart(SingleTonSafeThread.RunThread)); t1.Start(); t2.Start(); t3.Start(); t4.Start(); t1.Join(); t2.Join(); t3.Join(); t4.Join(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

316

(Source code: Appendix Thread\SingletonThreadSafe\SingletonThreadSafe\Program.cs)

Volatile
public sealed class SingltonVolatile { static volatile SingltonVolatile instance = null; static readonly object padlock = new object(); SingltonVolatile() { } private static SingltonVolatile Instance() { if (instance == null) { lock (padlock) { if (instance == null) { Console.WriteLine("Creating instance..."); instance = new SingltonVolatile(); } } } return instance; } public static void RunThread() { Instance(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

317

(Source code: Appendix Thread\SingletonThreadSafe\SingletonThreadSafe\SingletonVolatile.cs) The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times. The volatile keyword alerts the compiler that multiple threads will access the data member, and therefore it should not make any optimization assumptions about the state of this member.

Test Program
static void Main(string[] args) { Thread t1 = new Thread(new ThreadStart(SingltonVolatile.RunThread)); Thread t2 = new Thread(new ThreadStart(SingltonVolatile.RunThread)); Thread t3 = new Thread(new ThreadStart(SingltonVolatile.RunThread)); Thread t4 = new Thread(new ThreadStart(SingltonVolatile.RunThread)); t1.Start(); 2.Start(); t3.Start(); t4.Start(); t1.Join(); t2.Join(); t3.Join(); t4.Join(); Console.WriteLine("Main end..."); Console.ReadLine(); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

318

(Source code: Appendix Thread\SingletonThreadSafe\SingletonThreadSafe\Program.cs)

Thread Pool
Using System.Threading; static void Main(string[] args) { int i, j; ThreadPool.GetMaxThreads(out i, out j); Console.WriteLine("Available Worker thread = " + i); Console.WriteLine("Available Asynchronus I/O thread = " + j); ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc)); Thread.Sleep(1000); Console.WriteLine("Main thread exits."); Console.ReadLine(); } // This thread procedure performs the task. static void ThreadProc(Object stateInfo) { Console.WriteLine("Hello from the thread pool."); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

319

(Source code: \Appendix Thread\ProjThreadPool\Class1.cs)

Many applications create threads that spend a great deal of time in the sleeping state, waiting for an event to occur. Other threads might enter a sleeping state only to be awakened periodically to poll for a change or update status information. Thread pooling enables you to use threads more efficiently by providing your application with a pool of worker threads that are managed by the system. One thread monitors the status of several wait operations queued to the thread pool. When a wait operation completes, a worker thread from the thread pool executes the corresponding callback function. The thread pool is created the first time you create an instance of the ThreadPool class. A thread pool is a collection of threads that can be used to perform a number of tasks in the background. This leaves the primary thread free to perform other tasks asynchronously. Once a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task. Where are ThreadPools used? On servers and in batch processing applications. ThreadPool has internal logic that makes getting a thread much less expensive. This is because the threads are already made and are just "hooked up" when required.

Appendix : Iterators
Overview
Ienumerator Ienumerable

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

320

320

IEnumerator Example
class IEnumeratorExample { string[ ] w_Days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" }; public System.Collections.IEnumerator GetEnumerator() { for (int i = 0; i < w_Days.Length; i++) { yield return w_Days[i]; } } static void Main(string[ ] args) { IEnumeratorExample Days = new IEnumeratorExample(); // Iterate with the help of foreach foreach (string day in Days) { System.Console.Write(day + " "); } Console.ReadLine(); } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

321

(Source code: Module09\IteratorExample\IteratorExample\IEnumeratorExample.cs) When we use IEnumerator the name of the method is always GetEnumerator() and return type is IEnumerator. So, in a class we can have this method only once. To overcome this limitation they have introduced IEnumerable

321

IEnumerable Example
class IEnumerableExample { public int[] numbers = new int[] {5,10,15,20}; public string[] states = new string [] { "Maharashtra", "Gujarat", "Himachal" }; public IEnumerable BuildintCollection() { for (int i = 0; i < numbers.Length; i++) { yield return numbers[i]; } } public IEnumerable BuildStringCollection() { for (int i = 0; i < states.Length; i++) { yield return states[i]; } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

322

(Source code: Module09\IteratorExample\IteratorExample\IEnumerableExample.cs) An iterator is a method, get accessor or operator that enables foreach iteration in a class or structure. Iterator traverse the data structure in the class. You can have multiple IEnumerable methods because you can give your own name to this method. Each method must have a unique name and can be invoked in client code by foreach statement The return type of an iterator must be IEnumerable, IEnumerator, IEnumerable<T>, or IEnumerator<T>. The yield keyword is used to specify the return value. When the yield return statement is reached, the current location is stored. Execution is restarted from this location the next time the iterator is called.

322

IEnumerable Example

(Contd)

static void Main() { IEnumerableExample obj = new IEnumerableExample(); // Display the collection items: System.Console.WriteLine("Values in the int collection are:"); foreach (int i in obj.BuildintCollection()) { System.Console.Write(i + "\t"); } Console.WriteLine("\n----------------------\n"); System.Console.WriteLine("Values in the string collection are:"); foreach (string st in obj.BuildStringCollection()) { Console.Write (st +"\t"); } Console.ReadLine(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

323

(Source code: Module09\IteratorExample\IteratorExample\IEnumerableExample.cs)

323

Appendix: Reflection
Overview
Reflection mechanism Obtaining the content of assembly at run time

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

324

324

Reflection features
Reflection is ability to find out the information about the objects at run-time. Using reflection we can read types from assembly, create instances of types dynamically, invoke methods, etc. Add System.Reflection Namespace

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

325

Every managed application in .NET is deployed as an assembly and every assembly defines certain types (like class, interface, structure, enum, delegate). These types are revealed in the form of metadata. Metadata gives a detailed description of types and external assemblies that are used by the types. Reflection allows us to access data from assembly The System.Reflection namespace contains classes to read an assembly.

325

Hierarchical Representation of Metadata Information


Assembly Module(s) Type(s) class(s), interface(s), structure(S), enum(s) delegate(s)

Constructor(s) Parameter(s)

Method(s) Parameter(s)

Field(s)

Property(s)

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

326

326

Reflection Code
class Shape { int l, b; public Shape() { l = 5; b = 3; Console.WriteLine("inside constructor"); Console.WriteLine("--------------------"); } public void Display() { Console.WriteLine("Inside Display Method"); Console.WriteLine("l = " + l); Console.WriteLine("b = " + b); Console.WriteLine("----------------------"); } public int RectangleArea() { return l * b; } public static float CircleArea(int r) { return 3.14f * r * r; } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

327

(Source code: Appendix Reflection\Reflection\Reflection\Shape.cs)

327

Reflection Code

(Contd)

static void Main(string[ ] args) { Object obj; try { //load assembly Assembly assembly = Assembly.LoadFrom("Reflection.exe"); //search for the type Type[] types = assembly.GetTypes(); Console.WriteLine("The types contained within the assembly are : "); foreach (Type type in types) { Console.WriteLine("\tType name: " + type.Name); } Console.WriteLine("--------------------"); //load the type //assembly.GetType(string name,bool throwonerror, bool ignorecase ) Type ClassType = assembly.GetType("Reflection.Shape", true, true);
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

328

(Source code: Appendix Reflection\Reflection\Reflection\Program.cs)

328

Reflection Code

(Contd)

if (ClassType == null) Console.WriteLine(ClassType.Name + " type does not exist"); else Console.WriteLine(ClassType.Name + " type exist"); Console.WriteLine("--------------------"); //create the instance of the type obj = Activator.CreateInstance(ClassType); //method invoking MethodInfo methodinfo = ClassType.GetMethod("Display"); if (methodinfo.IsStatic == true) //invoke method //object on which to invoke the method (if method is static then null) //method parameter if no parameter then null methodinfo.Invoke(null, null); else if (methodinfo.IsStatic == false) methodinfo.Invoke(obj, null);
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

329

(Source code: Appendix Reflection\Reflection\Reflection\Program.cs)

329

Reflection Code

(Contd)

//method with return value MethodInfo methodinfo1 = ClassType.GetMethod("RectangleArea"); if (methodinfo1.IsStatic == true) Console.WriteLine("Area of Rectangle = " + methodinfo1.Invoke(null, null).ToString()); else if (methodinfo1.IsStatic == false) { Console.WriteLine("Area of Rectangle = " + methodinfo1.Invoke(obj, null).ToString()); } Console.WriteLine("--------------------");

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

330

(Source code: Appendix Reflection\Reflection\Reflection\Program.cs)

330

Reflection Code

(Contd)

//method with parameter int r = 10; Object[] param = new Object[1]; param[0] = r; MethodInfo methodinfo2 = ClassType.GetMethod("CircleArea"); if (methodinfo2.IsStatic == true) Console.WriteLine("Area of Circle = " + methodinfo2.Invoke(null, param).ToString()); else if (methodinfo2.IsStatic == false) Console.WriteLine("Area of Circle = " + methodinfo2.Invoke(obj, param).ToString()); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

331

(Source code: Appendix Reflection\Reflection\Reflection\Program.cs)

331

Appendix: Serialization
Overview
What is serialization Types of serialization
Binary SOAP XML

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

332

Serialization
Serialization allows programs to persist or transfer the state of an object into a stream (file, memory, network etc.) .Net offers Binary, SOAP and XML Serialization

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

333

Object Serialization is a process through which an object's state is transformed into some serial data format, such as XML or a binary format. Binary is more efficient (time and memory used) Binary is completely human unreadable. SOAP isnt much better. XML does not serialize private class members Mark the class wth [Serializable] attribute. For non serializing the member mark with the attribute [NonSerialized] or in case of XML Serialization mark with the attribute [XmlIgnore].

Class Person
[Serializable] class Person { private string strname; private DateTime dtbirthdate; [NonSerialized] private int intAge; public string Name { get { return strname; } set { strname = value; } } public DateTime Birthdate { get { return dtbirthdate; } set { dtbirthdate = value; } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

334

(Source code: Appendix Serialization\Serialization\Serialization\02BinarySerialization.cs\Person.cs)

Class Person (Contd)


public Person(string name, DateTime birthdate) { this.strname = name; this.dtbirthdate = birthdate; } public int Age { get { if (intAge == 0) { intAge = System.DateTime.Now.Year - Birthdate.Year; if (Birthdate.DayOfYear > System.DateTime.Now.DayOfYear) { intAge -= 1; } } return intAge; } } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

335

(Source code: Appendix Serialization\Serialization\Serialization\02BinarySerialization.cs\Person.cs)

Binary Serialization
Binary Formatter class is available in the namespace System.Runtime.Serialization.Formatters.Binary

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

336

(Source code: Appendix Serialization\Serialization\Serialization\02BinarySerialization.cs)

Binary Serialization Write Object


Add the namespace
using System.Runtime.Serialization.Formatters.Binary; using System.IO; Person p = new Person("Bhavana", Convert.ToDateTime("01/01/2001")); FileStream stream = new FileStream("c:\\Person.txt", FileMode.Create ); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, p); stream.Close(); richTextBox1.Text = "Data saved in a file";

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

337

(Source code: Appendix Serialization\Serialization\Serialization\02BinarySerialization.cs)

Binary Serialization Read Object


richTextBox1.Clear(); FileStream stream = new FileStream("c:\\Person.txt", FileMode.Open); BinaryFormatter formatter = new BinaryFormatter(); Person p =(Person) formatter.Deserialize(stream); stream.Close(); richTextBox1.AppendText("Name = " + p.Name + "\nAge = " + p.Age); richTextBox1.AppendText("\nBirthdate = " + p.Birthdate);

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

338

(Source code: Appendix Serialization\Serialization\Serialization\02BinarySerialization.cs)

Read & Write Multiple Object


List<Person> personlist = new List<Person>(); personlist.Add(new Person("Bhavana", Convert.ToDateTime("01/01/2001"))); personlist.Add(new Person("Shraddha", Convert.ToDateTime("01/01/2002"))); personlist.Add(new Person("Vishal", Convert.ToDateTime("01/01/2003"))); FileStream stream = new FileStream("C:\\Persons.txt", FileMode.Create); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, personlist); stream.Close(); FileStream stream1 = new FileStream("C:\\Persons.txt", FileMode.Open); List<Person> TotalPersons = (List<Person>)formatter.Deserialize(stream1); stream1.Close(); foreach (Person p in TotalPersons) { richTextBox1.AppendText(p.Name + " " + p.Birthdate + " " + p.Age.ToString() + "\n"); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

339

(Source code: Appendix Serialization\Serialization\Serialization\02BinarySerialization.cs)

SOAP Serialization
Add reference for the namespace System.Runtime.Serialization.Formatters.Soap

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

340

(Source code: Appendix Serialization\Serialization\Serialization\03SOAPSerialization.cs)

SOAP Serialization Write Object


Person p = new Person("Bhavana", Convert.ToDateTime("01/01/2001")); FileStream stream = new FileStream("c:\\PersonSoap.XML", FileMode.Create); SoapFormatter formatter = new SoapFormatter(); formatter.Serialize(stream, p); stream.Close(); richTextBox1.Text = "Data saved in a file";

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

341

(Source code: Appendix Serialization\Serialization\Serialization\03SOAPSerialization.cs)

SOAP Serialization Read Object


richTextBox1.Clear(); FileStream stream = new FileStream("c:\\PersonSoap.XML", FileMode.Open); SoapFormatter formatter = new SoapFormatter(); Person p = (Person)formatter.Deserialize(stream); stream.Close(); richTextBox1.AppendText("Name = " + p.Name + "\nAge = " + p.Age); richTextBox1.AppendText("\nBirthdate = " + p.Birthdate); richTextBox1.AppendText("\nBirthdate day of the year = " + p.Birthdate.DayOfYear.ToString()); richTextBox1.AppendText("\nCurrent day of the year = " + DateTime.Now.DayOfYear.ToString());

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

342

(Source code: Appendix Serialization\Serialization\Serialization\03SOAPSerialization.cs)

XML Serialization
Rules for creating class for XML Serialization XML serialization serializes only the public fields and property values of an object into an XML stream. XML serialization does not include type information. XML serialization serialize only the public type. XML serialization requires a default constructor to be declared in the class that is to be serialized. XML serialization requires all properties that are to be serialized as read write properties. Read only properties are not serialized.

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

343

XML was designed to be a technology for data exchange across heterogeneous systems. It can be easily transmitted between distributed components because of its platform independence and its simple, text-based, self-describing format.

Employee Class
Add the following namespace
using System.Xml.Serialization; using System.Collections;

public class Emp { [XmlAttribute("empNo")] public int empNo; [XmlElement("name")] public string name; //[XmlElement("address")] [XmlIgnore] public string address; [XmlElement("salary")] public double salary;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

344

(Source code: Appendix Serialization\Serialization\Serialization\Employee.cs)

Employee Class (Contd)


public Emp() {} public Emp(int empNo,string name, string address, double sal) { this.empNo = empNo; this.name = name; this.address = address; this.salary = sal; } public double AnnualSalary() { return salary * 12; } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

345

(Source code: Appendix Serialization\Serialization\Serialization\Employee.cs)

Employee Class (Contd)


[XmlRoot("employeeList")] public class Employee { private ArrayList listEmployee; public Employee() { listEmployee = new ArrayList(); } public int AddEmp(Emp emp) { return listEmployee.Add(emp); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

346

(Source code: Appendix Serialization\Serialization\Serialization\Employee.cs)

Employee Class (Contd)


[XmlElement("emp")] public Emp[] Emps { get { Emp[] emps = new Emp[listEmployee.Count]; listEmployee.CopyTo(emps); return emps; } Set { if (value == null) return; Emp[] emps = (Emp[])value; listEmployee.Clear(); foreach (Emp emp in emps) listEmployee.Add(emp); } } }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

347

(Source code: Appendix Serialization\Serialization\Serialization\Employee.cs)

Employee XML Serialization


using System.IO; using System.Xml.Serialization;

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

348

(Source code: Appendix Serialization\Serialization\Serialization\Employee.cs)

XML Serialization Write Object


Employee empList = new Employee(); empList.AddEmp(new Emp(1,"Bhavana", "Mumbai", 8000.00)); empList.AddEmp(new Emp(2,"Shraddha", "Pune", 7000.00)); empList.AddEmp(new Emp(3,"Vishal", "Delhi", 9000.00)); //serialization XmlSerializer serializer = new XmlSerializer(typeof(Employee)); StreamWriter writer = new StreamWriter("C:\\emp.xml"); serializer.Serialize(writer, empList); writer.Close();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

349

(Source code: Appendix Serialization\Serialization\Serialization\04EmployeeXMLSerialization.cs)

XML Serialization Read Object


richTextBox1.Clear(); Employee newList; XmlSerializer serializer = new XmlSerializer(typeof(Employee)); StreamReader reader = new StreamReader("C:\\emp.xml"); newList = (Employee) serializer.Deserialize(reader); reader.Close(); int empcount = newList.Emps.Count(); richTextBox1.AppendText("total No of Employees = " + empcount.ToString() + "\n"); for (int i = 0; i < empcount; i++) { richTextBox1.AppendText(newList.Emps[i].empNo.ToString() +" " + newList.Emps[i].name + " " + newList.Emps[i].address + " " + newList.Emps[i].salary.ToString() +" " + newList.Emps[i].AnnualSalary().ToString() + "\n"); }
350

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

(Source code: Appendix Serialization\Serialization\Serialization\04EmployeeXMLSerialization.cs)

Appendix:SQL Bulk Copy

string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr); conn.Open(); SqlCommand cmdcreatetable = new SqlCommand("create table Productnew1 (prodid int, prodname varchar(40))", conn); cmdcreatetable.ExecuteNonQuery(); conn.Close();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

351

(Source code: Module12\DatabaseApplication\DatabaseApplication\12SQLBulkCopy.cs)

351

SQL Bulk Copy

(Contd)

SqlConnection Sourceconn = new SqlConnection(connstr); Sourceconn.Open(); SqlCommand cmd = new SqlCommand("select productid, productname from products where productid > 70 and Productid <78", Sourceconn); SqlDataReader reader = cmd.ExecuteReader(); SqlConnection destConn = new SqlConnection(connstr); destConn.Open(); SqlBulkCopy bcp = new SqlBulkCopy(destConn); bcp.DestinationTableName = "ProductNew1"; //bcp.ColumnMappings.Add(0, 0) //bcp.ColumnMappings.Add(1, 1) bcp.ColumnMappings.Add("productid", "prodid"); bcp.ColumnMappings.Add("productname", "prodname"); bcp.WriteToServer(reader); destConn.Close(); reader.Close(); Sourceconn.Close(); MessageBox.Show("Record copied");
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

352

(Source code: Module12\DatabaseApplication\DatabaseApplication\12SQLBulkCopy.cs)

352

Appendix : Batch Update

Write the code in Batch Update Button Click Event string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr); SqlDataAdapter adp = new SqlDataAdapter("select * from productnew", conn); DataSet ds = new DataSet(); adp.Fill(ds); Console.WriteLine(ds.Tables.Count.ToString()); adp.RowUpdating += new SqlRowUpdatingEventHandler(adprowupdating); adp.RowUpdated += new SqlRowUpdatedEventHandler(adprowupdated); foreach (DataRow dr in ds.Tables[0].Rows) { string name = dr["prodname"].ToString(); dr["prodname"] = name; } Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com Pragati

353

(Source code: Module12\DatabaseApplication\DatabaseApplication\13BatchUpdate.cs)

353

Batch Update

(Contd)

adp.UpdateCommand = new SqlCommand("update productnew set prodname='xxx' where prodid>70", conn); adp.UpdateCommand.UpdatedRowSource = UpdateRowSource.None; adp.UpdateBatchSize = 2; adp.Update(ds); label1.Text = "Row updated = " + x; label2.Text = "Rwo updating = " + y; private void adprowupdated(object sender, EventArgs e) { x++; } private void adprowupdating(object sender, EventArgs e) { y++; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

354

(Source code: Module12\DatabaseApplication\DatabaseApplication\13BatchUpdate.cs)

354

Appendix : Multiple Active Result Set

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

355

(Source code: Module12\DatabaseApplication\DatabaseApplication\14MARS.cs)

355

Multiple Active Result Set

(Contd)

//By default, MARS is disabled when connecting to a MARS-enabled host such as SQL Server 2005. It must be enabled in the connection string. int categoryid; SqlDataReader productReader = null; string categorysql = "select categoryid, categoryname from categories"; string productsql = "select productid, productname from products where categoryid=@catid"; using (SqlConnection Connection = new SqlConnection("Data Source = .\\sa1; Integrated Security=true;Initial Catalog= Northwind; MultipleActiveResultSets=True )) { SqlCommand categoryCmd = new SqlCommand(categorysql, Connection); SqlCommand productCmd = new SqlCommand(productsql, Connection); productCmd.Parameters.Add("@catid", SqlDbType.Int); Connection.Open();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

356

(Source code: Module12\DatabaseApplication\DatabaseApplication\14MARS.cs)

356

Multiple Active Result Set

(Contd)

using (SqlDataReader categoryReader = categoryCmd.ExecuteReader()) { while (categoryReader.Read()) { lstmars.Items.Add (categoryReader["categoryname"].ToString()); categoryid = (int)categoryReader["categoryid"]; productCmd.Parameters["@catid"].Value = categoryid; // The following line of code requires a MARS-enabled connection. productReader = productCmd.ExecuteReader(); using (productReader) { while (productReader.Read()) { lstmars.Items.Add (" " + productReader[productName].ToString()); } } } Connection.Close(); } } }
357

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

(Source code: Module12\DatabaseApplication\DatabaseApplication\14MARS.cs)

357

Appendix : Reading and Writing Data to XML

DataSet ds;

Form Load Event


string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr); string sql = "select categoryid, categoryname from categories order by categoryid"; SqlDataAdapter adp = new SqlDataAdapter(sql, conn); ds = new DataSet(); adp.Fill(ds);
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

358

(Source code: Module12\DatabaseApplication\DatabaseApplication\15XML.cs)

358

Reading and Writing Data to XML


WriteXML Button
if (!File.Exists("C:\\category.xml")) { ds.WriteXml("c:\\category.xml"); } btnreadxml.Visible = true;

(Contd)

ReadXML Button
ds.Clear(); ds.ReadXml("C:\\category.xml"); dataGridView1.DataSource = ds.Tables[0];

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

359

(Source code: Module12\DatabaseApplication\DatabaseApplication\15XML.cs)

359

Appendix : Data Independent Provider

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

360

(Source code: Module12\DatabaseApplication\DatabaseApplication\16ProviderFactories.cs)

360

Data Independent Provider


Add the following namespace
using System.Data.Common;

(Contd)

Form Load Event


DataTable table = DbProviderFactories.GetFactoryClasses(); lstprovider.DisplayMember = table.Columns["InvariantName"].ToString(); lstprovider.ValueMember = table.Columns["InvariantName"].ToString(); lstprovider.DataSource = table;

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

361

(Source code: Module12\DatabaseApplication\DatabaseApplication\16ProviderFactories.cs)

361

Data Independent Provider

(Contd)

ListBox SelectedIndexChange Event


string provider = lstprovider.SelectedValue.ToString(); if (provider == "System.Data.SqlClient") { DbProviderFactory factory = DbProviderFactories.GetFactory(provider ); using (DbConnection conn = factory.CreateConnection()) { conn.ConnectionString = "data source=.\\sa1; initial catalog=northwind; integrated security=true"; conn.Open(); DbCommand cmd = factory.CreateCommand(); cmd.CommandText = "select * from customers"; cmd.Connection = conn; DbDataReader reader = cmd.ExecuteReader(); DataTable custtable = new DataTable(); custtable.Load(reader); conn.Close(); dataGridView1.DataSource = custtable; } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

362

(Source code: Module12\DatabaseApplication\DatabaseApplication\16ProviderFactories.cs)

362

Data Independent Provider

(Contd)

else if (provider == "System.Data.OleDb") { DbProviderFactory factory = DbProviderFactories.GetFactory(provider ); using (DbConnection conn = factory.CreateConnection()) { conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;data source=c:\\northwind.mdb;"; conn.Open(); DbCommand cmd = factory.CreateCommand(); cmd.CommandText = "select * from Categories"; cmd.Connection = conn; DbDataReader reader = cmd.ExecuteReader(); DataTable categorytable = new DataTable(); categorytable.Load(reader); conn.Close(); dataGridView1.DataSource = categorytable; } }
363

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

(Source code: Module12\DatabaseApplication\DatabaseApplication\16ProviderFactories.cs)

363

Appendix : TreeView Example with Database

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

364

(Source code: Module12\DatabaseApplication\DatabaseApplication\17TreeViewExample.cs)

TreeView Example with Database Code


Class level declaration
SqlConnection conn; SqlDataAdapter adp; DataSet ds = new DataSet();

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

365

TreeView Example with Database Code


Form Load Event
conn = new SqlConnection("server=.\\sa1;database=northwind;integrated security=true"); adp = new SqlDataAdapter("select table_name from information_schema.tables where table_type='Base Table' order by table_name", conn); adp.Fill(ds); treeView1.Nodes.Add("Northwind"); int rows = ds.Tables[0].Rows.Count; for (int i = 0; i <= rows - 1; i++) { treeView1.Nodes[0].Nodes.Add(ds.Tables[0].Rows[i][0].ToString()); } for (int i = 0; i <= rows - 1; i++) { treeView1.Nodes[0].Nodes[i].Nodes.Add("column"); treeView1.Nodes[0].Nodes[i].Nodes.Add("data"); }

Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

366

TreeView Example with Database Code


ds = new DataSet(); if (e.Node.Text == "column") { string str = e.Node.Parent.Text; adp = new SqlDataAdapter("select COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH from northwind.information_schema.columns where table_name = '" + str + "'", conn); adp.Fill(ds); dataGridView1.DataSource = ds.Tables[0]; } else if (e.Node.Text == "data") { string str = e.Node.Parent.Text; adp = new SqlDataAdapter("select * from [" + str + "]", conn); adp.Fill(ds); dataGridView1.DataSource = ds.Tables[0]; } Else { dataGridView1.DataSource = null; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com

367

You might also like