C# Dot Net
February 14, 2017 | Author: babu | Category: N/A
Short Description
Download C# Dot Net ...
Description
C# 2010 with Microsoft.Net Framework 4.0 Pragati Software Pvt. Ltd. www.pragatisoftware.com
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
1
1
Index Module
Particulars
Page
Module 1
Getting Started
4
Module 2
Basic Language Constructs
15
Module 3
Class and Object
37
Module 4
Class Library
47
Module 5
Inheritance
59
Module 6
Exception Handling
75
Module 7
Other C# Features
85
Module 8
String, StringBuilder and Dateformats
99
Module 9
Collection classes
117
Module 10
Generics and Nullable Types
129
Module 11
Windows Form Control I
137
Module 12
File I/O
159
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
2
2
Index
(Contd…)
Module 13
Working with DB
181
Module 14
Data Bound Controls
226
Module 15
DotNet Framework and Assembly
239
Module 16
Delegate
244
Module 17
Thread
253
Module 18
Introduction to Web Services
273
APPENDIX
Windows Form Control II
290
APPENDIX
Advance Thread
306
APPENDIX
Reflection
320
APPENDIX
Serialization
324
APPENDIX
Iterators
332
APPENDIX
SQL BULK copy
351
APPENDIX
Database Operations
353
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
3
3
Module 1: Getting Started • Overview ¾ ¾ ¾ ¾
Introduction to C# Types of applications Understanding some terms: solution, project, Visual Studio IDE Writing, compiling and running a simple program
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
4
4
Framework Version DLR C# 4.0
Code Contracts
VB 10
PLINQ
MEF
.Net Framework 4.0 Enhancement for WCF, WPF, WF C# 3.0 VB 9 LINQ AJAX
.Net Framework 3.5 WCF
WPF
WF
.Net Framework 3.0 C# 2.0
Card Space
VB 8.0
.Net Framework 2.0 CLR 4.0 Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
5
MEF : The Managed Extensibility Framework or MEF is a library for creating lightweight, extensible applications. It allows application developers to discover and use extensions with no configuration required. It also lets extension developers easily encapsulate code and avoid fragile hard dependencies. MEF not only allows extensions to be reused within applications, but across applications as well. DLR : The dynamic language runtime (DLR) is a runtime environment that adds a set of services for dynamic languages to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages.
.Net Framework
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
6
.NET Framework is a common platform for designing, developing and deploying the various types of applications such as: Console Application, Windows Application, Web Based Application, Class Library Application, Web services, WCF, WPF, WF etc.. A developer can develop application by using any of the language which is compatible with .NET Framework. The languages compatible with .NET Framework are such as C#, VB, J#, VC++, F# etc. The Base class library provides a comprehensive set of facilities for application development. The .NET Framework provides a run-time environment called the Common Language Runtime. It runs the code and provides the services which makes the development process easier. Microsoft provides IDE as a Visual Studio to implement the .NET Framework. .NET Framework comes with redistributable installer that contains the Common Language Runtime and .NET Framework components which are necessary to run .NET Framework applications. The .NET Framework is available as a stand-alone executable file, Dotnetfx.exe. NOTE:Prior to .NET Framework for developing different types of applications different technologies were used. E.g. : For developing Console applications languages such as C/C++ was used. For developing Windows based applications VB was introduced by the Microsoft. For developing and designing web based applications, technologies such as HTML, DHTML, JavaScript, classic ASP were used. It means for developing specific type of application, one has to use different technologies.
6
Types of Applications • • • • • • •
Console applications. Windows applications ASP.NET Web applications Class libraries Custom controls (User defined controls). Windows service Web Service
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
7
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.
7
Features of C# • • • • • • • •
Object-oriented features Structured exception handling Powerful Windows based applications Building Web based applications Simple data access Multithreading Simplified deployment XML Web Services
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
8
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.
8
Creating a New Project
(Contd...) 1. Framework Version
2. Language
3. Application Template
4. Project Name 5. Project Location 6. Solution Name Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
9
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.
9
Solutions and Projects 1. Solution name
• A solution usually acts as a container for one or more projects • A project typically contains all the files required for the application.
2. Project name
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
10
1. Solutions: A Visual Studio solution can include just one project or several projects built jointly by a development team. A complex application might require multiple solutions. 2. Projects: Visual Studio projects are used as containers within a solution to logically manage, build, and debug the items that comprise your application. The output of a project is usually an executable program (.exe) or a dynamic-link library (.dll) which known as Assembly.
10
Writing the First Program namespace Module01 { class Program { static void Main(string[] args) { Console.WriteLine("Hello World..."); Console.ReadLine(); } } }
• Click on Debug -> Start to view the output.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
11
(Source code: C:\Training\Module01\Module01\Module01\Program.cs) Namespace is a logical collection of the types such as: class interface struct enum delegate In class Program we have Main() method which is known as entry point. Console is a class under System namespace which has a WriteLine() and ReadLine() as a method.
11
Compilation Process in .NET Visual Basic
C#
J#
Compiler
Compiler
Compiler
Windows CLR
MAC CLR
JIT
JIT Managed code
CPU
CPU
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
12
.Net framework supports various languages to develop the applications. A developer may write a code by using any of the language (VB, C#, J#, VC++, F#) which is compatible with .Net Framework. What happens when the code is written and compiled in .Net framework? Every language has its own language compiler. Very first the code is compiled by the language compiler and it produces a MSIL (Microsoft Intermediate Language) code. It is also known as “IL” code. This MSIL code is now sent to the CLR (Common Language Runtime). Once the MSIL code is sent to the CLR, only the code which is required during runtime is getting compiled into native machine code. This process is known as “JITing” and it is performed by a component known as “JITer” (Just in Time Compiler). Once the native machine code is produced it goes through under tight security policy which is known as “CASPOL” (Code-Access-Security-Policy). If this code is safe then only it is executed on CPU. This code is also known as “managed code”. Same process happens for the other OS also.
12
Location of .exe file. 1. Location of .exe 2. Exe file
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
13
.Exe is always stored at location : project folder\bin\debug.
13
Components of CLR
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
14
Class Loader : It loads all the Base Class Libraries required during execution of code. Type Verifier : Type verifier checks for the type compatibility. It is also known as “CTS”(Common Type System). The specification for the types are specified by “CLS” (Common Language Specification). Exception Manager : Exception manager manages the exception during runtime. JIT : Just-In-Time compiler produces native machine code which is required while runtime. Garbage Collector : It is also known as “Heap Manager” or “Auto memory manager”. It releases the memory by removing unused/out of scope objects. In invokes automatically. One can not predict about 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
Module 2. Basic Language Constructs • Overview ¾ Variables and data types ¾ Operators (arithmetic, relational, logical, assignment, conditional, etc.) ¾ Conditional statements
• if – else • switch ¾ Looping Constructs
• while • do….loop while() • for ¾ Arrays
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
15
15
Data Types
(Contd…)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
16
The .NET platform provides Common Type System to all the supported languages. This means that all the languages must support the same data types as enforced by common language runtime. Data Types
Description
Example
object
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 val2=34L;
long val1=12;
byte
8-bit unsigned integral type
ushort
16-bit unsigned integral
byte 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;
ushort val1=12;
double Double-precision floating point type double val2=4.56D;
double val1=1.23;
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 Data C or c – Currency format D or d – double M or m – decimal F or f – float L or l - long
16
Variable and Data type Program static void Main(string[ ] args) { double centigrade; double fahrenheit; centigrade = 33.3; fahrenheit = (centigrade * 9 / 5) + 32; Console.WriteLine("33.3 Centigrade = " + fahrenheit + " Fahrenheit."); Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
17
(Source code: Module02\Module02\01variable.cs) Variable Declaration int num; double salary, balance; string name;
17
Common Type System (CTS)
Common Type System
VC++
C# CLS Visual Basic.NET
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
18
The Common Type System , is a part of the .net framework describes how the various data types must be declared, managed and used at runtime and plays a very crucial role for supporting cross language integration. Some of the most common functions it conducts are : 1.Type Safety, Cross language integration and high performance execution of code. 2.It has a set of rules that all .net compliant languages must follow so that the objects created in those languages can interact with each other . It supports the complete implementation of the programming languages. Common Language Specification (CLS) :
When you write code in one language and this code is then used by other programs that were developed in different languages, then that code should be CLS compliant, which simply means that it should abide by the rules specified in the CLS. The CLS describes features such as common data types for different languages. CLS compliance is important when software components that are created in one language will be used by other languages. The CLS is called as a subset of the CTS because it defines those set of rules that are a part of the CTS itself.
18
CLS C# int i; string str; double dbl;
VB.NET Dim i as Integer Dim str as String Dim dbl as double
.NET Type System.Int32 i; System.String str; System.Double dbl;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
19
If one application written in C# and one application written in VB.NET wants to communicate with each other, how the communication will happen? In .NET if C# uses int to store numeric value which has a storage size 32 bits and VB.NET uses Integer to store numeric value which also has a storage size 32 bits. Then Common language specification specifies the common type compatible with both the types and produces a result as Int32.
19
Named Constant static void Main(string[ ] args) { const float Pi = 3.14f; float radius, area; radius = 10.0f; area = Pi * radius * radius; Console.WriteLine("Area of circle = " + area.ToString()); Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
20
(Source code: Module02\Module02\02constant.cs) Named constants are created by declaring a variable with keyword const. Using a named constant can improve the readability of your code, as it becomes a form of documentation. Besides, since a named constant is defined in only one place in a program, if the value of the constant needs to be changed, it needs to be changed only in one place. Thus, use of named constants improves program maintenance also.
20
Writing comments static void Main(string[ ] args) { /* variable declaration */ const float Pi = 3.14f; float Radius, Area; Radius = 10.0f; /* Calculation */ Area = Pi * Radius * Radius; //Printing Result Console.WriteLine("Area of circle = " + Area.ToString()); Console.ReadLine(); }
Comment
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
21
comments can improve the readability (and thereby, maintainability) of source code. Single Line comment // text following // up to the end of the line is treated as a single line comment, and is ignored by the compiler. /* */ Similarly, any text between /* and the next */ is known as multi line comment, and is also ignored by the compiler. In C# you can add the contents by using short-cut keys (ctrl+E, C). And for uncommenting short-cut key used is (ctrl_E, U).
21
Taking Input from the User Input window
static void Main(string[ ] args) { const float Pi = 3.14f; float Radius, Area; Console.Write("Enter the value for radius : "); Radius = float.Parse (Console.ReadLine()); Area = Pi * Radius * Radius; Console.WriteLine("Area = " + Area.ToString()); Console.ReadLine(); } Output window
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
22
(Source code: (Source code: Module02\Module02\03userinput.cs) To take input from the user at the runtime we use Console.ReadLine() method and assigning the value to the variable “Radius”. When we take the input from the command line it is always taken as string type. The data type of the Radius variable is float, so we require to convert string type to float type. For that we are using the method Parse of the float type to convert string value to the float value.
When we print the value we are giving message and then we display the value. So every part of the Console.WriteLine() method has to be of a string type. So for printing we are converting the decimal value of area into string by using ToString() method.
22
Operators Operator
Language Element
Arithmetic
+, –, *, /, %
Unary
++ , --
Assignment
=, +=, -=, *=,
Comparison
==, !=, , =
Concatenation
+
Logical operations
&&, ||
/=
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
23
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 5 || num2 Num2) Console.WriteLine("Num1 is greater the Num2"); else Console.WriteLine("Num2 is greater then Num1"); Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
25
The multiple if Structure Example static void Main(string[] args) { int a = 5, b = 6, c = 7, min, max; if (a >= b) { if (a >= c) { max = a; if (b >= c) { min = c; } else { min = b; } } else { max = c; min = b; } } else if (b >= c) { max = b; if (a >= c) { min = c; }
else { min = a; } } else { max = c; if (a >= b) { min = b; } else { min = a; } } Console.WriteLine("max={0} min={1}", max, min); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
26
(Source code: Module02\Module02\04if.cs)
26
The switch statement switch (expression) { case value: statements; break; case value: statements; break; default: statements; break; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
27
To choose one option among the multiple choices switch-case statement is used.
27
The switch statement Example case 7: static void Main(string[] args) case 8: { case 9: int month = 1; case 10: switch (month) Console.WriteLine("Monsoon { season"); case 11: break; case 12: default: case 1: Console.WriteLine(“Invalid month); case 2: Console.WriteLine("Winter Season"); } break; } case 3: case 4: case 5: case 6: Console.WriteLine("Summer season"); break; Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
28
(Source code: Module02\Module02\06switch.cs)
28
while loop while (condition) { statements; increment / decrement statement } static void Main(string[ ] args) { int num = 1; while (num Console Application. 2. Save as ABCCorporation. 3. From the solutions drop-down list select -> Add to Solution.
52
Adding reference of dll to Application
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
53
Menu options: 1.Click on Project -> Add reference . 2.From the dialogue box select projects tab -> select EmployeeLibrary.dll. (It the dll and application is in the same solution otherwise click on browse tab and select the required dll from the path).
53
Creating a Test Application using EmployeeLibrary; class Program { static void Main(string[] args) { Employee employee = new Employee(1,"Trupti", 25000); double bonus=employee.CalcBonus(0.3); Console.WriteLine(“Bonus={0}”,bonus); Console.ReadLine(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
54
(Source code : C:\Training\Module04\EmployeeLibrary\ABCCorporation\Program.cs)
54
Set startup project
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
55
55
Static field • Static field is used when we want to have values that are shared across all instances of a particular class. • Static fields and static constants enable this to happen by belonging to the class and not to the actual objects. • In your application, you can declare a variable and refer to it regardless of which instance of an object you are using. Such a variable is called static.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
56
56
Static field public class Employee { …… private static int Id=0; public Employee() { empId = 0; empName =“unknown”; salary = 0; } public Employee(int id,string Name, double sal) { ++id; this.empId = id; …… } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
57
Assignment • Create a class library project. Add Product class with following members: Product -productId ; -productName ; -unitPrice ; -Quantity + GetProducts(productname,unitprice,Quantity);
• productId must me auto incremented. • Display totalprice of product available Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
58
Module 5. Inheritance • Overview ¾ Object Oriented Concepts ¾ Bank Case Study ¾ Inheritance ¾ Constructor in extended classes ¾ Overriding methods ¾ Polymorphism ¾ Use of Sealed keyword ¾ Abstract class and method ¾ Declaring Interface ¾ Implementing Interface
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
59
59
Object Oriented Concepts • • • •
Abstraction Encapsulation Inheritance Polymorphism
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
60
Abstraction refers to the description of externally visible behavior of an object. Abstraction is used to describe what an object does, rather than how it does it. Encapsulation is a description of the internal data structures and internal implementation that give rise to this externally visible behavior. Encapsulation deals with how the object does it. Inheritance facilitates reusability of code. A new class can inherit all the properties and methods of another existing class. Polymorphism refers to the ability to hide many implementations behind the common interface. Using polymorphism, a single name may denote objects of many different classes.
60
Bank Application • Create a class library project. • Save it as BankLibrary. • It will provide Business Logic of Banking Services.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
61
61
A BankAccount Class – the Super Class public class BankAccount { …. ; public BankAccount() { ….; } public BankAccount (string AccName, double Balance) { …. ; } public int AccNumber { get ; } public string AccName { get ; set ; } public double Balance { get ; set ; }
public double Withdraw(double amount) { …..; } public double Deposit(double amount) { ….. ; } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
62
(Source code: C:\Training\Module05\BankLibrary\BankLibrary\BankAccount.cs)
62
Inheritance Inheritance is a powerful feature of OOP. It provides following features: •Reusability •Easy maintenance of code. •Extendibility
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
63
Inheritance Inheritance is a powerful feature of object-oriented programming languages. This refers to the ability of a class to inherit the fields and operations of another class, and extend these further. Inheritance can also be useful when two or more classes have some fields and operations in common. Instead of duplicating these common aspects in various classes, we can keep them in a base class, that other classes inherit from. For example, in a banking application, we may have a SavingsAccount class as well as a CurrentAccount class. Both these classes may have some common operations and fields, in addition to having their own specific fields and operations. Such common fields and operations can be kept in a common base class called BankAccount. The SavingsAccount and CurrentAccount classes can then inherit from the BankAccount class. In .NET, there is a class called Object. Every other class explicitly or implicitly inherits from the Object class. .Net allows single inheritance of the class.
63
Access Specifiers Visibility / Access Specifier
private protected internal
public
protected internal
Same class
Yes
Yes
Yes
Yes
Yes
Derived class in same assembly
No
Yes
Yes
Yes
Yes
Other class
No
No
Yes
Yes
Yes
No
No
No
Yes
No
No
No
No
Yes
No
Other class in other assembly Derived class in other assembly
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
64
The SavingsAccount Class – the Sub Class public class SavingsAccount : BankAccount { ….; static SavingsAccount() { …. ; } public SavingsAccount(string AccName,double Balance,bool IsSalaryAccount) :base(AccName,Balance) { ….. ; } public double CalculateInterest() { …. ; } }
Using Derived class object static void Main(string[ ] args) { SavingsAccount savingobject = new SavingsAccount(); …. ; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
65
(Source code: Module04\Inheritance\SavingAccount.cs) An object of the SavingsAccount class would have all the fields other then private of its base class as well as the ones additionally defined within that class. Similarly, on an object of the SavingsAccount class, all the public and internal operations of the BankAccount class can be applied. In this program we have created the instance of SavingsAccount class, which is the derived class of the BankAccount class. All the members of the BankAccount class are created inside the memory of the SavingsAccount instance. It is calling the methods inherited from its base as well as of its own.
65
Calling parent class constructor class BankAccount { public BankAccount(float balance) { …. ; } } class SavingsAccount : BankAccount { public SavingsAccount(float balance, bool IsSalaryAccount) : base(balance) { .. } }
Object
BankAccount
SavingsAccount
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
66
(Source code: Module04\Inheritance\BankAccount.cs) (Source code: Module04\Inheritance\SavingAccount.cs) (Source code: Module04\Inheritance\Program.cs) A derived class must choose one of its super class constructors to invoke. The part of the object that is inherited from a super class must be initialized properly by the super class itself. The constructor of a derived class can invoke a base class's constructor using base keyword
66
Overriding Methods •A method in sub class with the same signature as a super class has but with different implementation is known as method overriding. •Same signature means methods must have ¾same name. ¾same number of arguments ¾same type of arguments. ¾same access specifier •Keyword virtual is used in base class method definition. •Virtual indicates that this method can be overriden by sub class.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
67
A subclass can replace its super class's implementation of a method with one of its own. This is known as overriding a method. Both the signature and return type must be the same as the super class. In .Net by default method of super class cannot be overridden by sub class. For this sub class require permission from the super class Super class method should have keyword virtual and sub class method should have keyword override. virtual indicates that this method can be overridden by an identically named method in a derived class. virtual is the default setting for a method that itself overrides a base class method. Override keyword specifies that a property or method overrides a member inherited from a base class. This keyword indicates that method overrides an identically named method in a base class. The number and data types of the arguments, and the data type of the return value, must exactly match those of the base class procedure.
67
Overriding Methods continued… class BankAccount { public virtual void Withdraw(float amount) { …. ; } } class SavingsAccount : BankAccount { public override void Withdraw(float amount) { ….. ; } public override ToString() { …. ; } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
68
(Source code: Module04\Inheritance\BankAccount.cs) (Source code: Module04\Inheritance\SavingAccount.cs) (Source code: Module04\Inheritance\Program.cs)
68
Polymorphism • Polymorphism is a Greek word which means “many-shaped”. • It has two distinct aspects: ¾ At run time object of inherited class may be treated as object of base class . ¾ Base classes may define and implement virtual methods and inherited classes may override these methods , which means inherited classes provide its own definition and implementation.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
69
Polymorphism class BankAccount { ….. ; public int AccountNumber { ….. ; } public float Balance { ….. ; } public BankAccount() { ….. ; } public BankAccount(float _balance) { ….. ; } public void Deposit(float amount) { ….. ; } public virtual void Withdraw(float amount) { … ; } } class SavingsAccount : BankAccount { ….. ; static SavingsAccount() { …. ;} public SavingsAccount() { ….. ; } public SavingsAccount(float balance, bool IsSalaryAccount) : base(balance) { ….. ; }
public float CalculateInterest() { ….. ; } public override void Withdraw(float amount) { …. ; } } class CurrentAccount : BankAccount { …… ; public CurrentAccount(float balance, float overdraftlimit) : base(balance) { ….. ; } public override void Withdraw(float amount) { ….. ; } } static void Main(string[ ] args) { BankAccount Bankref; Bankref = new SavingsAccount(7000,true); Bankref = new CurrentAccount(4000, 2000); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
70
70
Preventing Overriding class BankAccount { public virtual void Withdraw(float amount) { …. ; } } class SavingsAccount : BankAccount { public sealed override void Withdraw(float amount) { ….. ; } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
71
(Source code: Module04\SealedExample\BankAccount.cs) (Source code: Module04\SealedExample\SavingAccount.cs) (Source code: Module04\SealedExample\SubSavingAccount.cs) You can prevent subclasses from overriding the implementation of a method of a super class, by making it sealed. You can even make an entire class sealed, thereby preventing any extension of that class. All the methods of a sealed class are implicitly sealed. It can improve security. If a class is sealed, you know that nobody can extend it, and therefore, nobody can violate its contract. Similarly, if a method is sealed, you can rely on its implementation details. sealed is the default setting for a method that does not itself override a base class method.
71
Preventing Inheritance sealed class SavingsAccount : BankAccount { } class SubSaving : SavingsAccount // compile time error { }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
72
Sealed classes are primarily used to prevent the inheritance. A sealed class can not be a base class. But it can be instantiated.
72
Abstract Class •The abstract keyword enables you to create classes and class members solely for the purpose of inheritance. •The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. •An abstract class can not be instantiated. Abstract class public abstract class BankAccount { public abstract void Withdraw(float amount); } Abstract method
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
73
You can mark a class as abstract, which means that the class cannot be instantiated. This way you can create a class that cannot have objects, but serves as a base for other subclasses. For example in a bank we can have account as either saving or current but we cannot have account type as a bank. The use of this class would be only to extend it to SavingsAccount and BankAccount class for reducing duplication of work and maintenance. The opposite of abstract is concrete; a concrete class can be instantiated. For example, Clerk, Executive and Manager would be concrete classes, extending the Employee class. For example, SavingsAccount and CurrentAccount would be concrete classes, extending the BankAccount.
73
Interface •An interface contains only the signature of methods, delegates and events. •The implementation of the methods is done in the class which implements the interface. •An interface can inherit from one or more base interface. public interface Iinterest { float CaclulateInterest(float irate); }
Method signature
class SavingAccount : BankAccount, Iinterest { public float CaclulateInterest(float irate) { …. ; } }
Interface implementation
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
74
An interface is a way to declare a type consisting only of abstract methods, Events or Properties. An interface provides a protocol binding to the classes that implement it. An interface cannot be instantiated. It consists of abstract methods, Events or Properties, i.e., it does not contain any implementation. An interface also cannot contain any variables.
74
Module 6. Exceptions Handling • Overview ¾ ¾ ¾ ¾ ¾
What is Exception Handling? The “try-catch” Structure The finally Clause The throw Cause User Defined Exception
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
75
75
What is an Exception Handling? • Error which occurs during runtime is known as Exception. • The mechanism to handle such errors during runtime is called as Exception Handling.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
76
try-catch-finally • C# provides 3 keywords to handle an Exception. ¾ try :- The try keyword is required. It lets the compiler know that you are attempting a normal flow of a program. ¾ catch :-During runtime if any exception occurs instead of letting the program crash the flow of the program can be transferred to cache section. catch block is always followed by try. ¾ finally :- This block executes always. It is optional to use finally.
• Syntax for try-catch-finally try { error prone code; } catch { statement for exception handling ; } finally { statement for clean up ; } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
77
Structured Exception Handling concept is introduced in .NET Framework. The System.Exception is the base class for all the exceptions in .NET. C# provides three keywords try, catch and finally to do exception handling. The try keyword encloses the statements that might throw an exception whereas the catch keyword is used to handle an exception if one exists. The finally clause can be used for doing any clean up process
77
Understanding Exceptions static void Main(string[ ] args) { int num1, num2, ans; Exception occurs here num1 = 10; num2 = 0; ans = num1 / num2; Console.WriteLine("Answer = " + ans); Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
78
There are three types of errors which occurs in program, Syntax errors, run-time errors and logical errors. Exception handling is mechanism to detect and handle run time errors. .NET provides us Exception Handling techniques to overcome such situations. There are two types of exceptions: System Exception - Exceptions generated by CLR. Application Exception - Exceptions generated in application When we run the above code, it will get compile but at run time when control come to the line “ans = num1 \ num2", it will throw an exception. We require to manage this type of error which is known as Exception Handling
78
Exception Handling Mechanism static void Main(string[ ] args) { …. ; try { int num1, num2, ans; num1 = 10; num2 = 0; ans = num1 / num2; Console.WriteLine("Answer = " + ans); } catch (DivideByZeroException ex) { Console.WriteLine(ex.Message); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
79
(Source code: Module05\ExceptionHandling\ExceptionHandling\Program1.cs) If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks. If there is no exception occurred inside the try block, the control directly transfers to finally block. The statements inside the finally block is executed always.
79
Multiple Catch Block int num1, ans; int[ ] numarray = new int[1]; try { num1 = 10; numarray[0] = 5; ans = num1 / numarray[1]; Console.WriteLine("Answer = " + ans); } catch (DivideByZeroException ex) { …. ; } catch (IndexOutOfRangeException ex) { Console.WriteLine(ex.Message); } catch (Exception ex) { } finally { }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
80
(Source code: Module05\ExceptionHandling\ExceptionHandling\Program2.cs) A try block can throw multiple exceptions, which can be handled by using multiple catch blocks. We can use generalized Exception class to handle any type of runtime exception. Add the generalize catch block as the last catch block in the hierarchy otherwise at the compile time it will give an error. “A previous catch clause already catches all exceptions of this or of a super type ('System.Exception')” Some of the Exception classes are System.Exception System.DevideByZeroException System.NullReferenceException Syste.InvalidCastException System.IndexOutOfRangeException etc.
80
finally •finally : Code in finally block is always executed. It contain clean up code to release the resources. int num1, ans; int[ ] numarray = new int[1]; try { …; } catch (DivideByZeroException ex) { …. ; } catch (IndexOutOfRangeException ex) { …; } finally { Console.WriteLine(“End of Main Block”); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
81
Finally can be used in such cases where it’s needed to free-up the resources always. Finally block is optional.
81
throw • throw : Exceptions can be explicitly generated by using a “throw “ keyword. int num1, num2, ans; num1 = 10, num2 = 0; if(num1/num2) { throw new DivideByZeroException(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
82
We can create our own exception by creating a class and inheriting it from the Exception base class. To throw the exception throw keyword is used throw keyword is used to raise an Exception. Sometimes it may happen that a method that is called might be getting an exception which is handled by the caller of that method. In such situation the throw keyword is used.
82
User defined Exceptions •It is possible to create our own exception (user defined exception) classes. •System.Exception must be base class for all the exception classes. •In the constructor needs to define the steps which you want to perform.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
83
83
User Defined Exceptions class BalanceException : Exception { public BalanceException(string msg) :base(msg) { } } class SavingsAccount { ….. ; public SavingsAccount() { …. ; } public void Withdraw(float amount) { if ((balance - amount) > 500) balance -= amount; throw exception else throw new BalanceException("Not enough balance"); } }
User defined exception class static void Main() { SavingsAccount saving = new SavingsAccount(); try { saving.Withdraw(3000); } catch (BalanceException ex) { Console.WriteLine(ex.Message); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
84
(Source code: Module05\ExceptionHandling\ExceptionHandling\BalanceException.cs)
84
Module 7. Other C# Features • Overview ¾ ¾ ¾ ¾ ¾ ¾ ¾ ¾ ¾
Structure enum Type casting Boxing Unboxing ref and out parameter Operator overloading Partial class Static class
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
85
85
Structure •Structure is a generalization of the user defined data type. Used when a single variable is required to hold multiple types of data •Structure is a value type. struct Employee { ….. ; public Employee(int id, string name, string add, float sal) { ….. ; } public float AnnualSalary() { …. ; } } static void Main() { Employee emp1 = new Employee(101, “Smith", "Mumbai", 2000.00f); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
86
(Source code: Module06\Module06\StructureExample.cs) Structure is a type like a class which we can define within the namespace. The members of a structure cannot be initialized within the structure declaration A structure can have instance constructors only if they take parameters A structure can have property or method Structure procedures cannot handle events A structure is not inheritable A structure can implement interface Structure •Structure is Value Types. (Stack memory) •By default all elements declared in structure are public. •Can have instance constructor only if they take parameters. •Unlike classes, structure can be instantiated without using a new operator. •Structure can not inherit from other structure or classes •Structure can implement interface
86
enum •enum is a set of symbolic names that map to known numerical values. •enum is a set of named constant – collection of integer value. enum Months { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec } class enumExample { static void Main() { Console.WriteLine(Months.Apr); Console.WriteLine((int)Months.Apr); } } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
87
(Source code: Module06\Module06\enumExample.cs)
By default first enumerator value start from 0 and the value of each successive enumerator is increased by 1. enum Months { Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec } You can assign integer value to the individual enumerator and the value of each successive enumerator is increased by 1. enum Months { Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }
87
Type Casting • Converting value type to another value type OR
• Convert reference type to another reference type static void Main() { decimal number = 3.14M; int i = (int)number; Console.WriteLine("decimal value = {0}", number); Console.WriteLine("int i = {0}", i); Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
88
(Source code: Module06\Module06\TypecastingExample.cs)
88
Boxing - Unboxing • Boxing is an implicit conversion of a value type to the reference type. • Unboxing is an explicit conversion from the reference type to a value type. static void Main() { int i = 10; //value type object obj = i; //boxing int j = (int)obj; //unboxing Console.WriteLine(i.ToString()); Console.WriteLine(obj.ToString()); Console.WriteLine(j.ToString()); Console.ReadLine(); } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
89
Value types are stored on the stack memory and Reference types are stored on the Heap memory.
89
Ref Parameter class RefExample { static void Methodref(ref int i) { i = 100; } static void Main() { int number = 0; Console.WriteLine("Value of number = " + number.ToString()); Methodref(ref number); Console.WriteLine("Value of number = " + number.ToString()); Console.ReadLine(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
90
(Source code: Module06\Module06\RefExample.cs) Ref parameter means argument passing by reference. Any changes to the parameter in the method will be applied to the variable when the control passes back to the calling method. To use the ref parameter, both the method and the calling method must explicitly use the ref keyword. An argument passed to a ref parameter must first be initialized.
90
Out Parameter class OutExample { static void methodout(out int i, out string str) { i = 100; str="assigned value to out parameter"; } static void Main() { int number; string line; methodout(out number, out line); Console.WriteLine("number = " + number.ToString()); Console.WriteLine("line = " + line); Console.ReadLine(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
91
(Source code: Module06\Module06\OutExample.cs) out parameter means argument passing by reference. Any changes to the parameter in the method will be applied to the variable when the control passes back to the calling method. To use the out parameter, both the method and the calling method must explicitly use the out keyword. An argument passed to an out parameter do not require to be initialized first. Although variable passed as out arguments do not have to be initialized before being passed, the calling method is required to assign a value before the method returns.
91
Operator Overloading class OrderItem { private string productid; private Int32 quantity; private decimal unitprice; public string ProductID { get { return productid; } set { productid = value; } } public Int32 Quantity { get { return quantity; } set { quantity = value; } } public decimal UnitPrice { get { return unitprice; } set { unitprice = value; } } public decimal Total { get { return UnitPrice * Quantity; } } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
92
(Source code: Module06\Module06\OperatorOverloadingExample.cs) Operator overloading means use of operator with an object. It gives better readability Operator overloading method always have public static access specifiers. Operator overloading always return a type and never be void. At least one operand must be of user defined type. Relational operators are overloaded in pairs only. The ref and out parameters are not allowed as arguments. Syntax public static return_type operator op ( argument list ) {}
92
Operator Overloading
(Contd…)
public static OrderItem operator +(OrderItem Item1, OrderItem Item2) { if (Item1.ProductID != Item2.ProductID) { throw new Exception("You can only add OrderItems where the ProductID is the same for both objects"); } else if (Item1.UnitPrice != Item2.UnitPrice) { throw new Exception("You can only add OrderItems where the UnitPrice is the same for both objects"); } else { OrderItem item = new OrderItem(); item.ProductID = Item1.ProductID; item.Quantity = Item1.Quantity + Item2.Quantity; item.UnitPrice = Item1.UnitPrice; return item; } } } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
93
(Source code: Module06\Module06\OperatorOverloadingExample.cs) Operators All binary operators can be overloaded +, -, *, /, %, &, | etc. All unary operators can be overloaded +, -, !, ~, ++, --, true, false All relational operators can be overloaded, but only in pairs ==, !=, > , =, , new, is, as, sizeof, Following operators are automatically overloaded when the respective binary operator is overloaded +=, -=, *=, /=
93
Operator Overloading
(Contd…)
static void Main() { OrderItem Item1 = new OrderItem(); OrderItem Item2 = new OrderItem(); OrderItem Item3; try { Item1.ProductID = "1"; Item1.Quantity = 5; Item1.UnitPrice = 10; Item2.ProductID = "1"; Item2.Quantity = 4; Item2.UnitPrice = 10; Item3 = Item1 + Item2; Console.WriteLine(Item3.Total); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
94
(Source code: Module06\Module06\OperatorOverloadingExample.cs)
94
Partial Type partial class PartialTest { public void Method2(int i) { number = i; Console.WriteLine("number = " + number); } } partial class PartialTest { private int number; public int Method1(int i) { return i++; } } class PartialExample { static void Main() { PartialTest obj = new PartialTest(); Console.WriteLine(obj.Method1(100).ToString()); obj.Method2(10); Console.ReadLine(); } } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
95
(Source code: Module06\Module06\PartialExample.cs) Partial class means class or structure definition can be split into multiple physical files. And all files are combined when the application is compiled. Can be used when working on a large project, allow multiple programmer to work on it simultaneously. Separate the business logic( user defined code) and system generated code in separate file. For example Windows Form Rules of partial class •All parts require to be define in same namespace. •Each part require to be available at compile time. •Must use the same access specifiers. (public, private,…) •If any single part is defined as abstract, then the whole class is abstract. •If any single part is sealed, then the whole class is sealed. •If any part declare a base type, then the whole class inherits that base class. •Parts can specify different interface, but the whole class implements all interfaces.
95
Static class static class Temperature { public static double CelsiusToFahrenheit(double celsius) { //convert celsius to fahrenheit double Fahrenheit = (celsius * 9 / 5) + 32; return Fahrenheit; } public static double FahrenheitToCelsius(double fahrenheit) { double Celsius = (fahrenheit - 32) * 5 / 9; return Celsius; } }
class StaticExample { static void Main(){ double F, C; F= 100; C = 35; Console.WriteLine("{0} degree Celsius temperature in Fahrenheit: {1:F2}",C, Temperature.CelsiusToFahrenheit(C)); Console.WriteLine("{0} degree Fahrenhit temperature in Celsius: {1:F2}",F, Temperature.FahrenheitToCelsius(F)); Console.ReadLine(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
96
(Source code: Module06\Module06\StaticExample.cs) Static class means class cannot be instantiated. It can contain only static members. And the class is sealed means cannot be inherited.
96
Auto - Implemented Property class Person { public string Name { get; set; } public int Age { get; set; } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
97
(Source code: Module06\Module06\ObjectInitializerExample.cs)
Auto implemented Property Auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessor. Automatic properties allow you to avoid declaring manually a private field and write the get/set accessor -- instead the compiler create the private field and the default get/set accessor. You cannot write any validation for auto implemented properties. Auto-implemented properties must declare both a get and a set accessor. To create a readonly auto-implemented property, give it a private set accessor.
97
Object Initializer class ObjectInitializerExample { static void Main() { Person pobj = new Person { Name = "Bhavana", Age = 18 }; Console.WriteLine("Name = " + pobj.Name); Console.WriteLine("Age = " + pobj.Age); Console.ReadLine(); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
98
(Source code: Module06\Module06\ObjectInitializerExample.cs) Object initializer allow you to include an initializer that specifies the initial values of the members of a newly created object. This enables you to combine declaration and initialization in one step.
98
Module 8. String, StringBuilder, Dateformat • Overview ¾ ¾ ¾ ¾
Useful method of string class. StringBuilder class. Dateformats. Output formats.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
99
99
String Class methods • Various property and methods of string class • Property of string class • Length Gets the number of characters. string s= "welcome"; Console.WriteLine(s.Length);
//7
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
100
(Source code: Module07\StringExample\StringExample\Program.cs) String is an immutable, means data cannot be changed. Whenever we try to change the data of string type, it is returning or creating brand new string object Escape Characters \’ – Single quote \” – double quote \\ - file paths \a – triggers system alert(beep) \n – new line \t – horizontal tab
100
String class methods
(Contd…)
• Comparing Strings The compare method compares two strings and returns an integer value string s = "welcome"; string s1 = "Welcome"; int i; i = string.Compare(s, s1); Console.WriteLine(i); //-1 s = "welcome"; s1 = "welcome"; i = string.Compare(s, s1); Console.WriteLine(i); //0 s = "Welcome"; s1 = "welcome"; i = string.Compare(s, s1); Console.WriteLine(i); //+1 Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
101
(Source code: Module07\StringExample\StringExample\Program.cs)
101
String class methods
(Contd…)
• Concat the concat method concatenate two strings and returns a new string string s = "Hello"; string s1 = "World"; Console.WriteLine(string.Concat(s, s1));
//HelloWorid
• Copy Creates a new instance of string with the same value as a specified string string s = "Hello"; string s1; s1 = string.Copy(s); Console.WriteLine(s1); Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
102
(Source code: Module07\StringExample\StringExample\Program.cs)
102
String class methods
(Contd…)
• Ends with Determines whether the end of the string matches the specified string. Returns boolean result true or false. string s = "Welcome"; Console.WriteLine (s.EndsWith ("me")); // true
• Equals Determines whether two String objects have the same value. Returns Boolean result true or false. string s = "Welcome"; string s1= "welcome"; Console.WriteLine(s.Equals(s1)); //false
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
103
(Source code: Module07\StringExample\StringExample\Program.cs)
103
String class methods
(Contd…)
• IndexOf Return the index of the given String parameter in a Searched String. string s= "Welcome"; int i = s.IndexOf ("e"); //1 Console.WriteLine(i); i = s.IndexOf ("e", 2); //6 Console.WriteLine(i);
• LastIndexOf Returns the index position of the last occurrence of a specified String within the Searched String. string s= "Welcome"; int i = s.LastIndexOf ("e"); //6 Console.WriteLine(i); Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
104
(Source code: Module07\StringExample\StringExample\Program.cs)
104
String class methods
(Contd…)
• PadLeft Right-aligns the String, padding on the left with spaces or a specified character for a specified total length. • PadRight Left-aligns the String, padding on the right with spaces or a specified character, for a specified total length. string s= "Welcome"; Console.WriteLine(s.PadLeft(10, '*')); //***Welcome Console.WriteLine(s.PadRight(10, '*')); //Welcome***
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
105
(Source code: Module07\StringExample\StringExample\Program.cs)
105
String class methods
(Contd…)
• Remove Remove the characters from specified position in a given String. string s= "Welcome"; Console.WriteLine(s.Remove(3, 4)) ; // Wel
• Replace Replaces all occurrences of a specified character or String, with another specified character or string. string s = "Welcome"; Console.WriteLine (s.Replace ("e", "a")); // Walcoma
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
106
(Source code: Module07\StringExample\StringExample\Program.cs)
106
String class methods
(Contd…)
• StartWith Determines whether the beginning of the String matches the specified String parameter. Returns Boolean value true or false. string s = "Welcome"; Console.WriteLine (s.StartsWith ("We")); // true
• Substring Returns part of a string string s = "Welcome"; Console.WriteLine(s.Substring(3)); // come Console.WriteLine(s.Substring(3, 3)); // com
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
107
(Source code: Module07\StringExample\StringExample\Program.cs)
107
String class methods
(Contd…)
• ToLower Returns a String in lowercase • ToUpper Returns a copy of the String in uppercase. string s= "WELCOME"; Console.WriteLine (s.ToLower()); // welcome string s1 = "welcome"; Console.WriteLine (s1.ToUpper()); //WELCOME
• ToString Converts the value to a String type. Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
108
(Source code: Module07\StringExample\StringExample\Program.cs)
108
String class methods
(Contd…)
• Trim Removes all occurrences of a set of specified character from the beginning and end of the String.
• TrimEnd Removes all occurrences of a set of specified character from the end of the String.
• TrimStart Removes all occurrences of a set of specified character from the beginning of the String. String s= "-----------WELCOME-----------"; Console.WriteLine (s); Console.WriteLine (s.Trim('-')); //WELCOME Console.WriteLine (s.TrimEnd('-')); //-----------WELCOME Console.WriteLine (s.TrimStart('-')); //WELCOME---------Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
109
(Source code: Module07\StringExample\StringExample\Program.cs)
109
StringBuilder Class • The StringBuilder class represents a mutable string of characters. static void Main(string[ ] args) { StringBuilder builder = new StringBuilder("Hello wrold. "); Console.WriteLine(builder); builder.Append("This is class test."); Console.WriteLine(builder); builder.Insert(21, "StringBuilder "); Console.WriteLine(builder); builder.Remove(5, 6); Console.WriteLine(builder); builder.Replace(".", "!"); Console.WriteLine(builder); Console.WriteLine("Length = " + builder.Length); Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
110
(Source code: Module07\StringBuilderExample\StringBuilderExample\Program.cs) A string is a sequential collection of Unicode characters used to represent text. It is immutable because once specified the text can not be changed. There are methods to modify string but they will return a new string object with the changes made. These changes will not happen to the existing string object. The StringBuilder class represents a mutable string of characters. It's called mutable because it can be modified once it has been created by using Append, Insert, Remove, and Replace methods. The changes will happen to the existing StringBuilder object The StringBuilder class is defined in the System.Text namespace.
110
Date formats Specifier
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
111
Date formats continued… Specifier
Description
Output
M
Day / Month
r
RFC1123 date
8-Apr 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
112
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
113
Date formats continued… Specifier
Description
yy
2 digit year
yyyy
4 digit year seperator, e.g. {0:hh:mm:ss} seperator, e.g. {0:dd/MM/yyyy}
: /
Output 7 2012 9:08:59 8/4/2012
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
114
Date formats continued… DateTime time = DateTime.Now; string format = "ddd"+" "+"dd-MMM-yyyy"; Console.WriteLine(time.ToString(format)); Console.ReadLine();
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
115
Output formats Character C or c
Description
Examples
Output
Currency
Console.Write("{0:C}", 2.5);
$2.50
D or d
Decimal
Console.Write("{0:C}", -2.5); Console.Write("{0:D5}", 25);
($2.50) 25
E or e F or f
Scientific Fixed-point
Console.Write("{0:E}", 250000); Console.Write("{0:F2}", 25); Console.Write("{0:F0}", 25);
2.50E+05 25 25
G or g N or n
General Number
Console.Write("{0:G}", 2.5); 2.5 Console.Write("{0:N}", 2500000); 2,500,000.00
X or x
Hexadecimal Console.Write("{0:X}", 250); Console.Write("{0:X}", 0xffff);
FA FFFF
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
116
116
Module 9. Collections • Overview ¾ ¾ ¾ ¾
System.Collections Namespace. ArrayList HashTable Collection Initializer
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
117
117
Collection Classes • • • •
A collection is a set of objects. Using collection we can organize and manipulate the objects. Can keep the track of objects. The System.Collection namespace contains the different types of collection classes, such as Stack, Queue, ArrayList, HashTable, etc.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
118
118
ArrayList • • • • •
ArrayList is a collection of element of different types. It increases the size of the storage location as required. It stores the value as object. It represents dynamically sized array of objects. It is contained in the namespace System.Collections;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
119
ArrayList Example Using System.Collection; static void Main(string[ ] args) { ArrayList countryList = new ArrayList(); countryList.Add("India"); Console.WriteLine("Total items = " + countryList.Count.ToString()); for (int i = 0; i < countryList.Count; i++) { Console.WriteLine(countryList[i].ToString()); } //insert value countryList.Insert(1, "France"); Console.WriteLine("\n-------print specific item form the arraylist object-------\n"); Console.WriteLine(countryList[2].ToString()); }
//reverse countryList.Reverse(); //sort countryList.Sort(); //RemoveAt() countryList.RemoveAt(2); //Clear() countryList.Clear(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
120
(Source code: Module07\CollectionExample\CollectionExample\ArrayListExample.cs) ArrayList is the collection of elements of different type Elements in this collection can be accessed using an integer index. Indexes in this collection are zerobased.
120
HashTable • HashTable object contains Items in key and value pair. • Keys are used as indexes. • Values can be searched by using keys.
MH
Maharashtra
GA
Goa
GJ
Gujrat
TN
Tamilnadu
AP
Andra pradesh
RJ
Rajasthan
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
121
HashTable Example static void Main() { Hashtable hashlist = new Hashtable(); hashlist.Add("txt", "notepad.exe"); hashlist.Add("bmp", "paint.exe"); hashlist.Add("rtf", "wrodpad.exe"); // The Add method throws an exception if the new key is already in the hash table. try { hashlist.Add("txt", "winword.exe"); } catch { Console.WriteLine("An element with Key txt already exists."); }
Console.WriteLine("\n------------------------------\n"); //DictionaryEntry - Defines a dictionary key/value pair that can be set or retrieved. foreach (DictionaryEntry de in hashlist) { Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value); } Console.WriteLine("\n------------------------------\n"); //Printing the value of the specific key Console.WriteLine("For key = rtf, value = {0}.", hashlist["rtf"]); Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
122
(Source code: Module07\CollectionExample\CollectionExample\HashTableExample.cs) HashTable represents a collection of key/value pairs that are organized based on the hash code of the key.
122
Stack • Stack represents last-in-first-out (LIFO) . • You may assume kitchen dish stack. You can pull out a top most dish which is kept in stack very last. • It simply consists of non-generic collection of objects. pop
push
5 4 3 2 1 0
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
123
Stack Example static void Main() { Stack stackobj = new Stack(); stackobj.Push("Hello"); stackobj.Push("Stack"); stackobj.Push("class"); stackobj.Push("example"); Console.WriteLine("Count = " + stackobj.Count.ToString()); Console.WriteLine("\n------------------\n"); foreach (Object obj in stackobj) { Console.WriteLine(obj.ToString()); }
Console.WriteLine("\n---------Top Element- peek method---------\n"); Console.WriteLine(stackobj.Peek()); Console.WriteLine("\n---------Top Element- pop method---------\n"); Console.WriteLine(stackobj.Pop()); Console.WriteLine("\n---------count---------\n"); Console.WriteLine("Count = " + stackobj.Count.ToString()); foreach (Object obj in stackobj) { Console.WriteLine(obj.ToString()); } Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
124
124
Queue • Queue represents first-in-first-out (FIFO) . • We can Enqueue (add) items in queue. • We can Dequeue (remove) items from queue.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
125
Queue Class static void Main() { Queue queueobj = new Queue(); queueobj.Enqueue("Hello"); queueobj.Enqueue("Queue"); queueobj.Enqueue("class"); queueobj.Enqueue("example"); Console.WriteLine("Count = " + queueobj.Count.ToString()); foreach (Object obj in queueobj) { Console.WriteLine(obj.ToString()); } Console.WriteLine("\n---------Top Element- ---------\n“, queueobj.Dequeue()); Console.WriteLine("\n---------count----------\n“, queueobj.Count.ToString()); foreach (Object obj in queueobj) { Console.WriteLine(obj.ToString()); } Console.ReadLine(); } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
126
(Source code: Module07\CollectionExample\CollectionExample\QueueExample.cs)
126
Linked List • A Linked list is a data structure consisting of group nodes which together represents a sequence.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
127
Collection Initializer • Able to give values to collections in a concise and compact manner static void Main() { ArrayList countryList = new ArrayList { "India", "Usa", "Japan" }; for (int i = 0; i < countryList.Count; i++) { Console.WriteLine(countryList[i].ToString()); } Console.ReadLine(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
128
(Source code: Module07\CollectionExample\CollectionExample\CollectionInitializerExample.cs)
128
Module 10. Generics and Nullable Types • Overview ¾ ¾ ¾ ¾
Limitations of Collection Classes Understanding Generics Advantages of generics over collection Nullable Types
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
129
129
Limitation of Collection Classes class Person { for (int i = 0; i < list.Count; i++) { list[i]. //error 1 string name, address; public Person(string name, string address) { this.name = name; this.address = address; } //error 2 public void Display(){ ((Person)list[i]).Display(); } Console.WriteLine ("Name = " + name); Console.WriteLine("Address = " + address); } } static void Main(string[] args) { ArrayList list = new ArrayList(); //error 3 list.Add(new Person("Bhavana", "Mumbai")); int temp =int.Parse( list[0].ToString()); } list.Add(new Person("Vishal", "Mumbai")); list.Add("Krishna");
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
130
Whenever we store any data to the collection class object they are always maintained as Object type. Because of this it is possible that we can store different type of data in collection object. This feature one way is advantageous that we can store different types of value in collection, but this feature also have some disadvantages Error 1 We are storing different type of values in the ArrayList object We have added the object of Person class which is user defined type. While retrieving the members of the list object we typed list[i]. Which gives public member of the Object class only and it will not give the public member which you have defined in Person class. Error 2 You require to explicitly typecast the member. After typecasting it will give the public member of the Person class. But it will give an error at the run time when in the for loop when we try to retrieve the third item which is not of the Person type. Error 3 At the compilation time it allows us to convent any member of the ArrayList to int type or any other type. But at the run time when it require to assign the value of user defined type to an int type it will give an error.
130
Why Generics? • In the earlier code example two major issues were faced as follows: ¾ Boxing and unboxing overhead : Boxing and unboxing operations lead to performance overhead since it involves dynamic memory allocation and runtime type check. ¾ No strong type data at compilation time : The earlier code is technically correct. Error will be not be thrown at compile time. But when the code is executed it will throw an exception InvalidCastException.
• Generics has solution for these limitations.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
131
Generics • Type Safety -- Generic types enforce type compliance at compile-time, and not run-time (as in the case of using Object). This reduces the chances of data-type conflict during run-time • Performance -- The data types to be used in a Generic class are determined at compile-time, hence there is no need to perform type casting during run-time, which is a computationally costly process. • Code reuse -- Since you only need to write the class once and customize it to use with the various data types, there is a substantial amount of code-reuse.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
132
Comparison between Generic, Collection and Array •To define an array, we have to give the fix size. The size 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
Generics List Collection static void Main() { List liststr = new List(); 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 listperson = new List(); listperson.Add(new Person("Bhavana", "Mumbai")); listperson.Add(new Person("Pankaj", "Mumbai")); for (int i = 0; i < listperson.Count; i++) { listperson[i].Display(); } Console.ReadLine(); } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
133
133
Generic Dictionary collection class Customers { …. public Customers(string Name, string Location) { ….. } public int CustId { get ; } public string CustName { get; set; } public string CustLocation {get; set; } public void displayCust() { … } } static void Main(string[] args) { Dictionary customerDictionary = new Dictionary(); Customers customer3 = new Customers("Anju", "Borivali"); Customers customer4 = new Customers(“Amit", "Kalyan"); foreach (KeyValuePair custKeyValue in customerDictionary) { Console.WriteLine( custKeyValue.Key, custKeyValue.Value.CustName, custKeyValue.Value.CustLocation); } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
134
Generic Dictionary collection stores information into key/value pair. There is a non generic collection HashTable which also stores the information into key/value pair. But it stores data of type object.
134
Creating our own Generic Classes class GenericClass { T 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 obj1 = new UserdefinedGeneric("Trupti", “Hello"); obj1.Swap(); UserdefinedGeneric obj2 = new UserdefinedGeneric(“25", “50"); obj2.Swap();
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
135
Generic is a technique with which you can delay the specification of the type of one or more programming elements in a class or a method ,until the time of the usage of that class or method. With generics instead of specifying the data type of the parameters, you define labels, which can later be replaced by the data type that the user specifies at the time of using the generic method or class Generic is a type parameter, which allows to design a class or method where the value of the type is specified at the time of instantiating class or usage of a method.
135
Nullable Type static void Main() { int number1 = 10; Nullable number2 = null; int? number3 = null; try { Console.WriteLine("number1 = " + number1.ToString()); Console.WriteLine("number2 = " + number2.Value); Console.WriteLine("number3 = " + number3.ToString()); Console.WriteLine("\n------------------------------\n"); if (number2.HasValue == true) Console.WriteLine("number2 = " + number2.Value); else Console.WriteLine("Null value"); Console.WriteLine("\n------arithmatic operation with nullable type--------\n"); Console.WriteLine(number1 + number2.GetValueOrDefault(0)); number2 = 100; Console.WriteLine(number1 + number2.GetValueOrDefault(0)); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
136
Nullable type One of the primary differences between value types such as int or structures and reference types such as string is that reference types support a null value. That is to say, a reference type variable can contain the value null, which means that the variable doesn't actually refer to a value. In contrast, a value type variable always contains a value. An int variable always contains a value, even if that number is zero. Nullable type adds nullability to any value type.
136
Module 11. Windows Form - I • Overview ¾ ¾ ¾ ¾ ¾
Introduction to Window Forms IDE Creating forms with controls Responding to form events Using basic controls (e.g. Label, TextBox, Button, etc.) Anchor and Dock Properties
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
137
137
Visual Studio IDE ToolBox
Form Design View
Solution Explorer
Property Window
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
138
GUI application helps us to create user interface. A well designed interface makes the application more users friendly. In a windows based application, user interface is accomplished with windows Forms and controls. Windows form is a base container for user interface. A control is an object that can be drawn on to the Form to enable or enhance user interaction with the application. Examples of these control, TextBox, Button, Label, Radio Button etc. All these Windows Controls are based on the Control class, which is the base class for all controls. To create GUI application, Start Visual Studio .Net, from Project Window select Template type as Windows Application. System will open visual studio .net IDE which include Form Designer, Solution Explorer, Property window, toolbox etc.
138
Introduction to Controls Label
TextBox MultiLine TextBox
RadioButton ComboBox
ListBox
Button
CheckBox
GroupBox
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
139
Form is a base unit on which we can place the controls. Every controls including Form will have properties, methods and events. Forms properties Text – Value to be display in the title bar WindowState – Initial visual state of a form
139
Label Example • Display dynamic time.
private void timer1_Tick(object sender, EventArgs e) { lbldatetime.Text = DateTime.Now.ToString(); } private void DynamicTime_Load(object sender, EventArgs e) { lbldatetime.Text = DateTime.Now.ToString(); } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
140
(Source code: Module10\WinForm1\WinForm1\DynamicTime.cs) Label Properties Name – lbldatetime Text – empty Timer control from the component tab Properties Enable – True Interval – 1000
140
MessageBox Class • Use to display informative message to the user and can take user confirmation. •
MessageBox.Show("Welcome to GUI Application");
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
141
(Source code: Module10\WinForm1\WinForm1\Form1.cs) Static method MessageBox.show() is used to accept the message, title, buttons and icon as parameters. Only message is the compulsory parameter.
141
Login Form Example
public partial class LoginForm : Form { int count = 0; public LoginForm() { InitializeComponent(); } private void btncancel_Click(object sender, EventArgs e) { this.Close(); } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
142
(Source code: Module10\WinForm1\WinForm1\LoginForm.cs) Design a form which accept user name and password. Check username as “pragati” and password as “admin”. If username and password are correct then show the Win Form welcome else display the proper error message in the message box. Give three chance to write the correct username and password else display appropriate message and close the application. Label Display static text from providing information. Properties Name - Control Name Text – Value to be displayed AutoSize – Allow automatic resizing according to the txt length
142
Login Form Example
(Contd…)
private void btnsubmit_Click(object sender, EventArgs e) { if (txtusername.Text == "pragati" && txtpwd.Text == "admin") { Welcome frm = new Welcome(); this.Hide(); frm.Show(); } else { MessageBox.Show("Invalid username or password. Please provide the correct value", "Login"); count = count + 1; txtusername.Clear(); txtpwd.Clear(); txtusername.Focus(); } if (count == 3) { MessageBox.Show("Sorry! Please try again", "Login"); this.Close(); } } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
143
(Source code: Module10\WinForm1\WinForm1\LoginForm.cs) TextBox Display text to the user and accept the input from the user. Properties Name – Control Name Text – Display or accept the text Multiline – convert single line textbox into multi line textbox PasswordChar – set a character that acts as a placeholder for the characters. Button Perform an action Properties Name - Control name Text – Value to be displayed AutoSize – Controls automatically size itself to fit its content. Image – Image to be displayed
143
Welcome Form
private void btnclose_Click(object sender, EventArgs e) { Application.Exit(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
144
(Source code: Module10\WinForm1\WinForm1\Welcome.cs) This.Close() will close the individual form while Application.Exit() method will close all the form which are loaded in memory for that application.
144
ComboBox Example
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
145
(Source code: Module10\WinForm1\WinForm1\ComboBoxExample.cs) Select your qualification and computer skills from the list given below. Select the country from the combo dropdown. If users want he/she can add the country name in the combo dropdown. While adding the new data keep check that no duplication allowed. Same time if user wants he/she can delete the country name from the list. ComboBox Display a drop down list of items, from which user can select any one item. Properties Name – Control name Text – Selected text from the list Items – Collection of the items to be displayed in drop down DropdownStyle – Appearance and functionality of combo box Add some country name in combo box at design time by using Items property. We can also add data dynamically.
145
ComboBox Example
(Contd…)
private void btnadd_Click(object sender, EventArgs e) { int i, flag =0; for( i=0;i Add New Item ¾ From left hand side select “General” option and from the write hand side select “Application Configuration File”. ¾ Do not change the name of this file. ¾ Click on “Add” button to add the file in your project.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
189
•Config is a XML file. •if you have to change server name ,database name etc in connection string then you have to make changes in only .config file and not on each and every Forms. •you can also add more than one connection string in config file. •To access the connection string from the config file, first you have to add the reference to the System.Configuration namespace in your project. •use the System.Configuration namespace in every C# files, where you want to use the connection string from the config file.
189
Configuring Connection String in .config File (contd…) • Write the connection string in the confilg file within connectionStrings element
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
190
190
Using Connection String in C# file using System.Data.SqlClient; using System.Configuration; string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr);
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
191
191
Display Data using Connected Architecture
string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr); string sql = "select * from categories"; SqlCommand cmd = new SqlCommand(sql, conn); conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); DataTable table = new DataTable(); table.Load(reader); conn.Close(); dataGridView1.DataSource = table; Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
192
(Source code: Module12\DatabaseApplication\DatabaseApplication\02Connected.cs)
192
Apply Filter on DataSet
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
193
(Source code: Module12\DatabaseApplication\DatabaseApplication\03Filter.cs) DataSet data is the in memory data. After we retrive the data in dataset, we can apply the filter on it and display the specific data to the users. For this there are 2 methods 1] Select() method of the DataTable class and 2] DataView class object with RowFilter Property
193
Apply Filter on DataSet
(Contd…)
• Declare the 2 class level variable int catid = 0; DataSet ds;
• Form Load Event string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr); SqlDataAdapter adp = new SqlDataAdapter("select * from Categories", conn); ds = new DataSet(); adp.Fill(ds, "Categories"); adp = new SqlDataAdapter("Select * from Products", conn); adp.Fill(ds, "Products"); lstcategory.DisplayMember = ds.Tables["Categories"].Columns["CategoryName"].ToString(); lstcategory.ValueMember = ds.Tables["Categories"].Columns["CategoryID"].ToString(); lstcategory.DataSource = ds.Tables["Categories"]; Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
194
(Source code: Module12\DatabaseApplication\DatabaseApplication\03Filter.cs)
194
Apply Filter on DataSet •
(Contd…)
ListBox SelectedIndexChanged Event
if (lstcategory.SelectedIndex >0 && lstcategory.SelectedValue != null) { catid = (int) lstcategory.SelectedValue ; }
•
View Button Click Event
DataView view = ds.Tables["Products"].DefaultView; view.RowFilter="categoryid=" + catid; dataGridView1.DataSource = view;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
195
195
Apply Filter on DataSet – DataTable Select() Method • select button click event lstselect.Items.Clear(); DataRow[] row = ds.Tables["Products"].Select("categoryid=" + catid); if (row.Length > 0) { for (int i = 0; i < row.Length; i++) { lstselect.Items.Add(row[i]["productName"]); } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
196
(Source code: Module12\DatabaseApplication\DatabaseApplication\03Filter.cs)
196
Insert data using Connected Architecture
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
197
197
Insert data using Connected Architecture Code string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr); string sql = "Insert into products (productname, unitprice) values (@pname, @price)"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@pname", txtpname.Text); cmd.Parameters.AddWithValue("price", decimal.Parse(txtup.Text)); conn.Open(); int feedback = cmd.ExecuteNonQuery(); conn.Close(); MessageBox.Show(feedback + " record inserted"); cmd.CommandText = "select productid, productname, unitprice from products where productid >77"; conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); DataTable table = new DataTable(); table.Load(reader); conn.Close(); dataGridView1.DataSource = table; Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
198
198
Stored Procedure
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
199
(Source code: Module12\DatabaseApplication\DatabaseApplication\08spin.cs)
199
Stored Procedure
(Contd…)
• Write the following stored procedure in the MS SQL Server create proc InsertData (@prodname varchar(20), @unitprice numeric(10,2)) as begin transaction insert into products (productname, unitprice) values (@prodname, @unitprice) Commit transaction
• Code for the Insert Button Click string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr);
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
200
(Source code: Module12\DatabaseApplication\DatabaseApplication\08spin.cs)
200
Stored Procedure
(Contd…)
SqlCommand cmd = new SqlCommand ("Insertdata", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@prodname", txtpname.Text ); cmd.Parameters.AddWithValue("@unitprice", txtup.Text); conn.Open(); int feedback = cmd.ExecuteNonQuery(); conn.Close(); MessageBox.Show(feedback + " record inserted"); txtpname.Clear(); txtup.Clear(); conn.Open(); cmd = new SqlCommand("select * from products where productid>77",conn); SqlDataReader reader = cmd.ExecuteReader(); DataTable table = new DataTable(); table.Load(reader); conn.Close(); dataGridView1.DataSource = table; Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
201
(Source code: Module12\DatabaseApplication\DatabaseApplication\08spin.cs)
201
CommandBuilder for Update Data in Disconnected Architecture
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
202
(Source code: Module12\DatabaseApplication\DatabaseApplication\05CommandBuilder.cs) CommandBuilder - Automatically generates single-table commands that are used to
reconcile changes made to a DataSet with the associated database. Minimum requirement to pass the select command (select query) with command builder object. When associated with a DataAdapter, the DbCommandBuilder automatically generates the InsertCommand, UpdateCommand, and DeleteCommand properties of the DataAdapter The SelectCommand must also return at least one primary key or unique column. If none are present, an InvalidOperation exception is generated, and the commands are not generated.
202
Code for update data using CommandBuilder • Declare Class level members SqlConnection conn; SqlDataAdapter adp; SqlCommandBuilder cb; DataTable table;
• Write the following code in load event conn = new SqlConnection(connstr); string sql = "select * from products"; adp = new SqlDataAdapter(sql, conn); cb = new SqlCommandBuilder(adp); table = new DataTable(); adp.Fill(table); DataColumn[] pk = new DataColumn [1]; pk[0] = table.Columns["productid"]; table.PrimaryKey = pk; dataGridView1.DataSource = table; Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
203
(Source code: Module12\DatabaseApplication\DatabaseApplication\05CommandBuilder.cs)
203
Code for update data using CommandBuilder • Write the following code for the Update button click event try { table = (DataTable )dataGridView1.DataSource; adp.Update(table ); MessageBox.Show("Data modified in the Database"); } catch (Exception ex) { MessageBox.Show(ex.Message); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
204
(Source code: Module12\DatabaseApplication\DatabaseApplication\05CommandBuilder.cs)
204
Data Navigation
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
205
(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)
205
Data Navigation
(Contd…)
• Declare class level member SqlConnection conn; SqlDataAdapter adp; SqlCommandBuilder cb; DataSet ds; BindingManagerBase bm; int pid, flag; void Display() { txtpid.Text = ds.Tables["products"].Rows[bm.Position]["productid"].ToString(); txtpname.Text = ds.Tables["products"].Rows[bm.Position]["productname"].ToString(); txtup.Text = ds.Tables["products"].Rows[bm.Position]["unitprice"].ToString(); lblrecno.Text = bm.Position + 1 + " / " + bm.Count; } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
206
(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)
206
Data Navigation
(Contd…)
• Code for load event string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; conn = new SqlConnection(connstr); string sql = "select productid, productname,unitprice from products"; adp = new SqlDataAdapter(sql, conn); cb = new SqlCommandBuilder(adp); ds = new DataSet(); adp.Fill(ds, "products"); DataColumn[] pk = new DataColumn[1]; pk[0] = ds.Tables["products"].Columns["productid"]; ds.Tables["products"].PrimaryKey = pk; bm = this.BindingContext[ds, "products"]; bm.Position = 0; Display();
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
207
(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)
207
Data Navigation
(Contd…)
• First Button bm.Position = 0 Display()
• Next Button bm.Position += 1 Display()
• Prior Button bm.Position -= 1 Display()
• Last Button bm.Position = bm.Count - 1 Display()
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
208
(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)
208
Data Navigation
(Contd…)
• Add Button txtpid.Clear(); txtpname.Clear(); txtup.Clear(); flag = 1; btnsave.Enabled = true;
• Edit Button pid =int.Parse ( txtpid.Text); flag = 2; btnsave.Enabled = true;
• Delete Button DialogResult result = MessageBox.Show("Are you sure, you want to delete the record?", "Delete Box", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.Yes) { MessageBox.Show("Click save button to delete the record"); pid = int.Parse(txtpid.Text); flag = 3; btnsave.Enabled = true; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
209
(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)
209
Data Navigation
(Contd…)
• Save Button DataRow dr; if (flag == 1) { //Add dr = ds.Tables["products"].NewRow(); dr["productid"] = 0; dr["productname"] = txtpname.Text; dr["unitprice"] = decimal.Parse(txtup.Text); ds.Tables["products"].Rows.Add(dr); } else if (flag == 2) { //Edit dr = ds.Tables["products"].Rows.Find(pid); if (dr != null) { dr.BeginEdit(); dr["productid"] = pid; dr["productname"] = txtpname.Text; dr["unitprice"] = decimal.Parse(txtup.Text); dr.EndEdit(); } }
else if (flag == 3) { //Delete dr = 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;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
210
(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)
210
Data Navigation
(Contd…)
• Concurrency Check catch (Exception ex) { MessageBox.Show(ex.Message); if (ds.HasErrors) { foreach(DataTable table in ds.Tables) { if (table.HasErrors) { foreach (DataRow row in table.Rows) { if (row.HasErrors) { MessageBox.Show("Table : " + table.TableName + "\n Row : " + row["productid"].ToString() + "\n" + row.RowError, "Error Box"); row.ClearErrors(); row.RejectChanges(); } } } } } Pragati Software Pvt. Ltd., 312, }Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 211
(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)
211
Data Navigation
(Contd…)
• Exit Button Application.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"); else MessageBox.Show("Record not found", "Display Box");
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
212
(Source code: Module12\DatabaseApplication\DatabaseApplication\06DataNavigation.cs)
212
Data Navigation
(Contd…)
public _06FindProduct() { InitializeComponent(); } public int prodid; private void btnsubmit_Click(object sender, EventArgs e) { if (txtprodid.Text == "") prodid = 0; else prodid = int.Parse (txtprodid.Text); this.Close(); } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
213
(Source code: Module12\DatabaseApplication\DatabaseApplication\06FindProduct.cs)
213
Master Detail Relationship
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
214
(Source code: Module12\DatabaseApplication\DatabaseApplication\07MasterDetail.cs)
214
Master Detail Relationship
(Contd…)
Class level declaration SqlConnection 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; } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
215
(Source code: Module12\DatabaseApplication\DatabaseApplication\07MasterDetail.cs)
215
Master Detail Relationship
(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(); Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
216
(Source code: Module12\DatabaseApplication\DatabaseApplication\07MasterDetail.cs)
216
Master Detail Relationship
(Contd…)
• First Button bm.Position = 0; Display();
• Previous Button bm.Position = bm.Position + 1; Display();
• Next Button bm.Position = bm.Position + 1; Display();
• Last Button bm.Position = bm.Count - 1; Display();
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
217
(Source code: Module12\DatabaseApplication\DatabaseApplication\07MasterDetail.cs)
217
Stored Procedure with Out Parameter
• Write the following stored procedure in the MS SQL Server create proc TotalProduct (@catid int, @count int output) as select @count=count(productid) from products where Categoryid = @catid
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
218
(Source code: Module12\DatabaseApplication\DatabaseApplication\09spout.cs)
218
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"];
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
219
(Source code: Module12\DatabaseApplication\DatabaseApplication\09spout.cs)
219
Stored Procedure with Out Parameter
(Contd…)
• Type the following code in the ListBox SelectedIndexChanged 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(); Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
220
(Source code: Module12\DatabaseApplication\DatabaseApplication\09spout.cs)
220
Transaction
int result1, result2; string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr); conn.Open();
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
221
(Source code: Module12\DatabaseApplication\DatabaseApplication\10Transaction.cs)
221
Transaction
(Contd…)
cmd = conn.CreateCommand(); cmd.Connection = conn; cmd.CommandText = "insert into products (productname, unitprice) values ('Ipod',25000)"; MyTransaction = conn.BeginTransaction(); cmd.Transaction = MyTransaction; result1 = cmd.ExecuteNonQuery(); cmd.CommandText = "update products set unitprice=0 where productid=80"; result2 = cmd.ExecuteNonQuery(); if (result1 > 0 && result2 > 0) { MyTransaction.Commit(); MessageBox.Show("Transaction saved, Data modified"); } else { MyTransaction.Rollback(); MessageBox.Show("Transaction Rollback"); } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
222
(Source code: Module12\DatabaseApplication\DatabaseApplication\10Transaction.cs)
222
DataRelation
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
223
(Source code: Module12\DatabaseApplication\DatabaseApplication\11DataRelation.cs)
223
DataRelation
(Contd…)
• Form Load Event decimal total; string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr); SqlDataAdapter adpcategory = new SqlDataAdapter("select * from Categories", conn); SqlDataAdapter adpprod = new SqlDataAdapter("select * from products", conn); DataSet ds = new DataSet(); adpcategory.Fill(ds, "categories"); adpprod.Fill(ds, "products"); ds.Relations.Add("category", ds.Tables["categories"].Columns["categoryid"], ds.Tables["products"].Columns["categoryid"]);
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
224
(Source code: Module12\DatabaseApplication\DatabaseApplication\11DataRelation.cs)
224
DataRelation
(Contd…)
foreach (DataRow catrow in ds.Tables["categories"].Rows) { total = 0; lstrelation.Items.Add("CategoryID = " + catrow["categoryid"] + " " + "Category Name = " + catrow["categoryName"]); lstrelation.Items.Add("-------------------------------"); foreach (DataRow prodrow in catrow.GetChildRows("category")) { lstrelation.Items.Add("Productname = " + prodrow["productname"] + " " + "unitPrice = " + prodrow["unitprice"]); total += decimal.Parse(prodrow["unitprice"].ToString()); } lstrelation.Items.Add("-------------------------------------------------"); lstrelation.Items.Add("Total = " + total); lstrelation.Items.Add("-------------------------------------------------"); } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
225
(Source code: Module12\DatabaseApplication\DatabaseApplication\11DataRelation.cs)
225
Module 14. Data Bound Control • Overview ¾ Populating DataGridView Control using Wizard ¾ Populating ListBox Control using Wizard ¾ Binding Navigator
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
226
226
Populating DataGridView Control using Wizard • Add DataGridView Control from the data menu • Click on the smart tag • Click on Choose Data Source Drop Down arrow
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
227
(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)
227
Populating DataGridView Control using Wizard
(Contd…)
• Click on Add Project Data Source
• Select Database and click Next option
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
228
(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)
228
Populating DataGridView Control using Wizard
(Contd…)
• Click New Connection Button and specify the name of the SQL Server, Authentication and Database. • Click on Test Connection button. • If you get the message Test Connection Succeeded then click on OK button.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
229
(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)
229
Populating DataGridView Control using Wizard
(Contd…)
• Save the connection String in Application Configuration file • Click Next Button
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
230
(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)
230
Populating DataGridView Control using Wizard
(Contd…)
• Select “Categories” table from the list and click “Finish” button
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
231
(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)
231
Populating DataGridView Control using Wizard
(Contd…)
• Display the data in grid
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
232
(Source code: Module 13\DataBoundControl\DataBoundControl\01DataGridControl.cs)
232
Populating ListBox Control using Wizard • Add ListBox from the Common Controls • Click on smart option • Check “Use data bound items”
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
233
(Source code: Module 13\DataBoundControl\DataBoundControl\02ListBoxControl.cs)
233
Populating ListBox using Wizard (Contd…) • Select Data Source option • Specify Display Member and Value Member options
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
234
(Source code: Module 13\DataBoundControl\DataBoundControl\02ListBoxControl.cs)
234
Populating ListBox using Wizard (Contd…) • Add the Label and name the label as lblcatid. • Write the following code in the listbox SelectedIndexChanged event private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { if (listBox1.SelectedValue != null) lblcatid.Text = listBox1.SelectedValue.ToString(); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
235
(Source code: Module 13\DataBoundControl\DataBoundControl\02ListBoxControl.cs)
235
Populating ListBox using Wizard (Contd…) • Run the Form • Display Member property is used for display the column in the ListBox. • When we select the option from the ListBox it will display the Value Member.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
236
(Source code: Module 13\DataBoundControl\DataBoundControl\02ListBoxControl.cs)
236
Binding Navigator • • • • •
Add Binding Source Control from the Data Tab. Go to Property window and specify DataSource Property. Add 2 Labels and 2 Textboxes Add Binding Navigator Control from Data Tab. Go to Property window and specify BindingSource Property as BindingSource1 • DataMember Property as Categories • Select the txtcatid TextBox and assign the DataBinding Text property as Categoryid • Select the txtcatname TextBox and assign the DataBinding Text property as CategoryName
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
237
(Source code: Module 13\DataBoundControl\DataBoundControl\03Navigator.cs)
237
Binding Navigator
(Contd…)
• Run and Test the Program
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
238
(Source code: Module 13\DataBoundControl\DataBoundControl\03Navigator.cs)
238
Module 15. DotNet Framework & Assembly • Overview ¾ ¾ ¾ ¾ ¾ ¾ ¾ ¾
.Net Framework Assembly Type of Assembly Create Class Library Create Test Application Creating Shared Assembly Viewing the Manifest File Process of compiling and executing managed code
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
239
239
Assembly
Assembly Manifest Module Metadata MSIL Types
Types
Types
Types
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
240
An assembly is a single deployable unit that contains all the information about the implementation of classes, structure, interfaces, enum and delegates. An assembly stores all the information about itself. The information is called metadata, which includes the name and version number of the assembly, security information, information about the dependencies, and a list of the files that constitute the assembly. Assembly is a logical EXE or DLL. An assembly consists of manifest, module and type. Manifest – is the descriptor of the assembly. Module – is either a DLL or EXE. Type – can be a class, interface, structure, enum, delegates that contains data and logic.
240
Types of Assembly • Private Assembly • Shared Assembly
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
241
Private Assembly A private assembly is deployed and used exclusively with a single name. A private assembly is referenced by its simple name The simple name is defined in the assembly’s metadata. When you refer to private assembly , it get copied into the project which is referring to this assembly. Shared Assembly Shared assembly is also known as Strong Named Assembly It gives support to versioning and security of assembly Strong named assembly will have unique identification When you refer to shared assembly , it will not create the local copy of this assembly. It always refer to the location from where you have included the reference. Identity consist of •Simple Text Name •Version Number •Culture Information •Public Key •Digital Signature
241
Creating Shared Assembly
(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.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
242
242
Viewing Manifest File
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
243
Intermediate Language Disassembler (ILDASM) ILDASM is a tool for viewing the contents of assembly. Each assembly has a single manifest file which contains metadata. Go to Microsoft Visual Studio command Prompt and type ILDASM or go to start – program – Microsoft Windows SDK V6.OA – Tools – IL Disassembler Select File menu Click Open Select exe or dll file for which you want to see IL code
243
Module 16. Delegate • Overview ¾ Understanding Delegate ¾ SingleCast Delegate ¾ MultiCast Delegate ¾ Anonymous Method
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
244
244
Understanding Delegate • Declaring and invoking Delegate involves 4 steps ¾ Delegate declaration delegate returntype Name ([parameters]) ¾ Declare Delegate method Returntype Name ([parameters]) ¾ Delegate instantiation delegatename instancename = new delegatename(methodname) ¾ Delegate invocation Instancename(parameters value)
• Use of Delegate ¾ Events ¾ Threads ¾ Asynchronous Application Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
245
Features of Delegate •Delegate is one of the type which we can declare within the Namespace. •Delegates are termed as function pointers. •Delegates contain the address of the method that is to be executed. •Signature of delegate and method signature should be identical. •Delegates act as middle layer to communicate the event occurred to the system. •There are two types of delegates Singlecast and multicast. ¾Singlecase delegate can hold and invoke single method ¾Multicast delegate can hold and invoke multiple methods.
245
SingleCast Delegate //Declare Delegate delegate void DelegateString(string s); delegate int DelegateCube(int number); class _01SingleCastDelegate { //method public static void Greet(string Name) { Console.WriteLine("Hello..." + Name); } //method public static void Wish(string Name) { int Hour = System.DateTime.Now.Hour; if (Hour >= 5 && Hour < 12) Console.WriteLine("Good Morning..." + Name); else if (Hour >= 12 && Hour < 16) Console.WriteLine("Good Afternoon..." + Name); else if (Hour >= 16 && Hour < 22) Console.WriteLine("Good Evening..." + Name); else Console.WriteLine("Good Night..." + Name); } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
246
(Source code: Module 15\DelegateExample\DelegateExample\01SingleCastDelegate.cs)
246
SingleCast Delegate
(Contd…)
//method public static int NumberCube(int number) { return number * number * number; } public static void Main() { //instantiate delegate DelegateString delegateobj1 = new DelegateString(Greet); DelegateString delegateobj2 = new DelegateString(Wish ); //Invoke delegate delegateobj1("Bhavana"); Console.WriteLine("-----------------------------------"); delegateobj2("Bhavana"); Console.WriteLine("====================================="); DelegateCube delegatecubeobj = new DelegateCube(NumberCube); Console.WriteLine("Cube of Number 3 = " + delegatecubeobj(3)); Console.ReadLine(); } } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
247
(Source code: Module 15\DelegateExample\DelegateExample\01SingleCastDelegate.cs)
247
MultiCast Delegate delegate void DelegateMultiCast (int value1, int value2); class _02MultiCastDelegate { public static void AddNumbers(int number1, int number2) { int total = number1 + number2; Console.WriteLine("Addition of 2 numbers {0}, {1} = {2}", number1, number2,total); } public static void MultiplyNumbers(int number1, int number2) { int total = number1 * number2; Console.WriteLine("Multiplication of 2 numbers {0}, {1} = {2}", number1, number2, total); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
248
(Source code: Module 15\DelegateExample\DelegateExample\02MultiCastDelegate.cs) Using multicast delegate you can call more then one method through single delegate instance. It will successively call each method in order. The delegate signature should return a void, otherwise, you would only get the result of the last invoked method. If one of the method invoked by the delegate throws an exception, the execution stops.
248
MultiCast Delegate
(Contd…)
public static void Power(int number1, int number2) { int total=1; for (int i = 1; i System.DateTime.Now.DayOfYear) { intAge -= 1; } } return intAge; } } } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
335
(Source code: Appendix Serialization\Serialization\Serialization\02BinarySerialization.cs\Person.cs)
Binary Serialization Binary Formatter class is available in the namespace System.Runtime.Serialization.Formatters.Binary
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
(Source code: Appendix Serialization\Serialization\Serialization\02BinarySerialization.cs)
336
Binary Serialization Write Object • Add the namespace using System.Runtime.Serialization.Formatters.Binary; using System.IO; Person p = new Person("Bhavana", Convert.ToDateTime("01/01/2001")); FileStream stream = new FileStream("c:\\Person.txt", FileMode.Create ); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, p); stream.Close(); richTextBox1.Text = "Data saved in a file";
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
(Source code: Appendix Serialization\Serialization\Serialization\02BinarySerialization.cs)
337
Binary Serialization Read Object richTextBox1.Clear(); FileStream stream = new FileStream("c:\\Person.txt", FileMode.Open); BinaryFormatter formatter = new BinaryFormatter(); Person p =(Person) formatter.Deserialize(stream); stream.Close(); richTextBox1.AppendText("Name = " + p.Name + "\nAge = " + p.Age); richTextBox1.AppendText("\nBirthdate = " + p.Birthdate);
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
(Source code: Appendix Serialization\Serialization\Serialization\02BinarySerialization.cs)
338
Read & Write Multiple Object List personlist = new List(); 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 TotalPersons = (List)formatter.Deserialize(stream1); stream1.Close(); foreach (Person p in TotalPersons) { richTextBox1.AppendText(p.Name + " " + p.Birthdate + " " + p.Age.ToString() + "\n"); } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
(Source code: Appendix Serialization\Serialization\Serialization\02BinarySerialization.cs)
339
SOAP Serialization Add reference for the namespace System.Runtime.Serialization.Formatters.Soap
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
(Source code: Appendix Serialization\Serialization\Serialization\03SOAPSerialization.cs)
340
SOAP Serialization Write Object Person p = new Person("Bhavana", Convert.ToDateTime("01/01/2001")); FileStream stream = new FileStream("c:\\PersonSoap.XML", FileMode.Create); SoapFormatter formatter = new SoapFormatter(); formatter.Serialize(stream, p); stream.Close(); richTextBox1.Text = "Data saved in a file";
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
(Source code: Appendix Serialization\Serialization\Serialization\03SOAPSerialization.cs)
341
SOAP Serialization Read Object richTextBox1.Clear(); FileStream stream = new FileStream("c:\\PersonSoap.XML", FileMode.Open); SoapFormatter formatter = new SoapFormatter(); Person p = (Person)formatter.Deserialize(stream); stream.Close(); richTextBox1.AppendText("Name = " + p.Name + "\nAge = " + p.Age); richTextBox1.AppendText("\nBirthdate = " + p.Birthdate); richTextBox1.AppendText("\nBirthdate day of the year = " + p.Birthdate.DayOfYear.ToString()); richTextBox1.AppendText("\nCurrent day of the year = " + DateTime.Now.DayOfYear.ToString());
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
(Source code: Appendix Serialization\Serialization\Serialization\03SOAPSerialization.cs)
342
XML Serialization • Rules for creating class for XML Serialization ¾ XML serialization serializes only the public fields and property values of an object into an XML stream. ¾ XML serialization does not include type information. ¾ XML serialization serialize only the public type. ¾ XML serialization requires a default constructor to be declared in the class that is to be serialized. ¾ XML serialization requires all properties that are to be serialized as read write properties. Read only properties are not serialized.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
343
XML was designed to be a technology for data exchange across heterogeneous systems. It can be easily transmitted between distributed components because of its platform independence and its simple, text-based, self-describing format.
Employee Class • Add the following namespace using System.Xml.Serialization; using System.Collections;
public class Emp { [XmlAttribute("empNo")] public int empNo; [XmlElement("name")] public string name; //[XmlElement("address")] [XmlIgnore] public string address; [XmlElement("salary")] public double salary; Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
344
(Source code: Appendix Serialization\Serialization\Serialization\Employee.cs)
Employee Class (Contd…) public Emp() {} public Emp(int empNo,string name, string address, double sal) { this.empNo = empNo; this.name = name; this.address = address; this.salary = sal; } public double AnnualSalary() { return salary * 12; } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
345
(Source code: Appendix Serialization\Serialization\Serialization\Employee.cs)
Employee Class (Contd…) [XmlRoot("employeeList")] public class Employee { private ArrayList listEmployee; public Employee() { listEmployee = new ArrayList(); } public int AddEmp(Emp emp) { return listEmployee.Add(emp); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
346
(Source code: Appendix Serialization\Serialization\Serialization\Employee.cs)
Employee Class (Contd…) [XmlElement("emp")] public Emp[] Emps { get { Emp[] emps = new Emp[listEmployee.Count]; listEmployee.CopyTo(emps); return emps; } Set { if (value == null) return; Emp[] emps = (Emp[])value; listEmployee.Clear(); foreach (Emp emp in emps) listEmployee.Add(emp); } } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
347
(Source code: Appendix Serialization\Serialization\Serialization\Employee.cs)
Employee XML Serialization using System.IO; using System.Xml.Serialization;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
348
(Source code: Appendix Serialization\Serialization\Serialization\Employee.cs)
XML Serialization Write Object Employee empList = new Employee(); empList.AddEmp(new Emp(1,"Bhavana", "Mumbai", 8000.00)); empList.AddEmp(new Emp(2,"Shraddha", "Pune", 7000.00)); empList.AddEmp(new Emp(3,"Vishal", "Delhi", 9000.00)); //serialization XmlSerializer serializer = new XmlSerializer(typeof(Employee)); StreamWriter writer = new StreamWriter("C:\\emp.xml"); serializer.Serialize(writer, empList); writer.Close();
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
(Source code: Appendix Serialization\Serialization\Serialization\04EmployeeXMLSerialization.cs)
349
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"); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
(Source code: Appendix Serialization\Serialization\Serialization\04EmployeeXMLSerialization.cs)
350
Appendix:SQL Bulk Copy
string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr); conn.Open(); SqlCommand cmdcreatetable = new SqlCommand("create table Productnew1 (prodid int, prodname varchar(40))", conn); cmdcreatetable.ExecuteNonQuery(); conn.Close();
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
351
(Source code: Module12\DatabaseApplication\DatabaseApplication\12SQLBulkCopy.cs)
351
SQL Bulk Copy
(Contd…)
SqlConnection Sourceconn = new SqlConnection(connstr); Sourceconn.Open(); SqlCommand cmd = new SqlCommand("select productid, productname from products where productid > 70 and Productid 70", conn); adp.UpdateCommand.UpdatedRowSource = UpdateRowSource.None; adp.UpdateBatchSize = 2; adp.Update(ds); label1.Text = "Row updated = " + x; label2.Text = "Rwo updating = " + y; private void adprowupdated(object sender, EventArgs e) { x++; } private void adprowupdating(object sender, EventArgs e) { y++; } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
354
(Source code: Module12\DatabaseApplication\DatabaseApplication\13BatchUpdate.cs)
354
Appendix : Multiple Active Result Set
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
355
(Source code: Module12\DatabaseApplication\DatabaseApplication\14MARS.cs)
355
Multiple Active Result Set
(Contd…)
//By default, MARS is disabled when connecting to a MARS-enabled host such as SQL Server 2005. It must be enabled in the connection string. int categoryid; SqlDataReader productReader = null; string categorysql = "select categoryid, categoryname from categories"; string productsql = "select productid, productname from products where categoryid=@catid"; using (SqlConnection Connection = new SqlConnection("Data Source = .\\sa1; Integrated Security=true;Initial Catalog= Northwind; MultipleActiveResultSets=True“ )) { SqlCommand categoryCmd = new SqlCommand(categorysql, Connection); SqlCommand productCmd = new SqlCommand(productsql, Connection); productCmd.Parameters.Add("@catid", SqlDbType.Int); Connection.Open();
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
356
(Source code: Module12\DatabaseApplication\DatabaseApplication\14MARS.cs)
356
Multiple Active Result Set
(Contd…)
using (SqlDataReader categoryReader = categoryCmd.ExecuteReader()) { while (categoryReader.Read()) { lstmars.Items.Add (categoryReader["categoryname"].ToString()); categoryid = (int)categoryReader["categoryid"]; productCmd.Parameters["@catid"].Value = categoryid; // The following line of code requires a MARS-enabled connection. productReader = productCmd.ExecuteReader(); using (productReader) { while (productReader.Read()) { lstmars.Items.Add (" " + productReader[“productName”].ToString()); } } } Connection.Close(); } } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
357
(Source code: Module12\DatabaseApplication\DatabaseApplication\14MARS.cs)
357
Appendix : Reading and Writing Data to XML
DataSet ds;
• Form Load Event string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString; SqlConnection conn = new SqlConnection(connstr); string sql = "select categoryid, categoryname from categories order by categoryid"; SqlDataAdapter adp = new SqlDataAdapter(sql, conn); ds = new DataSet(); adp.Fill(ds); Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
358
(Source code: Module12\DatabaseApplication\DatabaseApplication\15XML.cs)
358
Reading and Writing Data to XML
(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];
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
359
(Source code: Module12\DatabaseApplication\DatabaseApplication\15XML.cs)
359
Appendix : Data Independent Provider
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
360
(Source code: Module12\DatabaseApplication\DatabaseApplication\16ProviderFactories.cs)
360
Data Independent Provider
(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;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
361
(Source code: Module12\DatabaseApplication\DatabaseApplication\16ProviderFactories.cs)
361
Data Independent Provider
(Contd…)
• ListBox SelectedIndexChange Event string provider = lstprovider.SelectedValue.ToString(); if (provider == "System.Data.SqlClient") { DbProviderFactory factory = DbProviderFactories.GetFactory(provider ); using (DbConnection conn = factory.CreateConnection()) { conn.ConnectionString = "data source=.\\sa1; initial catalog=northwind; integrated security=true"; conn.Open(); DbCommand cmd = factory.CreateCommand(); cmd.CommandText = "select * from customers"; cmd.Connection = conn; DbDataReader reader = cmd.ExecuteReader(); DataTable custtable = new DataTable(); custtable.Load(reader); conn.Close(); dataGridView1.DataSource = custtable; } } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
362
(Source code: Module12\DatabaseApplication\DatabaseApplication\16ProviderFactories.cs)
362
Data Independent Provider
(Contd…)
else if (provider == "System.Data.OleDb") { DbProviderFactory factory = DbProviderFactories.GetFactory(provider ); using (DbConnection conn = factory.CreateConnection()) { conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;data source=c:\\northwind.mdb;"; conn.Open(); DbCommand cmd = factory.CreateCommand(); cmd.CommandText = "select * from Categories"; cmd.Connection = conn; DbDataReader reader = cmd.ExecuteReader(); DataTable categorytable = new DataTable(); categorytable.Load(reader); conn.Close(); dataGridView1.DataSource = categorytable; } }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
363
(Source code: Module12\DatabaseApplication\DatabaseApplication\16ProviderFactories.cs)
363
Appendix : TreeView Example with Database
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
(Source code: Module12\DatabaseApplication\DatabaseApplication\17TreeViewExample.cs)
364
TreeView Example with Database Code • Class level declaration SqlConnection conn; SqlDataAdapter adp; DataSet ds = new DataSet();
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
365
TreeView Example with Database Code • Form Load Event conn = new SqlConnection("server=.\\sa1;database=northwind;integrated security=true"); adp = new SqlDataAdapter("select table_name from information_schema.tables where table_type='Base Table' order by table_name", conn); adp.Fill(ds); treeView1.Nodes.Add("Northwind"); int rows = ds.Tables[0].Rows.Count; for (int i = 0; i
View more...
Comments