Search This Blog
29 June, 2010
Types of Application
You should be aware what is a program. What all are the key factors in a program...
So first lets start with the Basics.....
We all are creating Applications. So lets check what all are the functions performed by an Application.
The functions performed by an application can be divided into three categories
User services
Business services and
Data Services
User Services layer constitutes the front end of the solution. It is also called the Presentation Layer because it provides the interactive user interface.
The business services layer controls the enforcement of business rules on the data of an organization.
Business rules encompass those practices and activities that define the behavior of an organization.
The data services layer comprises of the data and the functions for manipulating this data.
TYPES OF APPLICATIONS
Applications may vary from Single-tier desktop applications to multi-tier applications (two, three or n-tier architecture).
SINGLE-TIER Architecture
In a single-tier architecture a single executable file handles all functions relating to the user, business and data service layers. Such an Application is also called Monolithic applications.
TWO-TIER Architecture
The tow-tier architecture divides an application into two components:-
Client - Implements the user interface
Server - Stores Data
In case for this architecture the user and data services are located separately either on same machine or in separate machine.
THREE-TIER Architecture
In case of Three-Tier architecture all the three service layers reside Separately, either on the same machine or on different machine. The user interface interacts with the Business logic. Business logic validates the data sent by the interfaces and forwards it to the database if it confirms to the requirement.
n-TIER Architecture
An n-tier application uses business objects for handling business rules and data access. It has multiple servers handling business services. This application architecture provides various advantages over other types of application architectures. The advantages include extensibility, resilience to change, maintainability and scalability of the application.
What is Object Oriented Programming?
Object Oriented Programming(OOP)
Object Oriented Programming was first introduced in 1960’s.The main reason behind this programming is to make the program user friendly. OOP concept is related to the real-world system (i.e concept of Classes and Objects).
What is a CLASS?
Class is just a Virtual concept of a collection of related items together which we cannot see or feel.In programming we create Classes to define collection of related variables and functions.
Class is a user defined Data Type
What is an Object?
In simple words -- Object is an Instance of a Class. We can access a Class only through its Objects.Without objects we cannot say a Class is existing.A thing which has the properties of a class is known as Objects.
For eg:- Car is a Class and Tata Indica is an Object of the class Car
Objects….
We generally identify object by its State, Behavior and Identity.
If we take a car Indica its state is its color, wheel, body, etc….
Its Behavior is moving, changing gears etc…
And the identity of the car is its Number lets say KL-7 AD 2544.
Here state and behavior may be same for many objects but the identity of object will not be same for other object.
Characteristics of OOProgramming…
The main characteristics of Object Oriented Programming are:-
Inheritance
Encapsulation
Abstraction
Polymorphism
INHERITANCE
The ability of a class (Derived Class) to derive or Inherit the properties of another class (Base Class) is called Inheritance.Inheritance helps in the reusability of code hence making the program smaller and easy to use.
Eg:- Parent child relationship. Child is Inherited from its parents
ENCAPSULATION
Process of Hiding the data from a user is called Encapsulation; also called Data Hiding.
ABSTRACTION
The process of showing essential features without giving any explanations is known as Abstraction.
POLYMORPHISM
The name Poly Morphism means Many Forms. It is the process by which we create same things with different behaviors.
Eg:- Function overloading…
Access Specifiers in C#
An access specifier defines the scope of a class member. A class member refers to the variables and functions in a class. A program can have many classes. The programmer gets the privilege to decide the of use access specifier to implement encapsulation and abstraction in C#.
So, when we use Access Specifiers in C# they help the other class members to know how they can access the methods or variables declared/defined inside another class.
C# supports five types of access specifiers to tell the extent of visibility of a class member. They are:-
public,
private,
protected,
internal and
protected internal.
Let's now go into detail.
public:
The public access specifier in C# allows a class to expose its member variables and member functions to other functions and objects. So any member declared public can be accessed outside the class also.
Let's check an example for this..
----------------------------------------------------------------
using System;
namespace HelloWorld
{
class hello
{
public int iNum1;
}
class MyMainClass
{
static void Main(string[] args)
{
hello HelloObject=new hello();
HelloObject.iNum1=10; /* since variable iNum1 is public it can be accessed in other classes also*/
Console.WriteLine(HelloObject.iNum1);
}
}
}
----------------------------------------------------------------
private:
The private access specifier in C# is just opposite to the public access specifier. That is it allows a class to hide its member variables and member functions from other class objects and functions. So it is not visible outside the class. By default, the access specifier is private; if public, private or protected is not specified.
Let's check an example for this..
----------------------------------------------------------------
using System;
namespace HelloWorld
{
class hello
{
public int iNum1;
private int iNum2;
public hello()
{
iNum1=0;
iNum2=10;
}
}
class MyMainClass
{
static void Main(string[] args)
{
hello HelloObject=new hello();
//CORRECT METHOD
HelloObject.iNum1=10; //Here since variable iNum1 is public it can be accessed in other classes also
//WRONG METHOD
HelloObject.iNum2=20; /*This line will return an Error since the access to this variable is Private. So it cannot be accessed outside the class*/
Console.WriteLine(HelloObject.iNum1);
}
}
}
----------------------------------------------------------------
protected:
The protected access specifier in C# allows a class to hide its member variables and member functions from other class objects and functions, except the child class. This access specifier is used when we need to use Inheritance in the program.
Let's check an example for this..
----------------------------------------------------------------
using System;
namespace HelloWorld
{
class hello
{
public int iNum1;
protected int iNum2;
}
class world : hello
{
public int AddDetails()
{
iNum1=20;
iNum2=10;
return iNum1+iNum2;
}
}
class MyMainClass
{
static void Main(string[] args)
{
world worldObject=new world();
worldObject.iNum1=50; //Line 1 No Error
worldObject.iNum2=10; //Line 2 Error
Console.WriteLine(worldObject.AddDetails().ToString());
}
}
}
----------------------------------------------------------------
In the above case we have not called the object of the class hello. But we have inherited the class hello to the class world. So all the public and protected members inside the class is accessible inside the derived class also. We don't need to create objects for the base class to access the variables or methods we have in our parent class.
Now inside the Main() function we are assigning value to iNum1 and iNum2. Line 1 will not return any error because the variable iNum1 is public. So, it can be accessed from anywhere in the program, but Line2 will give an Compilation Error saying "iNum2 is inaccessible due to protection level". This is because access of the variable iNum2 is set to protected. The protected members can only be accessed inside the Child class and its parent class.
internal:
The internal access specifier in C# allows a class to expose its member variables and member functions to other function and objects. It can be accessed from any class or method defined with the application in which the member is defined. The default access specifier is internal for a class.
protected internal:
The protected internal access specifier in C# allows methods or member variables accessible to a class and its derived classes inside the same assembly or namespace within a file. These members cannot be accessed from class inside another assembly or a file.
Lets now understand the above with an example:
----------------------------------------------------------------
using System;
class Student
{
private string sAddress;
protected string sPhNo;
protected internal long iZipCode;
void Hello()
{
Console.WriteLine(“Hello World!”);
}
internal void Hello2()
{
Console.WriteLine(“Hello Student!”);
}
public void SetAddress()
{
Console.WriteLine(“Enter your Address:”)
sAddress = Console.ReadLine();
}
public void SetPhNo()
{
Console.WriteLine(“Enter your Phone Number:”)
sPhNo = Console.ReadLine();
}
public void SetZipCode()
{
Console.WriteLine(“Enter the Zip Code: “);
iZipCode =Convert.ToInt64(Console.ReadLine());
}
public void DisplayStudent()
{
Console.WriteLine(“The Address is: {0}”, sAddress);
}
}
class Display
{
static void Main(string[] args)
{
Student John = new Student();
Console.WriteLine(John.sAddress); //Error: protected members cannot be accessed
John.SetAddress(); //public members can be accessed outside the class definition
John.SetPhNo(); //public members can be accessed outside the class definition
Console.WriteLine(John.sPhNo); //error: protected internal members cannot be accessed outside the class definition
John.SetZipCode(); //public members can be accessed outside the class definition
John.DisplayStudent(); // public members can be accessed outside the class definition
Console.WriteLine(John.sAddress); //error: private members cannot be accessed outside the class definition
John.Hello(); //error: private members cannot be accessed outside the class definition
John.Hello2(); //displays Hello student!
Console.ReadLine();
}
}
----------------------------------------------------------------
C# Array
Let’s see how we can declare an array in C#.
If you need to create a character array to store ten elements then we can declare it like this…
char[] cArr=new char[10];
To pass values to an Array at the time of declaration we can write an array like this…
char[] cArr={‘H’,’e’,’l’,’l’,’o’,’!’};
Since this is a character array we can only pass single values.
We’ll now see how we create arrays for each type..
Integer Array in C#
--------------------
int[] iArr=new int[10];
or
int[] iArr={1,2,3,4,5};
String Array in C#
-------------------
string[] sArr=new string[10];
or
string[] sArr={“Hello”,”world”};
In an array.. items are stored in index of the array. For retrieving values in an array we must mention the index. Always the first index of an array will be 0 and the last index will be the size of the index minus 1 ie if the size is 10 for an array the last index will be 9.
In the above case of the string array the values “Hello” and "World" will be stored in two index of the array. The index of the “Hello” will be 0 and “World” will be 1.
If we need to just print hello on the screen then we must have to write..
Console.WriteLine(sArr[0]);
Here in the above code sArr is the Array name and 0 is used to mention the Element in which index should be selected likewise if we need to print World then we must have to say sArr[1]..
Now we will check how we can print all items in an Array. For doing this we can use two types of loops.
The first one is for loop…
For loop to display Elements in an Array
-----------------------------------------
for(int i=0;i
{
Console.WriteLine(sArr[i]);
}
Here in the above case we have written int i=0 in the for loop and for printing we have just written it sArr[i] here we says I because its having the values from 0 to the value less than the length of the array.
So, when the loop works for the first time its value will be 0 so it prints “Hello” and when it goes for the second time the value is 1 so it prints “World” and when it goes for the third time the value is not less than 2 ie the length is two for the array and now the value of I is also two so it terminates…..
When we use for loop it have a drawback ie we must know the size of the array. For curing that we have another loop ie foreach loop in c#.
In a foreach loop its not necessary to know the size of the array…
We’ll just see one foreach loop for the same array…
Foreach loop to display items in an array..
-------------------------------------------
foreach(string s in sArr)
{
Console.WriteLine(s);
}
In the above code we are using foreach loop if just see the two loops itself we can see the difference. In a Foreach loop we don’t need to mention the array size to be printed…. When we run the foreach loop it will store the first element in string variable s and prints it and next time it will automatically gets incremented to the next element and prints the second element…. Likewise it will run till the array terminates..
Destructor in C#
If there is a class with the name "Hello" we can represent its destructor as
~Hello()
Destructors cannot be overloaded, Inhertied or have Modifiers defined to it.
we can see a Simple program..
-------------------------------------------------
using System;
namespace Destructorss
{
class One
{
//Constructor
public One()
{
Console.WriteLine("First Constructor Called");
}
//Destructor
~One()
{
Console.WriteLine("First destructor is called.");
}
}
class Two : One
{
//Constructor
public Two()
{
Console.WriteLine("Second Constructor Called");
}
//Destructor
~Two()
{
Console.WriteLine("Second destructor is called.");
}
}
class Three : Two
{
//Constructor
public Three()
{
Console.WriteLine("Third Constructor Called");
}
//Destructor
~Three()
{
Console.WriteLine("Third destructor is called.");
}
}
class MyDestructor
{
static void Main()
{
Three t = new Three();
}
}
}
/*The result of this Program will be:-
First Constructor Called
Second Constructor Called
Third Constructor Called
Third destructor is called.
Second destructor is called.
First destructor is called.
*/
-------------------------------------------------
In the above program we have constructors and Destructors. Constuctors invoke from the First to the Third while Destructors go just in the Opposite way ie it starts from Third destrucor and goes to First....
C# Enum - Enumerator
Let's see an example for that
--------------------------------------
enum Gender { Male, Female };
or
enum Gender : int { Male, Female };
--------------------------------------
The above one is and Enumerator with the name Gender. Now we can get the values Male or Female using the enumerator Gender. By default the Value of the First element of the enumerator will be 0 and the rest will be increased by 1.
If you need to use the Enumerator then you can access it using the Gender keyword.
--------------------------------------
Console.WriteLine(Gender.Male);
or
Console.WriteLine(Gender.Female);
--------------------------------------
and if you need to take the value of this Enumerator you can do it like this..
--------------------------------------
int i=(int)Gender.Male;
--------------------------------------
Here in the above code the value will be 0 for the variable i, and if you can take Female the value will be 1.
You can change the values of the enumerator elements in manual.
--------------------------------------
enum Gender { Male=1, Female };
--------------------------------------
Here we forcefully change the value of the first element of the enumerator, so all the rest will be having values after that.
Now let's See and Example for C# Enumerator..
--------------------------------------
using System;
namespace ConsoleApplication1
{
class Program
{
//Creating an Enumerator
enum WeekDays { Sunday=1, Monday,Tuesday, Wednesday,Thursday, Friday, Saturday};
static void Main(string[] args)
{
Console.WriteLine("The value for the week day {0} is {1}",WeekDays.Thursday, (int)WeekDays.Thursday);
}
}
}
--------------------------------------
The output of the Program will be:-
The value for the week day Thursday is 5.
C# Functions/Methods
When a complex application is divided into methods, code becomes more flexible, easy to maintain and to debug. For performing repetitive tasks methods are useful. Methods allow breaking an application into discrete logical units, which makes the application more readable. Code written in a method can be reused since it can be executed any number of times by calling the method itself with little or no modification.
The syntax of defining a method is given below:
-------------------------------------------------
<> (Parameter list)
{
//Method body
}
-------------------------------------------------
Let's look at an example:
-------------------------------------------------
public void Hello()
{
Console.WriteLine("Hello World!");
}
-------------------------------------------------
Here "public" keyword shows the access to this method/function. When we use public access specifier the method can be accessible inside and outside the class.
"void" refers to the return type of the method. Void means nothing should be returned and Hello() is the function/method name. Functions/methods will be having opening and closing parenthesis.
What is an Interface in C#?
This will be certain contracts that we need to Implement into our C# class. Interface will not be having any definitions for the methods and properties it has. We just create the Prototype of methods and Properties we need to implement inside the class. Which all classes Inherit these Interfaces Must have the definitions for the Methods and Properties which we have Declared inside the Interface. We create an Interface using the interface keyword.
C# Interface
Here is an example for the Interface program.
----------------------------------------
interface IStudent
{
int RollNo
{
get;
set;
}
string Name
{
get;
set;
}
void DispDetails();
}
-----------------------------------------
The above one is an interface named IStudent. In this there are two Properties namely RollNo and Name. There is also a Method named DispDetails(). If you look at the codes... we don't have any definitions for these properties and Method(s).
Now, we will check how we can implement these codes inside a Class.
Exaple for C# Interface:-
-----------------------------------------
//Inheriting interface IStudent to class MySchool
class MySchool : IStudent
{
int iRollNo = 0;
string sName = "";]
//Definition for Property Declared inside the Interface
public int RollNo
{
get { return iRollNo; }
set { iRollNo = value; }
}
public string Name
{
get { return sName; }
set { sName = value; }
}
//Definition for Method Declared inside the Interface.
public void DispDetails()
{
Console.WriteLine("The RollNo is:{0} and the Name is {1}", iRollNo, sName);
}
static void Main(string[] args)
{
MySchool sObj = new MySchool();
sObj.RollNo = 12500;
sObj.Name = "SMILU";
sObj.DispDetails();
}
}
--------------------------------------------
In the above class MySchool we have Inherited the IStudent interface. So it's mandatory that we must write the Definitions for those methods and Properties declared inside the Interface.
Now, If in case we don't give a definition for any method or property declared inside the Interface, it will throw Error(s) and we will not be able to execute the program.
C# Functions/Methods
When a complex application is divided into methods, code becomes more flexible, easy to maintain and to debug. For performing repetitive tasks methods are useful. Methods allow breaking an application into discrete logical units, which makes the application more readable. Code written in a method can be reused since it can be executed any number of times by calling the method itself with little or no modification.
The syntax of defining a method is given below:
-------------------------------------------------
<> (Parameter list)
{
//Method body
}
-------------------------------------------------
Let's look at an example:
-------------------------------------------------
public void Hello()
{
Console.WriteLine("Hello World!");
}
-------------------------------------------------
Here "public" keyword shows the access to this method/function. When we use public access specifier the method can be accessible inside and outside the class.
"void" refers to the return type of the method. Void means nothing should be returned and Hello() is the function/method name. Functions/methods will be having opening and closing parenthesis.
Methods with return type in C#
We use methods with a return type when we need a method to return some values to the place from which the method has been called. Return type can be of any type. If we need to return and Integer we can use int keyword. Likewise we can return string, float, double, Class etc...
While we create a method with a return type it should have the keyword "return" followed by the value of the type the method returns...
If the method is returning an integer we can write it as return 0. Because 0 is an integer.
Let's check an example for methods with a return type...
-----------------------------------------
Example 1:-
------------
//Method with an integer return type
public int Add()
{
int iResult=10+20;
return iResult;
}
------------
Here we have used the return keyword to return the value inside the integer variable iResult. So if we call the method Add() we will be getting the sum of the two numbers.
Example 2:-
------------
//Method with a string return type
public string HelloWorld()
{
return "Hello World!";
}
------------
In the above example we have created a method with a string return type. Here we are returning the string "Hello World!".
-----------------------------------------
While we call a method with a return type it should also be stored into the same type. Like wise we can create method(s) with return types.
Now we'll see methods with parameters that return values.
Parameters are used inside a method to pass values to a method at the time of call. We must specify the types of variables inside the method parenthesis for accepting values. Parameters which we declare inside the method parenthesis is also known as Function signatures. While we pass values to methods which accepts values, it should be passed in the exact order in which we have defined that method.
Let's check a method with parameters:-
-----------------------------------------
class Calculator
{
public int AddNumber(int num1, int num2)
{
int result;
result = num1 + num2;
return result;
}
}
-----------------------------------------
Here AddNumber is the name of the method. Since the access specifier is public, the method can be accessed from outside the class also. The method is taking two integers as the parameters and returning the value stored in the result variable. So, we must have to pass two integer values while we call this method. The values passed to this method will be stored in num1 and num2 variables.
eg:-
static void Main(string[] args)
{
int iResult=AddNumber(10,20);
Console.WriteLine(i);
}
Here we have called the method AddNumber. Since the method returns an integer it is assigned to an integer variable. Likewise we should do in each function which have return type..
Conditional Operators in C#
if-else constructor is used to check conditions using. if-else will be always having two conditions True or False.
Let's see a simple if-else constructor.
--------------------------------------
if(Condition)
{
// true part;
}
else
{
// false part;
}
---------------------------------------
In the above set of code we are using an if-else constructor to check a condition. Now if the Condition we have typed inside the if is TRUE it will get inside the True part of the constructor and if the condition is false it will enter inside the false part. The CONDITION may Contain operators like Arithmetic, Relational and Logical for checking different types of conditions.
Now, Lets check a real problem with if-else....
I have two integer variables nameley iNum1 and iNum2. I am going to check which number is bigger.
----------------------------------------
//Assigning values for the two variables
iNum1=10;
iNum2=20;
//Starting the condition
if(iNum1>iNum2)
{
Console.WriteLine("The condition is TRUE");
}
else
{
Console.WriteLine("The condition is FALSE");
}
----------------------------------------
Here iNum1 is assigned a value of 10 and iNum2 is assigned a value of 20. Now when the program gets executed the condition will be returning false because iNum1 variable is smaller than iNum2.
So, it will print "The condition is FALSE" on the screen.
Like this if the condition gets true it will enter into the true part ie the "if" body of the program and if condition gets false it enters into the else part of the Program.
We can also have multiple nested if conditions on a single if-else constructor. Let's check another example of checking which number is bigger out of three numbers.
I have three variables namely iNum1,iNum2,iNum3.
------------------------------------------
if(iNum1>iNum2 && iNum1>iNum3)
{
Console.WriteLine("iNum1 is the biggest number");
}
else if(iNum2>iNum1 && iNum2>iNum3)
{
Console.WriteLine("iNum2 is the biggest number");
}
else
{
Console.WriteLine("iNum3 is the biggest number");
}
------------------------------------------
Here in the above code we are using Relational and Logical operators. When we have multiple conditions like this we can use operators as shown above.
We have actually three conditions here so we can use Nested if's like this. When the if condition gets false it will enter the else if condition and when and only else if condition gets false it will enter the else condition of the program.
This is how we use if-else constructor in programs.
-------------------------------------------------------------
switch-case conditions.
switch case conditional statements are used to check conditions according to the incoming values to the variables. Here we will switch a variable and inside the cases we will check for the conditions.......
Let's see and example for this...
--------------------------------------------------------------
switch(iMonth)
{
case 1:
{
Console.WriteLine("January");
break;
}
case 2:
{
Console.WriteLine("February");
break;
}
case 3:
{
Console.WriteLine("March");
break;
}
default:
{
Console.WriteLine("Please enter a Valid number");
break;
}
}
------------------------------------------------------------
Here in the above code we are switching a variable inside the switch body. Now the switch will check for cases with the value inside the switch variable. If it matches any of the value inside any case it will get into the Case body.
If we pass a value 2 into the variable iMonth the switch will get into the case 2: and print "February".
Since we are using integer Datatype we can straight away write the numbers in the cases with a single space seperated.
The "default" statement gets printed in the case if a number(value) which is not the case conditions is assigned to the switch variable.
Now if you are passing a Character Datatype you must write the cases like this...
--------
case 'A':
{
//statements
break;
}
case 'C':
{
//statements
break;
}
---------
and in the case of strings you can write the cases like this....
---------
case "C#.net"
{
Console.WriteLine("Windows programming");
break;
}
case "ASP.net"
{
Console.WriteLine("Web Programming");
}
---------
you must have checked "break" statements after each case and default statements.
We must use break statements inside this just because it may jump into next Case. In C# break statements are compulsory and if we dont use break statements it will return an error.
We can have multiple cases in the switch statement but only a single default statement in the switch statement....
That's all about switch case and If else conditions.........
C# Constructor(s)
Constructors are methods that gets automatically invoked when an object of a class is created. Constructors are used to Initialize values to variables inside the class automatically at the time of object creation.
Constructors will be having the same name of the class itself. Constructor doesn't return any value.
Let's see an example for Constructor..
-------------------------------------
using System;
class HelloWorld
{
int iNum1,iNum2;
string sName,sAddress;
//Creating a Constructor
public HeloWorld() //Line1
{
iNum1=iNum2=0;
sName="";
sAddress="";
}
}
-------------------------------------
Here, in the above code we have created a default constructor with the name of the class. Constructors will not be having a return type.
The Line1 represents the constructor for the class HelloWorld. The same name of the class itself will be given to constructor also.
We can have multiple constructors inside a class but should be overloaded. We use overloaded constructors for initializing values by passing it to the object of the class.
Eg
-------------------------------------
using System;
class HelloWorld
{
int iNum1,iNum2;
string sName,sAddress;
//Creating a Constructor
public HeloWorld() //Line1
{
iNum1=iNum2=0;
sName="";
sAddress="";
}
//Overloaded constructor
public HelloWorld(int _iNum,string _sName,string _sAddress)
{
iNum1=_iNum; //Line1
sName=_sName;
sAddress=_sAddress;
iNum2=0;
}
}
-------------------------------------
Here, in the above code we have two constructors but our function signatures are different in both Constructors. In the first constructor the Function signature or parameter is void and in the second one we have three parameters one Integer and two strings. So for invoking the second constructor we must have to pass values to the object.
Eg
--------------------------
//Invokes the Default Constructor
HelloWorld hwObj=new HelloWorld();
//This invokes the Second constructor
HelloWorld hwObj1=new HelloWorld(20,"SMILU","TPRA");
--------------------------
Like this we can have many constructors inside a Class.
Now, if in the case we have Static class and variables and have to initialize those variables we need another type of constructors called Static constructors.
Static constructors are used for initializing values inside Static classes. We cannot have instance constructors inside the static classes.
For Creating a static constructor we can use the static keyword.
-----------------------------------------
static class HelloWorld
{
static int i;
static HelloWorld()
{
i=10;
}
}
------------------------------------------
Data Types in C#
Now we will check some other programs in C#.
What do you mean by a Data Type?
In simple words Data Type means the type of data. The data may be mainly of three types. They are
Integer, Character and Float. These are also called base data types.
Integer are used to store integers or numbers without decimals.
eg:- 1,123,1452,9999 etc...
Characters are used to accept letters. Basically a character Data type can accept only one byte. So, it will store only one Letter.
eg:- a,A,b,c,d etc....
If we write -AB- it will return an error...
Float is used to accept Floating numbers or numbers with decimals..
eg:- 1.8F,21.3F etc
Some data types are :-
Name. . . . . Description
byte . . . . .. . 8-bits '
sbyte . . . .. . 8-bits
int. . . . . . . .. 32-bit
uint. . . . . . .. 32 bit
short. . . . . ..16-bit
ushort . . . .. 16-bit
long. . . . . . .. 64-bit
ulong. . . . . .. 64-bit
float . . . . . .. 32-bit
double. . . . .. 64-bit
decimal . . . . 96-bit
bool . . . . . . . true and false
char. . . . . . . 16-bit
Write a Program to show numbers in Fibonacci Series in C#??
0 1 1 2 3 5 8......... n..
Here, the first no is 0 and the second no is 1 so the third number must be 0+1, and the fourth number must be Sum of Second and Third.. ie 1+1, like wise we must create it for the Entire Series....
Here is the Program to show the first ten digits in Fibonacci Series in C#...
----------------------------------------------
using System;
namespace MyFibonacciApp
{
class _FibonacciSeries
{
static void Main(string[] args)
{
int j = 0;
int k = 0;
int l = 1;
for(int i = 0; i <10;i++)
{
Console.Write("{0} ", k);
j = l;
l = k;
k = l + j;
}
}
}
}
----------------------------------
Function Overloading
-------------------------------------------------
class MethodOverloading
{
//Method one
public void Add(int i, int j)
{
Console.WriteLine(i+j);
}
//Method Two
public void Add(string s, string k)
{
Console.WriteLine(s+k);
}
}
--------------------------------------------------
Here in the above code we have two methods with the same name Add. This method is overloaded since the signatures inside it changes in the second method. In the first method we have passed two Integer values as parameters and in the second method we have passed two string values into the method. Now when we call this method, if we are passing two integer values to the method then the first method will be invoked and will be adding the two integers and showing the result to us. In the other case if we are passing two String values into the same function the second method will be invoked and it will be concatenating the two strings and the concatenated string is displayed.
Here when we used function overloading it does not vary in the return type. But the behavior has changed according to the values we pass to the functions.
In the above case Method 1 and Method 2 have the same return Type but are varied in the signature.
Method 1 has two integer parameter and Method 2 has two string parameters.
Now we’ll check some more examples for function overloading..
class MethodOverloading
{
public int Display(int i)
{
return i;
}
public void Display(int j, int k)
{
return j+k;
}
public void Display(int l, int m,int n)
{
return (l+m-n);
}
}
-------------
Here in the above cases in all the functions we have integer parameters. These are also overloaded because the parameters passed to each method vary in number ie; the First method has only one parameter; the second have two parameters and the third have three parameters.
Loops used in C# .net
Loops we use in C# are:
while Loop,
do...while Loop
for Loop and
foreach Loop
C# while Loop
While loop and do..while loops are used in conditions like the Number of iterations are Unkown ie, the number of times the loop should work is unknown. While loop works only if the Condition gets true.
Let's check the structure of a while loop...
----------------------------------
while(condition==true)
{
//Statements
}
----------------------------------
While loop only works if the Condition is true. Here in this case if the condition doesnt gets false it will become an infinite loop.
C# do ... while loop
-----------------------------------
while loop have a disadvantage that it dosnt gets executed even for one time if the condition is false. To overcome this problem we have do while loop.
do...while loop is also like a while loop but it gets into the loop for the first time even if the condition is false. But from the second time if the loop wants to work the while condition checks for the condition to become true.
The structure of a do...while loop is...
----------------------------------
do
{
//Statements
}while(Condition==true);
----------------------------------
Here from the second time it works only if the Condition or the testexpression becomes true..... In this loop also the number of iterations is not Known.
C# for loop....
For loop is used when the number of iterations is fixed. If we know how many times the loop needs to work we use the For Loop.
The structure of a for loop is...
----------------------------------
for(initialisation;testexpression;increment/decrementoperator)
{
//statements
}
----------------------------------
Here in this case the initialisation is the place we declare or define some values to the variables which should be used inside the loop...
Testexpression checks the condition of the loop ie it defines the number of iteration of the Loop...
increment/decrement This is used to make the condition of the loop to become false so the loop gets stopped at certain interval.
I'll show you an example to get the first ten numbers...
----------------------------------
for(int i=1;i<=10;i++)
{
Console.WriteLine(i);
}
----------------------------------
The above loop will print the first ten numbers. Here itself if we loop at it we can see the Initialisation as int i=1. This is I am declaring a variable with the name i and setting its value as 1. In the second expression I have given a Condition asking whether the variable i have the value less than or equal to 10 and in the third case when each time the loop works the value of variable i gets added by 1. So when it becomes 11 the loop gets terminated.
Working of a for loop...
----------------------------------
While we use a for loop... the initialisation expression is only called for the first time. When the loop starts to run from the second time it doesn't enter to the Initialisation expression instead it increments the value of the variable and checks whether the test expression is true or false.
Step 1: Initialisation
Step 2: Condition
Step 3: Increment or Decrement
For the first time it calls STEP 1
then goes to the Step 2 and enters into the loop body
From the second time when it comes to the loop it goes to Step 3 and then to Step 2..... and if it returns true it enters the loop body...
C# foreach loop...
foreach loop is a new loop introduced in C#. This loop is same as for loop but this loop will be commonly used for working with arrays collections etc.. If we are using a for loop for displaying the values of an array we need to know the size of the array. But in the case of a foreach loop the size of the array need not be known. foreach loop automatically takes the size of the array and calculates it....
Let's see an example for that...
----------------------------------
foreach(DataType var in DataTypeCollection)
{
//Statements
}
----------------------------------
In this type of loop we will be creating a variable which will be the same as the collection datatype to be worked with. If you are going to print all elements of an array collection then the variable should be on the DataType that can store the value of the Array. Like this we can run this for loop even for Controls in .net like ListBox, ComboBox etc.....
Just check how it works.....
----------------------------------
char[] arr=new char[10];
//I need to print all the elements in this array for doing that we can use a foreach loop
for(char c in arr)
{
Console.WriteLine(c);
}
----------------------------------
Here in the above case it will create a Character variable "c" and when the loop starts to work each time it will assign value at the appropriate index to the variable and print it....
What is an object?
An object is a combination of messages and data. Objects can receive and send messages and use messages to interact with each other. The messages contain information that is to be passed to the recipient object.
Look at the program given below:
using System;
---------------------------------------
namespace prime_no
{
class prime
{
int num;
public void acceptNo()
{
Console.WriteLine("Enter a number:");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\n");
}
public void primeNosTill()
{
int i, j;
bool answer = false;
Console.WriteLine("The prime numbers till entered number are: ");
for (i = 2; i <= num; i++)
{
for (j = 2; j <>
{
if (i % j == 0)
{
answer = true;
break;
}
}
if (answer == false)
Console.WriteLine(i);
else
answer = false;
}
}
class execute
{
public static void Main(string[] a)
{
prime primeNo = new prime();
primeNo.acceptNo();
primeNo. primeNosTill();
Console.Read();
}
}
}
}
---------------------------------------
The prerequisite of object creation is a class i.e. you can only create an object of a class. For the declaration of a class, the class keyword is used. In the above code, class keyword defines the class prime. The braces know as delimiters, are used to indicate the start and end of a class.
The functions of a class are called member functions. A function is a set of statements that performs a specific task in response to a message. Member functions are declared inside the class. The function declaration introduces the function in the class and function definition contains the function code. The two member functions in the above code are acceptNo and primeNosTill.
The execute class is declared with the Main() method. The execute is used as a class from where the prime class can be instantiated. To use the members of the class, the object of that must be created.
The above code contain class prime and the object has been named primeno.
prime primeno = new prime();
The member functions (acceptNo and primeNosTill), can be accessed through the object (primeno) of the class prime using “.” operator.
primeno.acceptNo();
primeno. primeNosTill();
The acceptNo function accepts the number from the user and primeNosTill function displays all the prime numbers till the number entered by the user.
OOPS in c#
So, we are going to start with C#. C# is an Object Oriented Language developed by Microsoft Corporation for working with .NET platform. For working with C# you must have any version of Visual Studio installed on your Computer. For the latest case you will get Light Components like Microsoft C# Express Edition to Download from Microsoft which is absolutely free.
Now we can see a simple program in C#.
-------------------------------------------------
using System;
namespace smilu
{
class cHello
{
public static void Main(string[] args)
{
Console.Write("Hello World");
}
}
}
--------------------------------------------------------
I know that if you are a fresher to C#; you may be wondering seeing the Code. There is nothing in much in the above code....
Let's be now familiar with what is written in the above code.
In the above code go from the begining...
The first line is
using System;
The using statement is used to add a NAMESPACE into this program.
Namespaces are collection of Classes. These Namespaces are used to avoid Class Name Conflicts. ie, there may be situations where we must have two or more CLASSes with the same Name. So, inside a program, it will not allow to create two classes with the same name. So there exists a problem. So to avoid these types of conflicts we use Namespaces. So we create a namespace and add the classes inside the namespace and we create the other class with the same name in another namespace.
In the above program we have added System namespace into this program. The System namespace contains CLASSes for implementing base datatypes.
Now the second step
namespace smilu
This step is used to create a User Defined namespace which contain classes. Here we have created a Namespace in the name of "smilu".
Then you must have noticed curly brackets throughout this program. These are the Bodies of Namespace, Classes and Functions.
The Third step
class cHello
As I have said in the earlier topics that C# is an Object Oriented Language. So an Object Oriented Language(OOL) must have a class. Without class we cannot say a program is purely Object Oriented(refer). So, in this step we are creating a CLASS with name "cHello".
We will be writing rest of the Codes inside the CLASS
The Fourth Step
public static void Main(string[] args)
or
public static void Main()
This is the most important Function of a Program. Without the Main() function a program will not Execute. We write the Main() function in C# like this. All the things written there are not necessary. We will check each keyword in the Declaration.
public:
public written in the function refers it Access to others.It is known as "Access Specifier" ie we have Given a public access to the Main function,so anywhere within the program we can access this function.
Static:
C# is an OOL. So member variables and member functions can only be accessed through objects. Here in the case of Main it is the heart of a program. When we execute a program the first thing which gets executed is the Main() function. This is the first class so Object for this class can only be created inside the Main() function. So we must have to get the program started by executing the Main() function. That is why we declare a Static keyword to Main() function. So it is not necessary to create object for the class.
void:
void means NOTHING.... void represents the return type of the Main() function. ie, what the main should return to the program. Here in this case we doesn't need anything to be returned.. so, we have given the return type as void.
Main(string[] args) :
string[] args is used to store Command Line Arguments(if any). Command Line Arguments are arguments which we pass to a program while its execution with its Name.
The Fifth Step
Console.Write("Hello World");
Here we are creating Console application ie, we create a DOS based program. System.Console is a class which contains definitions for Write(), Read() etc... We mainly use
Write(); For writing in the same line(output)
WriteLine() This is used to Write in a string and set a break to the Line after that.
Read() Read a single line
ReadLine() Reading the strings.
Here in the above code inside the write function I have written "Hello World". The text inside the double quotes("") represenets the text to be printed as the output. What all we are write inside the "" of the Write() or WriteLine() functions will be printed as that itself exept some Escape charactors like...
Commonly used escape charactors are...
\n - For new Line
\t - For a Tab Space
\b - For a BackSpace etc...
NOTE:- C# is a case sensitive Language. So it is necessary that you write codes in appropriate cases itself as written above.
After you type the program save the file with a Filename with extension ".cs"(eg:- Hello.cs).
For executing the program take the Microsoft Visual Studio 2005 Command Prompt from
START->PROGRAMS->MICROSOFT VISUAL STUDIO 2005->MICROSOFT VISUAL STUDIO TOOLS->MICROSOFT VISUAL STUDIO 2005 COMMAND PROMPT
Operators in c#
Operators are used to do perform some operations on variables.
We have four types of operators in C#.
Arithmetic Operators,
Relational operators ,
Logical operators and
Unary operators.
Arithmetic Operators :-
Arithmetic Operators are used to do mathematical operations
The basic arithmetic Operators are
+ for addition
- for subtraction
* multiplication
/ division
% modulo operator(This operator is used to return the Remainder of two numbers).
Relational Operators:-
Relational operators are mainly used for checking conditions between two or more variables.
The relational operators we use in C# are..
> Greater than(Checks which number is greater)
<>= Greater than or equal to(Checks whether the given number is greater than or equal to the second number)
<= Less than or equal to(Checks whether the given number is less than or equal to the second number) == Equal to(Checks whether the second number is equal to the first number) != not equal to(Checks whether the second number is not equal to the first number) Logical Operators :
Logical operators are used to check logical conditions with a block of two or more relations
Logical operators we use in C# are AND, OR and NOT.
AND operator is represented with && (two ampersand)
OR operator is represented with || (two pipes) and
NOT operator is represented with !(Exclamation).
eg:-
((iNum1>iNum2) && (iNum1!=0))
In the above example we are checking whether the first variable is greater than the second variable AND iNum1 is not equal to ZERO. Here if both the conditions are true only the condition will execute.
How Logical operators work.
AND(&&)
&&(AND) operator becomes true only if all the conditions are true. If any of the conditions are false && operator returns false.
OR(||)
||(OR) operator becomes false only if all conditions are false. If any of the condition becomes true || operator becomes true.
NOT(!)
!(NOT) operator becomes true if the condition is false and false if the condition is true.
Unary Operators
Unary operators are used to add or subtract a variable by 1.
We have mainly two types of unary operators
Increment and
Decrement.
Increment operator is represented by ++ and decrement operator is represeted by --.
Increment operator adds a variable by one and decrement operator subracts a variable value by
one.
i++, i--.
Unary operators can be used in two ways POSTFIX and PREFIX.
In a postfix notation the unary operator will be placed after the variable(i++)
In a prefix notation the unary operator will be placed before the variable(++i)
Assignment Operator
An assignment operator is used to assign a value to a variable. An = (equal to) symbol is known as an assignment operator.
int i=10;
means assigning the integer variable i a vlaue of 10.
C# string handling
functions.
C# string Split() - Splitting a string to an Array
The split() can be used to Split an entire string in to an string array. This will be
done using this split method. This can be used when you need long strings to be splitted
to seperate string objects.
---------------------------------------------
string mString = "This is to show Splitting in strings";
string[] mArr = mString.Split(' ');
---------------------------------------------
Here in the above code we have a string named mString and we have assigned a string to
it. Now check the second line of it. We have created an String Array to store the values
that gets Splitted.
mString.Split(' ') method splits the Entire string into an array. We have given a white
space as the argument for the Split method for the string. This will allow it to split
the string whenever it sees a white space inside the string.
Now, if you need to get the Splitted values of the string you must have to fetch the
entire items of the Array mArr using some loops.
C# string.Join() - Joining an Array as a String
The Join() method can be used to join an Array to a single String. If we have an array
to be used as a single string you can use this string.Join() method.
Let's see an example for it
---------------------------------------------
string joinedString = string.Join("-", mArr);
//Here the JoinedString variables value will be
// "This-is-to-show-Splitting-in-strings"
---------------------------------------------
In the above code in the Join function we have two overloads mainly
string.Join("String Separator","The array to Join");
Here in the above we have set the Separator as "-"(hyphen). So it will attach each Array
element with this "-". Like wise we can join the Strings in any way we like.
What is a Variable?
Variable will be having a memory address value
For eg:-
int iNum1
char cName
float fNum etc..
Here, int,char,float represents the Data type to be used and iNum1,cName,fNum are the variable names given for those DataTypes.
Rules For Declaring a Variables :-
A Variable name Should Start with an Alphabet
Key Words representing the program should not be used as variable name.
for eg: numeric, int, console etc.. should not be used.
Special characters except an underscore( _ ) are not allowed
Variable names should not start with a number.
25 February, 2010
Difference between WCF and Web service
Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them.
| Features | Web Service | WCF |
|---|---|---|
| Hosting | It can be hosted in IIS | It can be hosted in IIS, windows activation service, Self-hosting, Windows service |
| Programming | [WebService] attribute has to be added to the class | [ServiceContraact] attribute has to be added to the class |
| Model | [WebMethod] attribute represents the method exposed to client | [OperationContract] attribute represents the method exposed to client |
| Operation | One-way, Request- Response are the different operations supported in web service | One-Way, Request-Response, Duplex are different type of operations supported in WCF |
| XML | System.Xml.serialization name space is used for serialization | System.Runtime.Serialization namespace is used for serialization |
| Encoding | XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom | XML 1.0, MTOM, Binary, Custom |
| Transports | Can be accessed through HTTP, TCP, Custom | Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom |
| Protocols | Security | Security, Reliable messaging, Transactions |
WCF Videos
Windows Communication Foundation:" Hello World"
The Windows Communication Foundation is a new framework for building distributed applications. In this session we'll take a look at the basics of getting an application up and running
Click here to watch the video online or here to download a zip file to watch offline
Windows Communication Foundation: Type Serialization
The WCF offers a number of different serialization technologies for turning .NET object types into XML for transmission across service boundaries. This session explores what's available.
Click here to watch the video online
Windows Communication Foundation: DataContract Serialization
The DataContract is the standard mechanism in the WCF for serializing .NET object types into XML. This session looks at the various options that DataContract makes available.
Click here to watch the video online
Windows Communication Foundation: Typed and Untyped Messages
The WCF has a lot of flexibility in the way in which it goes from .NET objects to SOAP messages. It can handle parameters and typed/untyped messages. Let's take a look.
Click here to watch the video online
Windows Communication Foundation: Bindings
A great deal of power and flexibility comes from the use of bindings in the WCF to specify communication details. Here we explore a little of the standard bindings and how we can configure them.
Click here to watch the video online
Windows Communication Foundation: Message Encoding
The WCF offers a flexible choice of mechanisms for turning a SOAP message into something that we can transmit between services. In this session we'll look at the options.
Click here to watch the video online
Windows Communication Foundation: Message Patterns
And you thought service communication was just request and response? This session looks at how we can use the WCF for one way and two way message exchanges.
Click here to watch the video online
Windows Communication Foundation: Sessions
The WCF has facilities for maintaining a session of messages between a client and a service. In this session we'll take a look at how we can make use of those facilities.
Click here to watch the video online
Windows Communication Foundation: Instancing
WCF services can be singletons, they can be single-call objects or they can have a lifetime that is tied to the session. Let's dive into how we make this work.
Click here to watch the video online
Windows Communication Foundation: Concurrency
In an server side development, concurrency always crops up and the WCF is no exception. Here we explore the options for single and multi-threaded services.
Click here to watch the video online
Windows Communication Foundation: Exceptions
Every piece of code needs to think about how to deal with exceptions - the WCF has particular mechanisms for translating .NET exceptions into SOAP faults which we explore here.
Click here to watch the video online
Windows Communication Foundation: Transactions
The WCF has facilities for coordinating work done by multiple pieces of software under a single atomic transaction. In this session we'll look at getting that set up and working.
Click here to watch the video online
Windows Communication Foundation: HTTPS Transport Security
The WCF provides transfer security for messages either by relying on the transport or by using message level mechanisms. In this session we'll look at using HTTPS at the transport layer to provide integrity, privacy and authentication for messages in transit.
Click here to watch the video online
Windows Communication Foundation: Message Security
The WCF provides transfer security for messages either by relying on the transport or by using message level mechanisms. In this session we'll look at using message security in order to perform authentication and provide privacy and integrity for messages.
Click here to watch the video online
Windows Communication Foundation: Authorisation
In this session we'll look at some basic mechanisms for authorising access to service operations that the WCF offers.
Click here to watch the video online
Windows Communication Foundation: Auditing
The WCF has facilities for auditing message authentication operations and service authorisation operations. In this session we'll look at how we can configure those facilities.
24 February, 2010
The Motivation behind WCF
However, WCF provides a single unified model to access these previously diverse technologies. WCF
integrates the services of previous distributed technologies (COM+, .NET remoting, XML web services,
MSMQ, P2P, and so on) into a streamlined API. Without WCF, the wide array of distributed technologies
made it difficult to pick the right tool for the job.
The core problem was each API was an island unto itself (different programming models, different
fundamental data types, different ways to define contracts, among other issues). This was further
complicated by the fact that several of these technologies overlapped in the services they provide (i.e.,
providing numerous ways to do the same thing). Even when a .NET developer selected what appear to be the
‘correct’ technologies for the task at hand, maintaining and configuring such an application was complex at
best.
Although new, the WCF API builds on top of the success of previous concepts. As WCF is a SOA-based
system, WCF services look very similar to a traditional XML web service. WCF applications also borrow
several aspects found when building software making use of .NET remoting (*.config files, choice of
transportation layers and data persistence, and so on).
Beyond integration of diverse APIs, WCF provides a rich software fabric that complements the distributed
technologies it exposes, including the following examples:
• Support for strongly typed, as well as untyped, messages. This approach allows .NET
applications to share custom types simply and efficiently, while software created using other
platforms such as Java can consume streams of loosely typed XML.
• Support for several endpoints (raw HTTP, HTTP + SOAP, TCP, MSMQ, and named pipes) to
allow you to choose the most appropriate plumbing to transport data.
• Tracing, messaging, and performance counter APIs.
• Security APIs, including a new security feature named CardSpace (.NET 3.0 and higher).
• Transactional and peer-to-peer (P2P) APIs.
WCF Architecture

Contracts
Contracts layer are next to that of Application layer. Developer will directly use this contract to develop the service. We are also going to do the same now. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system.
Service contracts
- Describe about the operation that service can provide. Example, Service provided to know the temperature of the city based on the zip code, this service we call as Service contract. It will be created using Service and Operational Contract attribute.
Data contract
- It describes the custom data type which is exposed to the client. This defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or datatype cannot be identified by the client e.g. Employee data type. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method.
Message Contract
- Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.
Policies and Binding
- Specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding.
Service Runtime
- It contains the behaviors that occur during runtime of service.
* Throttling Behavior- Controls how many messages are processed.
* Error Behavior - Specifies what occurs, when internal error occurs on the service.
* Metadata Behavior - Tells how and whether metadata is available to outside world.
* Instance Behavior - Specifies how many instance of the service has to be created while running.
* Transaction Behavior - Enables the rollback of transacted operations if a failure occurs.
* Dispatch Behavior - Controls how a message is processed by the WCF Infrastructure.
Messaging
- Messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as
* Transport Channels
Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.
* Protocol Channels
Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.
Activation and Hosting
- Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF service can be hosted by following mechanism
* IIS
Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.
* Windows Activation Service
(WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.
* Self-Hosting
WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.
* Windows Service
WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).
WCF Hosting
Beyond operating platform and choice of protocol, other features available to the hosting environment also influence deployment decisions and choice of host. This article describes the desired features of a hosting environment; provides you with an overview of WCF hosting options and their availability; and explains how to implement scenarios applicable to each environment.
WCF is part of the .NET Framework 3.0 stack and thus is supported on the following operating platforms: Windows XP/SP2, Windows Vista, Windows Server 2003, and Windows "Longhorn" Server. Regardless of platform, you can access WCF services over many protocols including HTTP, TCP, IPC and MSMQ. Unfortunately, not all hosting environments are available to each platform, nor does every host support the entire suite of protocols—limiting your options at times.
Features of a Great Host
Hosting environments make it possible to expose your services to client applications. They facilitate request processing to service operations, but they can also play a critical role in the availability and scalability of your services. A great hosting environment should provide these important features:
* Executable Process/Application Domain: You can use any managed process to host WCF services, which implies the existence of an application domain ("app domain").
* Configuration: A mechanism for external configuration should be available to support deployment and manageability. For managed hosts this is supplied by the application configuration file (app.config or web.config).
* Activation: Ultimately the service model instantiates the appropriate service type to handle incoming requests, but the host process must initialize the channel stack that receives incoming messages. You can do this activation at host startup but it is preferably done through message-based activation.
"Self-hosting is the simplest way to host your services-and the approach that yields the least number of hosting features."
* Idle-Time Management: To conserve server resources during idle time, hosts can release unused resources. Hosts that support this feature usually provide a configurable timeout. Idle-time management relies on the activation capabilities of the host to instantiate resources as needed.
* Health Monitoring: To ensure availability a host process must always be running to service requests. Some hosting environments can proactively monitor their processes to ensure a new host process is started when existing processes are unable to service requests.
* Process Recycling: To avoid problems associated with memory leaks or faulty code, some hosting environments support configurable process recycling to "freshen up" running host processes.
* Management Tools: Sophisticated hosting environments also provide tools for configuring hosting features for greater control and manageability. This toolset sometimes contains tools for monitoring the health and status of running host processes.
There are three types of hosting environments for WCF services: IIS, WAS, and self-hosting. The term "self-hosting" refers to any application that provides its own code to initialize the hosting environment. This includes console, Windows Forms, WPF, and managed Windows services. Table 1 provides a summary of these three hosting environments and the features they support.
Table 1: A summary of hosting options and supported features.
At a minimum, all WCF hosts provide an executable process and application domain in which services are loaded. They also provide support for external configuration. The remaining hosting features discussed here are built into IIS and WAS, but not provided by self-hosting environments. Despite this fact, self-hosting does have its value under the right circumstances.
In the sections to follow, I'll discuss how the service model exposes WCF services, and then I'll describe scenarios for self-hosting, IIS, and WAS.
18 February, 2010
Regarding WCF Question and Answers
1) Address --- Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this location to communicate with our service.
2) Contract --- Specifies the interface between client and the server. It’s a simple interface with some attribute.
3) Binding --- Specifies how the two paries will communicate in term of transport and encoding and protocols
What is WCF?
The Windows Presentation Foundation (WPF) is a next generation graphics platform that is part of .NET 3.0 and .NET 3.5. It allows you to build advanced user interfaces that incorporate documents, media, 2D and 3D graphics, animations, and web-like characteristics. In just 24 sessions of one hour or less, you will be able to begin effectively using WPF to solve real-world problems, developing rich user interfaces in less time than you thought possible. Using a straightforward, step-by-step approach, each lesson builds on a real-world foundation forged in both technology and business matters, allowing you to learn the essentials of WPF from the ground up
What is WCF?
Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types.
WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it.
Difference between WCF and Web services?
Web Services
1.It Can be accessed only over HTTP
2.It works in stateless environment
WCF
WCF is flexible because its services can be hosted in different types of applications. The following lists several common scenarios for hosting WCF services:
IIS
WAS
Self-hosting
Managed Windows Service
What are the various ways of hosting a WCF service?
Self hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of ServiceHost class and the service closes when you call the Close of the ServiceHost class.
Host in application domain or process provided by IIS Server.
Host in Application domain and process provided by WAS (Windows Activation Service) Server.
What is three major points in WCF?
We Should remember ABC.
Address --- Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this location to communicate with our service.
Binding --- Specifies how the two paries will communicate in term of transport and encoding and protocols
Contract --- Specifies the interface between client and the server.It's a simple interface with some attribute.
What is the difference WCF and Web services?
Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type.
Second web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.
We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc
For more details, read http://msdn.microsoft.com/en-us/library/aa738737.aspx
What are various ways of hosting WCF Services?
There are three major ways of hosting a WCF services
• Self-hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of Service Host class and the service closes when you call the Close of the Service Host class.
• Host in application domain or process provided by IIS Server.
• Host in Application domain and process provided by WAS (Windows Activation Service) Server.
What was the code name for WCF?
The code name of WCF was Indigo .
WCF is a unification of .NET framework communication technologies which unites the following technologies:-
NET remoting
MSMQ
Web services
COM+
What are the main components of WCF?
The main components of WCF are
1. Service class
2. Hosting environment
3. End point
How to set the timeout property for the WCF Service client call?
The timeout property can be set for the WCF Service client call using binding tag.
bindingConfiguration = "LongTimeout"
/>
If no timeout has been specified, the default is considered as 1 minute.
How to deal with operation overloading while exposing the WCF services?
By default overload operations (methods) are not supported in WSDL based operation. However by using Name property of OperationContract attribute, we can deal with operation overloading scenario.
[ServiceContract]
interface ICalculator
{
[OperationContract(Name = "AddInt")]
int Add(int arg1,int arg2);
[OperationContract(Name = "AddDouble")]
double Add(double arg1,double arg2);
}
Notice that both method name in the above interface is same (Add), however the Name property of the OperationContract is different. In this case client proxy will have two methods with different name AddInt and AddDouble.
How to configure Reliability while communicating with WCF Services?
Reliability can be configured in the client config file by adding reliableSession under binding tag.
binding = "netTcpBinding"
bindingConfiguration = "ReliableCommunication"
contract = "IMyContract"
/>
Reliability is supported by following bindings only
NetTcpBinding
WSHttpBinding
WSFederationHttpBinding
WSDualHttpBinding
What is Transport and Message Reliability?
Transport reliability (such as the one offered by TCP) offers point-to-point guaranteed delivery at the network packet level, as well as guarantees the order of the packets. Transport reliability is not resilient to dropping network connections and a variety of other communication problems.
Message reliability deals with reliability at the message level independent of how many packets are required to deliver the message. Message reliability provides for end-to-end guaranteed delivery and order of messages, regardless of how many intermediaries are involved, and how many network hops are required to deliver the message from the client to the service.
What are different elements of WCF Srevices Client configuration file?
WCF Services client configuration file contains endpoint, address, binding and contract. A sample client config file looks like
binding = "wsHttpBinding"
contract = "IMyContract"
/>
What is Proxy and how to generate proxy for WCF Services?
The proxy is a CLR class that exposes a single CLR interface representing the service contract. The proxy provides the same operations as service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service. The proxy completely encapsulates every aspect of the service: its location, its implementation technology and runtime platform, and the communication transport.
The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference. This brings up the Add Service Reference dialog box, where you need to supply the base address of the service (or a base address and a MEX URI) and the namespace to contain the proxy.
Proxy can also be generated by using SvcUtil.exe command-line utility. We need to provide SvcUtil with the HTTP-GET address or the metadata exchange endpoint address and, optionally, with a proxy filename. The default proxy filename is output.cs but you can also use the /out switch to indicate a different name.
SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs
When we are hosting in IIS and selecting a port other than port 80 (such as port 88), we must provide that port number as part of the base address:
SvcUtil http://localhost:88/MyService/MyService.svc /out:Proxy.cs
What are contracts in WCF?
In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.
WCF defines four types of contracts.
Service contracts
Describe which operations the client can perform on the service.
There are two types of Service Contracts.
ServiceContract - This attribute is used to define the Interface.
OperationContract - This attribute is used to define the method inside Interface.
[ServiceContract]
interface IMyContract
{
[OperationContract]
string MyMethod( );
}
class MyService : IMyContract
{
public string MyMethod( )
{
return "Hello World";
}
}
Data contracts
Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.
There are two types of Data Contracts.
DataContract - attribute used to define the class
DataMember - attribute used to define the properties.
[DataContract]
class Contact
{
[DataMember]
public string FirstName;
[DataMember]
public string LastName;
}
If DataMember attributes are not specified for a properties in the class, that property can't be passed to-from web service.
Fault contracts
Define which errors are raised by the service, and how the service handles and propagates errors to its clients.
Message contracts
Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.
What is the address formats of the WCF transport schemas?
Address format of WCF transport schema always follow
[transport]://[machine or domain][:optional port] format.
for example:
HTTP Address Format
http://localhost:8888
the way to read the above url is
"Using HTTP, go to the machine called localhost, where on port 8888 someone is waiting"
When the port number is not specified, the default port is 80.
TCP Address Format
net.tcp://localhost:8888/MyService
When a port number is not specified, the default port is 808:
net.tcp://localhost/MyService
NOTE: Two HTTP and TCP addresses from the same host can share a port, even on the same machine.
IPC Address Format
net.pipe://localhost/MyPipe
We can only open a named pipe once per machine, and therefore it is not possible for two named pipe addresses to share a pipe name on the same machine.
MSMQ Address Format
net.msmq://localhost/private/MyService
net.msmq://localhost/MyService
How to define a service as REST based service in WCF?
WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding.
The below code shows how to expose a RESTful service
[ServiceContract]
interface IStock
{
[OperationContract]
[WebGet]
int GetStock(string StockId);
}
By adding the WebGetAttribute, we can define a service as REST based service that can be accessible using HTTP GET operation.
What is endpoint in WCF?
Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint.
The Endpoint is the fusion of Address, Contract and Binding.
What is binding and how many types of bindings are there in WCF?
A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.
WCF supports nine types of bindings.
Basic binding
Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.
TCP binding
Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.
Peer network binding
Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.
IPC binding
Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.
Web Service (WS) binding
Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.
Federated WS binding
Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.
Duplex WS binding
Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.
MSMQ binding
Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.
MSMQ integration binding
Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.
For WCF binding comparison, see http://www.pluralsight.com/community/blogs/aaron/archive/2007/03/22/46560.aspx
Where we can host WCF services?
Every WCF services must be hosted somewhere. There are three ways of hosting WCF services.
They are
1. IIS
2. Self Hosting
3. WAS (Windows Activation Service)
For more details see http://msdn.microsoft.com/en-us/library/bb332338.aspx
What is address in WCF and how many types of transport schemas are there in WCF?
Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas.
WCF supports following transport schemas
HTTP
TCP
Peer network
IPC (Inter-Process Communication over named pipes)
MSMQ
The sample address for above transport schema may look like
http://localhost:81
http://localhost:81/MyService
net.tcp://localhost:82/MyService
net.pipe://localhost/MyPipeService
net.msmq://localhost/private/MyMsMqService
net.msmq://localhost/MyMsMqService
What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world. The client of a service is merely the party consuming the service.
1. A user has a service with a one-way operation that includes a fault contract, and he
gets an exception when he tries to host the service. Why?
This happens because, to return faults, the service needs some form of a two-way communication channel in place, which is not the case with one-way operations.
2. A user has a service he wants to expose on the Internet, and it needs to send notifications
out to its consumers. Would the WCF Duplex MEP be a good choice for
implementing this?
No. The WCF Duplex MEP can be problematic to enable, even inside an enterprise.
Its implementation depends upon the service establishing a connection back to the consumer, which can’t happen in certain scenarios, such as when the client’s machine uses NAT behind a firewall. On the Internet, where you are never certain
where your consumers are coming from, this type of callback channel would rarely, if ever, work. When you factor in the security risks it could pose and the scalability concerns with the fact that callback channels require the presence of sessions
between client and service, it isn’t a feasible solution.
3. You have a Data contract specifying a Person class from which you derive a Customer class. Does a Customer object automatically have a Data contract as well?
No. The Data contract is not inherited, so any derived class, such as the Customer class, would have to be explicitly declared as having a Data contract as well.
4. Your company has its own proprietary authentication mechanism, and you are required to authenticate every message coming into the service. What is the best way to handle using this mechanism with WCF?
Likely the best way to handle this would be to design a Message contract that accepts these proprietary authentication tokens in the header.
5. Can you support the Rpc SOAP style by using the DataContractSerializer?
Yes. You need only adorn your service with the DataContractFormatAttribute and explicitly set the attribute’s Style property to OperationFormatStyle.Rpc.
6. What does the “ABCs of endpoints” refer to?
The ABCs of endpoints refers to the three required elements that comprise a service endpoint: address, binding, and contract.
7. Which standard binding could be used for a service that was designed to replace an existing ASMX Web service?
The basicHttpBinding standard binding was designed to expose a service as if it were an ASMX Web service. This enables you to support existing clients as applications are upgraded to WCF.
8. What is the main disadvantage of using IIS to host a service?
Using IIS to host your services means that you will not be able to support non-HTTP protocols such as TCP, named pipes, and MSMQ. You will have access to the many built-in features available with IIS such as process recycling and messagebased
activation.
9. Which file specifies the types that your service will expose in IIS?
Service types are exposed through IIS by using the service file. This file must have an .svc file extension and should reside in the application directory for your IIS hosting application. This file will include an @ServiceHost directive, which specifies
the service name and language for the service code files. These files should be located in an App_Code subdirectory.
1.) How does Windows Communication Foundation address Service Oriented Architecture (SOA)?
WCF is the first programming model built from the ground up to provide implicit service-oriented application development, enabling developers to work autonomously and build applications that are more version independent, thereby increasing application resilience to change.
2.) How to deal with operation overloading while exposing the WCF services?
By default overload operations are not supported in WSDL based
operation. However by using Name property of OperationContract attribute, we can deal with operation overloading scenario.
[ServiceContract]
interface Isum
{
[OperationContract(Name = "MultiplyInt")]
int Multiply(int arg1,int arg2);
[OperationContract(Name = "MultiplyDouble")]
double Multiply(double arg1,double arg2);
}
Notice that both method name in the above interface is same (Add), however the Name property of the OperationContract is different. In this case client proxy will have two methods with different name MultiplyInt and MultiplyDouble.
3.) Is Windows Communication Foundation going to interoperate with my existing applications?
The current plan is for Windows Communication Foundation to provide wire-level interoperability with WSE3, System.Messaging, .NET Enterprise Services, and ASMX applications. With minimal or no changes to code, applications built with these technologies will be able to call Windows Communication Foundation services and be callable by Windows Communication Foundation services.
4.) How to configure Reliability while communicating with WCF Services?
Reliability can be configured in the client config file by adding reliableSession under binding tag.
Reliability is supported by following bindings only:
NetTcpBinding
WSHttpBindingWSFederationHttpBinding
WSDualHttpBinding
5.) Will Windows Communication Foundation applications interoperate with Web services built with other technologi
es?
Yes. By default,services built with WCF will communicate with other services based on the interoperable Web services specifications. This means that WCF services will communicate with any application built on an infrastructure that also conforms to these standards. Microsoft is deeply committed to p
latform interoperability and is an active member of key standards organizations defining the latest Web services standards.
6.) How to set the timeout property for the WCF Service client call?
The timeout property can be set for the WCF Service client call using binding tag. If no timeout has been specified, the default is considered as 1 minute.
7.) What are the core components of an Windows Communication Foundation service?
A host environment—an application domain and process—in which the service runs;
A service class, implemented in C# or VB.NET or another CLR-based language that implements one or more methods;
One or more endpoints that allow clients to access the service.
8.) What are different elements of WCF Srevices Client configuration file?
WCF Services client configuration file contains endpoint, address, binding and contract.