1
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 1
C# 2010 with Microsoft.Net
Framework 4.0
Pragati Software Pvt. Ltd.www.pragatisoftware.com
2
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 2
IndexModule Particulars PageModule 1 Getting Started 4Module 2 Basic Language Constructs 15Module 3 Class and Object 37Module 4 Class Library 47Module 5 Inheritance 59Module 6 Exception Handling 75Module 7 Other C# Features 85Module 8 String, StringBuilder and Dateformats 99Module 9 Collection classes 117
Module 10 Generics and Nullable Types 129Module 11 Windows Form Control I 137Module 12 File I/O 159
3
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 3
Index (Contd…)
Module 13 Working with DB 181Module 14 Data Bound Controls 226Module 15 DotNet Framework and Assembly 239Module 16 Delegate 244Module 17 Thread 253Module 18 Introduction to Web Services 273APPENDIX Windows Form Control II 290APPENDIX Advance Thread 306APPENDIX Reflection 320APPENDIX Serialization 324
APPENDIX Iterators 332APPENDIX SQL BULK copy 351APPENDIX Database Operations 353
4
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 4
Module 1: Getting Started
• OverviewIntroduction to C#Types of applicationsUnderstanding some terms: solution, project, Visual Studio IDEWriting, 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 5
Framework Version
CLR 4.0
.Net Framework 2.0C# 2.0 VB 8.0
.Net Framework 3.5C# 3.0 VB 9 LINQ AJAX
Enhancement for WCF, WPF, WF
.Net Framework 3.0WCF WPF WF Card Space
.Net Framework 4.0C# 4.0 VB 10 PLINQ MEF
DLR Code Contracts
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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 6
.Net Framework
.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 thecode 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.
6
7
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 7
Types of Applications
• Console applications. • Windows applications • ASP.NET Web applications• Class libraries • Custom controls (User defined controls). • Windows service• Web Service
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.
8
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 8
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
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.
9
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 9
Creating a New Project (Contd...)
2.Language
1. Framework Version
3. Application Template
4. Project Name
5. Project Location
6. Solution Name
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.
10
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 10
Solutions and Projects
• A solution usually acts as a container for one or more projects
• A project typically contains all the files required for the application.
1. Solution name
2. Project name
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.
11
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 11
Writing the First Program
• Click on Debug -> Start to view the output.
namespace Module01{
class Program{
static void Main(string[] args){
Console.WriteLine("Hello World...");Console.ReadLine();
}}
}
(Source code: C:\Training\Module01\Module01\Module01\Program.cs)
Namespace is a logical collection of the types such as:classinterfacestructenumdelegate
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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 12
Compilation Process in .NET
Visual Basic C# J#
Compiler
CPU CPU
JIT JIT
Windows CLR MAC CLR
Managed code
Compiler Compiler
.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
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 13
Location of .exe file.
1. Location of .exe
2. Exe file
.Exe is always stored at location : project folder\bin\debug.
13
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 14
Components of CLR
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 it’s 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
15
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 15
Module 2. Basic Language Constructs
• OverviewVariables and data typesOperators (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 16
Data Types (Contd…)
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 Description Exampleobject The ultimate base type of all other types object o = null;string String type; a string is a sequence of Unicode characters string s = "hello";sbyte 8-bit signed integral type sbyte val = 12;short 16-bit signed integral type short val =12;int 32-bit signed integral type int val=12;long 64-bit signed integral type long val1=12; long val2=34L;byte 8-bit unsigned integral type byte val1=12;ushort 16-bit unsigned integral ushort val1=12;uint 32-bit unsigned integral type uint val1=12; unit val2=34U;ulong 64-bit unsigned integral type ulong val1=12; float Single=precision floating point float val = 1.23f;double Double-precision floating point type double val1=1.23; double val2=4.56D;bool Boolean type; a bool value is either true or false bool val1=true;char Character type; a char value is a Unicode character char val1=‘h’;decimal Precise decimal type with 28 significant digits decimal val = 1.23M;
Formatting Numeric DataC or c – Currency formatD or d – doubleM or m – decimalF or f – floatL or l - long 16
17
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 17
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();
}
(Source code: Module02\Module02\01variable.cs)Variable Declarationint num;double salary, balance;string name;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 18
Common Type System (CTS)
Visual Basic.NET
CLS
C#VC++
Common Type System
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
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 19
CLS
C#int i;
string str; double dbl;
VB.NETDim i as IntegerDim str as String
Dim dbl as double
.NET TypeSystem.Int32 i;
System.String str;System.Double dbl;
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
20
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 20
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();
}
(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.
21
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 21
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 ResultConsole.WriteLine("Area of circle = " + Area.ToString());Console.ReadLine();
}
Comment
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).
22
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 22
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();
}
Input window
Output window
(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.
23
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 23
Operators
Operator Language Element
Arithmetic +, –, *, /, %
Unary ++ , --
Assignment =, +=, -=, *=, /=
Comparison ==, !=, <, >, <=, >=
Concatenation +
Logical operations &&, ||
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.
24
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 24
The if...else Structure
if (expression)statement;
if (expression)statement1;
elsestatement2;
if (expression)statement1;
else if (expression)statement2;
elsestatement3;
if (expression){
statement1;if (expression)
statement2;}else
statement3;
If-else is a decision making statement. Returns true if the condition is true or returns false in else part.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 25
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();
}
26
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 26
The multiple if Structure Examplestatic 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);
}
(Source code: Module02\Module02\04if.cs)
27
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 27
The switch statement
switch (expression){
case value:statements;break;
case value:statements;break;
default:statements;break;
}
To choose one option among the multiple choices switch-case statement is used.
28
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 28
The switch statement Examplestatic void Main(string[] args){
int month = 1;switch (month){
case 11:case 12:case 1:case 2:
Console.WriteLine("Winter Season");break;
case 3:case 4:case 5:case 6:
Console.WriteLine("Summer season");break;
case 7:case 8:case 9:case 10:
Console.WriteLine("Monsoonseason");
break;default:
Console.WriteLine(“Invalid month);
} }
(Source code: Module02\Module02\06switch.cs)
29
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 29
while loop
static void Main(string[ ] args){
int num = 1;while (num <= 5){
Console.WriteLine("Number = " + num.ToString());num++;
}Console.ReadLine();
}
while (condition) {statements;increment / decrement
statement}
(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.
30
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 30
do…while Example
static void Main(string[ ] args){
int num = 0;do{
Console.WriteLine("Number = " + num.ToString());num+=2;
} while(num<=10);Console.ReadLine();
}
do{
statements;increment / decrement statement
} while (condition);
(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.
31
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 31
for (initialize; condition; increment/decrement){
statements;}
For Loop
static void Main(string[ ] args){
for (int number = 101; number <= 105; number++){
Console.WriteLine("Number = " + number);}Console.ReadLine();
}
(Source code: Module02\Module02\09for.cs)
For loop is used for fixed iteration.
32
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 32
Array
• Array is a group of elements having same name, same data type and different index.
stack
heap
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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 33
Array (continued…)
• int [ ] numbers = new int[5];Or
int [ ] numbers = new int [ ] {10,20,30,40,50};
Orint [ ] numbers ={1,2,3,4,5};
1-D Array
ReferenceArray Object
10 20 30 40 50
Syntax:-Datatype [ ] arrayname = new Datatype [size];
343434
As every string itself is an object, array of strings is nothing but array of references to string objects.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 34
Memory Map of array (contd…)
String [ ] zones = { "East", "West", "North", "South“ } ;
1-D Array
North
ReferenceArray Object
East South West
35
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 35
Array class and methods
Method Explaination Syntax ExampleReverse() Revereses the
order of array elements.
Array.Reverse(array); int [] numbers =new int{24,12,3,43,43};Array.Reverse(numbers);
Sort() Sorts array in ascending order.
Array.Sort(array); Array.Sort(numbers);
Clear() Sets the range of elements in the array to zero, or to false, or to Nothing depending on the type of array
Clear(Arrayname,int,int) Array.Clear(numbers,0,5);
Array class is the base class for all the arrays in CLR.
(Source code: Module02\Module02\10Array.cs)
36
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 36
Multidimensional Array
int[,] number = new int[3,3];number [0,0]= 10;number[0,1] = 20;Orint[,] num = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
2-D Array
ReferenceArray Object
1 2 3 4 5 6
SyntaxDatatype [,] arrayname = new Datatype [rows, columns];
(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.
37
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 37
Module 3: Classes and Objects
• OverviewClasses and ObjectsFields and MethodsAccess ControlThe “this” referenceConstructorsOverloadingPropertiesStatic Methods and Fields
38
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 38
Classes and Objects
• ObjectAn 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.
• ClassA 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 39
Classes and Objects Continued…
Object Class Attributes Behaviourcar Vehicle Wheels, Engine,
HeadlightsSpeed(),
john (Emp) Employee Empid, Empname, Salary
CalcBonus()
bankAccoutntObj BankAccount Accno, Accname, Balance
Deposit(),Withdraw()
smith Student Name,Address,Semester
Get Result()
coffee Product ProductId, Productname, Quanity, Price
CalcTotalPrice()
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
40
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 40
Classes and Objects
Rectangle Class
CalcPerimeter()CalcArea()
length=5 width=8
41
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 41
Creating a Rectangle Classclass 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 InstantiationRectangle rectangleObject = new Rectangle();Console.WriteLine(“Area={0}”,rectangleObject.CalcArea().ToString());Console.WriteLine(“Perimeter={0}”,rectangleObject.CalcPerimeter().ToString()); Console.ReadLine();
}
(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 Rectangle’s object. Using this reference the CalcArea() and CalcPerimeter() method is invoked through which the data is set.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 42
Properties • In the previous example the values are assigned in the class
itself. • What if one wants to get input from the user?
It’s 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.
(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
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 43
Properties (continued…)
//propertyprivate float length;public float Length {
get { return length; }set { length = value; }
}private float breadth;public float Breadth {…}
Private field
Private field
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();}
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
44
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 44
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;//constructorpublic Rectangle() {
length = 0;breadth = 0;
}}
static void Main(string[] args){
Rectangle rectangleObject1 = new Rectangle();…;} Instance creation
Constructor invoked
Constructorsis 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.
45
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 45
Constructor Overloading
class RectangleVersion2{float length;float breadth;
//constructorpublic 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();
}
(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.
46
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 46
The “this” Reference
public RectangleVersion2(){
this.length = 0;this.breadth = 0;
}
(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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 47
Module 4: Class Library
• Overview Overview of Class LibraryCreate 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 48
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 .dllwhich needs to be referenced from the executables.
.dll
UI Application
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 49
Create Class Library
1. Start Microsoft Visual studio 2010 New Project.2. From the project types select Class Library. 3. Name it as HRSystem.
49
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 50
Create Class Librarypublic class Employee {private int empId;private string empName;private double salary;
public Employee() {… }public Employee(int id,string Name, double sal)
{this.empId = id;this.empName = Name;this.salary = sal;}
//properties....
public double CalcBonus(double percentage){
return salary * percentage;}
}
50
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 51
Creating Class Library continued…
• Build EmployeeLibrary. • It will generate .DLL file.
Menu options for building project:1. Click on Build Menu -> Build EmployeeLibrary.
51
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 52
Create a Test Application
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
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 53
Adding reference of dll to Application
Menu options:1.Click on Project -> Add reference .2.From the dialogue box select projects tab -> select EmployeeLibrary.dll. (It the dlland application is in the same solution otherwise click on browse tab and select the required dll from the path).
53
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 54
Creating a Test Applicationusing 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();
}}
(Source code : C:\Training\Module04\EmployeeLibrary\ABCCorporation\Program.cs)
54
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 55
Set startup project
55
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 56
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.
56
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 57
Static fieldpublic 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 58
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
59
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 59
Module 5. Inheritance
• OverviewObject Oriented ConceptsBank Case StudyInheritanceConstructor in extended classesOverriding methodsPolymorphismUse of Sealed keywordAbstract class and methodDeclaring InterfaceImplementing Interface
60
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 60
Object Oriented Concepts
• Abstraction• Encapsulation• Inheritance• Polymorphism
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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 61
Bank Application
• Create a class library project.• Save it as BankLibrary.• It will provide Business Logic of Banking Services.
61
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 62
A BankAccount Class – the Super Classpublic 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) {….. ; }
}
(Source code: C:\Training\Module05\BankLibrary\BankLibrary\BankAccount.cs)
62
63
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 OOP. It provides following features:
•Reusability •Easy maintenance of code.•Extendibility
InheritanceInheritance 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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 64
Access Specifiers
Visibility / Access Specifier
private protected internal public protected internal
Same class Yes Yes Yes Yes YesDerived class in same assembly No Yes Yes Yes Yes
Other class No No Yes Yes Yes
Other class in other assembly No No No Yes No
Derived class in other assembly No No No Yes No
65
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 65
The SavingsAccount Class – the Sub Classpublic class SavingsAccount : BankAccount {
….;static SavingsAccount() {
…. ; }
public SavingsAccount(string AccName,double Balance,bool IsSalaryAccount) :base(AccName,Balance) { ….. ; }
public double CalculateInterest() { …. ; }}
Using Derived class objectstatic void Main(string[ ] args) {
SavingsAccount savingobject = new SavingsAccount();…. ;}
(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 SavingsAccountclass, 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.
66
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 66
Calling parent class constructor class BankAccount {
public BankAccount(float balance) {…. ;
}}class SavingsAccount : BankAccount {
public SavingsAccount(float balance, bool IsSalaryAccount) : base(balance) { .. }}
Object
BankAccount
SavingsAccount
(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
67
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 67
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 argumentssame 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.
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.
68
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 68
Overriding Methods continued…class BankAccount {
public virtual void Withdraw(float amount) { …. ; }}
class SavingsAccount : BankAccount {public override void Withdraw(float amount) { ….. ; }public override ToString() { …. ; }
}
(Source code: Module04\Inheritance\BankAccount.cs)(Source code: Module04\Inheritance\SavingAccount.cs)(Source code: Module04\Inheritance\Program.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 69
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.
70
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 70
Polymorphismclass 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);}
71
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 71
Preventing Overriding
class BankAccount {public virtual void Withdraw(float amount){ …. ; }
}
class SavingsAccount : BankAccount {public sealed override void Withdraw(float amount){
….. ; }}
(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.
72
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 72
Preventing Inheritance
sealed class SavingsAccount : BankAccount{}
class SubSaving : SavingsAccount // compile time error{}
Sealed classes are primarily used to prevent the inheritance. A sealed class can not be a base class. But it can be instantiated.
73
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 73
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.
public abstract class BankAccount{
public abstract void Withdraw(float amount);}
Abstract class
Abstract method
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.
74
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 74
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);}
class SavingAccount : BankAccount, Iinterest {public float CaclulateInterest(float irate) {
…. ; }
}
Method signature
Interface implementation
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.
75
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 75
Module 6. Exceptions Handling
• OverviewWhat is Exception Handling?The “try-catch” StructureThe finally ClauseThe throw CauseUser Defined Exception
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 76
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 77
try-catch-finally
• C# provides 3 keywords to handle an Exception.try :- The try keyword is required. It lets the compiler know that youare 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 ; }
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
78
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 78
Understanding Exceptionsstatic void Main(string[ ] args)
{int num1, num2, ans;num1 = 10;num2 = 0;ans = num1 / num2;Console.WriteLine("Answer = " + ans);Console.ReadLine();
}
Exception occurs here
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
79
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 79
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);
}}
(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.
80
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 80
Multiple Catch Blockint 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 { }
(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.ExceptionSystem.DevideByZeroExceptionSystem.NullReferenceExceptionSyste.InvalidCastExceptionSystem.IndexOutOfRangeExceptionetc.
81
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 81
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”);}
Finally can be used in such cases where it’s needed to free-up the resources always. Finally block is optional.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 82
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();}
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
83
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 83
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.
84
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 84
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;
elsethrow new
BalanceException("Not enough balance");
}}
static void Main(){
SavingsAccount saving = new SavingsAccount();
try{
saving.Withdraw(3000);}catch (BalanceException ex){Console.WriteLine(ex.Message);
}}
User defined exception class
throw exception
(Source code: Module05\ExceptionHandling\ExceptionHandling\BalanceException.cs)
85
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 85
Module 7. Other C# Features
• OverviewStructureenumType castingBoxingUnboxingref and out parameterOperator overloadingPartial classStatic class
86
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 86
Structure
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);}
•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.
(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 declarationA structure can have instance constructors only if they take parametersA structure can have property or methodStructure procedures cannot handle events A structure is not inheritableA 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
87
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 87
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);
}}
(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}
88
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 88
Type Casting
• Converting value type to another value typeOR
• 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();
}
(Source code: Module06\Module06\TypecastingExample.cs)
89
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 89
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 typeobject obj = i; //boxingint j = (int)obj; //unboxingConsole.WriteLine(i.ToString());Console.WriteLine(obj.ToString());Console.WriteLine(j.ToString());Console.ReadLine();
}
Value types are stored on the stack memory and Reference types are stored on the Heap memory.
90
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 90
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();
}}
(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.
91
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 91
Out Parameterclass 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();
}}
(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.
92
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 92
Operator Overloadingclass 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; }}
(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 ){}
93
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 93
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;
}}
}
(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+=, -=, *=, /=
94
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 94
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();
}
(Source code: Module06\Module06\OperatorOverloadingExample.cs)
95
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 95
Partial Typepartial 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();
}}
(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.
96
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 96
Static classstatic class Temperature {
public static double CelsiusToFahrenheit(double celsius) {
//convert celsius to fahrenheitdouble 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(); }}
(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.
97
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 97
Auto - Implemented Property
class Person {public string Name{
get;set;
}public int Age{
get;set;
}}
(Source code: Module06\Module06\ObjectInitializerExample.cs)
Auto implemented PropertyAuto-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.
98
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 98
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();
}}
(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.
99
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 99
Module 8. String, StringBuilder, Dateformat
• OverviewUseful method of string class.StringBuilder class.Dateformats.Output formats.
100
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 100
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
(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
101
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 101
String class methods (Contd…)
• Comparing StringsThe 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); //-1s = "welcome";s1 = "welcome";i = string.Compare(s, s1);Console.WriteLine(i); //0s = "Welcome";s1 = "welcome";i = string.Compare(s, s1);Console.WriteLine(i); //+1
(Source code: Module07\StringExample\StringExample\Program.cs)
102
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 102
String class methods (Contd…)
• Concatthe concat method concatenate two strings and returns a new stringstring s = "Hello";string s1 = "World";Console.WriteLine(string.Concat(s, s1)); //HelloWorid
• CopyCreates a new instance of string with the same value as a specified stringstring s = "Hello";string s1;s1 = string.Copy(s);Console.WriteLine(s1);
(Source code: Module07\StringExample\StringExample\Program.cs)
103
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 103
String class methods (Contd…)
• Ends withDetermines 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
• EqualsDetermines 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
(Source code: Module07\StringExample\StringExample\Program.cs)
104
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 104
String class methods (Contd…)
• IndexOfReturn the index of the given String parameter in a Searched String.string s= "Welcome";int i = s.IndexOf ("e"); //1Console.WriteLine(i);i = s.IndexOf ("e", 2); //6Console.WriteLine(i);
• LastIndexOfReturns the index position of the last occurrence of a specified String within the Searched String.string s= "Welcome";int i = s.LastIndexOf ("e"); //6Console.WriteLine(i);
(Source code: Module07\StringExample\StringExample\Program.cs)
105
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 105
String class methods (Contd…)
• PadLeftRight-aligns the String, padding on the left with spaces or a specified character for a specified total length.
• PadRightLeft-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, '*')); //***WelcomeConsole.WriteLine(s.PadRight(10, '*')); //Welcome***
(Source code: Module07\StringExample\StringExample\Program.cs)
106
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 106
String class methods (Contd…)
• RemoveRemove the characters from specified position in a given String.string s= "Welcome";Console.WriteLine(s.Remove(3, 4)) ; // Wel
• ReplaceReplaces all occurrences of a specified character or String, with another specified character or string.string s = "Welcome";
Console.WriteLine (s.Replace ("e", "a")); // Walcoma
(Source code: Module07\StringExample\StringExample\Program.cs)
107
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 107
String class methods (Contd…)
• StartWithDetermines 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
• SubstringReturns part of a string string s = "Welcome";Console.WriteLine(s.Substring(3)); // comeConsole.WriteLine(s.Substring(3, 3)); // com
(Source code: Module07\StringExample\StringExample\Program.cs)
108
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 108
String class methods (Contd…)
• ToLowerReturns a String in lowercase
• ToUpperReturns a copy of the String in uppercase.string s= "WELCOME";Console.WriteLine (s.ToLower()); // welcomestring s1 = "welcome";Console.WriteLine (s1.ToUpper()); //WELCOME
• ToStringConverts the value to a String type.
(Source code: Module07\StringExample\StringExample\Program.cs)
109
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 109
String class methods (Contd…)
• TrimRemoves all occurrences of a set of specified character from thebeginning and end of the String.
• TrimEndRemoves all occurrences of a set of specified character from the end of the String.
• TrimStartRemoves all occurrences of a set of specified character from thebeginning of the String.
String s= "-----------WELCOME-----------";Console.WriteLine (s);Console.WriteLine (s.Trim('-')); //WELCOMEConsole.WriteLine (s.TrimEnd('-')); //-----------WELCOMEConsole.WriteLine (s.TrimStart('-')); //WELCOME----------
(Source code: Module07\StringExample\StringExample\Program.cs)
110
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 110
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();
}
(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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 111
Date formats
Specifier Description Output
d Short Date 8/4/2012
D Long Date 8-Apr-12
t Short Time 21:08
T Long Time 21:08:59
f Full date and time 4/8/2012 21:08
F Full date and time (long) 4/8/2012 21:08
g Default date and time 8/4/2012 21:08
G Default date and time (long) 8/4/2012 21:08
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 112
Date formats continued…
Specifier Description Output
M Day / Month 8-Apr
r RFC1123 date Sun, 08 Apr 2012 21:08:59 GMT
s Sortable date/time 2012-04-08T21:08:59
u Universal time, local timezone 2012-04-08 21:08:59Z
Y Month / Year Apr-12
dd Day 8
ddd Short Day Name Sun
dddd Full Day Name Sunday
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 113
Date formats continued…
Specifier Description Output
hh 2 digit hour 9
HH 2 digit hour (24 hour) 21
mm 2 digit minute 8
MM Month 4
MMM Short Month name Apr
MMMM Month name April
ss seconds 59
tt AM/PM PM
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 114
Date formats continued…
Specifier Description Output
yy 2 digit year 7
yyyy 4 digit year 2012
: seperator, e.g. {0:hh:mm:ss} 9:08:59
/ seperator, e.g. {0:dd/MM/yyyy} 8/4/2012
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 115
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 116
Output formats
Character Description Examples OutputC or c Currency Console.Write("{0:C}", 2.5); $2.50
Console.Write("{0:C}", -2.5); ($2.50)D or d Decimal Console.Write("{0:D5}", 25); 25E or e Scientific Console.Write("{0:E}", 250000); 2.50E+05F or f Fixed-point Console.Write("{0:F2}", 25); 25
Console.Write("{0:F0}", 25); 25
G or g General Console.Write("{0:G}", 2.5); 2.5N or n Number Console.Write("{0:N}", 2500000); 2,500,000.00
X or x Hexadecimal Console.Write("{0:X}", 250); FA
Console.Write("{0:X}", 0xffff); FFFF
116
117
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 117
Module 9. Collections
• OverviewSystem.Collections Namespace.ArrayListHashTableCollection Initializer
118
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 118
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 119
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;
120
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 120
ArrayList ExampleUsing 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());
}
//reversecountryList.Reverse();//sort countryList.Sort();
//RemoveAt()countryList.RemoveAt(2);//Clear()countryList.Clear();
}
(Source code: Module07\CollectionExample\CollectionExample\ArrayListExample.cs)ArrayList is the collection of elements of different typeElements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 121
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
122
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 122
HashTable Examplestatic 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 keyConsole.WriteLine("For key = rtf, value
= {0}.", hashlist["rtf"]);Console.ReadLine();
}
(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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 123
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
012345
124
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 124
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 125
Queue
• Queue represents first-in-first-out (FIFO) .• We can Enqueue (add) items in queue.• We can Dequeue (remove) items from queue.
126
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 126
Queue Classstatic 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();
}
(Source code: Module07\CollectionExample\CollectionExample\QueueExample.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 127
Linked List
• A Linked list is a data structure consisting of group nodes which together represents a sequence.
128
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 128
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();
}
(Source code: Module07\CollectionExample\CollectionExample\CollectionInitializerExample.cs)
129
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 129
Module 10. Generics and Nullable Types
• OverviewLimitations of Collection ClassesUnderstanding GenericsAdvantages of generics over collectionNullable Types
130
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 130
Limitation of Collection Classesclass Person {
string name, address;public Person(string name, string address) {
this.name = name; this.address = address; }
public void Display(){Console.WriteLine ("Name = " + name);Console.WriteLine("Address = " + address);
} }static void Main(string[] args) {
ArrayList list = new ArrayList();list.Add(new Person("Bhavana", "Mumbai"));list.Add(new Person("Vishal", "Mumbai"));list.Add("Krishna");
for (int i = 0; i < list.Count; i++) {list[i]. //error 1
//error 2((Person)list[i]).Display();
}
//error 3int temp =int.Parse( list[0].ToString()); }
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 1We 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 2You 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 3At 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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 131
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 132
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.
Comparison between Generic, Collection and Array
•To define an array, we have to give the fix size. The size can’t 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
133
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 133
Generics List<T> Collectionstatic 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 134
Generic Dictionary<key,value> collectionclass 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);}
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
135
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 135
Creating our own Generic Classesclass 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();
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.
136
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 136
Nullable Typestatic 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();
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.
137
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 137
Module 11. Windows Form - I
• OverviewIntroduction to Window Forms IDECreating forms with controlsResponding to form eventsUsing basic controls (e.g. Label, TextBox, Button, etc.)Anchor and Dock Properties
138
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 138
Visual Studio IDE
ToolBox Form Design View Solution Explorer Property Window
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.
139
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 139
Introduction to Controls
Label TextBox MultiLineTextBox
ListBox CheckBox
RadioButton Button GroupBoxComboBox
Form is a base unit on which we can place the controls. Every controls including Form will have properties, methods and events.
Forms propertiesText – Value to be display in the title barWindowState – Initial visual state of a form
140
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 140
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();
}
(Source code: Module10\WinForm1\WinForm1\DynamicTime.cs)
LabelProperties
Name – lbldatetimeText – empty
Timer control from the component tabProperties
Enable – TrueInterval – 1000
141
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 141
MessageBox Class
• Use to display informative message to the user and can take user confirmation.
• MessageBox.Show("Welcome to GUI Application");
(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.
142
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 142
Login Form Example
public partial class LoginForm : Form {int count = 0;public LoginForm() {
InitializeComponent();}
private void btncancel_Click(object sender, EventArgs e) {this.Close();
}
(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.
LabelDisplay static text from providing information.
PropertiesName - Control NameText – Value to be displayedAutoSize – Allow automatic resizing according to the txt length
143
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 143
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();
}}
(Source code: Module10\WinForm1\WinForm1\LoginForm.cs)
TextBoxDisplay text to the user and accept the input from the user.
PropertiesName – Control NameText – Display or accept the textMultiline – convert single line textbox into multi line textboxPasswordChar – set a character that acts as a placeholder for the characters.
ButtonPerform an action
PropertiesName - Control nameText – Value to be displayedAutoSize – Controls automatically size itself to fit its content.Image – Image to be displayed
144
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 144
Welcome Form
private void btnclose_Click(object sender, EventArgs e){
Application.Exit();}
(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.
145
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 145
ComboBox Example
(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.
ComboBoxDisplay a drop down list of items, from which user can select any one item.
PropertiesName – Control nameText – Selected text from the listItems – Collection of the items to be displayed in drop downDropdownStyle – 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.
146
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 146
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");
}}
(Source code: Module10\WinForm1\WinForm1\ComboBoxExample.cs)
147
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 147
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();}
(Source code: Module10\WinForm1\WinForm1\ComboBoxExample.cs)
148
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 148
ListBox Example
(Source code: Module10\WinForm1\WinForm1\ListBoxExample.cs)
ListBoxDisplay a list of items, from which user can select one or more items
PropertiesName – Control nameItems – Collection of the items to be displayed in list boxSelectionMode – 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.
149
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 149
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;
}
(Source code: Module10\WinForm1\WinForm1\ListBoxExample.cs)
150
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 150
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);
}
(Source code: Module10\WinForm1\WinForm1\ListBoxExample.cs)
151
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 151
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;
}
(Source code: Module10\WinForm1\WinForm1\ListBoxExample.cs)
152
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 152
RadioButton Example
(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.
GroupBoxThe 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.
PropertiesName – Control NameText – Get or Set the Caption Value.
153
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 153
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="";}
(Source code: Module10\WinForm1\WinForm1\RadioButtonExample.cs)
Panelcontains other controls.PropertiesName Control NameAutoScroll – 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
RadioButtonFrom a given choice user can select any one option.
Name – Control NameText – Get or Set the text associated with the control.Checked – Gets or Sets a value indicating whether the control is checked.
154
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 154
CheckBox Example
(Source code: Module10\WinForm1\WinForm1\CheckBoxExample.cs)
CheckBoxFrom a given choice user can select one, multiple, all or none.
PropertiesName – Control NameText – Get or set the text associated with the controlChecked – Indicates whether the check box is checked or unchecked
155
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 155
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(); }
(Source code: Module10\WinForm1\WinForm1\CheckBoxExample.cs)
156
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 156
MessageBox Exampleprivate 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();}
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
OKOKCancelAbortRetryIgnoreYesNoCancelYesNoRetryCancel
Integer values of the individual memberOk 1Cancel 2Abort 3Retry 4Ignore 5Yes 6No 7
MessageBoxIcon enumerationQuestionStopExclamationWarning
157
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 157
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.
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.
158
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 158
Dock Property
• Align control to the edges of the form by setting the Dock property.
Top
Bottom
FillLeft Right
Control Location of the dock property
Setting Effects
DockStyle.Top Dock to the top of the form
DockStyle.Bottom Dock to the bottom of the form
DockStyle.Left 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
159
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 159
Module 12. File I/O
• OverviewSystem.IO NamespaceThe Directory and File ClassesThe FileStream ClassReading and Writing to File using StreamReader and StreamWriter.
160
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 160
Input and Output
• Input means reading• Output means writing
Standard input – keyboard and mouseStandard 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 161
File IO
File
File Stream
Stream Reader/ Stream Writer
Binary Reader/ Binary Writer
Stream
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
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 162
File IO classes
Stream
Stream Reader
Text Reader Text Writer
Stream Writer
File Stream
Binary Reader
Binary Writer
Network Stream
Base class in File IO operations is Stream class which is present in System.IOnamespace. File IO provides various stream classes such as StreamWriter, StreamWriter, File Stream, BinaryReader, BinaryWriter, NetworkStream etc…
162
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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 163
The Directory Class
•Method of the Directory class
Remove the directory and its contents.Directory.Delete(“c:\\examples”)
Delete
Checked whether the directory exist at the specified location if exists return true else false.Messagebox.show(Directory.Exists(“c:\\examples”))
Exists
Create a directory at a specified path locationDirectory.CreateDirectory(“c:\\examples”)
CreateDirecotryUseMethod
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 164
The Directory Class (Contd…)
Returns the names of all sub directory available under specified pathAdd textbox and buttonOn 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”);}
GetDirectories
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 165
The Directory Class (Contd…)
Returns the names of all files available under specified pathint i;String[ ] file; file = Directory.GetFiles("c:\\")For (i=0;i<file.Length;i++) {
TextBox1.AppendText(file[i] + “\n”);}
GetFiles
Returns the parent directory of the specified pathDirectoryInfo di;di = Directory.GetParent("c:\\examples")MessageBox.Show(di.ToString())
GetParent
Return the root information about the specified pathDirectory. GetDirectoryRoot(Messagebox.show(“c:\\examples”) )
GetDirectoryRoot
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 166
The Directory Class (Contd…)
Retruns the name of the logical drives of the computerInt I;String[ ] drive;drive = Directory.GetLogicalDrives();for (i=0;i<drive.length;i++) {
TextBox1.AppendText(drive[i] + “\n”);}
getLogicalDrives
Move a file or a directory to a new locationDirectory.move(“c:\\sample\data”, c:\\examples\data”)
Move
167
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 167
FileStream Class
• This class provides access to standard input and output files.
• FileStream fs = new FileStream(“path”, FileMode);
This class provides access to standard input and output files. We use the members of FileModeenumerations 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 ModesAppend - 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 fileTruncate - 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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 168
StreamReader and StreamWriter Class
168
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 169
Save Button Codeusing 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();
}
169
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 170
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();
}
170
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 171
Write and Read using same stream
• Write&Read button click eventFileStream 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();
171
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 172
Binary Reading and Writing
Binary is basically used to read primitive data.
172
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 173
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();
173
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 174
Split method
• Use as a string tokenize
string str = textBox1.Text;int count =str.Split(new char[] {' '}).Length ;MessageBox.Show(count.ToString());
175
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 175
Input Form
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.
176
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 176
Input Form Codeprivate 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;
elsetxttel.Enabled = false;
}private void chkmobile_CheckedChanged(object sender, EventArgs e) {
if (chkmobile.Checked == true)txtmobile.Enabled = true;
elsetxtmobile.Enabled = false;
}
177
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 177
Input Form Code (Contd…)
private void btnsave_Click(object sender, EventArgs e) {
string tel = null, mobile = null, gender = null, status = null, qualification = null, message = null;
string name = txtuname.Text;string pwd = txtpwd.Text;string address = txtaddress.Text;int itemno = cmbcountry.SelectedIndex;string country =
cmbcountry.Items[itemno].ToString();if (txttel.Text != "")
tel = txttel.Text;else
tel = "No Telephone";if (txtmobile.Text != "")
mobile = txtmobile.Text;else
mobile = "No Mobile";
if (rdbmale.Checked == true)gender = "Male";
if (rdbfemale.Checked == true)gender = "Female";
if (rdbsingle.Checked == true)status = "Single";
if (rdbmarried.Checked == true)status = "Married";
for (int i = 0; i <= lstqualification.Items.Count - 1; i++) {
if (lstqualification.GetSelected(i) == true) {
qualification += lstqualification.Items[i];qualification += " “;}
}
178
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 178
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;
179
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 179
Input Form Code (Contd…)
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();
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; }
180
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 180
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);}
}
(Source code: Module11\FileIO\FileIO\Registration.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 181
Module 13. Working with Databases
• OverviewIntroduction to Ado.NetAdo.Net disconnected modelAdo.Net connected ModelData ProvidersDisconnected Database ConnectivityConfiguring Connection String in Config fileConnected Database ConnectivityFilterInsert data using connected architectureCommand BuilderData NavigationMaster – Detail RelationshipStored Procedure
181
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 182
Overview (Contd…)
TransactionData RelationSQL Bulk CopyBatch UpdateMultiple Active Result SetReading and writing data to XMLData Independent Provider
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 183
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
183
184
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 184
ADO.NET Disconnected Model
Connection
Data Adapter
Client Application
Database
DataSet Select Command
Insert Command
Update Command
Delete Command
Provider
DataSet
XML
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 DataAdapterclass.
These methods internally maintain connection object.
185
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 185
ADO.NET Connected Model
Connection
Command
Data Reader
Client Application Database
Provider
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 commandExecuteNonQuery()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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 186
Date Providers (NameSpaces)
• System.Data• System.Data.OleDb• System.Data.SqlClient• System.Data.OracleClient• System.Data.Common
•System.DataDataSet, DataTable, DataColumn, DataRow, DataRelation, DataView etc.
•System.Data.OleDbCan be used with all the databases like Ms Access, Ms SQL Server,
Oracle, Sybase, DB2 etc.
•System.Data.SqlClientUsed only with Ms SQL Server 7.0 and above versionWill 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.OracleClientUsed only with Oracle databaseSupport the Data Type of Oracle Database like CLOB, BLOB, BFILE etc.
•System.Data.CommonIt 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
187
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 187
Disconnected Database Connectivity with Different Databases
188
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 188
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 Eventtry {
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);}
Disconnected connectivity with MS Access Add the following namespace in the programusing System.Data.OleDb;Write code for Ms Access Button Click Eventtry {
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 AccessAdd the following namespace in the programusing System.Data.OracleClient;Write code for Oracle button Click Eventtry {
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);}
189
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 189
Configuring Connection String in .config File• To add the App.config file in your project click menu
Project -> Add New ItemFrom 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.
•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.
190
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 190
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 191
Using Connection String in C# file
using System.Data.SqlClient;using System.Configuration;
string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString;SqlConnection conn = new SqlConnection(connstr);
191
192
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 192
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;
(Source code: Module12\DatabaseApplication\DatabaseApplication\02Connected.cs)
193
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 193
Apply Filter on DataSet
(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 methods1] Select() method of the DataTable class and 2] DataView class object with RowFilter Property
194
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 194
Apply Filter on DataSet (Contd…)
• Declare the 2 class level variableint catid = 0;DataSet ds;• Form Load Eventstring 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"];
(Source code: Module12\DatabaseApplication\DatabaseApplication\03Filter.cs)
195
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 195
Apply Filter on DataSet (Contd…)
• ListBox SelectedIndexChanged Eventif (lstcategory.SelectedIndex >0 && lstcategory.SelectedValue != null) {
catid = (int) lstcategory.SelectedValue ;}• View Button Click EventDataView view = ds.Tables["Products"].DefaultView;view.RowFilter="categoryid=" + catid;dataGridView1.DataSource = view;
196
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 196
Apply Filter on DataSet – DataTable Select() Method
• select button click eventlstselect.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"]);
}}
(Source code: Module12\DatabaseApplication\DatabaseApplication\03Filter.cs)
197
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 197
Insert data using Connected Architecture
198
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 198
Insert data using Connected Architecture Codestring 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;
199
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 199
Stored Procedure
(Source code: Module12\DatabaseApplication\DatabaseApplication\08spin.cs)
200
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 200
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 Clickstring connstr =
ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString;SqlConnection conn = new SqlConnection(connstr);
(Source code: Module12\DatabaseApplication\DatabaseApplication\08spin.cs)
201
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 201
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;
(Source code: Module12\DatabaseApplication\DatabaseApplication\08spin.cs)
202
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 202
CommandBuilder for Update Data in Disconnected Architecture
(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.
203
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 203
Code for update data using CommandBuilder
• Declare Class level membersSqlConnection 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;
(Source code: Module12\DatabaseApplication\DatabaseApplication\05CommandBuilder.cs)
204
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 204
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);
}
(Source code: Module12\DatabaseApplication\DatabaseApplication\05CommandBuilder.cs)
205
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 205
Data Navigation
(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)
206
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 206
Data Navigation (Contd…)
• Declare class level memberSqlConnection 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;
}
(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)
207
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 207
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();
(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)
208
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 208
Data Navigation (Contd…)
• First Buttonbm.Position = 0Display()
• Next Buttonbm.Position += 1Display()
• Prior Buttonbm.Position -= 1Display()
• Last Buttonbm.Position = bm.Count - 1Display()
(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)
209
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 209
Data Navigation (Contd…)
• Add Buttontxtpid.Clear();txtpname.Clear();txtup.Clear();flag = 1;btnsave.Enabled = true;
• Edit Buttonpid =int.Parse ( txtpid.Text);flag = 2;btnsave.Enabled = true;
• Delete ButtonDialogResult 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;
}
(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)
210
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 210
Data Navigation (Contd…)
• Save ButtonDataRow 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) { //Editdr = 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();} }
else if (flag == 3) { //Deletedr = ds.Tables["products"].Rows.Find(pid);if (dr != null) {
dr.Delete();}
}
adp.Update(ds, "products");MessageBox.Show("Data modified");ds.Clear();adp.Fill(ds, "products");bm.Position = 0;Display();flag = 0;btnsave.Enabled = false;
(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)
211
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 211
Data Navigation (Contd…)
• Concurrency Checkcatch (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();
}}
}}
}}
(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)
212
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 212
Data Navigation (Contd…)
• Exit ButtonApplication.Exit();
• 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");
elseMessageBox.Show("Record not found", "Display Box");
(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)
213
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 213
Data Navigation (Contd…)
public _06FindProduct() {InitializeComponent();
}public int prodid;private void btnsubmit_Click(object sender, EventArgs e) {
if (txtprodid.Text == "")prodid = 0;
elseprodid = int.Parse (txtprodid.Text);
this.Close();}
(Source code: Module12\DatabaseApplication\DatabaseApplication\06FindProduct.cs)
214
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 214
Master Detail Relationship
(Source code: Module12\DatabaseApplication\DatabaseApplication\07MasterDetail.cs)
215
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 215
Master Detail Relationship (Contd…)
Class level declarationSqlConnection conn;SqlDataAdapter adp;SqlCommandBuilder cb;DataSet ds;BindingManagerBase bm;
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;
}
(Source code: Module12\DatabaseApplication\DatabaseApplication\07MasterDetail.cs)
216
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 216
Master Detail Relationship (Contd…)
Form Load Event
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();
(Source code: Module12\DatabaseApplication\DatabaseApplication\07MasterDetail.cs)
217
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 217
Master Detail Relationship (Contd…)
• First Buttonbm.Position = 0;Display();
• Previous Buttonbm.Position = bm.Position + 1;Display();
• Next Buttonbm.Position = bm.Position + 1;Display();
• Last Buttonbm.Position = bm.Count - 1;Display();
(Source code: Module12\DatabaseApplication\DatabaseApplication\07MasterDetail.cs)
218
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 218
Stored Procedure with Out Parameter
• Write the following stored procedure in the MS SQL Server
create proc TotalProduct (@catid int, @count int output) asselect @count=count(productid) from products where Categoryid = @catid
(Source code: Module12\DatabaseApplication\DatabaseApplication\09spout.cs)
219
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 219
Stored Procedure with Out Parameter (Contd…)
• Form Load event populate the list box
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"];
(Source code: Module12\DatabaseApplication\DatabaseApplication\09spout.cs)
220
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 220
Stored Procedure with Out Parameter (Contd…)
• Type the following code in the ListBoxSelectedIndexChanged event
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();
(Source code: Module12\DatabaseApplication\DatabaseApplication\09spout.cs)
221
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 221
Transaction
int result1, result2;
string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString;
SqlConnection conn = new SqlConnection(connstr);conn.Open();
(Source code: Module12\DatabaseApplication\DatabaseApplication\10Transaction.cs)
222
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 222
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");
}
(Source code: Module12\DatabaseApplication\DatabaseApplication\10Transaction.cs)
223
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 223
DataRelation
(Source code: Module12\DatabaseApplication\DatabaseApplication\11DataRelation.cs)
224
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 224
DataRelation (Contd…)
• Form Load Eventdecimal 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"]);
(Source code: Module12\DatabaseApplication\DatabaseApplication\11DataRelation.cs)
225
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 225
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("-------------------------------------------------");
}
(Source code: Module12\DatabaseApplication\DatabaseApplication\11DataRelation.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 226
Module 14. Data Bound Control
• OverviewPopulating DataGridView Control using WizardPopulating ListBox Control using WizardBinding Navigator
226
227
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 227
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
(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)
228
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 228
Populating DataGridView Control using Wizard (Contd…)
• Click on Add Project Data Source
• Select Database and click Next option
(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)
229
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 229
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.
(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)
230
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 230
Populating DataGridView Control using Wizard (Contd…)
• Save the connection String in Application Configuration file• Click Next Button
(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)
231
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 231
Populating DataGridView Control using Wizard (Contd…)
• Select “Categories” table from the list and click “Finish”button
(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)
232
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 232
Populating DataGridView Control using Wizard (Contd…)
• Display the data in grid
(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)
233
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 233
Populating ListBox Control using Wizard
• Add ListBox from the Common Controls• Click on smart option• Check “Use data bound items”
(Source code: Module 13\DataBoundControl\DataBoundControl\02ListBoxControl.cs)
234
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 234
Populating ListBox using Wizard (Contd…)
• Select Data Source option• Specify Display Member and Value Member options
(Source code: Module 13\DataBoundControl\DataBoundControl\02ListBoxControl.cs)
235
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 235
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();
}
(Source code: Module 13\DataBoundControl\DataBoundControl\02ListBoxControl.cs)
236
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 236
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.
(Source code: Module 13\DataBoundControl\DataBoundControl\02ListBoxControl.cs)
237
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 237
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
(Source code: Module 13\DataBoundControl\DataBoundControl\03Navigator.cs)
238
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 238
Binding Navigator (Contd…)
• Run and Test the Program
(Source code: Module 13\DataBoundControl\DataBoundControl\03Navigator.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 239
Module 15. DotNet Framework & Assembly
• Overview.Net FrameworkAssemblyType of AssemblyCreate Class Library Create Test ApplicationCreating Shared AssemblyViewing the Manifest FileProcess of compiling and executing managed code
239
240
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 240
Assembly
AssemblyManifest
ModuleMetadata
MSIL
Types TypesTypesTypes
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.
241
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 241
Types of Assembly
• Private Assembly• Shared Assembly
Private AssemblyA private assembly is deployed and used exclusively with a single name.A private assembly is referenced by its simple nameThe simple name is defined in the assembly’s metadata.When you refer to private assembly , it get copied into the project which is referring to this assembly.
Shared AssemblyShared assembly is also known as Strong Named AssemblyIt gives support to versioning and security of assemblyStrong named assembly will have unique identificationWhen 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
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 242
Creating Shared Assembly (Contd…)
• Adding the dll file in GAC folder(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
243
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 243
Viewing Manifest File
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 DisassemblerSelect File menuClick OpenSelect exe or dll file for which you want to see IL code
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 244
Module 16. Delegate
• OverviewUnderstanding DelegateSingleCast DelegateMultiCast DelegateAnonymous Method
244
245
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 245
Understanding Delegate
• Declaring and invoking Delegate involves 4 stepsDelegate declarationdelegate returntype Name ([parameters]) Declare Delegate methodReturntype Name ([parameters]) Delegate instantiationdelegatename instancename = new delegatename(methodname)Delegate invocationInstancename(parameters value)
• Use of DelegateEventsThreadsAsynchronous Application
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 methodMulticast delegate can hold and invoke multiple methods.
246
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 246
SingleCast Delegate//Declare Delegatedelegate void DelegateString(string s);delegate int DelegateCube(int number);class _01SingleCastDelegate {
//methodpublic static void Greet(string Name) {
Console.WriteLine("Hello..." + Name);}//methodpublic 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);}
(Source code: Module 15\DelegateExample\DelegateExample\01SingleCastDelegate.cs)
247
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 247
SingleCast Delegate (Contd…)
//methodpublic static int NumberCube(int number) {
return number * number * number;}public static void Main() {
//instantiate delegateDelegateString delegateobj1 = new DelegateString(Greet);DelegateString delegateobj2 = new DelegateString(Wish );//Invoke delegatedelegateobj1("Bhavana");Console.WriteLine("-----------------------------------");delegateobj2("Bhavana");Console.WriteLine("=====================================");DelegateCube delegatecubeobj = new DelegateCube(NumberCube);Console.WriteLine("Cube of Number 3 = " + delegatecubeobj(3));Console.ReadLine();
}}
(Source code: Module 15\DelegateExample\DelegateExample\01SingleCastDelegate.cs)
248
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 248
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);}
(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.
249
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 249
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();
}}
(Source code: Module 15\DelegateExample\DelegateExample\02MultiCastDelegate.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 250
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 251
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(); } }
252
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 252
Anonymous Methoddelegate 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();
}}
(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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 253
Module 17. Threads
• OverviewUnderstanding ThreadsCreating, executing and terminating threadsParametizeThreadStart DelegateThread PrioritiesSynchronization among threads
253
254
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 254
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
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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 255
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
255
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 256
Thread State
Wait/Sleep/Join
Unstarted Running Abort Requested
Stopped
Start
Thread Blocks
Thread Unblocks
Abort
Abort
Thread Ends
Thread Ends
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.
257
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 257
Creating Threadvoid 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 threadt.Start();//print some message to the console windowfor (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");
}
(Source code: Module 16\ThreadApplication\ThreadApplication\01Thread.cs)Methods of Thread
StartStart the ThreadChange the ThreadState to Running modeThreadState specifies the execution states of a Thread
SleepBlock the current Thread for the specified number of milliseconds.
AbortTerminate the Thread
JoinBlock the calling Thread until a thread terminates or complete the task.
258
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 258
Creating Thread (Contd…)
static void Main(string[ ] args) {_01Thread obj = new _01Thread();obj.RunThread();Console.ReadLine();
}
(Source code: Module 16\ThreadApplication\ThreadApplication\01Thread.cs)
259
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 259
ParameterizedThreadStart Delegatevoid 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();
}
260
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 260
ParameterizedThreadStart Delegate (Contd…)
static void Main(string[ ] args){
_02ThreadParameter obj = new _02ThreadParameter();obj.RunparametizedThread();Console.WriteLine("Thread Program over");Console.ReadLine();
}
(Source code: Module 16\ThreadApplication\ThreadApplication\02ThreadParameter.cs)
261
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 261
Thread Priority
• ThreadPriority EnumerationAbove NormalBelow NormalHighestLowestNormal
• Default priority for all thread is Normal
Threads are scheduled for execution based on their priority. It determines the order of thread execution. It can be very with each Operating System.
262
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 262
Thread Priority (Contd…)
public long count;
public void StartCount() {while (true) {
count += 1;}
}
(Source code: Module 16\ThreadApplication\ThreadApplication\03Priority.cs)
263
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 263
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();
}
(Source code: Module 16\ThreadApplication\ThreadApplication\03Priority.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 264
Creating Multiple Thread
• In this process the last recorded transaction updates the balance.
Teller1Teller2
File cabinets
264
265
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 265
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;
}
(Source code: Module 16\ThreadApplication\ThreadApplication\04SavingMultiThread.cs)
266
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 266
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("==================================");
}
(Source code: Module 16\ThreadApplication\ThreadApplication\04SavingMultiThread.cs)
267
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 267
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();
}
(Source code: Module 16\ThreadApplication\ThreadApplication\04SavingMultiThread.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 268
Thread Synchronization
• This type of locking tells when to use that filing cabinet and when not to.
Teller2
Wait until I am Finished !!!
Teller1
File cabinets
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 namespaceSystem.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
269
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 269
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.
Object lockBalance = 5000
Sub Deposit (byval amt as Decimal) A synchronized transaction
Thread@1 Thread@2 Thread@3
270
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 270
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);
}
(Source code: Module 16\ThreadApplication\ThreadApplication\05SavingSynchronizee.cs)
271
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 271
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();
}
(Source code: Module 16\ThreadApplication\ThreadApplication\05SavingSynchronizee.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 272
Thread pool
• Collection of threads• Performs a number of tasks in background process.• Primary thread leaves free to perform other tasks
asynchronously.
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
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 273
Module 18. Introduction to Web Services
• OverviewOverview of Web ServicesCreating and Testing Web ServiceConsuming Web Service
273
274
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 274
Definition
• XML Web Service is a programmable logic accessible by standard web protocols
Allow applications to send and receive information across the internetLanguage and Platform independent
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 ServiceAuthentication ServicesWeather ReportsExchange RateStock QuotesEtc.
275
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 275
Components of Web Services
Client Application Web Service
UDDI Registry
Locate a Web Service
WSDL Document
Describes
Communication through SOAP messages
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)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 276
Creating Web Services
• Select File – New – Web Site
276
277
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 277
Code for Web Services
public class ServiceHello : System.Web.Services.WebService{
[WebMethod]public string HelloWorld() {
return "Hello World";}
}
(Source code: Module 18\WebServiceHello\App_Code\ServiceHello.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 278
Test Web Services
278
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 279
Consuming Web Services
• Start Windows Application
279
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 280
Add Web Service Reference
• Click on Project Menu – Add Web Reference• Click “Web Service on the local machine”
280
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 281
Select the Web Service from the List
281
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 282
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”
282
283
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 283
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();
(Source code: Module 18\WebServiceHelloTest\WebServiceHelloTest\Form1.cs)
284
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 284
Exchange Rate Web Service Example
(Source code: Module 18\WebServiceExchangeRateTest\WebServiceExchangeRateTest\Form1.cs)
285
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 285
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>
(Source code: Module 18\WebServiceExchangeRate\ExchangeRate.XML)
286
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 286
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();
}
(Source code: Module 18\WebServiceExchangeRate\App_Code\ServiceExchangeRate.cs)
287
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 287
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;
}
(Source code: Module 18\WebServiceExchangeRate\App_Code\ServiceExchangeRate.cs)
288
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 288
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);}
}
(Source code: Module 18\WebServiceExchangeRateTest\WebServiceExchangeRateTest\Form1.cs)
289
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 289
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();
}
(Source code: Module 18\WebServiceExchangeRateTest\WebServiceExchangeRateTest\Form1.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 290
APPENDIX: Windows Form - II
• OverViewMenuStip ControlContextMenuStrip ControlToolStrip ControlStatusStrip ControlDialog ControlsMDI Application
291
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 291
Notepad Example
Menu Strip Tool Strip ContextMenu StripRichTextBox
Status Strip
(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs)
Example where we cover the controls likeMenu StripTool StripStatus StripContextMenu Strip - is a short cut menu which get activated when user click with
Right Mouse Button on a specific controlRich Text Box
292
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 292
Notepad Example (Contd…)
FileStream fs;StreamReader reader;StreamWriter writer;string FileName = null;
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();}
(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs)
MenuItem StripThe strip is to show menu at the top of the form.
PropertiesName – Menu Control NameTextShort Cut – Key Board short cut
293
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 293
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);} } }
(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs)
ToolBar StripIt shows toolbar within the space provided below menu strip. It facilitates accessing
menu items through short cuts.
PropertiesNameItems
Select type as Button and click addNameTextImage
294
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 294
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();
}}
(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs)
Status StripProvides status menu strip at the bottom of the form. It gives meta
information/messages/properties about the task.
PropertiesNameItems
295
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 295
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);}
}}
(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs)
296
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 296
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();}
(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs)
SaveDialog BoxShows dialog box for saving the information.
PropertiesName Control NameDefaultExt Default extension txtFilter 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 itemInitialDirectory The initial directory for the dialogRestoreDirectory Dialog restore the current directory before closing
True / False
FontDialog BoxShow dialog box for selecting fonts from the list of installed fonts on the platform.
PropertiesName Control NameShowColor Show Color Choice TrueShowApply Show the Apply Button True
297
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 297
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();}
(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs)
Color Dialog BoxShows dialog box to select color.
PropertiesName Control NameFullOpen Show the custom color section True
298
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 298
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);}
}
(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs)
299
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 299
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();}
(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs)
300
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 300
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);}
(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs)
301
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 301
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);}
(Source code: APPENDIX\NotepadApplication\NotepadApplication\Notepad.cs)
302
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 302
MDI Application
• Three steps for creating MDI ApplicationCreate a Parent FormCreate a Child FormCall Child Form from a Parent Form
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.
303
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 303
MDI Application Example
(Source code: APPENDIX\MdiApplication\MdiAppliation)
304
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 304
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 declarationint count=0;
305
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 305
MDI Application Example (Contd…)
New Menu Itemcount = 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 Itemthis.LayoutMdi(MdiLayout.TileHorizontal)
Vertical Menu Itemthis.LayoutMdi(MdiLayout.TileVertical)
(Source code: APPENDIX\MDIApplication\MDIApplication\MDIParent.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 306
Appendix: Advance Threads
• OverviewThread Safe classSingleton Pattern Thread Safe
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 307
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
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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 308
Error Log Program
• Add the following namespaces in your programusing 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.
(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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 309
Error Log Program (Contd…)
[MethodImpl(MethodImplOptions.Synchronized)]public static void LogStart(string sFile) {
//open Trace Log fileErrorLog = new StreamWriter(File.Open(sFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite));
}
(Source code: Appendix Thread\SynchronizedThreadEx\SynchronizedThreadEx\Logfile.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 310
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();
}
(Source code: Appendix Thread\SynchronizedThreadEx\SynchronizedThreadEx\Logfile.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 311
Test Programstatic 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();
}
(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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 312
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.
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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 313
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();}
}
(Source code: Appendix Thread\SingletonThreadSafe\SingletonThreadSafe\Singleton.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 314
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();
}
(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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 315
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();}
}
(Source code: Appendix Thread\SingletonThreadSafe\SingletonThreadSafe\SingletonThreadSafe.cs)Mark the method as thread safe.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 316
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();
}
(Source code: Appendix Thread\SingletonThreadSafe\SingletonThreadSafe\Program.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 317
Volatilepublic 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();}
}
(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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 318
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();
}
(Source code: Appendix Thread\SingletonThreadSafe\SingletonThreadSafe\Program.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 319
Thread PoolUsing 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.");}
(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.
320
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 320
Appendix : Iterators
• OverviewIenumeratorIenumerable
321
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 321
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 foreachforeach (string day in Days) {
System.Console.Write(day + " ");}Console.ReadLine();
}}
(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
322
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 322
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];
}}
(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.
323
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 323
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();
}}
(Source code: Module09\IteratorExample\IteratorExample\IEnumerableExample.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 324
Appendix: Reflection
• OverviewReflection mechanismObtaining the content of assembly at run time
324
325
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 325
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
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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 326
Hierarchical Representation of Metadata Information
Assembly
Module(s)
Constructor(s) Method(s)
Parameter(s)
Field(s) Property(s)
Type(s)class(s), interface(s), structure(S), enum(s)
delegate(s)
Parameter(s)
326
327
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 327
Reflection Codeclass 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;}
}
(Source code: Appendix Reflection\Reflection\Reflection\Shape.cs)
328
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 328
Reflection Code (Contd…)
static void Main(string[ ] args) {Object obj;try {
//load assemblyAssembly assembly = Assembly.LoadFrom("Reflection.exe");
//search for the typeType[] 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);
(Source code: Appendix Reflection\Reflection\Reflection\Program.cs)
329
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 329
Reflection Code (Contd…)
if (ClassType == null)Console.WriteLine(ClassType.Name + " type does not exist");
elseConsole.WriteLine(ClassType.Name + " type exist");
Console.WriteLine("--------------------");
//create the instance of the typeobj = Activator.CreateInstance(ClassType);
//method invokingMethodInfo 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);
(Source code: Appendix Reflection\Reflection\Reflection\Program.cs)
330
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 330
Reflection Code (Contd…)
//method with return valueMethodInfo 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("--------------------");
(Source code: Appendix Reflection\Reflection\Reflection\Program.cs)
331
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 331
Reflection Code (Contd…)
//method with parameterint 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();
}
(Source code: Appendix Reflection\Reflection\Reflection\Program.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 332
Appendix: Serialization
• OverviewWhat is serializationTypes of serialization
• Binary• SOAP• XML
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 333
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
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 isn’t 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].
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 334
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; }
}
(Source code: Appendix Serialization\Serialization\Serialization\02BinarySerialization.cs\Person.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 335
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;
}}
}
(Source code: Appendix Serialization\Serialization\Serialization\02BinarySerialization.cs\Person.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 336
Binary Serialization
Binary Formatter class is available in the namespace
System.Runtime.Serialization.Formatters.Binary
(Source code: Appendix Serialization\Serialization\Serialization\02BinarySerialization.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 337
Binary Serialization Write Object
• Add the namespaceusing 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";
(Source code: Appendix Serialization\Serialization\Serialization\02BinarySerialization.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 338
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);
(Source code: Appendix Serialization\Serialization\Serialization\02BinarySerialization.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 339
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");}
(Source code: Appendix Serialization\Serialization\Serialization\02BinarySerialization.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 340
SOAP Serialization
Add reference for the namespace
System.Runtime.Serialization.Formatters.Soap
(Source code: Appendix Serialization\Serialization\Serialization\03SOAPSerialization.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 341
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";
(Source code: Appendix Serialization\Serialization\Serialization\03SOAPSerialization.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 342
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());
(Source code: Appendix Serialization\Serialization\Serialization\03SOAPSerialization.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 343
XML Serialization
• Rules for creating class for XML SerializationXML 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.
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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 344
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;
(Source code: Appendix Serialization\Serialization\Serialization\Employee.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 345
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;}
}
(Source code: Appendix Serialization\Serialization\Serialization\Employee.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 346
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);
}
(Source code: Appendix Serialization\Serialization\Serialization\Employee.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 347
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);}
}}
(Source code: Appendix Serialization\Serialization\Serialization\Employee.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 348
Employee XML Serialization
using System.IO;using System.Xml.Serialization;
(Source code: Appendix Serialization\Serialization\Serialization\Employee.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 349
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));//serializationXmlSerializer serializer = new XmlSerializer(typeof(Employee));StreamWriter writer = new StreamWriter("C:\\emp.xml");serializer.Serialize(writer, empList);writer.Close();
(Source code: Appendix Serialization\Serialization\Serialization\04EmployeeXMLSerialization.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 350
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");
}
(Source code: Appendix Serialization\Serialization\Serialization\04EmployeeXMLSerialization.cs)
351
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 351
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();
(Source code: Module12\DatabaseApplication\DatabaseApplication\12SQLBulkCopy.cs)
352
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 352
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");
(Source code: Module12\DatabaseApplication\DatabaseApplication\12SQLBulkCopy.cs)
353
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 353
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;
}
(Source code: Module12\DatabaseApplication\DatabaseApplication\13BatchUpdate.cs)
354
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 354
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++;}
(Source code: Module12\DatabaseApplication\DatabaseApplication\13BatchUpdate.cs)
355
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 355
Appendix : Multiple Active Result Set
(Source code: Module12\DatabaseApplication\DatabaseApplication\14MARS.cs)
356
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 356
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();
(Source code: Module12\DatabaseApplication\DatabaseApplication\14MARS.cs)
357
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 357
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();
}}
}
(Source code: Module12\DatabaseApplication\DatabaseApplication\14MARS.cs)
358
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 358
Appendix : Reading and Writing Data to XML
DataSet ds;
• Form Load Eventstring 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);
(Source code: Module12\DatabaseApplication\DatabaseApplication\15XML.cs)
359
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 359
Reading and Writing Data to XML (Contd…)
• WriteXML Button
if (!File.Exists("C:\\category.xml")) {ds.WriteXml("c:\\category.xml");
}btnreadxml.Visible = true;
• ReadXML Button
ds.Clear();ds.ReadXml("C:\\category.xml");dataGridView1.DataSource = ds.Tables[0];
(Source code: Module12\DatabaseApplication\DatabaseApplication\15XML.cs)
360
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 360
Appendix : Data Independent Provider
(Source code: Module12\DatabaseApplication\DatabaseApplication\16ProviderFactories.cs)
361
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 361
Data Independent Provider (Contd…)
• Add the following namespace• using System.Data.Common;• Form Load Event
DataTable table = DbProviderFactories.GetFactoryClasses();lstprovider.DisplayMember = table.Columns["InvariantName"].ToString();lstprovider.ValueMember = table.Columns["InvariantName"].ToString();lstprovider.DataSource = table;
(Source code: Module12\DatabaseApplication\DatabaseApplication\16ProviderFactories.cs)
362
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 362
Data Independent Provider (Contd…)
• ListBox SelectedIndexChange Eventstring 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;}
}
(Source code: Module12\DatabaseApplication\DatabaseApplication\16ProviderFactories.cs)
363
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 363
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;}
}
(Source code: Module12\DatabaseApplication\DatabaseApplication\16ProviderFactories.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 364
Appendix : TreeView Example with Database
(Source code: Module12\DatabaseApplication\DatabaseApplication\17TreeViewExample.cs)
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
• 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 366
TreeView Example with Database Code
• Form Load Event
conn = new SqlConnection("server=.\\sa1;database=northwind;integratedsecurity=true");
adp = new SqlDataAdapter("select table_name from information_schema.tableswhere 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 367
TreeView Example with Database Code
ds = new DataSet();if (e.Node.Text == "column") {
string str = e.Node.Parent.Text;adp = new SqlDataAdapter("selectCOLUMN_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;}