109
Objectives Why Microsoft. Net. Versions of MS.Net. Features of Microsoft. Net 2.0. Features of Microsoft. Net 3.5. Features of Microsoft. Net 4.0. Why Microsoft. Net. DOS based application/Console Class libraries Windows control libraries Windows services Crystal reports Setup and deployment applications Web services Mobile applications BizTalk applications Device applications GUI application/windows Web application Component development Service development Distributed application Muti threaded application What is Microsoft. Net. MS.net is a collection of languages, technologies, frameworks, tools, libraries etc… integrated in one environment which enables to communicate device to device or application to application. It provides one environment for developing different applications rapidly and efficiently. versions of MS.net MS.NET 1.0 ----2000 MS.NET 1.1 ----2003 MS.NET 2.0 ----2005 MS.NET 3.5 ----2008 MS.NET 4.0 ----2010 MS.NET 1.0 ----2002 Multi language support (nearly 17 languages) Multi application support Multi server support Multi server support Separate installation of crystal reports is Required Separate installation of Mobile Applications Required MS.NET 1.1 ----2003 Multi language support (nearly 21 languages) Multi application support Multi server support Multi service support Inbuilt crystal reports Inbuilt Mobile Applications Required. Separate installation sqlserver

C# .Net

Embed Size (px)

Citation preview

Page 1: C# .Net

Objectives

• Why Microsoft. Net. • Versions of MS.Net. • Features of Microsoft. Net 2.0. • Features of Microsoft. Net 3.5. • Features of Microsoft. Net 4.0.

Why Microsoft. Net.

• DOS based application/Console • Class libraries • Windows control libraries • Windows services • Crystal reports • Setup and deployment applications • Web services • Mobile applications • BizTalk applications • Device applications • GUI application/windows • Web application • Component development • Service development • Distributed application • Muti threaded application

What is Microsoft. Net.

MS.net is a collection of languages, technologies, frameworks, tools, libraries etc… integrated in one environment which enables to communicate device to device or application to application. It provides one environment for developing different applications rapidly and efficiently. versions of MS.net

• MS.NET 1.0 ----2000 • MS.NET 1.1 ----2003 • MS.NET 2.0 ----2005 • MS.NET 3.5 ----2008 • MS.NET 4.0 ----2010

MS.NET 1.0 ----2002 • Multi language support (nearly 17

languages) • Multi application support • Multi server support • Multi server support • Separate installation of crystal reports

is Required • Separate installation of Mobile

Applications Required

MS.NET 1.1 ----2003 • Multi language support (nearly 21

languages) • Multi application support • Multi server support • Multi service support • Inbuilt crystal reports • Inbuilt Mobile Applications Required. • Separate installation sqlserver

Page 2: C# .Net

MS.NET 2.0 ----2005

• Multi language support (nearly 32 languages). • Multi application support. • Multi server support. • Multi service support. • Inbuilt crystal reports . • Inbuilt Mobile Applications Required. • Inbuilt SqlServer in the form of Server Explorer. • Master Pages. • Themes and Skins. • Generic Classes. • Sealed Classes. • Partial Classes. • Nullable types etc…

MS.NET 3.5 ----2008

• Supports nearly 64 languages • WPF(Windows Presentation Foundation) • WCF(Windows Communication Foundation) • WWF(Windows Workflow Foundation) • AJAX(Asynchronous JavaScript and Xml) • LINQ • Silver Light • Richer HTML/CSS Designer Support • List View Control • Data Pager Control • Nested master pages • Intellisense for CSS styles in the markup editor • Intellisense for JavaScript in the markup editor

LINQ

Page 3: C# .Net

Net Framework Languages

• C # .NET • VB .NET • J# . NET • JSCRIPT.NET • PYTHONSCRIPT.NET • PEARLSCRIPT.NET • EFFEL.NET • F#.NET • COBOLSCRIPT.NET • VISUAL C++.NET • VBSCRIPT.NET ETC…….. ETC……..

1).NET FRAMEWORK: it protects the OS and enables the application execution

CLR: it is the runtime environment used to execute all the .net applications .

it applies security, memory management and monitors the execution of the program.

Base Class Libraries: it provides some predefined functionality which can be reused for developing the application in .net environment.

Nearly 4000 predefined Classes are provided for developing the applications

2) MICROSOFT PRODUCTS: MS has provided its products for faster development of applications and testing of the applications

a. MS VISUAL STUDIO EDITOR

b. POCKET PC SIMULATOR

MS VISUAL STUDIO EDITOR: it is an integrated development environment for developing different types of applications i.e. execution, debugging, designing etc……

POCKET PC SIMULATOR: it is a special type of environment used for testing mobiles and smart pc applications

3) .NET SERVICES: a service is a back roundly running program which is used for automatic the process

Ex: passport, alert, contact, address, webservice, calendar etc…..

4) .NET SERVERS: MS has provided nearly 14 servers support like

a). IIS :which acts as the web server for ASP.net web application

b).MOBILE IIS: which acts as a web server for mobile application

c).MS SQLSERVER:it acts as a database for storing information permanently

MICROSOFT.NET

Page 4: C# .Net

d).ISS: Internet security server it is used for applying security for ASP.net applications

e).BISTALK SERVER: it is used to store the information in XML format

f).EXCHANGE SERVER: it is used for exchanging mails

g).ECOMMERCE: it is used for online banking etc….

5).NET TOOLS: it is used for compiling and executing or checking the structure of files by using built-in tools like Compilers,interpreters,debuggers,assemblers,disassemblers etc…

APPLICATION LAYER: This layer is used for presenting the application by developing the front ends. This layer provides some collection of languages and application from which we can choose and develop the application

BASECLASSLIBRARIES: This layer provides some predefined functionalities which are used by application layer for developing the application

TRANSLATING LAYER: This layer is used to convert your application to OS understandable language by managing the memory, checking the security and monitoring the program

LIFE CYCLE EXECUTION OF .NET APPLICATION

->Any .NET application choose their respective compilers and compiles the program . -> Any .NET application compiled format is IL code which is given to CLR for converting it to native OS understandable format at the time of execution

Page 5: C# .Net

IL (intermediate language):it is the compiled format of any .NET program which is OS independent.

It can be called as MSIL, CIL, and assembly

IL format is of two types

• .dll format: it is reusable format it is not executable format • .exe format: it is executable format it is not reusable

ILARCHETECTURE: it consists of 4 parts and 1 wrapper to describe itself

METADATA: it is used to describe the data of the IL file i.e. it provides the structure of the program like class names, method names etc…

CODE: it provides the actual instructions of IL file

RESOURCE: it provides the additional information like images,cursors,icons etc…

MANIFEST: it provides documentary information like product name, company name, version no, strong name etc….

PE WRAPPER: it contains some executable format which invokes the CLR.

Note: if you want to view the complete IL file then ILDASM.exe

ILDASM.exe: it is a build-in tool of .net used to show the wrapper file or IL file

Visual Studio .NET

Development tool that contains a rich set of productivity and debugging features

• Supports managed and unmanaged applications • Supports C#, C++, VB.NET, … • Many useful tools and wizards • Windows Forms Designer • ASP.NET Web Forms Designer • Web Services support • SQL Server integration with ADO.NET and XML

Page 6: C# .Net

VS.NET – Single Development Environment & Skill Set

• From Visual Studio.NET you can: � Write code � Design user interface � Study documentation � Debug � Test � Deploy

• Same tools for all languages • Same tools for all platforms

.Net platform features

• Automatic memory management • Explicit Versioning • OO features in any languages • Accessing system functionality throw a hierarchical namespace • Code security • Interoperability with COM

Automatic Memory Management

• The CLR manages memory for managed code • All allocations of objects and buffers made from a Managed Heap • Unused objects and buffers are cleaned up automatically through Garbage Collection

Managed & Unmanaged Code

• .NET supports two kind of coding • Managed Code • Unmanaged Code

Managed Code

• Code that targets the CLR is referred to as managed code. • Code that relies on CLR to do the memory allocation and de-allocation. • All managed code has the features of the CLR

� Object-oriented � Type-safe � Cross-language integration � Cross language exception handling � Multiple version support

• Managed Code provides the following benefits: • Complete object-oriented design. • Very strong type safety. • A good blend of Visual Basic simplicity and C++ power. • Garbage collection.

Page 7: C# .Net

Unmanaged Code

Any code that tries to bypass the CLR and attempts to handle these functions itself is considered "unsafe"; and the compiler would not compile the code. If the user insists on bypassing the CLR memory management functionality then he must specifically write such code in using the "unsafe" and "fixed" key words. Such a code is called "unmanaged" code.

Namespaces

Namespaces are a mechanism for logically grouping similar classes into a hierarchical structure. This prevents naming conflicts. The structure is implemented using dot-separated words. The top level namespace for most of the .NET framework is System . Under the System namespace you'll find the following:

• System.IO • System.Net • System.Net.Sockets • System.Reflection • System.Threading

.NET Framework Namespaces

Base Class Library Namespaces

Page 8: C# .Net

Base Class Library

• Data types, conversions, formatting • Collections: ArrayList, Hashtable, etc. • Globalization: Cultures, sorting, etc. • I/O: Binary and text streams, files, etc. • Networking: HTTP, TCP/IP sockets, etc. • Reflection: Metadata and IL emit • Security: Permissions, cryptography • Text: Encodings, regular expressions

Data And XML Namespaces

ADO.NET And XML

• ADO.NET consumes all types of data � XML (hierarchical), relational, etc.

• Powerful in-memory data cache (DataSet) � DataSet contains various data objects: tables, views, relations, constraints, etc. � Lightweight, stateless, disconnected � Supports both relational and XML access

• High-performance, low overhead stream access • Great XML support including:

� W3C DOM, XSL/T, XPath, and Schema

ADO.NET (Data and XML)

• New objects (e.g., DataSets) • Separates connected / disconnected issues • Language neutral data access • Uses same types as CLR • Great support for XML

Page 9: C# .Net

Windows Forms Namespaces

CLR

• CLR is common language runtime • It is a runtime environment used to convert IL file to native OS understandable format and also

provides some services like memory management ,type checking, monitoring the lifecycle of the program etc…

• It is the heart and soul of .net frame work used to perform every operation in .net • It consists of • IL loader • Access controllers • Memory management • Jit compiler

IL LOADER: it is used to load the complete Il file in to the clr.

Access Controller: it is used to check the security privileges of IL file

Different types of access controllers are

CTS:common type system :it provides common data types for all .net languages and checks whether IL file is using those data types are not

CLS:common language specification: it provides some common rules for all .net languages and check whether IL file is following those rules are not

CAS:code access security: it checks whether the code is executing on the O.S and if it is invalid code it displays error message

Page 10: C# .Net

RBS:role based security:

It checks whether the login user is valid or invalid and it provides permissions for accessing and executing .net applications. by default administrator have the privileges for accessing .net applications

Memory management:

It look after the memory allocation and memory deallocation .it uses GIGO process for memory management.

Note: Managed applications: the applications whose memory management will look after by runtime environment i.e. by CLR

Without any user interface is called managed application.

JIT compiler:

It is used for converting IL code in to native machine understandable format by compiling it

Types of compilers:

PreJIT: it is used to convert the complete IL code into native machine understandable format

Standard JIT: it is used to convert only the called method to machine understandable format use it and remove it from the memory

Echno JIT: it is used to convert the called method to machine understandable format use it and maintain the copy in the temporary location for the next request

Page 11: C# .Net

MSVISUAL STUDIO EDITOR

using System; using System.Collections.Generic; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) {

} } }

using Keyword

• The .NET Framework has a huge set of classes. They are grouped under namespaces for easy accessibility and better categorization.

• The methods has to be called along with its complete path in the hierarchy, a really tiresome process to do repeatedly. This is when the using keyword comes into aid by importing the namespaces. When imported, the classes inside the namespace can be accessed just by their names.

• Any .NET application that we make, has to reside in a namespace of its own, so we write the statement namespace Hello World. All the classes you create under this namespace can be accessed as NameSpaceName.ClassName.

static void Main

• Main is the entry point for the application. The entry point must be declared as static because that way the main function can be invoked even without creating an object of the Program class. Also the name of the entry function should be Main, the capital M counts too.

String[ ] args

• Any application can take parameters, when run from the command prompt. Say you ran the Notepad application as follows Notepad.exe MyFile.txt. The text MyFile.txt is the parameter passed to it, Notepad reads this parameter and opens the file. Similarly, we may need to work with arguments passed to your application. This is why we use the string[ ] args inside the Main function.

Console.WriteLine(“zenic”)

• The Console class resides in the System namespace and represents the standard input, output and error streams for console application.

• The WriteLine method displays the supplied argument(s) on the console

Page 12: C# .Net

Console.ReadLine();

• This nifty method will allow you to take alphabetic, it will take the input as a string or text .

Tokens

• The basic element recognized by the compiler is the "token." A token is sourcethe compiler does not break down into com

• token:

• keyword

• identifier

• constant

• operator

• punctuators ( brackets ([ ]), braces ({ }), parentheses ( ( ) ), and commas (,) )

Escape Sequences

Variables

• A Variable is a named location that stores a value. Although variables are RAM, their actual memory address is not known to the programmer. We can use the variables via the name we give them. These are the rules for naming a variable:

• The name must begin with a letter or an underscore & can be followed b(A-Z), digits (0-9) or underscore (_)

• Special Characters such as ? name.

• A variable name must not be the same as a reserved keyword such as using, public, etc.

• The name can contain any number of the allowed characters

This nifty method will allow you to take in user input. Whether the user input is numeric or alphabetic, it will take the input as a string or text .

The basic element recognized by the compiler is the "token." A token is sourcethe compiler does not break down into component elements.

( brackets ([ ]), braces ({ }), parentheses ( ( ) ), and commas (,) )

A Variable is a named location that stores a value. Although variables are RAM, their actual memory address is not known to the programmer. We can use the variables via the name we give them. These are the rules for naming a variable:-

The name must begin with a letter or an underscore & can be followed by a sequence of letters 9) or underscore (_)

Special Characters such as ? - + * / \ ! @ # $ % ^ ( ) [ ] { } , ; : . cannot be used in the variable

A variable name must not be the same as a reserved keyword such as using, public, etc.

The name can contain any number of the allowed characters

in user input. Whether the user input is numeric or

The basic element recognized by the compiler is the "token." A token is source-program text that

( brackets ([ ]), braces ({ }), parentheses ( ( ) ), and commas (,) )

A Variable is a named location that stores a value. Although variables are physically stored in the RAM, their actual memory address is not known to the programmer. We can use the variables via

y a sequence of letters

! @ # $ % ^ ( ) [ ] { } , ; : . cannot be used in the variable

A variable name must not be the same as a reserved keyword such as using, public, etc.

Page 13: C# .Net

• Variables with the same scope cannot have the same name

• Note: C# being a case-sensitive language, two variables such as var1 and Var1 would be different.

• All variables can be divided into seven main categories depending on the context of usage:

• Static variables

• Variable of instance

• Array's elements

• Parameters given by reference

• Parameters given by value

• Returned values

• Local variables.

Variable Declaration

• <data type> <variable name>;

For Example:-

• int Age; char Sex; string Name; bool IsMarried;

Initialization

• int Age = 20; char Sex = 'M'; string Name = “Max Steel”; bool Is Married = false;

Displaying Variables

• Displaying Single Variable

� int A = 6; Console.WriteLine(A);

• Displaying Multiple Variables

� int A = 6, B = 9; Console.WriteLine("{0},{1}", A, B);

� int A = 6, B = 9; Console.WriteLine("The value of A = {0} and B = {1}", A, B);

Page 14: C# .Net

Comments

• // This is a comment /* These are two lines of comments */

Constants

• Constants are variables whose values once defined cannot be changed by the program.

• const double pi=3.14;

Data Types

• A data type is a classification done by identifying one of various types of data, as floating-point, integer, or boolean, stating the possible values, operations that can be done and the way the values of that type are stored.

• It specifies the type of data that is stored in a variable

• .NET framework has provided its build in data types under CTS concept

• CTS provides common data types for all .NET languages and they are build in structures

• C# .NET has provided some alias for CTS

Page 15: C# .Net

Different types variables

Value Types

• Value type objects directly contain the actual data in a variables. With value types, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other. Memory allocation on Stack.

• int i = 10;

• Ex: int, float, bool, double…, struct are value types.

Reference Types

• Reference type variables stores the reference of the actual data. With reference types, it is possible for two variables to reference the same object, and thus possible for operations on one variable to affect the object referenced by the other variable. Memory allocation on Heap.

• A objMygo = new A();

• Ex: string, object…,classes & interfaces are reference types.

Type converstion diagram

Type conversion: it is a process of converting one data type to another data type

BOXING : it is a process of converting value type data type to reference type data type

Boxing requires explicit conversion by using To String(); which converts any data type to string type

Page 16: C# .Net

Example:

using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int i = 10;//value type

object o;//reference type o = i;//boxing Console.WriteLine("i={0} and o={1}",i,o); int n = 5;//valuetype String s;//reference type s = n.ToString();//boxing Console.WriteLine("n={0} and s={1}",n,s); Console.ReadLine(); } } }

Unboxing: it is a process of converting reference type to value type

It compulsory requires explicit conversion

Convert class: it provides some build in methods by taking any data type to the respective data type format

Convert.ToInt32(anytype)

Convert.ToInt16(anytype)

Convert.ToInt64(anytype)

Convert.Tobyte(anytype)

Convert.Tochar(anytype)

Convert.Toboolean(anytype) etc…

Parse method: this method is used to provided all C# and CTS data types which is used to convert string to any data type format

Int.Parse(String)

Long.Parse(String) etc….

Example:

static void Main(string[] args) { object o = 5;//ref type int n;//value type // n = (int)o; //unboxing n = Convert.ToInt32(0);//unboxing Console.WriteLine("o={0} and n={1}",o,n);

String s = "10";//ref type int i;//value type i = Int32.Parse(s);//unboxing i = int.Parse(s); Console.WriteLine("s={0} and i={1}", s, i); Console.ReadLine(); } } }

Page 17: C# .Net

Type casting: converting one value type to another value type or one reference type to another reference type is called as type cast

Widening: it is a process of converting small data type values to large data type values. it does not require explicit casting

Exmple:

class Program { static void Main(string[] args) { int i = 1000;//value type long l;//value type

l = i;//widening Console.WriteLine("i={0} and l={1}",i,l); Console.ReadLine(); } }

Narrowing : it is a process of converting large data type values to small data types this type of conversion is risky becoz you may lose the value in it requires explicit conversion

• Checked block checks the narrowing conversion is valid or not by checking the range of the data types and raises runtime error if invalid

Syntax: checked

{

Stat1…..;

Stat2…..;

Stat3…..;

}

Unchecked block use to allow the narrowing conversion by truncating the value

• Ex: if byte is assigned with 256 then automatically the value truncates to 0 becoz the range of byte is 0-255

Syntax: unchecked

{

Stat1…;

Stat2…;

}

• note: c#. net narrowing conversion is by default unchecked

Page 18: C# .Net

Example:

class Program { static void Main(string[] args) { Console.WriteLine("range of byte is {0}-{1}", byte.MinValue, byte.MaxValue); checked {

int i = 257;//4 bytes byte b;//1 byte b = (byte)i;//narrowing Console.WriteLine("i={0} and b={1}",i,b); } Console.ReadLine(); }

Example 1:

private void button1_Click(object sender, EventArgs e)

{

int sal = 5000;

MessageBox.Show(sal); // It will give Error.

MessageBox.Show(sal . ToString());

}

Obs: 1) MessageBox.Show() is capable to print only strings.

2) Local variables must be initialized before using.

Example 2:

private void button1_Click(object sender, EventArgs e)

{

byte b1 = 10, b2 = 20;

byte c = b1 + b2; // Error

int c = b1 + b2; // Correct

MessageBox.Show(c.ToString());

}

Obs: Above statement gives an error as [+] operator returns ‘int’ as output, which cannot be stored in byte.

Page 19: C# .Net

Example 3:

private void button1_Click(object sender, EventArgs e)

{

float x = 4.3; // Error

float x = 4.3f; // Correct

MessageBox.Show(x . ToString ());

}

Example :4:

private void button1_Click(object sender, EventArgs e)

{

int i = 150; // int i=300; -> The output will come

another number like 44

//byte sal = i; //Wrong

byte sal = (byte)i; //Correct

MessageBox.Show(sal.ToString());

}

Note: Drawback of C++ style of Type casting, A possibility for data lost.

Example :5

private void button1_Click(object sender, EventArgs e)

{

MessageBox.Show(int.MinValue.ToString());

MessageBox.Show(int.MaxValue.ToString());

}

Example :6

private void button1_Click(object sender, EventArgs e)

{

MessageBox.Show(textBox1.Text + textBox2.Text);

// It will be concatenated, Not added.

int s = int.Parse(textBox1.Text);

Page 20: C# .Net

int i = int.Parse(textBox2.Text);

int ts = s + i;

MessageBox.Show(ts.ToString());

}

Obs:- ‘+’ Operator can be used for two operations.

Adding numbers.

Concatenating Strings.

“10” + “10” = 1010

10 + 10 = 20

“10” + 10 = Error

WORKING WITH CONVERTING:

Convert is a predefined class.

It’s have so many pre defined “Methods”.

Convert.Tochar(--) ToInt16(--)

Convert..ToByte(--) ToInt32(--)

Convert..ToFloat (--) ToInt64 (--)

Convert..ToDouble (--)

Convert..ToDecimal (--)

Convert..ToBoolean (--)

Note: If we give file name like (Convert). We give this file name it will not show any methods when typing convert.(Dot), because the file name is a predefined method. So we give a file name other like (Convert Demo).

Example :7

private void button1_Click(object sender, EventArgs e)

{

int i = 65;

char c = Convert.ToChar(i);

MessageBox.Show(c.ToString());

}

Page 21: C# .Net

Example :8 if-else

private void button1_Click

{

int i = 10, j = 5;

if (i > j)

this.BackColor = Color.Green;

else

this.BackColor = Color.Red;

}

Example :9 switch case

private void button1_Click_1(object sender, EventArgs e)

{

int i = int.Parse(textBox1.Text);

switch (i)

{

case 1:

this.BackColor = Color.Green;

break;

case 2:

ColorDialog cd = new ColorDialog();

cd.ShowDialog();

this.BackColor = cd.Color;

break;

default:

Application.Exit();

break;

}

}

Page 22: C# .Net

OOPS CONCEPTS

OOPS is a concept which relates to a real world problem in a system design by providing everything as a object.

Code founder of oops-� Grady booch

• OOPS will provide communication between different objects and helps the information displaying fastly

Class:

Features of OOPS:

• Data organization: it is used for organizing the data in a single block for fast accessing and to increase the performance of the application because in c program data was scattering in a stack which requires searching time while accessing the data

• Data security: with the traditional languages it supports global variables declarations where data is not secured so OOPS provides accessibility levels for the data by using access modifiers i.e. private and protected

• Reusability :it enables the developer to use the existing functionality for developing a new software model fastly with less cost and maintenance

• Extensibility :it provides to manipulate the existing software model by adding the new features required with the feature criteria

• Reimplementation :it supports the changing of body of the existing functionality depending on a criteria

OOPS concepts stands on three important pillars

1. Encapsulation

2. Inheritance

3. Polymorphism

Encapsulation: it is process of wrapping up of data members, methods in a single entity for providing data organization and security.

Inheritance :it is a process of defining a new software model from the existing one by using reusability and extensibility

Polymorphism: it is a process of defining multiple forms with same name to provide reimplementation and versioning of software's

OOPS is supported by different languages and provides a new classification

Page 23: C# .Net

Object: An object is any thing that exists physically.ait is a variable of a class type which holds the address of the class by allocating the memory for it and can provide accessibility for the class members

It is also called as instance of the class or blue print of a class

Object memory are allocated on heap

Types of objects:

1. Reference object: an object which informs the compiler that it is of a particular class type whose memory will be allocated on stack

Syn: <class name> <object>;

Ex: Sample s;

Generally reference object is supported with late or dynamic binding of polymorphism

2. Instance object: an object which informs the compiler that it is of a particular class type and holds the address of a specific class

Its syntax performs two operations

Allocate the memory for the class on heap

Assign the address of the class in the object on the stack

Types of Classes:

Page 24: C# .Net

Data members

These are the variables which are used to store some data

Every variable will have some data type and that data type specifies that the type of data we are storing in a variable.

Let us consider a class called customer the members of the customer class ma

Ex: int CustId;

string CustName ;

string CustAddress

Int Age; etc…

METHODS IN CLASSES

A method is a sub program which contains some executable statements and are executed when u call a method.

Note: Procedure will does not return any value

Method will always return a value

C#.net supports only methods but vb.net supports procedures.

Keywords

� Static for static methods direct or class name accessibility)� Abstract incomplete method� Sealed not overridable method� Virtual overridable method

Return types:

� Any data type � Class name � Structure name � Enum name � Void

Mode: value,ref,out,params

These are the variables which are used to store some data

Every variable will have some data type and that data type specifies that the type of data we are storing in

Let us consider a class called customer the members of the customer class may be

A method is a sub program which contains some executable statements and are executed when u call a

Note: Procedure will does not return any value

Method will always return a value

C#.net supports only methods but vb.net supports procedures.

Static for static methods direct or class name accessibility) Abstract incomplete method

overridable method Virtual overridable method

Every variable will have some data type and that data type specifies that the type of data we are storing in

y be

A method is a sub program which contains some executable statements and are executed when u call a

Page 25: C# .Net

Return Type The return type determines the type of value that the function will return. It can be any of the atomic data types (int, char, string, bool, float, etc) or the user defined types (enums, objects, structures). A function that does not return any value should have a return type of void.

Function Name The function name can be anything that follows the naming rules.

Parameters Functions take values as input, process it and return the output. These inputs are in the form of parameters. The parameters themselves are composed of the data type and the parameter name. The data type restricts the values that can be passed to the function (int only allows Integer values, bool allows Boolean values and so on) and the parameter name can be used like a regular variable under the function body. This variable would be initialized with the value that is passed to the function when it is invoked (called). A function can have any number of parameters each of which need to separated by a comma.

A parameter can have two variations - ref and out.

Example to get customer data and display customer data

#region CustomerClass

class Customer

{ #region Variables

int _custNo;

string _custName;

string _custAddress;

int _custAge;

#endregion

#region Methods

#region GetCustomerData

public void GetCustomerData()

{ Console.WriteLine("Enter Customer No,Customer name,Customer Address,Customer Age");

_custNo =int.Parse(Console.ReadLine());

_custName = Console.ReadLine();

_custAddress = Console.ReadLine();

_custAge =Convert.ToInt32(Console.ReadLine());

} #endregion

Page 26: C# .Net

#region DisplayCustomerData public void DisplayCustomerData() { Console.WriteLine("Customer No is"+_custNo); Console.WriteLine("Customer Name is"+_custName); Console.WriteLine("Customer Address is"+_custAddress); Console.WriteLine("Customer Age is"+_custAge); Console.ReadLine(); } #endregion #endregion } #endregion

#region MainClass class Program { static void Main(string[] args) { //syntax for creating an object //classname objname=new class name(); Customer obj = new Customer(); //call the method //syntax for calling the method //objname.methodname(); obj.GetCustomerData(); obj.DisplayCustomerData(); } } #endregion

Example for a class to accept Employee Sal Details

namespace ConsoleApplication10

{

class Class Salary

{

int EmpNo;

string EmpName ;

double Basic;

double DA;

double HRA;

double Gross;

Page 27: C# .Net

public void RetrieveSalary() { Console.WriteLine("Enter EmpNo,EmpName,Basic,DA,HRA,Gross:-"); EmpNo = int.Parse(Console.ReadLine()); EmpName = Console.ReadLine(); Basic = Convert.ToDouble(Console.ReadLine()); } public void Calculate() { DA = 0.4 * Basic; HRA = 0.2 * Basic; Gross = Basic + DA + HRA; } public void DisplaySalData() { Console.WriteLine("Employee No is :-"+EmpNo); Console.WriteLine("Employee Name is:-"+EmpName);

Console.WriteLine("Employee Basic is:-"+Basic); Console.WriteLine("Employee DA is:-"+DA); Console.WriteLine("Employee HRA is:-"+HRA); Console.WriteLine("Employee Gross is:-"+Gross); } } class Program { static void Main(string[] args) { ClassSalary sal = new ClassSalary(); sal.RetrieveSalary(); sal.Calculate(); sal.DisplaySalData(); Console.ReadLine(); } } }

Concrete class: a class which supports inheritance ,polymorphism is called as a concrete class

Data members: the variables declared inside the class are called as data members

Types of data members

• Instance data members

• Static data members • Constant data members

• Read-only data member

Instance data members: the data members whose memory is created when an instance object is created

Page 28: C# .Net

Static data members: the data members whose memory allocated automatically when the class is loaded before main method on the stack this data member declaration requires static keyword and they can be accessible directly within the class and using class name in some other class

Syntax: <access specifier> static<data type> <variable>;

Constant data members : the data members which are static in nature and requires some rules at the time of declaration

• 1st rule: needs const keyword

• 2nd rule : needs value at the time of declaration

• 3rd rule: its value cannot change throughout the program

Syn: <acess specifier> const<data type> <variable>=value;

Constructor:

• Constructor is a method in the class which gets executed when its object is created. Usually we put the initialization code in the constructor. Whose task is to initialize the objects of its classes.

• There is no need to write any explicit statements to involve the constructor method

• Constructor name and class name is same

• A constructor doesn’t have any return type even void also but method has a return type, hence it not returns value

Types of constructors:

Page 29: C# .Net

Default constructors:

#region Customer

class Customer

{

#region Variables

int _cNo;

string _cName;

string _custAddress;

int _custAge;

#endregion

#region Constructor public Customer() { _cNo = 101; _cName = "sunil"; _custAddress = "hyderabad"; _custAge = 23; } #endregion #region Methods public void GetCustomerData() { Console.WriteLine("customer no is"+_cNo); Console.WriteLine("customer name is"+_cName); Console.WriteLine("customer address is"+_custAddress); Console.WriteLine("cust age is"+_custAge); Console.ReadLine(); } #endregion } #endregion

#region MainClass class Program { static void Main(string[] args) { //created an object Customer obj = new Customer(); //call the method obj.GetCustomerData(); } } #endregion

Page 30: C# .Net

System defined default constructor

When there is no constructor present within the class then system will create its own constructor and will assign default values in to the data fields

class Employee { int Empid, Eage; String Ename, Eaddress; public void DisplayEmpdata() { Console.WriteLine("EMPLOYEE ID IS:" + Empid); Console.WriteLine("EMPLOYEE NAME IS:" + Ename); Console.WriteLine("EMPLOYEE ADDRESS IS:" + Eaddress); Console.WriteLine("EMPLOYEE AGE IS:" + Eage); } }

class class2 { static void Main(string[] args) { Employee e1 = new Employee(); e1.DisplayEmpdata(); Console.ReadLine(); } }

This Keyword

� This is a keyword which represents the current class. � This keyword acts like an object for a current class which can be used in the current class.

public Customer()

{

this._CustNo = 10;

this._CustName = "Anil";

this._CustAddress= "Hyderabad";

this._CustAge= 24;

}

Disadvantages of default constructor

� Any no of objects might be created for class all objects data fields will store same set of values � To overcome this drawback we use parameterized constructor

parameterized constructor :

� This constructor will accept parameters those values can be stored wit the data fields of the class � Parameterized constructor is used to store different set of values for each object we create for the

class

Page 31: C# .Net

Rules to follow:

1. The no of arguments for every constructor should differ

2. If the no of arguments are same they should differ with type of arguments if the type of the args are also same then they should differ with mode of the arguments

3. When more than one constructor is defined in a single class then it is called as constructor overloading

Syn:

Public <class name>(………….)

{

…………..

}

parameterized constructor

class Customer

{

int _CustNo;

string _CustName;

string _CustAddress;

int _CustAge;

public Customer(int _cno,string _cname,string _cstaddress,int _cage) { this._CustNo = _cno; this._CustName = _cname; this._CustAddress = _cstaddress; this._CustAge = _cage; } public void DisplayData() { Console.WriteLine(" CustNo is"+_CustNo); Console.WriteLine("CustName is"+_CustName); Console.WriteLine("CustAddress is"+_CustAddress); Console.WriteLine("Cust Age is"+_CustAge);

} } class Program { static void Main(string[] args) { Customer objcust1 = new Customer(100,"Anil","Hyderabad",24); Customer objcust2 = new Customer(200, "Sunil", "Calcutta", 24); objcust1.DisplayData(); objcust2.DisplayData(); Console.ReadLine(); } }

Page 32: C# .Net

STATIC CONSTRUCTOR

• Static constructors are invoked only once during the execution of the program and can be used to initialize the static variables.

• This is a special constructor and gets called before the first object is created of the class. The time of execution cannot be determined, but it is definitely before the first object creation.

• There can be only one static constructor in the class. • The static constructor should be without parameters. • It can only access the static members of the class. • There should be no access modifier in static constructor definition.

Reason!!!

• No Access modifier & No Parameters

• The call to the static constructor is made by the CLR and not by the object, so we do not need to have the access modifier to it.

• As it is going to be called by CLR, who can pass the parameters to it (if required). So, we cannot have parameterized static constructor

• Only Static Members

• Non-static members in the class are specific to the object instance so static constructor, if allowed to work on non-static members, will reflect the changes in all the object instances, which is impractical. So static constructor can access only static members of the class.

Static constructor:

� A constructor which is used to initialize only static members of a class and which is automatically called before any static member is accessible

Syntax:

Static <class name> ()

{

…………….

…………….

}

Rules to declare static constructor

1. It declaration should not include any access modifier

2. It should not include any arguments

3. A class can contain only one static constructor

Page 33: C# .Net

#region Date

class Date

{

static int date, month, year;

static Date()

{

date = DateTime.Now.Day;

month = DateTime.Now.Month;

year = DateTime.Now.Year;

}

public static void DisplayData() { Console.WriteLine("date is:{0}-{1}-{2}",date,month,year); Console.ReadLine(); } } #end region

#region Program class Program { static void Main(string[] args) { Date.DisplayData(); } } #end region }

Destructors : it is a method of a class which is used to destroy the object of a class

It was supported in c# only due to the backward compatibility with c++

Its syntax is similar with a constructor i. e its name should be same as class name preceded with a tild (~) symbol

Syntax: ~ <class name>( )

{…..........................}

Destructor should not be specified with arguments

class A { public A() { Console.WriteLine("This Constructor"); } ~A() { Console.WriteLine("this is destructor"); } }

class Program { static void Main(string[] args) { A obj = new A(); } }

Page 34: C# .Net

Inheritance

• Inheritance is the process of deriving the the base class members in to the derived class whenever we are creating an object for derived class.

• Derived class is also called as child class or subclass • Base class is also called as Parent class or super class • It enables easy maintenance of code by reusability. • Any changes made to the base class automatically changes the behavior of its subclasses.

Sample Inheritance

class BaseClass

{

public void Show()

{

Console.WriteLine("in Base Class Show method");

}

}

class DerivedClass:BaseClass { public void Display() { Console.WriteLine("in Derived class Display method"); } }

class Program { static void Main(string[] args) { BaseClass obj1 = new BaseClass(); obj1.Show(); DerivedClass obj2 = new DerivedClass(); obj2.Show(); obj2.Display(); BaseClass obj3 = new DerivedClass(); obj3.Show(); // DerivedClass obj4 = new BaseClass(); } }

OUTPUT

Page 35: C# .Net

Types of Inheritance

� Single Inheritance � Multi – Level Inheritance � Multiple Inheritance � Hierarchical Inheritance � Hybrid Inheritance

Single Inheritance

� It is a process of deriving the Base class members in to the Derived Class whenever we are creating an object for Derived Class.

� Here in the above example A is super class and B is Derived Class � The operator ‘:’is used to indicate that a class is inherited from another class.

#region College

class College

{

int _collegeNo;

string _CollegeName;

string _CollegeAddress;

string _CollegeLocation;

Page 36: C# .Net

public void GetCollegeData() { Console.WriteLine("Enter collegeno,collegename,collegeaddress,collegelocation:-"); _collegeNo = Convert.ToInt32(Console.ReadLine()); _CollegeName = Console.ReadLine(); _CollegeAddress = Console.ReadLine(); _CollegeLocation =Console.ReadLine(); } public void DisplayCollegeData() { Console.WriteLine("College No is" + _collegeNo); Console.WriteLine("College Name is" + _CollegeName); Console.WriteLine("College Address is" + _CollegeAddress); Console.WriteLine("College Location is" + _CollegeLocation); }} #endregion #region StudentEce class Student : College { int _stNo; string _stName; string _stAddress; string _stMarks; int _Age; public void GetStudentData() { Console.WriteLine("Enter StNo,StName,StAddress,StMarks,stAge"); _stNo = Convert.ToInt32(Console.ReadLine()); _stName = Console.ReadLine(); _stAddress = Console.ReadLine(); _stMarks = Console.ReadLine(); _Age = Convert.ToInt32(Console.ReadLine()); }

public void DisplayStudentData() { Console.WriteLine("StuentNo is:-" + _stNo); Console.WriteLine("Student Name is:-" + _stName); Console.WriteLine("Student Address:-" + _stAddress); Console.WriteLine("Student Marks:-" + _stMarks); Console.WriteLine("Student Age:-" + _Age); } #endregion class Program { static void Main(string[] args) { Student st = new Student(); st.GetCollegeData(); st.DisplayCollegeData(); st.GetStudentData(); st.DisplayStudentData(); Console.ReadLine(); } } } OUTPUT:

Page 37: C# .Net

Multi – Level Inheritance

It is a process of deriving a new class from already existing derived class

#region College class College { int _cNo; string _cName; string _cAddress; #region GetCollegeData public void GetCollegeData() { Console.WriteLine("Enter CollegeNo,CollegeName,CollegeAddress"); _cNo = Convert.ToInt32(Console.ReadLine()); _cName = Console.ReadLine(); _cAddress = Console.ReadLine(); } #endregion

#region DisplayCollegeData public void DisplayCollegeData() { Console.WriteLine("College No is" + _cNo); Console.WriteLine("College Name is" + _cName); Console.WriteLine("College Address is" + _cAddress); } #endregion } #endregion

Page 38: C# .Net

#region Faculty class Faculty : College { int _FacId; string _FacName; string _FacAddress; int _FacAge; #region GetFacultyData public void GetFacultyData() { Console.WriteLine("Enter FacId,FacName,FacAddress,FacAge"); _FacId = Convert.ToInt32(Console.ReadLine()); _FacName = Console.ReadLine(); _FacAddress = Console.ReadLine(); _FacAge =Convert.ToInt32(Console.ReadLine()); } #endregion #region DisplayFacultyData public void DisplayFacultyData() { Console.WriteLine("FacId is"+_FacId); Console.WriteLine("FacultyName is"+_FacName); Console.WriteLine("Faculty Address is"+_FacAddress); Console.WriteLine("Faculty Age is"+_FacAge); } #endregion } #endregion #region Salary class Salary : Faculty { double Basic; double HRA; double DA; double Gross;

public void GetSalaryData() { Console.WriteLine("Enter Basic,HRA,DA and Gross"); Basic = Convert.ToDouble(Console.ReadLine()); } public void CalculateEmployeeSalary() { DA = 0.4 * Basic; HRA = 0.2 * Basic; Gross = Basic + DA + HRA; } public void DisplaySalaryData() { Console.WriteLine("Basic sal is"+Basic); Console.WriteLine("DA is"+DA); Console.WriteLine("HRA is"+HRA); Console.WriteLine("Gross Salary is"+Gross); Console.ReadLine(); }} #endregion #region Program public class Program { static void Main(string[] args) { Salary obj2 = new Salary(); obj2.GetCollegeData(); obj2.DisplayCollegeData(); obj2.GetFacultyData(); obj2.DisplayFacultyData(); obj2.GetSalaryData(); obj2.CalculateEmployeeSalary(); obj2.DisplaySalaryData(); } } #endregion

Page 39: C# .Net

#region College class College { int _cNo; string _cName; string _cAddress; #region GetCollegeData protected void GetCollegeData() { Console.WriteLine("Enter CollegeNo,CollegeName,CollegeAddress"); _cNo = Convert.ToInt32(Console.ReadLine()); _cName = Console.ReadLine(); _cAddress = Console.ReadLine();

} #endregion #region DisplayCollegeData protected void DisplayCollegeData() { Console.WriteLine("College No is" + _cNo); Console.WriteLine("College Name is" + _cName); Console.WriteLine("College Address is" + _cAddress); } #endregion} #endregion

Page 40: C# .Net

#region Faculty class Faculty : College { int _FacId; string _FacName; string _FacAddress; int _FacAge; #region GetFacultyData protected void GetFacultyData() { base.GetCollegeData(); base.DisplayCollegeData(); Console.WriteLine("Enter FacId,FacName,FacAddress,FacAge"); _FacId = Convert.ToInt32(Console.ReadLine()); _FacName = Console.ReadLine(); _FacAddress = Console.ReadLine(); _FacAge =Convert.ToInt32(Console.ReadLine()); } #endregion #region DisplayFacultyData protected void DisplayFacultyData() { Console.WriteLine("FacId is"+_FacId); Console.WriteLine("FacultyName is"+_FacName); Console.WriteLine("Faculty Address is"+_FacAddress); Console.WriteLine("Faculty Age is"+_FacAge); } #endregion } #endregion #region Salary class Salary : Faculty { double Basic; double HRA; double DA; double Gross;

public void GetSalaryData() { Console.WriteLine("Enter Basic,HRA,DA and Gross"); Basic = Convert.ToDouble(Console.ReadLine()); } public void CalculateEmployeeSalary() { DA = 0.4 * Basic; HRA = 0.2 * Basic; Gross = Basic + DA + HRA; } public void DisplaySalaryData() { base.GetFacultyData(); base.DisplayFacultyData(); GetSalaryData(); CalculateEmployeeSalary(); Console.WriteLine("Basic sal is"+Basic); Console.WriteLine("DA is"+DA); Console.WriteLine("HRA is"+HRA); Console.WriteLine("Gross Salary is"+Gross); Console.ReadLine(); } } #endregion #region Program public class Program { static void Main(string[] args) { Salary obj2 = new Salary(); obj2.CalculateEmployeeSalary(); obj2.DisplaySalaryData(); obj2.GetSalaryData(); } } #endregion

Page 41: C# .Net

Hierarchical Inheritance

class Parent { public void Car() { Console.WriteLine("This is car method"); } public void Bike() { Console.WriteLine("This is Bike method "); } protected void Naclace() { Console.WriteLine("This is nacklace method"); } public void House() { Console.WriteLine("This is House method"); } }

class Son:Parent { } class Daughter:Parent { public void GoldRing() { Base.Nacklace(); Console.WriteLine(“this is Ring); } } class Program { static void Main(string[] args) { Daughter obj = new Daughter(); obj.Bike(); obj.Car(); obj.House(); Son obj1 = new Son(); obj1.Bike(); obj1.Car(); obj1.House(); } }

Page 42: C# .Net

Multiple Inheritance

Interfaces

Page 43: C# .Net

Example for multiple inheritance using interfaces

interface I1

{

void Show();

}

interface I2

{

void Display();

}

class A:I1,I2

{

public void Show()

{

Console.WriteLine("in I1 Show method");

}

public void Display()

{

Console.WriteLine("in I2 Display cmethod");

} }

class Program

{

static void Main(string[] args)

{

A obj = new A();

obj.Show();

obj.Display();

}

}

Page 44: C# .Net

If I am declaring an interface I1 and an interface I2 and in I1 I have declared Show() and in I2 I have declared Show() how to call the I1 and I2 show methods

interface I1 { void Show(); } interface I2 { void Show(); } class A:I1,I2 { void I1.Show() { Console.WriteLine("in I1.show()"); } void I2.Show() { Console.WriteLine("in I2.show()"); } }

class Program { static void Main(string[] args) { A obj = new A(); ((I1)obj).Show(); ((I2)obj).Show(); } }

Page 45: C# .Net

interface IWritable { void Write(string s); } interface IReadable { string ReadLine(); } interface IFile:IWritable,IReadable { void Open(string filename); void Close(); } class MyFile:IFile { private string filename; public void Open(string filename) { this.filename = filename; Console.WriteLine("opening file: {0}",filename); } public string ReadLine() { return "reading a file from MyFile:" + filename; }

public void Write(string s) { Console.WriteLine("Writing `{0}' in the file: {1}", s, filename); } public void Close() { Console.WriteLine("Closing the file : {0}", filename); } } #region MainClass class Program { static void Main(string[] args) { MyFile afile = new MyFile(); afile.Open("C:\\csharp.txt"); afile.Write("My name is Kanna"); Console.WriteLine(afile.ReadLine()); afile.Close(); Console.ReadLine(); } } #endregion

Hybrid Inheritance

Page 46: C# .Net

Access Modifier Description

Private: private members can only be accessed within the class that contains them.

Protected internal:This type of member can be accessed from the current project or from the types inherited from their containing type.

Internal : Can only be accessed from the current project.

Protected: Can be accessed from a containing class and types inherited from the containing class.

Public :public members are not restricted to anyone. Anyone who can see them can also access them.

ABSTRACT CLASSES

Page 47: C# .Net

• Abstract class must contain abstract keyword • We can declare variables in abstract class • We cannot create an object for Abstract class

How can we access the methods of the abstract class

• Abstract class contain abstract methods but it must contain only declaration like interface • When a method is getting inherited by name abstract we need to declare the definition of the

method in a concrete class • Abstract methods are by default virtual in nature • So we need to keep override keyword in the abstract method body definition • For an abstract class method definition the access modifier must be public • If a method is declared as abstract and the class is not declared as abstract so it is wrong.i.e

concrete class must not contain abstract methods • When we create an object for a concrete class we can access the abstract methods • An abstract class can contain all the members of a class i.e

datafields,functions,constructors,destructors,properties,indexers and events. • Abstract classes can have abstract methods and normal methods

abstract class A { public void Show() { Console.WriteLine("in A class Show method"); } public abstract void Display(); } class B:A { public override void Display() { Console.WriteLine("in B class Display method");

} } class Program { static void Main(string[ ] args) { B obj = new B(); obj.Show(); obj.Display(); } }

Page 48: C# .Net

#region Employee abstract class Employee { protected int _empNo; protected string _empName; protected string _eAddress; protected int _eAge; public abstract void GetEmpData(); public virtual void DisplayEmpData() { Console.WriteLine("employee ID is:-" + _empNo); Console.WriteLine("employee name is:-" + _empName); Console.WriteLine("emp address is:-" + _eAddress); Console.WriteLine("emp age is:-" + _eAge); } } #endregion #region Manager class Manager:Employee { int _CA; int _Bonus; public override void GetEmpData() { Console.WriteLine("Enter Manager no,Name,address,Age,Ca"); _empNo =Convert.ToInt32(Console.ReadLine()); _empName = Console.ReadLine(); _eAddress = Console.ReadLine();

_eAge =Convert.ToInt32(Console.ReadLine()); _CA = Convert.ToInt32(Console.ReadLine()); _Bonus = Convert.ToInt32(Console.ReadLine()); } public override void DisplayEmpData() { Console.WriteLine("Manager ID is:-"+_empNo); Console.WriteLine("Manager Name is:-"+_empName); Console.WriteLine("CA is:-"+_CA); Console.WriteLine("Bonus is:-"+_Bonus); } } #endregion #region MainClass class Program { static void Main(string[] args) { Manager obj = new Manager(); obj.GetEmpData(); obj.DisplayEmpData(); } } #endregion

Page 49: C# .Net
Page 50: C# .Net

POLYMORPHISM

It is a process of defining multiple functionalities with same name either in single class or the base and derived class.

Polymorphism in c#.net is classified in to three types

• Overloading

• Overriding

POLYMORPHISM IS OF TWO TYPES

COMPILE TIME POLYMORPHISM OR STATIC POLYMORPHISM OR EARLY BINDING OVERLOADING

It is a process of defining multiple functionalities with same name but with different signature in a single class.

Rules to work with overloading:

• The argument list must differ with every functionality • If the argument list is same they should differ with the significance of the arguments. • Overloading does not contain any access modifiers and return type.

TYPES OF OVERLOADING

• METHOD OVERLOADING • CONSTRUCTOR OVERLOADING

Page 51: C# .Net

METHOD OVERLOADING

• Defining multiple methods with same name is called as method overloading • Method overloading is used to implement static polymorphism

Example:

#region ClassA

class A

{

public void Show()

{

Console.WriteLine("this is Show1");

}

public void Show(int a) { Console.WriteLine("the value of a is"+a); } public void Show(int a,int b) { int c =Convert.ToInt32(a + b); Console.WriteLine("the value of a+b is"+c); } } #endregion

#region MainClass class Program { static void Main(string[] args) { A obj = new A(); obj.Show(); obj.Show(10); obj.Show(10, 20); Console.ReadLine(); } } #endregion

CONSTRUCTOR OVERLOADING

#region StudentClass

class Student

{ #region Variables

int _studNo;

string _studName;

int _studAge;

string _studAddress;

#endregion

Page 52: C# .Net

#region DefaultConstructor public Student() { this._studNo = 101; this._studName = "sunil"; this._studAge = 23; this._studAddress = "hyd"; } #endregion #region CopyConstructor public Student(Student obj2) { this._studNo = obj2._studNo; this._studName = obj2._studName; this._studAge = obj2._studAge; this._studAddress = obj2._studAddress; } #endregion #region Methods public void GetData() { Console.WriteLine("Enter Studno,StudName,studAge,StudAddress"); _studNo = Convert.ToInt32(Console.ReadLine()); _studName =Console.ReadLine(); _studAge =Convert.ToInt32(Console.ReadLine()); _studAddress = Console.ReadLine(); }

public void DisplayData() { Console.WriteLine("student no is"+_studNo); Console.WriteLine("student name is"+_studName); Console.WriteLine("student age is"+_studAge); Console.WriteLine("student address is"+_studAddress); } #endregion } #endregion #region MainClass class Program { static void Main(string[] args) { Student obj1 = new Student(); //obj1.GetData(); Student obj2 = new Student(obj1); obj1.DisplayData(); obj2.DisplayData(); Console.ReadLine(); } } #endregion

Compile time warning

class A { public void Show() { Console.WriteLine("A class Show()"); } } class B:A { public void Show() { Console.WriteLine("B class Show()"); } }

class Program { static void Main(string[] args) { B obj = new B(); obj.Show(); } } Complie-Time Warning When we compile the above program, the compiler will show a warning, since we try to hide a Base class data member inside the Derived class. By using the keyword new along with the data member declaration inside the Derived class, it is possible to suppress this compiler warning.

Page 53: C# .Net

class A { public void Show() { Console.WriteLine("A class Show()"); } } class B:A { public void Show() { Console.WriteLine("B class Show()"); } }

class Program { static void Main(string[] args) { A obj = new B(); obj.Show(); // B obj = new A(); } }

Output:A class Show()

Virtual and override

class A { public virtual void Show() { Console.WriteLine("A class Show()"); } } class B:A { public override void Show() { Console.WriteLine("B class Show()"); } }

class Program { static void Main(string[] args) { A obj = new B(); obj.Show(); // B obj = new A(); } } Output:B class Show()

� When we want to override a virtual method polymorphically inside a Derived class, we have to use the keyword override along with the method declaration.

� In C#, a Base class reference can hold an object of the Derived class and when it invokes the methods, it will invoke always the Derived class methods, if you already override that method inside the Derived class by using the override keyword. Also the Base class method must declare using the keyword virtual. This is known as Polymorphism in C#.

Override keyword

� Overriding is the action of modifying or replacing the implementation of the parent class with a new one. Parent classes with virtual or abstract members allow derived classes to override them.

Page 54: C# .Net

Example:

#region Customer

class Customer

{

protected int _custNo, _custAge;

protected string _custName;

protected string _custAddress;

public virtual void GetCustData() { Console.WriteLine("Enter custno,custname,custaddress,and age:-"); _custNo = Convert.ToInt32(Console.ReadLine()); _custName = Console.ReadLine(); _custAddress = Console.ReadLine(); _custAge = Convert.ToInt32(Console.ReadLine()); } public virtual void DispalyCustomerData() { Console.WriteLine("Customer id is" + _custNo); Console.WriteLine("customer name is" + _custName); Console.WriteLine("customer address is" + _custAddress); Console.WriteLine("customer age is" + _custAge); } } #endregion #region Supplier class Supplier : Customer { int _CA, _Bonus; public override void GetCustData() { Console.WriteLine("enter Managerid,Name,CA,Bonus"

_custNo = Convert.ToInt32(Console.ReadLine()); _custName = Console.ReadLine(); _CA = Convert.ToInt32(Console.ReadLine()); _Bonus = Convert.ToInt32(Console.ReadLine()); } public override void DispalyCustomerData() { Console.WriteLine("manager id is:-" + _custNo); Console.WriteLine("manager name is:-" + _custName); Console.WriteLine("manger CA is:-" + _CA); Console.WriteLine("manager Bonus is:-" + _Bonus); } } #endregion #region Program class Program { static void Main(string[] args) { Customer c = new Customer(); c.GetCustData(); c.DispalyCustomerData(); Console.ReadLine(); } } #endregion

Page 55: C# .Net

PROPERTIES

In C++ and Java, when creating the member variables of a class, programmers usually "hide" these members in private sections (C++) or create them as private (Java). This technique makes sure that a member variable is not accessible outside of the class so that the clients of the class cannot directly influence the value of the member variable. If you create a member variable as private but still want other classes to access or get the value of such a field, you must then create one or two "accessories" must pass through to access the field.

This private field cannot be accessed by an outside class. To let the outside classes access this variable, you would/can create a property.

A property is a special data member of a class which is used for setting and getting the values for private data members of the class.

The properties contain two accessors

Set Accessor-------used to assign a value

Get Accessor……..used to return a value

Properties are called smart fields of a class.

Accessor: it is a member of a property which is used to provide accessibility (reading and writing ) of the data fields.

Set Accessor: it is used to write the data into data fields of the class.

Set accessor will have a fixed and default variable named as value.

Any data we write will come and store by default into value variable.

GetAccessor: this is used to read data from data fields of the class.

Syntax for properties: <access modifier> <return type> <Property Name>

{

set

{

variablename=value;

}

get

{

return variablename;

}

}

Page 56: C# .Net

Types of properties

� Read Only � Write Only � Read-Write

Read Only

� This property is used to read the data from the data field of a class. � To read the data from the data fields of the class we use get accessor.

Syntax for Read Only property

<Access modifier><datatype><propertyname>

{

get

{

return variable name;

}

}

Example: Go to class1.cs and write the following code

using System.Text; namespace ConsoleApplication17 { #region StoreDepartment class StoreDepartment { #region Variables int _itemNo; string _itemName; double _itemPrice; double _size; #endregion #region itemnoproperty public int itemno { get { return _itemNo; } } #endregion

#region itemnameproperty public string itemname { get { return _itemName; } } #endregion #region itempriceproperty public double itemprice { get { return _itemPrice; } } #endregion

Page 57: C# .Net

#region SizeProperty public double size { get { return _size; } } #endregion #endregion

#region Constructor public StoreDepartment(int ino,string iname,double iprice,double isize) { _itemNo = ino; _itemName = iname; _itemPrice = iprice; _size = isize; } #endregion } #endregion }

Go to program.cs and write the folowing code

namespace ConsoleApplication17 { #region MainClass class Program { static void Main(string[] args) { #region Variables int itno; string itname; double itprice; double itsize; #endregion Console.WriteLine("-------------------------"); Console.WriteLine("SPENCERS DEPARTMENT STORE"); Console.WriteLine("-------------------------"); Console.WriteLine("Enteritemno,itemname,itemprice,itemsize"); itno =int.Parse(Console.ReadLine()); itname = Console.ReadLine(); itprice = double.Parse(Console.ReadLine()); itsize = double.Parse(Console.ReadLine());

StoreDepartment store=new StoreDepartment(itno,itname,itprice,itsize); Console.WriteLine("-------------------------"); Console.WriteLine("-------------------------"); Console.WriteLine("item no is"+store.itemno); Console.WriteLine("item name is"+store.itemname); Console.WriteLine("itemprice is"+store.itemprice); Console.WriteLine("item size is"+store.size); Console.WriteLine("total amount is"+store.itemprice*store.size); Console.WriteLine("-------------------------"); Console.WriteLine("-------------------------"); Console.ReadLine(); } } #endregion }

Page 58: C# .Net

Write only

� This property is used to write the data from the data field of a class. � To write the data from the data fields of the class we use set accessor.

Syntax for set accessor

<Access modifier><datatype><propertyname>

{

set

{

variable name=value;

}

}

• A property will not allocate memory to store data.it is used to transfer the data • Properties must not have any arguments • Properties will not have any variables • When we are declaring a property datatype of the property must and should be same with

datatype of the variable

Read-Write Property

� This property is used to read and write the data from the data field of a class. � Read write property consists set and get accessor.

Page 59: C# .Net

Syntax for Read-Write property

Syntax for set and get accessor

<Access modifier><datatype><propertyname>

{

set

{

variable name=value;

}

get

{

Return datafield name;

}

}

Example:

#region StudentClass

class Student

{

#region Variables

int _studentNo;

string _studentName;

int _studentAge;

double _marksinEnglish;

double _marksinMaths;

double _marksinScience;

double _obtainedMarks;

double _percentage;

double _totalMarks=300;

#endregion

Page 60: C# .Net

#region Properties #region studentNo public int studentNo { set { _studentNo = value; } get { return _studentNo; } } #endregion #region StudentName public string StudentName { set { _studentName = value; } get { return _studentName; } } #endregion #region studentage public int studentage { set { _studentAge = value; } get { return _studentAge; } } #endregion #region marksinmaths public double marksinmaths { set { if (value >= 0 && value <= 100) { _marksinMaths = value; } else

{ _marksinMaths = 0; } } get { return _marksinMaths; } } #endregion #region marksinenglish public double marksinenglish { set { if (value >= 0 && value <= 100) { _marksinEnglish = value; } else { _marksinEnglish= 0; } } get { return _marksinEnglish; } } #endregion #region marksinscience public double marksinscience { set { if (value >= 0 && value <= 100) { _marksinScience = value; } else { _marksinScience= 0; } } get { return _marksinScience; } } #endregion

Page 61: C# .Net

#region obtainedmarks public double obtainedmarks { set { _obtainedMarks= value; } get { return _obtainedMarks; } } #endregion #region percentage public double percentage { set { _percentage = value; } get { return _percentage; } } #endregion #region totalmarks public double totalmarks { set { _totalMarks = value; } get { return _totalMarks; } } #endregion #endregion #region Methods public void CalculatetotalMarks() { obtainedmarks = _marksinEnglish + _marksinMaths + _marksinScience; }

#region PercentageOfMarks public void Calculatepercentage() { percentage = (double)_obtainedMarks / _totalMarks * 100; } #endregion #endregion } #endregion #region MainClass class Program { static void Main(string[] args) { #region Variables int _stNo; string _stName; int _stAge; double _minEnglish; double _minMaths; double _minScience; double _omarks; double _percent; #endregion Console.WriteLine("------------------------------------------------------"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine("STUDENT PROGRESS REPORT"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine("ENTER STUDENT ROLLNO:"); _stNo =int.Parse(Console.ReadLine()); Console.WriteLine("ENTER STUDENT ANME:"); _stName = Console.ReadLine(); Console.WriteLine("ENTER STUDENT AGE:");

Page 62: C# .Net

_stAge = int.Parse(Console.ReadLine());

Console.WriteLine("ENTER STUDENT MAKS IN ENGLISH:");

_minEnglish = double.Parse(Console.ReadLine());

Console.WriteLine("ENTER STUDENT MAKS IN MATHS:");

_minMaths = double.Parse(Console.ReadLine());

Console.WriteLine("ENTER STUDENT MAKS IN SCIENCE:");

_minScience = double.Parse(Console.ReadLine());

Student obj = new Student();

obj.studentNo = _stNo;

obj.StudentName = _stName;

obj.studentage = _stAge;

obj.marksinenglish = _minEnglish;

obj.marksinmaths = _minMaths;

obj.marksinscience=_minScience;

obj.CalculatetotalMarks();

_omarks = obj.obtainedmarks;

obj.Calculatepercentage();

_percent=obj.percentage;

Console.WriteLine("-----------------------------------------------------");

Console.WriteLine("-----------------------------------------------------");

Console.WriteLine("STUDENT TOTALMARKS IS:"+_omarks);

Console.WriteLine("TOTAL PERCENTAGE OF MARKS IS:"+_percent+"%");

Console.ReadLine();

}

}#endregion

Page 63: C# .Net

READ-WRITE

namespace ConsoleApplication13

{

#region PersonClass

class Person

{

#region Variables

float _height;

float _weight;

string _name;

int _age;

char _gender;

#endregion

#region Properties public float Height { set { _height = value; } get { return _height; } } public float Weight { set { _weight = value; } get { return _weight; } }

public string Name { set { _name = value; } get { return _name; } } public int Age { set { _age = value; } get { return _age; } }

Page 64: C# .Net

public char Gender { set { _gender = value; } get { return _gender; } } #endregion } #endregion #region MainClass class Program { static void Main(string[] args) {

Person obj=new Person(); obj.Age = 10; obj.Gender = 'm'; obj.Height = 6; obj.Name = “Sunil"; obj.Weight = 30; Console.WriteLine("height is"+obj.Height); Console.WriteLine("name is"+obj.Name); Console.WriteLine("age is"+obj.Age); Console.WriteLine("weight is"+obj.Weight); Console.WriteLine("gender is"+obj.Gender); Console.ReadLine(); } } #endregion

Page 65: C# .Net

Indexers

If we declared an array as a member variable of a class, to access the elements of that member, we had to use an instance of the class, followed by the period operator, followed by the member variable applied with the square brackets. Instead of accessing each element through its member variable, you can create a type of property referred to as an indexer.

Syntax of indexers: Accessmodifier datatype this[int index]

{

get

{

return Arrayname[index];

}

set

{

Array[index] = value;

}

}

EXAMPLE

namespace INDEXERS { #region Sample class Sample { float[] _temp=new float[5]{10.0F,20.3F,30.9F,43.7F,39.8F}; public float this[int index] { get { return _temp[index]; } set { _temp[index] = value; } } } #endregion

#region MyRegion class Program { static void Main(string[] args) { Sample obj = new Sample(); obj[2] = 77.6F; Console.WriteLine(obj[2].ToString()); } Console.ReadLine(); } #endregion }

Page 66: C# .Net

ARRAYS

� An array is a userdefined reference type data type used to store multiple values using same name. � Each array location of the array is identified using its index value. � Always the index start with 0 and end with size-1 � First index of the array is known as lower bound and the last index of the array is known as upper

bound.

Syntax to create an array in C#.net:

Syntax:1 To declare an array

Data type [ ] Array name=new Data type [size];

Ex : int[ ] A=new int[5];

A [0]=10;

A [1]=20;

A [2]=30;

A [3]=40;

A [4]=50;

Syntax:2 To declare an array

Data type [ ] Array name=new Data type [size] {intialising elements};

Ex :Int [ ] A=new int[5]{10,20,30,40,50};

Syntax:3 To declare an array

Data type [ ] Array name=new Data type [ ]{intialising elements};

Ex :Int [ ] A=new int[ ]{10,20,30,40,50};

datatype[] ArrayName; Where datatype is the type of data that the array will store - int, string, char, etc. [] Specifies the size of the array. ArrayName is the name with which we would be using the array

Example usage:- int[] Marks; Initialization Memory is allocated to the array only when it is instantiated. The instantiation can be done in the following methods. Once initialized a default value is assigned to all of the elements depending on their data type - 0 for int, "" (NULL String) for char or string, etc.

Page 67: C# .Net

Arrays can be divided into four categories

� single-dimensional arrays� multidimensional arrays or rectangular arrays� jagged arrays � mixed arrays.

SINGLE DIMENSIONAL A

� An array contains a single row or single column is known as single dimension array.� Single-dimensional arrays are the simplest form of arrays. These types of arrays are used to store

number of items of a predefined type. All items in a single dimension array are stored in a row starting from 0 to the size of array

In C# arrays are objects. That means declaring an array doesn't create an array. After declaring an array, you need to instantiate an array by using the "new" operator.SD Array Structure

ArrayName = new datatype[size]; This step can be done along with the declaration. datatype[] ArrayName = new datatype[size]; Example Usage:- int[] Marks = new int[10]; Note: This creates 10 elements starting from 0 to 9

Arrays can be divided into four categories. These categories are

dimensional arrays imensional arrays or rectangular arrays

SINGLE DIMENSIONAL A RRAY

An array contains a single row or single column is known as single dimension array.dimensional arrays are the simplest form of arrays. These types of arrays are used to store

number of items of a predefined type. All items in a single dimension array are stored in a row starting from 0 to the size of array -1.

jects. That means declaring an array doesn't create an array. After declaring an array, you need to instantiate an array by using the "new" operator.

ArrayName = new datatype[size];

This step can be done along with the declaration.

datatype[] ArrayName = new datatype[size];

Note: This creates 10 elements starting from 0 to 9

An array contains a single row or single column is known as single dimension array. dimensional arrays are the simplest form of arrays. These types of arrays are used to store

number of items of a predefined type. All items in a single dimension array are stored in a row

jects. That means declaring an array doesn't create an array. After declaring an array,

Page 68: C# .Net

Assigning values Each element of the array can be accessed by specifying their index along with the ArrayName. ArrayName[index] = value; Example:- Marks[5] = 99; Values can also be assigned during declaration as follows:- datatype[] ArrayName = {value1, value2, value3 and so on}; Example:- int[] Marks = {100, 13, 69, 99};

Using this process implicitly sets the size for the array. In this case it would be 4. The elements can be accessed by their indexes starting from 0 to 3. Note: In C# Index always starts at 0. Using the following is equivalent to using the above line of code. int[] Marks =new int[4] {100, 13, 69, 99};

Foreach statement

This statement is explicitly used to traverse through arrays. The benefit of using foreach over the normal for statement is that it is not needed to check the size of the array while using the former. Syntax:- foreach(type identifier in expression) { statement 1; statement 2; .... }

EX:For statement

class Program { static void Main(string[] args) { string[] student_names =new string[]{ "kanna", "sunil", "anil", "kareem" };

for (int i = 0; i <student_names.Length ; i++) { Console.WriteLine(student_names[i]); } Console.ReadLine(); } }

Page 69: C# .Net

For each Loop

� Foreach loop is used when no of elements are unknown� In Foreach Loop data type of the loop variable must nd should be the same as data type of the

array or collection � This statement is explicitly used to traverse through arrays. The benefit of using

normal for statement is that it is not needed to chec

In the above program foreach will copy the value

EX:Foreach statement

class Program { static void Main(string[] args) { string[] student_names =new string[]{ "kanna", "Sunil", "anil", "Kareem" };

Multi Dimensional Arrays

Declaration The number of commas ( , ) inside the square brackets [ ] should be one less than the number of dimensions required for the array.Example Usage:- int [ , ] Numbers;

Initialization

int[,] Numbers = new int[3, 4] { {10, 20, 30,40}, {50, 60, 70,80}, {90, 100, 110,120} };

Foreach loop is used when no of elements are unknown Loop data type of the loop variable must nd should be the same as data type of the

This statement is explicitly used to traverse through arrays. The benefit of usingstatement is that it is not needed to check the size of the array while using the former

am foreach will copy the value for Each location

static void Main(string[] args)

string[] student_names =new string[]{ "kanna", "Sunil", "anil", "Kareem" };

foreach (string st in student_names) { Console.WriteLine(st); } Console.ReadLine(); } }

The number of commas ( , ) inside the square brackets [ ] should be one less than the number of dimensions required for the array.

int[,] Numbers = new int[3, 4]

Loop data type of the loop variable must nd should be the same as data type of the

This statement is explicitly used to traverse through arrays. The benefit of using Foreach over the k the size of the array while using the former

foreach (string st in student_names)

Console.WriteLine(st);

Console.ReadLine();

The number of commas ( , ) inside the square brackets [ ] should be one less than the number of

Page 70: C# .Net

Assigning Values Values can be assigned as:- Numbers[0, 2] = 30;

class Program { static void Main(string[] args) { int[,] A = new int[3, 4] { { 10, 20, 30, 40 }, { 50, 60, 70, 80 }, { 90, 100, 110, 120 }}; for (int R = 0; R < 3; R++)

{

for (int c = 0; c < 4; c++) { Console.WriteLine(A[R,c]+" "); } } Console.ReadLine(); } }

Another Example

class Program { static void Main(string[] args) { #region MULDimeArray Syntax-1 int[,] even_nos = new int[3, 4]; even_nos[0, 0] = 2; even_nos[0, 1] = 4; even_nos[0, 2] = 6; even_nos[0, 3] = 8; even_nos[1, 0] = 10; even_nos[1, 1] = 12; even_nos[1, 2] = 14; even_nos[1, 3] = 16; even_nos[2, 0] = 18; even_nos[2, 1] = 20; even_nos[2, 2] = 22; even_nos[2, 3] = 24;

for (int i = 0; i < even_nos.GetLength(0); i++) { for (int j = 0; j < even_nos.GetLength(1); j++) {

Console.Write(even_nos[i,j]+"\t"); } Console.WriteLine(); } Console.ReadLine();

#endregion

Another example

class Program { static void Main(string[] args) { #region MulDimarray-2

float[,] float_nos = new float[3, 3] { { 10, 20, 30 }, { 40, 50, 60 }, { 70, 80, 90 } }; for (int i = 0; i < float_nos.GetLength(0); i++) { for (int j = 0; j <float_nos.GetLength(1); j++)

{ Console.Write(float_nos[i,j]+"\t");

} Console.WriteLine(); } Console.ReadLine(); #endregion } } #endregion

Page 71: C# .Net

Jagged Array

An array inside an array is called jagged array

� To create jagged array first we need to create inner array and then we must create the main array

Syntax:Datatype[ ][ ] Array name =new Data type[ ][ ]{initializing array}

Int[ ] A1=new int[3] {10,20,30};

Int[ ] A2=new int[4] {40,50,60,70};

Int[ ][ ] A=new int[ ][ ]{A1,A2};

A[0][0]…….>10 A[0][1]…….>20 A[0][2]…….>30

A[1][0]…….>40 A[1][1]…….>50 A[1][2]…….>60 A[1][3]…….>70

Example

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication7 { class Program { static void Main(string[] args) { int[]A1=new int[3]{10,20,30}; int[] A2 = new int[4] { 40, 50, 60, 70 }; int[][] A = new int[][]{ A1, A2 }; Console.WriteLine("elements of jagged array");

for (int R = 0; R < A.Length; R++) { if (R == 0) { for (int c = 0; c < A1.Length; c++) { Console.WriteLine(A[R][c] + " "); }Console.WriteLine(); } else { for (int c = 0; c < A2.Length; c++) { Console.WriteLine(A[R][c]+" "); } } } Console.ReadLine(); } } }

Page 72: C# .Net

COLLECTIONS

using System. Collections;

• It is the namespace which is used for providing some predefined classes and interfaces to introduce data structures in .NET.

• Some of the collection classes in this namespace are

� Array List

� Stack

� Queue

� Hash Table

� Sorted List

Array List

� Arraylist will accept any datatype

� The length of array is fixed but arraylist length will automaticaly set dynamically

� This class is used for maintaining different types of information with variant type, dynamic size and provides some methods to overcome all the drawbacks of arrays.

� Syntax for Array List:

� ArrayList Ar = new ArrayList();

Methods in ArrayList Class

� Add():this method is used for adding the elements into arraylist

� Insert():this method is used to insert the elements in arraylist

� Remove():this method is used to remove an elemt from arraylist

� Clear():this method is used to clear

� Reverse():this method is used to arrange the elements of array in reverse order

� Sort():this method is used to sort the elements of array in ascending order.

Page 73: C# .Net

For each Loop

� Foreach loop is used when no of elements are unknown

� In Foreach Loop is much more flexible and useful and can be applied to an array of any size and any datatype

� If you wish to work on arrays to change the individual elements go for foreach loop

� The benefit of using Foreach over the normal for statement is that it is not needed to check the size of the array while using the former

syntax

foreach (var item in collection)

{

…………

}

Example to Add( )in Arraylist

class Program {

static void Main(string[] args) {

ArrayList Ar = new ArrayList(); Ar.Add(10); Ar.Add(20); Ar.Add(30); Ar.Add(40); Ar.Add(50); Ar.Add(60); Ar.Insert(3, 90);

Ar.Remove(20); Ar.RemoveAt(2);

Ar.Sort(); Ar.Clear(); foreach (object Ar1 in Ar) { Console.WriteLine(Ar1); } Console.ReadLine(); }

Page 74: C# .Net

EXAMPLE-2 WITH ARRAYLIST

#region MainClass class Program { static void Main(string[] args) { ArrayList Ar = new ArrayList(); object obj1; object obj2; Console.WriteLine("Enter no and name");

obj1 = Console.ReadLine(); obj2 = Console.ReadLine(); Ar.Add(obj1); Ar.Add(obj2); foreach (object Ar1 in Ar) { Console.WriteLine(Ar1); } Console.ReadLine(); } }#endregion

STACK

� This class is used for maintaining variant type of information with a dynamic size by using LIFO(Last in First Out)

� Ex :Dining Plates.

� It performs insertion and deletions only from one end.

� Methods :

� Push():is used to insert the record

� Pop():it is used to remove the inserted record

#region Stack class Program { static void Main(string[] args) { Stack st = new Stack(); st.Push(10); st.Push(20); st.Push(30); st.Push(40); st.Push(50); st.Push(60);

st.Pop(); St.Clear(); foreach (object st1 in st) { Console.WriteLine(st1.ToString()); } Console.ReadLine(); } } #endregion

Page 75: C# .Net

QUEUE

� It is used for maintaining the information with dynamic size and variant type in FIFO � In queue the insertions will be from one end and deletions from the other end

Methods:

� Enquee():used to insert a value � Dequee():used to remove a value

#region Queue class Program { static void Main(string[] args) { Queue qu = new Queue(); qu.Enqueue(10); qu.Enqueue(20); qu.Enqueue(30); qu.Enqueue(40); qu.Dequeue(); qu.Clear();

foreach (object qu1 in qu) { Console.WriteLine(qu1.ToString()); } Console.ReadLine(); } } #endregion

Hash Table

� This class is used for maintaining the information in key and value pair format. � It is used for fast searching and accessing the elements. � Hash table is used to display the data randomly � Hash Table is implemented from the interfaces like Idictionary,Icollection,Ienumerable,

DictionaryEntry. C# uses an object of this type when using the foreach loop with Hashtables. That's because it automatically returns both the Key and the Value. IDictionaryEnumerator etc……

#region Hashtable class Hashtable { static void Main(string[] args) { Hashtable ht = new Hashtable(); ht.Add(0, 25); ht.Add(10, 250); ht.Add(67, 980); ht.Add(45, 655); ht.Add(70, 225);

foreach (DictionaryEntry d in ht) { Console.WriteLine("the value of key is {0} and the value of value is {1}", d.Key, d.Value); } Console.ReadLine(); } } #endregion

Page 76: C# .Net

Sorted List

� It is used for maintaining the information in key and value pair format as a sorted with key

#region Hashtable class A { static void Main(string[] args) { SortedList st = new SortedList(); st.Add(10, 456); st.Add(0, 56); st.Add(30, 6); st.Add(50, 356); st.Add(63, 63); st.Add(75, 466); st.Add(91, 896);

foreach (DictionaryEntry d in st) { Console.WriteLine("the value of key is {0} and the value of value is {1}",d.Key,d.Value); } Console.ReadLine(); } } #endregion

EXCEPTIONS

� We can overcome three types of errors in our visual studio editor

1. Syntax Errors

2. Compilation Errors

3. Runtime Errors

Syntax Errors

� If the user is typing any syntax then the error will occur. � These errors can be identified when we type the syntax and can be rectified immediately before

execution only. � These errors will not cause any harm to the program which can be easily rectified.

Compilation Errors

� These errors will occur at the time of compiling the code.

� Like assigning the wrong data type to a variable

� Creating an object for abstract class or interface

� Missing the no of arguments for a method, missing return types to a method etc……

� These errors can be rectified while compiling the code and can be rectified easily

� These errors will not cause any harm to the program which can be easily rectified.

Page 77: C# .Net

Runtime Errors

� The error which occur at the time of executing � The program is known as runtime error. � Exception is known as runtime error. � Like entering wrong i/p to a variable � Giving the wrong index value which is out of the range. � Accessing a file for which there are no permissions etc…

Exceptions

� Exceptions cant be identified whenever we type the code and compile the code so we cant rectify the exceptions.

� Exceptions will cause abnormal termination of the program execution as we cannot rectify the exceptions we can handle the exceptions to avoid abnormal termination of the program

Methods to Handle the Exceptions

� Logical Implementation

� Try-Catch Implementation

� On-error go to implementation

Logical Implementation

int a, b, c; private void button1_Click(object sender, EventArgs e) { a = Convert.ToInt32(textBox1.Text); b = Convert.ToInt32(textBox2.Text); if (b == 0)

{ label1.Text = "second no must not be zero"; } else { c = a / b; textBox3.Text = c.ToString(); } }

All the exceptions may not be possible to handle using logical implementation then we use Try-Catch Implementation

Page 78: C# .Net

Try-Catch Implementation

Syntax for try-catch

try

{

----------------------statements

}

catch (Exception class object)

{

----------------------statements

}

finally

{

---------statements

}

Try Block

� It contains all the statements in which there is a possibility of error occurrance. � A Try block should be followed by minimum one catch block. � A try block can contain one or more catch blocks.

Catch Block

� Catch block contains all the statements that what we need to do whenever an exception is raised Finally

� The code that is written in finally block will be executed even if the exception occurs

Page 79: C# .Net

EXCEPTION CLASS

MS has provided different exception classes to handle the exceptions raised by different reasons.

� Exception is the super class for all the exceptions

Properties:

Message: this property stores about the reason why error has been occurred

� System.ArithmeticException-A base class for exceptions that occur during arithmetic operations, such as System.DivideByZeroException

� System.ArrayTypeMismatchException-Thrown when a store into an array fails because the actual type of the stored element is incompatible with the actual type of the array.

� System.DivideByZeroException-Thrown when an attempt to divide an integral value by zero occurs.

� System.IndexOutOfRangeException-Thrown when an attempt to index an array via an index that is less than zero or outside the bounds of the array.

� System.InvalidCastExceptionThrown when an explicit conversion from a base type or interface to derived types fails at run time.

� System.MulticastNotSupportedException-Thrown when an attempt to combine two non-null delegates fails, because the delegate type does not have a void return type.

� System.NullReferenceException-Thrown when a null reference is used in a way that causes the referenced object to be required.

� System.OutOfMemoryException-Thrown when an attempt to allocate memory (via new) fails. � System.OverflowException-Thrown when an arithmetic operation in a checked context

overflows.

Divide by Zero Exception predefined exception

int a, b, c; private void button1_Click(object sender, EventArgs e) { try { a = Convert.ToInt32(textBox1.Text); b = Convert.ToInt32(textBox2.Text); c = a / b;

textBox3.Text = c.ToString(); } catch (Exception e1) { MessageBox.Show(e1.Message); } }

Page 80: C# .Net

User defined exception

private void button1_Click(object sender, EventArgs e) { try { a = Convert.ToInt32(textBox1.Text); b = Convert.ToInt32(textBox2.Text); c = a / b;

textBox3.Text = c.ToString(); } catch (DivideByZeroException) { MessageBox.Show("denominator must not be zero"); }

� While declaring multiple catch blocks the order must be

catch (DivideByZeroException)

{

MessageBox.Show("denominator must not be zero");

}

catch (Exception e1)

{

MessageBox.Show(e1.Message);

}

� If the parent exception class is declared first which is not allowed where it has to handle the remaining exceptions

� In the reverse order it will raise the compile time error.

Page 81: C# .Net

IndexOutOfRangeException

class Program { static void Main(string[] args) { try { int[] Ar = new int[5]; for (int i = 0; i < 10; i++) { Ar[i] = i; } } catch (Exception e1) { Console.WriteLine(e1.Message); } } }

static void Main(string[] args) { try { int[] Ar = new int[5]; for (int i = 0; i < 10; i++) { Ar[i] = i; } } catch (IndexOutOfRangeException) { Console.WriteLine("the array size is 5 but you have incremented with 10"); } }

SqlException

class Program { static void Main(string[] args) { try { SqlConnection con = new SqlConnection("user id=sa;password=1234;database=emp;data source=localhost"); con.Open(); con.Close(); } catch (SqlException) { Console.WriteLine("invalid user credentials"); } } }

try { SqlConnection con = new SqlConnection ("user id=sa;password=1234;database=emp;data source=localhost"); con.Open(); int[] Ar = new int[5]; for (int i = 0; i < 10; i++) { Ar[i] = i; } con.Close(); } catch (IndexOutOfRangeException e2) { Console.WriteLine(e2.Message); } catch (SqlException) { Console.WriteLine("invalid user credentials"); }

Page 82: C# .Net

Logical Exception

private void Form1_Load(object sender, EventArgs e) { SqlConnection con = new SqlConnection("user id=sa;password=1234;database=emp;data source=localhost"); try { con.Open(); con.Close(); }

catch (SqlException) { MessageBox.Show("invalid credentials"); } finally { if (con.State==ConnectionState.Open) { con.Close(); } } }

Format Exception

private void button1_Click(object sender, EventArgs e) { try { a = Convert.ToInt32(textBox1.Text); b = Convert.ToInt32(textBox2.Text); c = a / b; textBox3.Text = c.ToString(); } catch (FormatException) { MessageBox.Show("enter only numbers"); } }

Overflow Exception

catch (Overflow Exception)

{

MessageBox.Show("Enter numbers between " + Int32.MinValue.ToString() + " and " + Int32.MaxValue.ToString());

}

Page 83: C# .Net

Classifications of Exceptions

� System Exceptions : All .NET defined exceptions are examples of System Exceptions. DivideByZeroException,OverflowException etc.. are examples of System Exceptions. All predefined .NET exceptions derive directly or indirectly from SystemException class. SystemException class derives from Exception class.

� Application Exceptions : If none of the exceptions available in .NET, are useful for your program, you can create userdefined exceptions. Userdefined exceptions usually derive from ApplicationException class. ApplicationException class derive from Exception class

ApplicationException

class UserDefinedException:ApplicationException { public UserDefinedException() { Console.WriteLine("userdefined exception"); } } class Program { static void Main(string[] args) { try { throw new UserDefinedException(); }

catch (UserDefinedException e1) { Console.WriteLine(e1.Message); } } } finally { Console.WriteLine("hi"); }

Note

� All exceptions directly or indirectly derive from System. Exception base class.

� It is a compile time error to have try block in isolation. A try block should be followed by a catch or finally block.

� A single try block can have multiple catch blocks but only one finally block.

� We use the throw keyword to raise exceptions programmatically.

Page 84: C# .Net

public delegate void SingleDelegate();

class Program

{

public static void MyFunction()

{

Console.WriteLine("in single func()");

}

static void Main(string[] args)

{

SingleDelegate obj = new SingleDelegate(MyFunction);

obj();

}

}

public delegate int mydelegate(int val1,int val2);

class Program

{ public static int Fun(int a, int b)

{

return a * b;

}

static void Main(string[] args)

{ mydelegate obj = new mydelegate(Fun);

Console.WriteLine("Enter values");

int val1 = int.Parse(Console.ReadLine());

int val2 = int.Parse(Console.ReadLine());

int res=obj(val1,val2);

Console.WriteLine("result"+res);

Console.ReadLine();

} }

Page 85: C# .Net

Multi caste delegate

delegate void mydelegate(int x,int y);

class Program

{

static void Fun1(int x, int y)

{

Console.WriteLine("in method 1");

}

static void Fun2(int x, int y)

{

Console.WriteLine("in method2");

}

static void Main(string[] args)

{

mydelegate obj = new mydelegate(Fun1);

obj += new mydelegate(Fun2);

obj(1, 2);

Console.ReadLine();

}

}

delegate void mydelegate(string s);

class Program

{

public static void Hello(string s)

{

Console.WriteLine("hello, {0}",s);

}

public static void Goodbye(string s)

{

Page 86: C# .Net

Console.WriteLine("goodbye, {0}", s);

}

static void Main(string[] args)

{

mydelegate a, b;

//method hello

a = new mydelegate(Hello);

b = new mydelegate(Goodbye);

Console.WriteLine("invoking delegate a:");

a("A");

Console.WriteLine("invoking delegate b:");

b("B");

Console.ReadLine();

}

}

Files

#region Directory info Class

#region To display the files in the directory

//DirectoryInfo dir = new DirectoryInfo("D:\\6AM");

//FileInfo[] Ar = dir.GetFiles();

//for (int i = 0; i < Ar.Length; i++)

//{

// Console.WriteLine(Ar[i].Name);

//}

#endregion

#region createfileandreadfiles

//StreamWriter sw = new StreamWriter("D:\\ABC.txt");

//sw.WriteLine("hi");

//sw.Close();

Page 87: C# .Net

//Console.WriteLine(File.ReadAllText("D:\\ABC.txt"));

#endregion

#region get the folders in adirectory

//DirectoryInfo dir = new DirectoryInfo("D:\\6AM");

//DirectoryInfo[] Ar = dir.GetDirectories();

//for (int i = 0; i < Ar.Length; i++)

//{

// Console.WriteLine(Ar[i].Name);

//}

#endregion

#region directory history

//DirectoryInfo dirobj = new DirectoryInfo("D:\\6AM");

//Console.WriteLine("---directory info---");

//Console.WriteLine("directory full name is:" + dirobj.FullName);

//Console.WriteLine("directory name is:" + dirobj.Name);

//Console.WriteLine("directory parent " + dirobj.Parent);

//Console.WriteLine("creation time" + dirobj.CreationTime);

//Console.WriteLine("root is" + dirobj.Root);

#endregion

#region GetBmpinformation

//Console.WriteLine("directory bmpinfo");

//DirectoryInfo dirobj = new DirectoryInfo("D:\\");

////to get all files with bmp extension

//FileInfo[] bitmapfiles = dirobj.GetFiles("*.bmp");

////how many were found

//Console.WriteLine("founf {0} *.bmp files \n",bitmapfiles.Length);

//foreach (FileInfo f in bitmapfiles)

//{

// Console.WriteLine( "************* ***************\n");

Page 88: C# .Net

// Console.WriteLine("file name is :"+f.Name);

// Console.WriteLine("file size:"+f.Length);

// Console.WriteLine("creation time"+f.CreationTime);

#endregion

#region createsubdirectoriesin adirectory

//DirectoryInfo dirobj=new DirectoryInfo("D:\\6AM");

//Console.WriteLine( dirobj.CreateSubdirectory("MyFoo"));

//Console.WriteLine( dirobj.CreateSubdirectory("MyFoo\\MyBooks"));

#endregion

#region Getalldrives

//string[] drives = Directory.GetLogicalDrives();

//Console.WriteLine("here are your drives");

//foreach (string s in drives)

//{

// Console.WriteLine(s);

//}

#endregion

#region deletecreateddrives

//Console.WriteLine("press enter to delete directories");

//Console.ReadLine();

//Directory.Delete("D:\\6AM\\MyFoo");

////to delete directory in directory

//Directory.Delete(@"C:\Windows\MyBar", true);

#endregion

#region getinformationregarding all drives

////to get information regarding all drives

//DriveInfo[] mydrive = DriveInfo.GetDrives();

////print drive states

//foreach (DriveInfo d in mydrive)

Page 89: C# .Net

//{

// Console.WriteLine("name is:"+d.Name);

// Console.WriteLine("type is:"+d.DriveType);

// //check to see if the drive is mounted

// Console.WriteLine("free space is "+d.TotalFreeSpace);

// Console.WriteLine("format is:"+d.DriveFormat);

// Console.WriteLine("label is:"+d.VolumeLabel);

//}

#endregion

#endregion

#region FileInfoClass

FileInfo f = new FileInfo("D:\\6AM\\hello.txt");

FileStream fs = f.Create();

fs.Close();

FileInfo f2 = new FileInfo("D:\\6AM\\hello.txt");

FileStream fs2 = f2.Open(FileMode.Open);

Console.WriteLine(fs2);

fs2.Close();

#endregion

Page 90: C# .Net

WINDOWS COMMUNICATION FOUNDATION

OVERVIEW

Windows Communication Foundation takes many existing communication technologies, such as Web

Services, Windows Remoting, Microsoft Message Queuing, and abstracts them into a single technology.

In most cases, this simplifies the way you communicate with other applications. It also allows you to

communicate with other applications without being coupled to a specific technology. Therefore, you

could use Web Services over SOAP to begin with, and later move to remote procedure calls (RPC)

without changing your code, just the configuration of WCF.

THE BASICS

There are a few basic tasks when creating a WCF service. The basic tasks that must be performed are, in

order:

1. Define the service contract. A service contract specifies the signature of a service, the data it

exchanges, and other contractually required data.

2. Implement the contract. To implement a service contract, create the class that implements the

contract and specify some custom behaviors that the runtime should have.

3. Configure the service by specifying endpoint information and other behavior information.

4. Host the service in an application.

5. Build a client application.

For more information, see http://msdn2.microsoft.com/en-us/library/ms732098.aspx

EXAMPLE

To display a step-by-step enactment of the above steps, let’s define a web service that reports the

current date/time:

1.1 DEFINE A SERVICE CONTRACT

First, let’s create a project to house our service contract. Let’s call it

WCFDateTime.Service .

Page 91: C# .Net

1.2 DEFINE A SERVICE CONTRACT

Then, let’s define an interface that represents the service we’re going to provide. In this case,

let’s call it IDateTimeService .

public interface IDateTimeService { }

1.3 DEFINE A SERVICE CONTRACT

We need to add a method to our service that will return the current date/time:

public interface IDateTimeService {

DateTime GetCurrentDateTime(); }

1.4 DEFINE A SERVICE CONTRACT

Now, we need to decorate our code with attributes so that WCF will recognize our interface and

its methods. Namely, we will add the following attributes:

• ServiceContractAttribute

o Identifies an interface as a WCF service contract

• OperationContractAttribute

o Identifies methods of an interface as WCF service operations, that is, methods

that can be called through WCF

using System.ServiceModel; [ServiceContract] public interface IDateTimeService { [OperationContract]

DateTime GetCurrentDateTime(); }

In order to use the above attributes, you’ll need to add a reference to the

System.ServiceModel assembly. The service contract is now ready to be used.

Page 92: C# .Net

2.1 IMPLEMENT THE CONTRACT

Now that we’ve defined our service contract, we can move on to implementing it. First,

let’s create another project to house our server application. Let’s call it

WCFDateTime.Server , and make it a Console Application project.

2.2 IMPLEMENT THE CONTRACT

Now, let’s implement the IDateTimeService . The implementation is going to run on

our server, to provide the date/time to whoever is going to consume our service.

In the WCFDateTime.Server project, let’s create a class called DateTimeService and

have it implement IDateTimeService :

using WCFDateTime.Service; public class DateTimeService : IDateTimeService { }

Remember to add a reference to the WCFDateTime.Service project so you can use

IDateTimeService .

2.3 IMPLEMENT THE CONTRACT

The above code will obviously not compile, because we did not implement the

GetCurrentDateTime method:

public class DateTimeService : IDateTimeService { public DateTime GetCurrentDateTime() { return DateTime.Now; } }

That’s it! The DateTimeService is now ready to be used.

3.1 CONFIGURE THE SERVICE

Now we need to configure our service so it can be consumed by client applications. The

simplest way to accomplish this is by adding an application configuration file (app.config or

web.config) to the WCFDateTime.Server project:

<?xml version="1.0" encoding="utf-8" ?> <configuration>

Page 93: C# .Net

<system.serviceModel> <services> <service name="WCFDateTime.Server.DateT imeService"> <endpoint address="http://localhost:8081/ DateTimeService" binding="wsHttpBinding" contract="WCFDateTime.Service.I DateTimeService" /> </service> </services> </system.serviceModel> </configuration>

When defining an endpoint for WCF, remember your A-B-Cs:

1. Address (where)

2. Binding (how)

3. Contract (what)

The address specifies the address where you want the service to be located.

The binding specifies the transport you want to use in order to provide the service.

The contract specifies what service will be provided

4.1 HOST THE SERVICE IN AN APPLICATION

Now that WCF has been configured, the simplest way to host this service is to create a Console

Application and use the ServiceHost class. First, add a reference to the

System.ServiceModel assembly. Then, In the program.cs file of

WCFDateTime.Server , do the following:

using System.ServiceModel; namespace WCFDateTime.Server { class Program { static public void Main(string[] args) { // Get a host for our service ServiceHost serviceHost = new ServiceHo st( typeof(DateTimeService) ); // Open the service host to start liste ning for incoming requests serviceHost.Open(); // The service can now be accessed

Console.WriteLine("The service is ready."); Console.WriteLine("Press <ENTER> to terminate service."); Console.ReadLine();

Page 94: C# .Net

// Close the service host serviceHost.Close(); } } }

By simply running this application, we expose our service so that client applications can use it.

Page 95: C# .Net

5.1 BUILD A CLIENT APPLICATION

To build a client application, we must create a new project for it. Let’s call it

WCFDateTime.Client , and make it a Console Application as well.

5.2 BUILD A CLIENT APPLICATION

Now, we need to add an Application Configuration file, and give it some settings that will allow

us to connect to the service we just created:

<?xml version="1.0" encoding="utf-8"?> <configuration> <system.serviceModel> <client> <endpoint address="http://localhost:8081/Date TimeService" binding="wsHttpBinding" contract="WCFDateTime.Service.IDate TimeService" name="MyDateTimeService"> </endpoint> </client> </system.serviceModel> </configuration>

Now that our we’ve configured our WCF client, we can connect to it. There are two ways to

connect to the WCF service we previously created:

1. Client proxy generation

2. Channel factories

Most Microsoft articles will point you in the direction of using client proxies; however, for our

purposes, channel factories are quicker to implement and more robust in a

Model/View/Presenter architecture.

Page 96: C# .Net

5.3 BUILD A CLIENT APPLICATION

Now, add a reference to the System.ServiceModel and WCFDateTime.Service assemblies,

and then add the following to the program.cs file:

using System.ServiceModel; using WCFDateTime.Service; class Program { public static void Main(string[] args) { // Get a channel factory for our service, // using the configuration for "MyDateTimeS ervice" // in the application configuration file. ChannelFactory<IDateTimeService> channelFac tory = new ChannelFactory<IDateTimeService>("M yDateTimeService"); // Get an instance of our service IDateTimeService service = channelFactory.C reateChannel(); // Get the server’s date/time DateTime dt = service.GetCurrentDateTime(); // Write the current server date/time Console.WriteLine("The current server time is " + dt); // Close the connection to our service channelFactory.Close(); } }

5.4 BUILD A CLIENT APPLICATION

Your client application is now ready to run! Simply start the WCFDateTime.Server

application, and once it’s running, run the WCFDateTime.Client application to see it work!

Page 97: C# .Net

WCF

1.Introduction

The aim of this article is to explain the basics of WCF in a manner as simple as possible.It is

assumed that the reader doesn’t know anything about WCF or .NET 3.0, however he/she is

expected to know .NET 2.0 and/or simple facts like what is a web service.While writing this

article (or for any other) I always try to avoid difficult technical words, which may confuse the

reader. I have tried to put it in as simple words as possible.At the end of this article, I would

hope you understand at least some of the key WCF areas and possibly be inspired enough to try

out a project on your own.

2.Contents

1. Introduction

2. The most suitable reader for this article.

3. Prerequisites

4. A brief overview of demo service

5. Explanations of fundamentals involved

6. The demo Service with code

7. Conclusion

The Most suitable reader for this article

Any .NET Developer who wants to start with WCF can be most benefitted from this article.

3. Prerequisites

To run the code supplied with this article you need to install .NET 3.0 API available with Visual

Studio 2008.

4. A brief overview of demo service

Page 98: C# .Net

In this demo WCF service we are trying to carry out the following functionality:

a) Create a service b) Host the service c) Create a client for the service d) Let the client interact with the service.

To achieve the above functionality we will create three inter related assemblies as mentioned below:

a) SampleService.dll – this is the actual WCF service that allows clients to connect

b) SampleHost.dll – this is the dll that hosts WCF service, SampleService.dll

c) SampleClient.dll – this is the client assembly which communicates with SampleService.dll.

Note that the programming language used here is C#.

5. Explanations of fundamentals involved

Assuming that the reader has no Background in WCF, there are a number of key concepts that

needs to be explained in order for the full application to be understood.

So I will just explain each of these a little bit at a time, so that the final application will be a little

easier to understand.

Key Concepts:

a) What is WCF?

WCF stands for Windows Communication Foundation.

WCF is advanced API (Application Programming Interface) for creating distributed

applications using .NET framework.

It is introduced in .NET 3.0.

Distributed system in its simplest form is two executable running and exchanging data.

WCF API is found in System.ServiceModel namespace.

WCF is based on basic concepts of Service oriented architecture (SOA)

Page 99: C# .Net

b) What is a WCF Service?

A WCF service is a program that exposes a collection of Endpoints (connections) for

communicating with either client applications or other service applications.

c) What are the components of WCF application?

There are three main components of a WCF application

i) a WCF service

ii) a WCF service host

iii) a WCF service client

d) What is the “ABC” of a WCF Service?

“ABC” of WCF stands for addresses Bindings and contracts respectively.

i) Addresses: This is location of the service in the form of an

URI (Uniform resource Identifier) generally mentioned

In the config file.

ii) Bindings: This includes the type of network protocol used by the

Service. For Example HTTP, TCP/IP or others.

iii) Contracts: This is in fact the methods exposed by the WCF service.

e) What is a Service Contract in WCF application?

Service contract is the name of the attribute which is applied to an interface in a WCF

service.

f) What is an Operation Contract in WCF application?

Operation contract is the name of the attribute which is applied to a method inside the

interface of a WCF service

Page 100: C# .Net

6. The demo Service with code

Before I start, I would like to remind you again that this is the simplest of WCF service only for

understanding purpose. In real world you might have to build/face much more complicated WCF

service.

I have divided this part in five sub-parts as below.

a) Building the WCF service

b) Building the WCF host

c) Building the Proxy to be used by client

d) Building WCF client

e) Testing the working of the whole application.

a) Building the WCF service

To understand the service better we will build the service as a c# class library project. Follow the

following steps:

In my case it created the class1.cs with content as below.

i) Open Visual Studio 2008

ii) Select Create ProjectàC# class library name it “Sample Service”

iii) It will crate a .cs file in the project. Open that file.

using System; using System.Collections.Generic; using System.Linq;

Page 101: C# .Net

using System.Text; namespace SampleService { public class Class1 { } }

Change the namespace SampleService to SampleServiceLib,

Rename the Class1 to SampleService.

Rename the Class1.cs file in the solutionExplorer to SampleService.cs

Add the namesapce using System.ServiceModel at the top.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace SampleServiceLib { public class SampleService { } } The SampleService.cs file should now look like below.

iv) At this point the project will not build, so please add a reference to

System.Service Model.

For this, Go to solution Explorer ,Right click on the reference Add Reference .NET

Tab Select System.ServiceModel OK.

Now you can successfully build the Project.

Page 102: C# .Net

v) Create an interface named IAnswer in this file inside SampleServiceLib

namespace.Create a method inside the interface IAnswer, named ObtainAnswer

The attributes for the interface and the method should be ServiceContract and

OperationContract respectively

vi) Implement the IAnswer interface in SampleService class as

Shown in the code sample below.

namespace SampleServiceLib { public class SampleService : IAnswer { public string ObtainAnswer(string Question) { return "My Profession is Software Development"; } } [ServiceContract] public interface IAnswer { [OperationContract] string ObtainAnswer(string Question); } }

vii) Now ad a constructor to the class SampleService and the final

code should look like this.Build this project.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace SampleServiceLib {

Page 103: C# .Net

public class SampleService : IAnswer { public SampleService() { Console.WriteLine("Ask question to SampleService... ."); } public string ObtainAnswer(string Question) { return "Your Profession is Software Dev eloper"; } } [ServiceContract] public interface IAnswer { [OperationContract] string ObtainAnswer(string Question); } }

viii) Save the sample service Project by File Save All. Then build it so that you will get a

SampleSevice.dll in its bin\release directory.

b) Building the WCF host

A WCF host may be IIS (Internet Information Server) , Windows Service, A console application

etc.The simplest of them is a console application host. So we will demonstrate that here.

Follow the following steps:

i) Open Visual Studio 2008

ii) Select Create ProjectàC# Console Application name it “Sample Host”

iii) From Solution Explorer,Add the reference of System.ServiceModel to this project as before

Page 104: C# .Net

and

iv) also add the reference of SampleServiceLib.dll from SmpleService Class library project you

created before by addreference Browse Tab Browse to the SampleServiceLib.dll in the project

SampleService’s Bin/release folder.

v) Open its Program.cs file and add the following two namespace to the

Using Section. Using System.ServiceModel Using SampleServiceLib

vi) Build the project successfully.

vii) Add the following console.Writeline codes to program.cs so that the final Program.cs

Should look Like as below.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using SampleServiceLib; namespace SampleHost { class Program { static void Main(string[] args) { Console.WriteLine("Sample Host of Sampl e Service is running...."); using (ServiceHost servicehost = new ServiceHost(typeof(SampleService))) { servicehost.Open(); Console.WriteLine("The SampleServic e is ready now..."); Console.WriteLine("Press enter to t erminate the SampleService..."); } Console.ReadLine(); } } }

Page 105: C# .Net

viii) Adding the config File to the Host :

Go to the Solution Explorer of the Sample Host

Right Click Add New Item Application Configuration File

A file named app.config will be added to the solution.

Initial content of the file is given below

<?xml version="1.0" encoding="utf-8" ?> <configuration> </configuration>

ix) Add the code inside the configuration tag of app.cofig so that the final app.cofig

should look like as below

<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <services> <service name="SampleServiceLib.SampleService " behaviorConfiguration="SampleServiceMEXBehavior"> <endpoint address="http://localhost:8080/SampleService" binding="basicHttpBinding" contract="SampleServiceLib.IAnswer"></endpoint> <endpoint address="mex" binding="mexHttpBin ding" contract="SampleServiceLib.IAnswer"></endpoint>

Page 106: C# .Net

<host> <baseAddresses> <add baseAddress="http://localhost:8080/SampleService"/> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="SampleServiceMEXBehavior" > <serviceMetadata httpGetEnabled="true" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>

x) Build the Service host application and run it. You should get a console Window while host

is running.

Page 107: C# .Net

c) Building the Proxy to be used by client

Before building a client you need to build a proxy of the service which the client will use to interact

with the service.

A proxy is nothing but a .cs file and a .config file generated by a tool called svcutil.exe using your

service Sampleservice.dll

Steps to create the Proxy:

i) Create a Proxy folder in your c:\ drive.

ii) Search for the svcutil.exe file on your computer and copy it to the Proxy folder.

iii) Copy the dll of the service you created (sampleservice.dll) to this Proxy folder.

iv) Go to Start Run cmd

v) On the command prompt change the directory to Proxy folder.

vi) Run the following command

C:\ Proxy svcutil.exe SampleService.dll

This will create a few files in the current directory like

.wsdl, .xsd etc

vii) The run the following command

C:\ Proxy svcutil.exe *.wsdl *.xsd /language:C#

/out:SampleProxy.cs /config:app.config

It will create two files in the Proxy folder

SampleProxy.cs and app.config.

These are your proxy files to be used in the Client.

viii) Open the SampleProxy.cs file, it has the AnswerClient class which has the ObtainAnswer

Method from SampleService.

d) Building WCF client

i) Open Visual Studio 2008

ii) Select Create ProjectàC# Console Application name it “SampleClient”

iii) From Solution Explorer,Add the reference of System.ServiceModel to the project as before.

iv) Add the two proxy file SampleProxy.cs and app.config to the solution.

v) Open the app.config File .You will find that inside of client Tag,the endpoint tag does not have

Page 108: C# .Net

“address” attribute.

vi) add the attribute address="http://localhost:8080/SampleService" to the endpoint tag of the

app.config file.

vii) Now add code to Program.cs so that final Program.cs should look like as below

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace SampleClient { class Program { static void Main(string[] args) { Console.WriteLine("Ask question"); //the name AnswerClient is generated au tometically by svcutil.exe tool which creates //chat proxy and app.cofig //by browsing the service url after ref erence. using (AnswerClient client = new Answer Client()) { Console.WriteLine("Your Question: "); string question = Console.ReadLine( ); string answer = client.ObtainAnswer (question); Console.WriteLine(answer); Console.ReadLine(); } } } }

viii) Build the application. Now the client is ready.

e) Testing the working of the whole application

Page 109: C# .Net

To Test the service follow the steps below.

i) Run the Sample Host Application

ii) Run the client application

iii) Write the following question on client console “What is my Profession”

iv) The reply fro service will come as “Your Profession is Software Developer.”

Conclusion

I have enjoyed writing this WCF Service article and I hope you will enjoy reading it. In real world you may

have to face far more complicated WCF services than this sample.

ALL THE BEST

M.Umamaheswara Reddy

[email protected]