Saturday, 12 March 2016

3-6 yr Experience Interview Questions in .Net Technologies

3-6 yr Experience Interview Questions in .Net Technologies

Hai Friends,
Below I am posting the questions and answers for the short questions for 3-6 years experience guys. These questions will be helpful for those who are either preparing for the interview or attending the interviews. This will also be helpful for the last minute preparation in quickest way.
If anyone has better answers, please reply to this post and I will include the better answer to the post as it will be helpful for all of us.

CLR and C#

1. Types of Authentication IIS.
A. Authentication is the process which helps web server(IIS) to check and confirm the identity of the client who request to access the website.
Types of Authentication: 
a. Http Authentication: Basic Authentication, Digest Authentication
b. Integrated Windows Authentication: NTLM(Network Lan Manager), Kerberos
c. Client Certificates Access
d. Anonymous and UnAuthenticated Access
e. Logon-Redirection based: Form Authentication(IIS 7.0)

2. Types of Authentication and Authorization in ASP.Net.
A. Types of Authentication: Windows Authentication, Forms Authentication
Types of Authorization:- File Authorization and URL Authorization

3. ASP.Net Life cycle. 
A. In ASP.Net, the request starts with the client and processed through IIS.  In IIS, there are 2 utilities- INetInfo.exe and ASPNet_ISAPI.dll.
The InetInfo.exe hosts the worker process and checks for the syntax and semantics of the request, while ASPNet_ISAPI.dll is used to filter the .aspx files(based on the extension). After the URL request split into 2 parts- 
Virtual directory name and Web Page name. 
The worker process which is nothing but the application factory basically contains all the virtual directories and checks for the current virtual directory. If this is first request, then there will be no Virtual directory available. Now the worker process (W3wp.exe) creates a memory area called as AppDomain to check for the current page. As AppDomain is the Page Handler factory so it contains all the processes pages. If this is the new page then it will not find here. The request further moves to the HttpPipeline where the actual execution of the page happens by using the ProcessRequest method and creates the events(init, load, render, unload) of the page. After creation of event and execution of all the event, the HTML page returned back to the user.

4. ASP.Net Page Life Cycle.
A. There are few events which gets generated during the page execution like: Page_BeginRequest, Page_Init, Page_Load, Page_Prerender, Page_Render, Page_Unload etc
For the details of the page life cycle, you can follow the previous question.

5. What are types: Value Type and Reference Type?
A. DataType specifies Type of the data as well as Size of the data. There are 2 type of DataTypes in C#:
a. Value Type: Value type holds data directly, Value type stored in the stack memory, we can get the direct value of the value types. Value type data type can’t be null.
b. Reference types: This type does not hold the data directly. They hold the address on which the actual data present. They stored in heap memory, Can have default values.
We can make and work with null reference type.

6. Boxing and Unboxing: Terminology, Advantages and Disadvantages.
A. Converting the Value type data into the Reference type is called as Boxing
byte b= 45;
Object o = b.Tostring();
Converting the Reference type data and keep its value to stack is called as the Unboxing.
Object o=10;
Int i= Convert.ToInt32(o.ToString());
The Advantage of boxing and unboxing is that we can convert one type of the object to another type. The disadvantage is that it requires lot of memory and CPU cycles to convert from one type to another type.

7. What is Type Safety? 
A. TypeSafe is a way through which the application or framework that the memory will not be leaked to outside environment. E.g. C# is the type safe language where you must have to assign any object before using it. In VB.Net it will take the default value. So C# is the type safe language while VB.Net is not.

8. What is Strong Name?
A. Strong Name (SN) is used to make the dll as the unique not by its name but by its version as:
SN -k fileName.dll
Now it will have the unique name with respect to the version. This assembly when placed in the GAC, it will treat as the unique with its version number and other details. 2 assemblies with the same name can exist in the GAC but both will have different version. The CLR takes the latest version assembly while running the application.

9. What are Extensions, modules and handlers?
A. HttpModule and HttpHandler are the utilities which are used in the HttpPipeline under the ASP.Net page life cycle. When the request received to Http Pipeline, the HttpModule checks for the Authentication of the request and then it route the request to the respective handler. After that HttpHandler takes that request and process it. Once the request is processed through handler, again the HttpModule takes the response and send it back to the worker process and finally to the user.

10. What is worker process?
A. Worker process (w3wp.exe) is an executable which is also called as the Application Factory. This is used for the execution of the request and handling of the request for the web pages.

11. CLR and DLR?
A. CLR (Common Language Runtime) is the utility in the .Net framework to run the application. It is the runtime engine which actually executes the application with many responsibilities like taking care of memory management, versioning, CasPol etc.
DLR is new with .Net 4.0 which is the Dynamic Language Runtime and used to run the application on the fly wherever required. CLR runs as statically while DLR runs dynamically.

12. In case more than one dll versions of an installable is installed, which version is invoked by default?
A. By default the CLR will take and invoke the latest version of the dll and execute it accordingly. There could be the same name assemblies exists in the GAC but they will have different versions altogether for their uniqueness.
So while running the application, CLR takes the latest version assembly and use in the application.

13. What are Globalization and localization? How to implement them?
A. Globalization is the concept of developing the application in more than one language while the Localization is used for a particular language. Like if we develop the application in more than one language we need to create the resource files (.resx) by using System. Globalization and when we open the application in a particular language, then the localizations used to convert that application to the selected language.

14. What is assembly, GAC? Where they are physically located?
A. Assembly is the collection of classes, namespaces, methods, properties which may be developed in different language and packed as a dll. So we can say that dll is also called as assembly.
There are 3 types of assemblies- 
- Private Assembly, Shared Assembly, and Satellite Assembly.
GAC (Global Assembly Cache)- When the assembly is  required by more than one project or application, we need to make the assembly with strong name and keep it in GAC or in Assembly folder by installing the assembly with the GACUtil command.
To make the assembly with strong name:
SN -k MyDll.dll
And to install it in GAC:
GacUtil -i MyDll.dll
GAC assemblies are physically stored in Assembly folder in the system.

15. How to configure HTTPS for a web application?
A. To configure the HTTPS (HTTP with Secure) for the web application, we need to have a client certificate. The client certificates can be purchased from the trusted providers and then we need to install that certificate for our site. By implementing the HTTPS, all the data which is passing will be in encrypted format, while makes the website more secure.

16. What are Inproc and Outproc in session? Where are session data stores in these cases?
A. Inproc and Outproc is the types of Sessions where the session data can be stored in the process memory of the application server(IIS) and in the separate state server.
When the session data is stored in the process memory(AppDomain) of the server(IIS), the session is called as the Inproc server. In this case when the server is restarted, the session data will be lost. So In the Inproc session mode, the session data stores in the memory object in AppDomain in Application Worker Process(AspNet_wp.exe)
When the session data is stored in the separate server like in state server or in Sql Server, the type of session is called as the Outproc session. In this case, if the server where the application is running is restarted, the session will be still remain in the separate servers.
So in the  inproc session state, the session data is stored in the Process memory of the Server where the application is running.
In the Outproc session state, the session data is stored in the separate server- may be state server or in sql server.

17. When the View state is saved, and when is it loaded? How to enable/ disable View states?
A. View State data is stored in the current page in base64 encoded format. It gets loaded with the page and displays the values to the controls after the decoded. Internally it actually saves the check-sum of all the control data where the view state is enabled.so that when the page gets loaded due to any post back, it again finds the check-sum and then decodes the Base64 encoded string and gets back the same data to the controls. We can see the view state base64 encoded string in View Source of the page. It will be like _VIEWETATE="DSDSDF8DGDGDFGFD5FDGGDJFF23BNN457M9UJOG"this.
View state won't take the client or server memory to keep the view state data.

18. Difference between GET and POST. Which one is more secure?
A. GET and POST methods are used for the data transfer between the web pages. GET mainly used for small data which is not secure because in case of GET method, the data which we are passing will be visible in the url so we can't keep the secure data which will be visible in the url. There is also limited data which can be passed in case of GET method (max 255 character).
POST is used for transferring the huge data between the pages where we can keep the secure data and can transfer it. In case of using the POST method, the data which is transferring between the pages will not be visible so it is more secure than the GET method. Also there is no limit for POST method to post the data to the next page.
POST is more secure.

19. What are Razor engine? How is it different from ASPX Engines?
A. Razor engine is the new execution engine in the ASP.Net MVC 3 which is mainly used to convert the rezor syntax views to HTML page in the MVC applications. It takes the cshtml pages as the input for the ASP.Net MVC application and then render to the HTML as the output. The ASPX engine takes the aspx code and then renders to the HTML.

20. Pros and cons of JavaScript and AJAX.
A. JavaScript is a scripting language and mainly used for client side validation. We can validate the client side data before sending to the server. So by this we can improve the performance of the application. 
Ajax is Asynchronous JavaScript and XML which is used for the Asynchronous calls to the server. It uses the JavaScript/JQuery for making the call and use XML for the Data Transfer. It basically uses the XmlHttpRequest for the asynchronous calls to the server and communicates with the XML data which is platform independent. So Ajax can be used with any technology.

21. In how many different ways JavaScript code can be used/called in an application?
A. JavaScript can be used for Client Side validation, can also be used for calling of server side methods and functions, can be used for calling the web services, WCF service, Web API's, Calling the Controller and Action methods in ASP.Net MVC etc.

22. What needs to be done to call a JavaScript function from code behind?
A. If we want to call the JavaScript function from the code behind, we need to attach the JavaScript to the events in the page_load event as:
protected void btnSave_cliekc9object sender, EventArgs e)
{
 btnSave.Attributes.Add("onclick,"JavaScript: retrun Validatedata();");
}
Here ValidateData is the JavaScript function which can be used to validate the page data and if validation fails, it will return and will not execute the server side btnSave_click event.

23. Difference between Server Controls and User controls?
A. User controls are used for the re-usability for the controls in the application. By using the Web User Control template, we create the new user controls and then we can use the same control in the various pages. User controls can be created by combining more than one control to extend the functionality of the existing controls. To use the user controls, first we need to register them in the web page where we want to use that control. A separate copy is needed in each page where we want to use the user control. User controls can't be included into the toolbox.
Web Server controls are those controls which can be found in the toolbox and can be directly drag to the application like other controls textbox, button etc. For the web server control, only 1 copy of the control is needed irrespective of the number of web pages. If we want 10 text-boxes to be added in our web page, we need only 1 copy of the textbox in the toolbox and can be dragged 10 times.

24. Difference between Var, object and Dynamic types.
A. var is the keyword introduced with .Net 3.5 and used to store any kind of data like data-set, data table, int, float, char etc. We can keep any kind of data into the var variable.
var myVar = new String[] {"hello", "world!!"} ;
Here the myVar is the var type variable which is used to store the string array. Like this we can store any type of data into the var.
Object is the type which is used to store the objects of any kind. These objects need to be type cast when used.
Like object myObject = "Hello"
Here the myObject variable of object type is used to keep the string variable. Now when we want this variable value, we need to typecast it like
string strvar= (string) myobject;
Var is the compile time where the type of the var variable gets defined at the compilation of the program. Once we define the type during compilation, we cant make the changes of the type during run time or at the later stages.
Let's say, if we define like
var myVar = new String[] {"hello", "world!!"} ;
so here myVar variable will be of string array. Now after this, I can;t make it like:
var myVar = 10 ;
If we do this, it will throw error.
Dynamic- It’s a keyword introduces with the .Net 4.0 and used to keep the data similar to the var keyword. The type of Dynamic type can be changed even at run time.
So if we define like:
dynamic myVar = new String[] {"hello", "world!!"} ;
Then the myVar is of type string array. Now if we do like:
dynamic myVar = "Hello" ;
Now the myVar type will be used as string type. So we can change the type in case of dynamic.
The difference between the var and dynamic is that the dynamic variable uses the same memory location to store the object and not changes throughout the application.

25. Difference between Functions and methods.
A. In.Net terminology, both function and method are same. In general, we use method in server side code of .Net but in scripting language we use function like JavaScript function.
Here the difference can be function always returns a value whereas method may or may not. It depends upon the return type of the method.  

26. Difference between Abstract classes and Interface. Explain with scenario where to implement one?
A. Abstract Class: Collection of the Abstract (Incomplete) and Concrete (complete) members is called as the Abstract class. If there is at least one abstract member in a class, the class must be declared as abstract class.
When there is the similar behavior, we can use the abstract class.
e.g. We want to calculate the area of few shapes. As this is not generic to the application. We have few shapes - like Circle, Ellipse, Parabola, Hyperbola, Triangle etc.
So we can create an abstract class and implement it like below:
public abstract class MyAbstractClass
{
 // some other concrete members
 public abstract void Area();// abstract method
}
Now in the child class, let’s say i have a circle class and want to calculate the area of the circle:
public class Circle: MyAbstractClass
{
 public override void Area()
 {
  // calculate the area of the circle
 }
}
In the similar fashion, we can calculate the area of other shapes.
Interface: Collection of abstract members is called as the Interface. When the behavior is not similar, we need to use the interface. All the members of the interface 
must be overridden in the child classes.
e.g. Print functionality of the application can have an interface method like:
interface Inf
{
 void Print();
}
Now as this is the generic functionality and can be implemented in any of the class so we have taken it as interface. We can implement this functionality into any page like:
class MyClass: System.Web.UI.Page, Inf
{
 public void Print()
 {
  // implement details about the Print method
 }
// Here we can implement any kind of print-like print to excel, xml, word all depends on the our decision.
}

27. Different forms of Polymorphism. Differences between Abstraction and Polymorphism.
A. Polymorphism is to use the same function in many forms. The polymorphism is of 2 types-
a. Classical polymorphism (Overloading)
b. AdHoc polymorphism (Overriding)
Polymorphism = Poly(many) + Morphism(Forms) 
Overloading: When the runtime (CLR) find the behavior of class members at the compilation of the program, it is called as the Classical polymorphism or Overloading. In this, the method name is same but prototypes (method + parameters) are different and it is implemented in the same class.
e.g.
public class MyClass
{
  public int  Add(int a, int b)
  {
   return a+b;
  }
  public int  Add(int a, int b, int c)
  {
   return a+b+c;
  }
}
Overriding: When the runtime (CLR) find the behavior of class members at the runtime of the program, it is called as the AdHoc polymorphism or Overriding. In this, the method name as well as the prototype (method + parameters) is same but they are implemented in the different class. We use virtual keyword in the base class method to override in the child class using the override keyword.
e.g.
public class MyBaseClass
{
 public virtual void Show(string  message)
 {
  Console.WriteLine(“Your message is : ”+ message);
 }
}
public class MyChildClass: MyBaseClass
{
 public override void Show(string message)
 {
  Console.WriteLine(“Your new message is : ”+ message);
 }
}
Abstraction is the behavior to get the required functionality. To implement the abstraction, we use access specifiers where if we declare the members as private, it means they will be available only to the current class and if we make them as public, the other classes can also use them. So Abstraction is used to show only the essential features It is also used to hide the unnecessary data which is not relevant but present.
Abstract keyword is also used to get the abstraction behavior. We can use Abstract Class and Interface to implement Abstraction.

28. What are Delegates and Events?
A.  A Delegate is an object, which points to another method in the application. Delegate holds- name of the method, arguments of the method (if any) and the return type of the method.
See the below points regarding the Delegate:-
·          delegate keyword is sealed type in System. Multicast namespace.
·          Delegate works like a function pointer in C language.
·          Delegate holds the address of the function.
·          Delegate hides the actual information which is written inside the method definition.
·          A delegate can hold address of a single function as well as the address of multiple functions.
·          There are 2 types of delegate- 
           - Single cast delegate (hold single function) and 
           - Multicast delegate(hold multiple functions).
·          Addition and subtraction are allowed for the delegates but NOT multiplication and division. It means, we can add delegates, subtract delegates etc.
e.g. To create a single cast delegate, first we can create a class with a method as:
public class DelegateDemo
{
 public void Show(string msg)
 {
  Console.WriteLine(msg);
 }
}
Now we can call the method Show using the delegate as:
public  delegate void MyDelegate(string message); //declare delegate
now we need to create the object of the delegate with the address of the method as:
DelegateDemo obj = new DelegateDemo();//class object
MyDelegate md= new MyDelegate(obj.Show(“Hello World!!”));
md(); // call the delegate
We can create the events and event handler by using delegate with the below syntax:
public delegate void textChangedEventHandler(Object sender, TextEventArgs e)
This event handler will be used to handle the textbox textchanged event.
More details about the delegate and events can be found at the below link:
http://msdn.microsoft.com/en-in/library/orm-9780596521066-01-17.aspx

29. Covariance and Contra-variance.
A.  covariance and contravariance are the new features added with the .Net 4.0. They are basically used for the implicit reference conversion for different .Net types like array, delegate, and generic etc.
You can go to the below link for more details with the examples that how we can use the covariance and contrvariance to implicate reference conversion:
http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx

30. What are Extension methods?
A. Extension methods are special types of methods which are static methods but called as the instance methods.  The extension methods are added with the .Net framework 3.5 and with the Visual Studio 2008.
These methods won’t affect the existing class and the label. These methods are used for the extra behavior which the calls can provide. There is no need to build the class again if we add any extension method to the class.
There are various inbuilt methods added in .Net 3.5 with the introduction of LINQ. We can see the extension methods like Order By when we use the Linq as:
e.g.
int[] numbers = { 10, 45, 15, 39, 21, 26 };
var orderedNumbers = numbers.OrderBy(a => a);

31. What are Anonymous methods and Lambda Expression?
A.  Anonymous methods are those methods which does not have the name. As they don’t have the name, so there is no way to call these methods. These methods are created by using the delegate as below:
button1.Click += delegate{listBox1.Items.Add(textBox1.Text)};
Lambda Expression: It’s an easy way to create anonymous functions. It is also an anonymous function which has the capability to contain expressions and statements. We can create the delegate and expression tree types using the lambda expression.
For more details regarding the anonymous method and lambda expression, we can go through the below link:
http://www.codeproject.com/Articles/47887/C-Delegates-Anonymous-Methods-and-Lambda-Expression

32. Multithreading. How to implement Multithreading?
A. Executing more than one processes simultaneously is called as multithreading. To implement the multithreading concept, we need to use the System. Threading .dll assembly and the System. Threading namespace.
To write the thread program, we need to create a class with the method. Now we can create the thread object and then pass the method by using the class object to the method.
After that we need to create the ThreadStart delegate which will call the actual method of the class.
You can go through below link for more explanation and other details regarding the implementation and the code snippet:
http://www.codeproject.com/Articles/1083/Multithreaded-Programming-Using-C

33. Which interface is used to-
a. Convert Boolean values to Visibility values?
b. Compare two integer values?
c. Compare String values?
A. Check the below interfaces which are used in these scenarios:
a. Convert Boolean values to Visibility values?
b. Compare two integer values?-  IComparable interface
c. Compare String values? IComparer interface

SQL Server

34. What is the difference between a View and a Cursor?
A. View: It is one of the database object which is also called as virtual table. We can also say that it is a window through which we can see some part of database. View is also called as stored query because we are going to fetch data using View.
View does not contain any data. It’s just a virtual table which is used to get the records from the base table for which the view is created. View is faster than ad hoc queries because when we create the view and execute it once. Next time onwards it will be available as the compiled format. So whenever the view is called, it will just execute rather than compiling.
Cursor: Cursor is a database object which is also the buffer area and created as a result of any sql statement to hold the intermediate values.
Cursor is used to format the rows individually. By using the cursor, we can process the individual rows. There are 4 types of cursors in Sql Server-
a. Static Cursor
b. Dynamic Cursor
c. Key set cursor
d. Read-only cursor

35. How to execute multiple update on different conditions in a single query?
A. To execute multiple update using a single Sql update statement is the new feature available with the SQL Server 2008. In this, we can update multiple rows using a single update command. 

36. Left outer joins and Right Outer joins
A. Joins are used to retrieve data from more than 1 tables using some conditions. There are 3 types of outer joins in SQL Server database-
a. Left Outer Join
b. Right Outer Join
c. Full Join
In order to extract the matched rows from both the tables and unmatched rows from the first table, left Outer join is used. The syntax for left outer join condition is:
T1.Col1* = T2.Col1
In order to extract the matched rows from both the tables and unmatched rows from the second table, right Outer join is used. The syntax for right outer join condition is:
T1.Col1 = *T2.Col1
In order to extract the matched rows from both the tables and unmatched rows from the first table and then unmatched row from the second table, full join is used. The syntax for full join condition is:
T1.Col1* = *T2.Col1

37. Exception handling.
A. Exception Handling is the way to handle the unexpected error at runtime of the application. From the SQL Server 2005 version, try…catch block is also supported to catch the exceptions in SQL Server database. There is various other ways to catch the error like using Global temporary variables @@Error, inbuilt method RaiseError etc. 

38. What is Performance Tuning? How do you implement it.
A. Performance Tuning is the process through which we can optimize the SQL Server objects like functions, triggers, stored procedure to achieve high response time to the front end applications. In the performance tuning process we generally check for the below point and optimize the objects processing:
a.  Through Query Execution plan, check for the processing time of the query execution.
b. Check the join conditions and break all the condition for executions of the queries individually.
c. Check for the error prone process, conditions in the queries.
d. Check for the loops whether they are terminated if any error occurs.
e. Check for the processes which are taking more time in execution and how to reduce the response time.

39. Difference between Having and Where clauses.
A.  When the 'where' clause is not able to evaluate the condition which consists of group functions, Having clause is used. Having clause is always followed by the Group By clause.
'Where' clause is used to filter the records based on the conditions. If there is the requirement to get the group data in the select statement and where clause is not able to get it, we can use the Having clause.
e.g. Display DeptNo, No.of Employees in the department for all the departments where more than 3 employees are working
SELECT DEPTNO, COUNT(*) AS TOTAL_EMPLOYEE
FROM EMP
GROUP BY DEPTNO HAVING COUNT(*) >3

40. Difference between Temp tables and Tables variables?
A. Temp Table in SQL Server: 
a. Temp table are the special type of tables which are used to store the intermediate data of the actual table.
b. Temp tables are only visible to the current sessions of the sql server instance. When the session end, these table data automatically drops.
c. We can’t join the temp tables as they don’t allow the foreign key constraints.
d. Temp tables are created in TempDB database.
e. We can use the same temp table name for the different user sessions.
f. Mostly used in stored procedure to handle the intermediate data.

41. What does @ and @@ suffixed by property names specify?
A. @- This is used for the variable declaration
e.g. @name varchar2(50)
@@- This is used for the Global variable declaration
e.g. @@Error=0

42. Self-join queries.
A. Self-Join is a type of join which is used to join the same table by creating the multiple instances of the same table. So we can join 2 instances of the same table in case of self-join. This type of join is used when there is the requirement to get the referenced data which is available in the same table.
e.g. A table contains EmpId, Ename and ManagerId
As the manager is also an employee. Now if we want that who is the manager of which employee. In this situation, we need to create the instance of the same table and get the required data as:
SELECT EMPID, ENAME, ENAME AS [MANAGER NAME]
FROM EMP E1, EMP E2
WHERE E1.EMPID= E2.MANAGERID

43. Types of Index.
A.  Index is one of the database objects which is used to improve the performance of the database queries. It reduces the table scan while retrieving the data from the database and the search gets fast-
There are 2 types of indexes used in the SQL server:
a. Clustered index
b. Non clustered index
There are 3 more types of index but those comes under the above two-
a. Unique index
b. Composite Index
c. XML Index-added in SQL Server 2005

The index basically works on searching like binary tree where the root value is the finding value and it will be compared with the partitioned value of the tree.

44. Difference between Primary key, Unique key and Candidate key?
A. Primary Key- It is a key to make the unique identification of the row in a table. It doesn't allow null values in the primary key column. We can create the lookup columns based on the primary key. One table allows maximum of 1 primary key and in 1 table, we can create the primary key column by using 16 columns. Due to one of the normalization rule, we have to create primary key for the table to make the rows unique.
Unique Key:- (Primary Key + Not null) is called as unique key. Unique key is also used to make the rows as unique in a table. The only difference between primary key and unique key is that primary key does not allow null value while the unique key allow. The limitation of the null in unique key is that it allows only one Null value. So only in one row, we can make the key as null for the unique key.
Candidate key- The key other than primary key, to make the rows as unique is called as candidate key. In candidate key, we take the columns which are not in the primary key and make the key for uniqueness of the row.

45. What is the default value for Datetime. What are Min and Max values for Date in 2008.
A.  The default value of Date is CURRENT_TIMESTAMP
Below are the new date and time values in Sql Server 2008:
In SQL Server 2008:
1. DateTime2

Min Value: 0001-01-01 00:00:00.0000000
Max Value: 9999-12-31 23:59:59.9999999
2. Date
Min Value: 0001-01-01

Max Value: 9999-12-31

You can go through the below link for couple of work around:
http://dhaneenja.blogspot.in/2008/06/minimum-year-value-in-sql-server.html

WCF

46. What is WCF also known as?
A.  WCF (Windows Communication Foundation) is also know as  Indigo by its code name.

47. Difference between WCF and Web Services?
A. Below are the main differences between the WCF and Web Service:
Web Service:
a. Can be hosted in IIS only
b. Only two types of operations affects- One-Way, Request-Response
c. To serialize the data use System.Xml.Serialization
d. To encode the data use- XML 1.0, MTOM, DIME, Custom
e. Web Service can be accessed through HTTP channel.
WCF service:
a. Can be hosted in IIS, Self Hosting, WAS, Windows Services etc
b. Three types of operations affects- One-Way, Request-Response and Duplex
c. To serialize the data use System.Runtimel.Serialization
d. To encode the data use- XML 1.0, MTOM,Binary, Custom
e. WCF Service can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P etc.

48. What are Endpoints?
A. The collection of Address, Binding and Contract is called as End Point. In Sort,
EndPoint = A+B+C
Address (Where)-  It means where the service is hosted. URL of the service shows the address.
Binding (How)- How to connect to the service, is defined by the Binding. It basically has the definition of the communication channel to communicate to the WCF service
Contract (what)- It means what the service contains for the client. What all the methods are implemented in the WCF service is implemented in the Contract.

49. What are Behavior and Bindings?
A. Binding mainly describes about the communication of the client and service. For this, there are protocols corresponding to the binding behavior which will take care of the communication channel. There are different protocols which we use for the different types of bindings. E.g. HTTP, TCP, MSMQ, Named Pipes etc.
Behavior is used for the common configurations that could be for endpoints. When we use the common behavior, they affect to all the end points. Adding the service behavior affect the service related stuff while the endpoint related behavior affects the end points. Also operations level behavior affects the operations. 

50. What are different types of Contracts supported?
A. There are mainly 5 type of contracts used in WCF service:
a. Service Contract
b. Operation Contract
c. Data Contract
d. Message Contract
e. Fault Contract

51. What is the difference between Transport and Message Security mode?
A. WCF supports 2 types of security- Transport Level Security and Message Level Security
Transport Level Security- In this type of security, we make the transport channel as secure so that the data flows in that channel will be automatically secured. For HTTP channel, we use the client certificate for the security of the web address. SSL is used for the HTTP channel security. As we don’t need to secure each of the messages which are floating between the client and the service, the speed is faster as direct message is going to the client from the service.
Message level security- This type of security in WCF is used where we don't have the fixed transport medium and we need to secure each message which is floating between the server and the client. In this type of security we use certain algorithms for making the message as secure message. We use some extra bits and send with the message. We also use some encryption techniques like SHA1 or MD5 which make the proper security for our message. As each message needs to be secured, this type of security makes some delay in the process of sending and receiving the messages.

52. How to configure WCF security to support Windows authentication?
A. To support the WCF security in Windows Authentication, we need to add the ClientCredetialType attribute to “Windows” under the security tab element:
transport clientCredentialType="Windows"

53. How to use Fault Contract?
A.  Fault Contract is mainly used for viewing and displaying the errors which occurred in the service. So it basically documents the error and the error message can be shown to the user in the understandable way. We can’t use here the try….catch block for the error handling because the try…catch is the technology specific (.Net Technology). If we use the try...catch block for handling the errors, the error will not be reached to the client who is consuming the service. Because this error will not be included in the message. So we use the Fault contract for the error handling.
e.g. To use the Fault contract, we can simply write like the below:
public  int Add(int number1,int number2)
{
  // write some implementation
 throw new FaultException (“Error while adding data..”);
}
Here the fault Exception method is the inbuilt method which will throw the exception and display the message . We can use the custom class so that the message can be customized and the customized message can be sent to the client.
So we can create  a clss like:
public Class CustomException
{
 public int ID {get;set;}
 public string Message {get;set;}
 public string Type{get;set;}
}
Now this custom type we can use with the Operation Contract as:
[ServiceContract] 
public interface IMyInterface
{
 [OperationContract]
 [FaultContract(typeOf(CustomException))]
 int Add(int num1,int num2);
}
Now while implementation of the Add method, we can assign the class properties.

WPF

54. Diff between XML and XAML.
A. XAML is the declarative XML based language which is used to define the objects and properties. XAML document is loaded by XAML parser. So XAML Parser initiates the objects and set those properties. XAML is mainly used in creating the objects in WPF and Silverlight applications. 
For more detailed explanation, you can go through the below link:
http://www.differencebetween.net/technology/software-technology/difference-between-xml-and-xaml/

55. Stack Panel and Wrap Panel.
A. StackPanel is one of layout control in WPF. We can place the child controls inside the stackpanel either horizontally or vertically. So it provides two types of orientations- Horizontal Orientation and Vertical orientation.
You can go through the below link for more detailed explanation and the code snippet:
http://wpftutorial.net/StackPanel.html

Wrap panel is another layout control which is similar to the StackPanel. Wrap panel not only keep the control in horizontal and vertical orientation but also wrap them into new line if there is no space. Here also the orientation can be set as Horizontal or Vertical. Its main use is to arrange the tabs in the tab control, menu control or in toolbar items.
You can go through the below link for more details:
http://wpftutorial.net/WrapPanel.html

56. Hierarchical Data Template.
A. Hierarchical Data Template is a type of data template which is used to bind the controls which  supports HeaderedItemsControl, like  TreeViewItem or MenuItem
We can bind those controls items using the Hierarchical Data Template. It displayed the data into Hierarchical structure in the tree structure. It could be in the left to right or top to bottom.
You can go through the below link for more details:
http://msdn.microsoft.com/en-us/library/system.windows.hierarchicaldatatemplate.aspx

57. Virtualization.
A. This is the feature in WPF which increases the efficiency of the programs when there are the large data objects. If the WPF ItemsControl is bound with the large collection data source object and we enabled the virtualization, then the controls will show only the data which is in the visual container for those items which are visible currently. This visual data is only the small part of the large data object. Now when the user will scroll down or up, the rest of the data will be visible and previous data will be hidden again. So this is increase the efficiency of the program from the UI prospective. 

58. Events and Routed Events.
A.  Routed event is special type of event which can invoke and handle multiple events from different objects rather than the event which is coming from one object. So it generally handles the object from the element tree. So whatever the elements inside the element tree and if they generate the event-may be multiple events, the routed event is capable of handling those events.
The routed event can be invoked in both the directions but in general it comes from the source element and then bubbled up in the element tree until the root element.

59. Bubbling and Tunneling.
A. Bubbling: When the events are raised form the innermost element in the visual tree and comes up towards the root element, is called as bubbling.
Tunneling: It is the opposite process of Bubbling where the events fired by the root element goes down towards the last child element control.
Please go through the below link for more details:
http://www.dotnetspider.com/forum/130497-event-bubbling-event-tunneling.aspx

60. Resource Dictionary, Static Resources and Dynamic Resources.
A. Static and Dynamic resources are used for binding the resources to the control objects. 
The main difference between StaticResource and DynamicResource is that how the resource is retrieved elements. If the resource is StaticResource, it will be retrieved only once by the element who is referencing it  and it will be used for all the resources. While the DynamicResource gets its value each time they reference to the objects. So StaticResource is faster than the DynamicResource , because StaticResource needs to get the value only once while the DynamicResource needs each time.

61. What is Prism? 
A. Prism is the framework or the set of guidelines which is used to develop the WPF desktop application as well as the Silverlight Rich Internet applications. So it’s a kind of Design pattern to Develop the XMAL based application. It also used to develop the Windows 7 applications. Prism mainly helps to design the loosely coupled components which can be easily integrated with the other components of the overall application. Prism mainly used to build the composite applications which need various other components to be integrated. 
Prism mainly guides of creating the applications using the Model-View-ViewModel (MVVM) model, Managed Extensibility Framework (MEF), and navigation in the application.
To use the Prism framework, we need to use their library called as Prism Library. So prism Library is the inbuilt set of components which can be used in developing the WPF and Silverlight applications.
You can go through the below link for more details and the use of the components of the Prism framework:
http://msdn.microsoft.com/en-us/library/ff648465.aspx

62. Dependency Injection, Event Aggregator.
A. For the details about the dependency injection, you can follow the below link:
http://wpftutorial.net/ReferenceArchitecture.html
EventAggregator : It is the utility service which contains the events and allows the decouple the publisher and subscriber so that they can be buildup independently. Decouple is primarily useful when a new module needs to be added or removed or modified. The new module can be added as per the event fired and defined in the shell.
For more details about the Event Aggregator, you can follow the below link:
http://msdn.microsoft.com/en-us/library/ff921122(v=pandp.20).aspx

63. Shell, Bootstrapper and Region Managers
A. Bootstrapper:- An utility in WPF engine which is mainly responsible for the initialization of the application by using the composite application library. By using the bootstrapper we can find out how the components of the application are wired up in the composite application library. The bootstrapper responsibility to create the Shell or main window. Composite application library has the default abstract class UnityBootstrapper which actually handles the initialization.
You can go through the below link for more details about the bootstrapper:
http://msdn.microsoft.com/en-us/library/ff921139(v=pandp.20).aspx
Region and Region Managers: This is concept of Prism framework. We define the region through XAML code and once a region is defined, automatically it will be registered with the RegionManager. Actually the Bootstrapper registers a service called the RegionManager at run time. RegionManager is a dictionary where the key is name of the region. The value of the key is the reference of the IRegion interface. RegionAdapter is used to create the instance reference of the IRegion interface.
You can go through the below link for more details about the Region and Region Manager:
http://msdn.microsoft.com/en-us/magazine/cc785479.aspx#id0090091

64. What are MEF and Unity?
A.  The MEF (Managed Extensibility Framework) is the new concept in .Net 4.0. It is used to create the lightweight and extensible applications to create Managed Extensibility Framework. It is not only allows the extension but also reused within the application. Extension can be easily encapsulating the code using the MEF.
For more details, you can go through the below link:
http://msdn.microsoft.com/en-us/library/dd460648.aspx

65. How to navigate to another page?
A. There is a class NavigationService which can be used for navigation of the WPF window:
this.NavigationService.GoForward();
//or
this.NavigationService.Navigate("MysecondPage.xaml")

Thursday, 15 August 2013

Good Stuff on WCF

Service Contract

Service contract describes the operation that service provide. A Service can have more than one service contract but it should have at least one Service contract.
Service Contract can be define using [ServiceContract] and [OperationContract] attribute. [ServiceContract] attribute is similar to the [WebServcie] attribute in the WebService and [OpeartionContract] is similar to the [WebMethod] in WebService.
  • It describes the client-callable operations (functions) exposed by the service
  • It maps the interface and methods of your service to a platform-independent description
  • It describes message exchange patterns that the service can have with another party. Some service operations might be one-way; others might require a request-reply pattern
  • It is analogous to the element in WSDL
To create a service contract you define an interface with related methods representative of a collection of service operations, and then decorate the interface with the ServiceContract Attribute to indicate it is a service contract. Methods in the interface that should be included in the service contract are decorated with the OperationContract Attribute.
[ServiceContract()]
    public interface ISimpleCalculator
    {
        [OperationContract()]
        int Add(int num1, int num2);
    }
Once we define Service contract in the interface, we can create implement class for this interface.
public  class SimpleCalculator : ISimpleCalculator
    {
    
        public int Add(int num1, int num2)
        {
            return num1 + num2;
        }

    }
With out creating the interface, we can also directly created the service by placing Contract in the implemented class. But it is not good practice of creating the service
[ServiceContract()]
   public class SimpleCalculator 
   {
       [OperationContract()]
       public int Add(int num1, int num2)
       {
           return num1 + num2;
       }

   }

Data Contract

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. Data contract can be explicit or implicit. Simple type such as int, string etc has an implicit data contract. User defined object are explicit or Complex type, for which you have to define a Data contract using [DataContract] and [DataMember] attribute. A data contract can be defined as follows:
  • It describes the external format of data passed to and from service operations
  • It defines the structure and types of data exchanged in service messages
  • It maps a CLR type to an XML Schema
  • t defines how data types are serialized and deserialized. Through serialization, you convert an object into a sequence of bytes that can be transmitted over a network. Through deserialization, you reassemble an object from a sequence of bytes that you receive from a calling application.
  • It is a versioning system that allows you to manage changes to structured data
We need to include System.Runtime.Serialization reference to the project. This assembly holds the DataContract and DataMember attribute. Create user defined data type called Employee. This data type should be identified for serialization and deserialization by mentioning with [DataContract] and [DataMember] attribute.
 [ServiceContract]
    public interface IEmployeeService
    {
        [OperationContract]
        Employee GetEmployeeDetails(int EmpId);
    }

    [DataContract]
    public class Employee
    {
        private string m_Name;
        private int m_Age;
        private int m_Salary;
        private string m_Designation;
        private string m_Manager;

        [DataMember]
        public string Name
        {
            get { return m_Name; }
            set { m_Name = value; }
        }

        [DataMember]
        public int Age
        {
            get { return m_Age; }
            set { m_Age = value; }
        }

        [DataMember]
        public int Salary
        {
            get { return m_Salary; }
            set { m_Salary = value; }
        }

        [DataMember]
        public string Designation
        {
            get { return m_Designation; }
            set { m_Designation = value; }
        }

        [DataMember]
        public string Manager
        {
            get { return m_Manager; }
            set { m_Manager = value; }
        }

    }
Implementation of the service class is shown below. In GetEmployee method we have created the Employee instance and return to the client. Since we have created the data contract for the Employee class, client will aware of this instance whenever he creates proxy for the service.
public class EmployeeService : IEmployeeService
    {
        public Employee GetEmployeeDetails(int empId)
        {
            
            Employee empDetail = new Employee();

            //Do something to get employee details and assign to 'empDetail' properties

            return empDetail;
        }
    }

Client side

On client side we can create the proxy for the service and make use of it. The client side code is shown below.
protected void btnGetDetails_Click(object sender, EventArgs e)
        {
            EmployeeServiceClient objEmployeeClient = new EmployeeServiceClient();
            Employee empDetails;
            empDetails = objEmployeeClient.GetEmployeeDetails(empId);
//Do something on employee details

Message Contract

Message

Message is the packet of data which contains important information. WCF uses these messages to transfer information from Source to destination.  WCF uses SOAP(Simple Object Access Protocol) Message format for communication. SOAP message contain Envelope, Header and Body.SOAP envelope contails name, namespace,header and body element. SOAP Hear contain important information which are not directly related to message. SOAP body contains information which is used by the target.
Diagram Soap envelope

Message Pattern

It describes how the programs will exchange message each other. There are three way of communication between source and destination
  1. Simplex - It is one way communication. Source will send message to target, but target will not respond to the message.
  2. Request/Replay - It is two way communications, when source send message to the target, it will resend response message to the source. But at a time only one can send a message
  3. Duplex - It is two way communication, both source and target can send and receive message simultaniouly.

What is Message contract?

As I said earlier, WCF uses SOAP message for communication. Most of the time developer will concentrate more on developing the DataContract, Serializing the data, etc. WCF will automatically take care of message. On Some critical issue, developer will also require control over the SOAP message format. In that case WCF provides Message Contract to customize the message as per requirement. WCF supports either RPC(Remote Procedure Call) or Message style operation model. In the RPC model, you can develop operation with Ref and out parameter. WCF will automatically create the message for operation at run time. In Message style operation WCF allows to customize the message header and define the security for header and body of the message.

Defining Message Contract

Message contract can be applied to type using MessageContract attribute. Custom Header and Body can be included to message using 'MessageHeader' and 'MessageBodyMember'atttribute. Let us see the sample message contract definition.
[MessageContract]
public class EmployeeDetails
{
    [MessageHeader]
    public string EmpID;
    [MessageBodyMember]
    public string Name;
    [MessageBodyMember]
    public string Designation;
    [MessageBodyMember]
    public int Salary;
    [MessageBodyMember]
    public string Location;
}
When I use this EmployeeDeatils type in the service operation as parameter. WCF will add extra header call 'EmpID' to the SOAP envelope. It also add Name, Designation, Salary, Location as extra member to the SOAP Body.

Rules :

You have to follow certain rules while working with Message contract
  1. When using Message contract type as parameter, Only one parameter can be used in servicie Operation
    [OperationContract]
    void SaveEmployeeDetails(EmployeeDetails emp);
    
  2. Service operation either should return Messagecontract type or it should not return any value
    [OperationContract]
    EmployeeDetails GetEmployeeDetails();
    
  3. Service operation will accept and return only message contract type. Other data types are not allowed.
    [OperationContract]
    EmployeeDetails ModifyEmployeeDetails(EmployeeDetails emp);
     

    Fault Contract

    Service that we develop might get error in come case. This error should be reported to the client in proper manner. Basically when we develop managed application or service, we will handle the exception using try- catch block. But these exceptions handlings are technology specific. In order to support interoperability and client will also be interested only, what wents wrong? not on how and where cause the error. By default when we throw any exception from service, it will not reach the client side. WCF provides the option to handle and convey the error message to client from service using SOAP Fault contract. Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error accorded in the service to client. This help as to easy identity the what error has accord. Let us try to understand the concept using sample example.  Step 1: I have created simple calculator service with Add operation which will throw general exception as shown below
    //Service interface
    [ServiceContract()]
        public interface ISimpleCalculator
        {
            [OperationContract()]
            int Add(int num1, int num2);
        }
    //Service implementation
    public  class SimpleCalculator : ISimpleCalculator
        {
        
            public int Add(int num1, int num2)
            {
                //Do something
                throw new Exception("Error while adding number");
                
            }
    
        }
    
    
    Step 2: On client side code. Exceptions are handled using try-Catch block. Even though I have capture the exception when I run the application. I got the message that exceptions are not handled properly.
    try
       {
          MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy
           = new MyCalculatorServiceProxy.MyCalculatorServiceProxy();
          Console.WriteLine("Client is running at " + DateTime.Now.ToString());
          Console.WriteLine("Sum of two numbers... 5+5 =" + proxy.Add(5, 5));
          Console.ReadLine();
       }
       catch (Exception ex) 
       {
          Console.WriteLine(ex.Message);
          Console.ReadLine();
       }
    
    Step 3: Now if you want to send exception information form service to client, you have to use FaultException as shown below.
            public int Add(int num1, int num2)
            {
                //Do something
                throw new FaultException("Error while adding number");
                
            }
    
    Step 4: Output window on the client side is show below.
    Step 5: You can also create your own Custom type and send the error information to the client using FaultContract. These are the steps to be followed to create the fault contract.
    • Define a type using the data contract and specify the fields you want to return.
    • Decorate the service operation with the FaultContract attribute and specify the type name.
    • Raise the exception from the service by creating an instance and assigning properties of the custom exception.
    Step 6: Defining the type using Data Contract
        [DataContract()]
        public class CustomException
        {
            [DataMember()]
            public string Title;
            [DataMember()]
            public string ExceptionMessage;
            [DataMember()]
            public string InnerException;
            [DataMember()]
            public string StackTrace;        
        }
    
    Step 7: Decorate the service operation with the FaultContract
        [ServiceContract()]
        public interface ISimpleCalculator
        {
            [OperationContract()]
            [FaultContract(typeof(CustomException))]
            int Add(int num1, int num2);
        }
    
    Step 8: Raise the exception from the service
            public int Add(int num1, int num2)
            {
                //Do something
                CustomException ex = new CustomException();
                ex.Title = "Error Funtion:Add()";
                ex.ExceptionMessage = "Error occur while doing add function.";
                ex.InnerException = "Inner exception message from serice";
                ex.StackTrace = "Stack Trace message from service.";
                throw new FaultException(ex,"Reason: Testing the Fault contract") ;
                
            }
    
    Step 9: On client side, you can capture the service exception and process the information, as shown below.
       try
       {
          MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy 
          = new MyCalculatorServiceProxy.MyCalculatorServiceProxy();
           Console.WriteLine("Client is running at " + DateTime.Now.ToString());
           Console.WriteLine("Sum of two numbers... 5+5 =" + proxy.Add(5, 5));
           Console.ReadLine();
        }
        catch (FaultException<MyCalculatorService.CustomException> ex)
         {
            //Process the Exception
         }

    Types of Binding

    Let us see more detailed on predefined binding

    BasicHttpBinding

    • It is suitable for communicating with ASP.NET Web services (ASMX)-based services that comfort with WS-Basic Profile conformant Web services.
    • This binding uses HTTP as the transport and text/XML as the default message encoding.
    • Security is disabled by default
    • This binding does not support WS-* functionalities like WS- Addressing, WS-Security, WS-ReliableMessaging
    • It is fairly weak on interoperability.

    WSHttpBinding

    • Defines a secure, reliable, interoperable binding suitable for non-duplex service contracts.
    • It offers lot more functionality in the area of interoperability.
    • It supports WS-* functionality and distributed transactions with reliable and secure sessions using SOAP security.
    • It uses HTTP and HTTPS transport for communication.
    • Reliable sessions are disabled by default.

    WSDualHttpBinding

    This binding is same as that of WSHttpBinding, except it supports duplex service. Duplex service is a service which uses duplex message pattern, which allows service to communicate with client via callback. In WSDualHttpBinding reliable sessions are enabled by default. It also supports communication via SOAP intermediaries.

    WSFederationHttpBinding

    This binding support federated security. It helps implementing federation which is the ability to flow and share identities across multiple enterprises or trust domains for authentication and authorization. It supports WS-Federation protocol.

    NetTcpBinding

    This binding provides secure and reliable binding environment for .Net to .Net cross machine communication. By default it creates communication stack using WS-ReliableMessaging protocol for reliability, TCP for message delivery and windows security for message and authentication at run time. It uses TCP protocol and provides support for security, transaction and reliability.

    NetNamedPipeBinding

    This binding provides secure and reliable binding environment for on-machine cross process communication. It uses NamedPipe protocol and provides full support for SOAP security, transaction and reliability. By default it creates communication stack with WS-ReliableMessaging for reliability, transport security for transfer security, named pipes for message delivery and binary encoding.

    NetMsmqBinding

    • This binding provides secure and reliable queued communication for cross-machine environment.
    • Queuing is provided by using MSMQ as transport.
    • It enables for disconnected operations, failure isolation and load leveling

    NetPeerTcpBinding

    • This binding provides secure binding for peer-to-peer environment and network applications.
    • It uses TCP protocol for communication
    • It provides full support for SOAP security, transaction and reliability.
    • Message Contract Properties

      ProtectionLevel

      You can mention the MessageHeader or MessageBodyMember to be signed or Encrypted usingProtectionLevel property. Example
       
      using System.Net.Security;
      
          [MessageContract]
          public class EmployeeDetails
          {
              [MessageHeader(ProtectionLevel=ProtectionLevel.None)]
              public string EmpID;
              [MessageBodyMember(ProtectionLevel = ProtectionLevel.Sign )]
              public string Name;
              [MessageBodyMember(ProtectionLevel = ProtectionLevel.Sign )]
              public string Designation;
              [MessageBodyMember(ProtectionLevel=ProtectionLevel.EncryptAndSign)]
              public int Salary;
      
          }
      
      In the above type definition, we have made the different protection level for body. But the protection level of the body is determind by the highest ProtectionLevel property. By default if you are not specifying the protection level it takes 'EncryptAndSign'. So it good if you specify minimum ProtectionLevel required.

      Name and Namespace:

      SOAP representation of the message element can be change by mentioning Name and Namespace property of the Header and Body member. By default namespace is the same as the namespace of the service contract that the message is participating. In the below example, I have mention the Name property to the EmpID and Name.
       
      [MessageContract]
          public class EmployeeDetails
          {
              [MessageHeader(Name="ID")]
              public string EmpID;
              [MessageBodyMember(Name="EmployeeName")]
              public string Name;
              [MessageBodyMember()]
              public string Designation;
              [MessageBodyMember()]
              public int Salary;
      
          }
      
      When SOAP message representation, its name is changed to ID and EmployeeName.
       
      <EmployeeDetails>
        <ID>45634</ID>
        <EmployeeName>Sam</EmployeeName>
        <Designation>Software Engineer</Designation>
        <Salary>25000</Salary>
      </EmployeeDetails>
      

      Order

      The order of the body elements are alpehabetical by default. But you can control the order, usiingOrder property in the MessageBody attribute.
       
      [MessageContract]
          public class EmployeeDetails
          {
              [MessageHeader()]
              public string EmpID;
              [MessageBodyMember(Order=2)]
              public string Name;
              [MessageBodyMember(Order=3)]
              public string Designation;
              [MessageBodyMember(Order=1)]
              public int Salary;
      
          }

      MessageHeaderArray Attribute

      Consider the Message contract type definition as shown below.
       
      [MessageContract]
          public class Department
          {
              [MessageHeader]
              public string DepartmentID;
              [MessageHeader]
              public string DepartmentName;
              [MessageHeader]
              public Employees Employee();
      
          }
      
      In this we are having array of Employee type as message header. When this converted to SOAP Header it looks as shown below.
      <Department>
        <DepartmentID>PRO1243</DepartmentID>
        <DepartmentName>Production</DepartmentName>
        <Employees>
          <Employee>Sam</Employee>
          <Employee>Ram</Employee>
          <Employee>Raja</Employee>
        </Employees>
      </Department>
      Suppose you want to show the all employee detail in same level. We can use MessageHeaderArray attribute which will serialize the array element independently. If you use the MessageHeaderArray attribute of Employees, SOAP message will look as shown below.
      <Department>
        <DepartmentID>PRO1243</DepartmentID>
        <DepartmentName>Production</DepartmentName>
        <Employee>Sam</Employee>
        <Employee>Ram</Employee>
        <Employee>Raja</Employee>
      </Department>

      Metadata Exchange Endpoint

      Exposing the metadata using HTTP-GET has a disadvantage, such that there is no guarantee that other platforms you interact will support it. There is other way of exposing the using special endpoint is called as Metadata Exchange Endpoint. You can have as many metadata exchange endpoints as you want.

      Address

      It is basically Uri to identify the metadata. You can specify as address in the endpoint but append with "mex" keyword. For example "http://localhost:9090/MyCalulatorService/mex"

      Binding

      There are four types of bindings supported for metadata exchange. They are mexHttpBinding, mexHttpsBinding, mexNamedPipesBinding, mexTcpBinding.

      Contract

      IMetadataExchange is the contract used for MEX endpoint. WCF service host automatically provides the implementation for this IMetadataExcahnge while hosting the service.
      You can create the Metadata Exchange Endpoint either Administrative (configuration file) or programmatically.

      Administrative (Configuration file):

      In the configuration file of the hosting application, you can add metadata exchange endpoint as shown below.
      <system.serviceModel>
      <services>
       <service name="MyService">
       <endpoint address="http://localhost/IISHostedService/MyService.svc"
       binding="wsHttpBinding" contract="IMyService">
       <identity>
       <dns value="localhost"/>
       </identity>
       </endpoint>
       <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
       </service>
      </services>  
      </system.serviceModel>
      

      Programming Model:

      In the following code I have mention about creating the Metadata Exchange Endpoint through coding. Steps to create the metadata endpoint are
      • Create the ServiceMetadataBehavior object and add to Service host description.
      • ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                    host.Description.Behaviors.Add(smb);
      • Create the metadata binding object using MetadataExchangeBinding
      • Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding ();
      • 3. Add the endpoint to the service host with address, binding and contract.
      • host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex");
      Complete code for hosting the service with metadata exchange endpoint is shown below.
      //Create a URI to serve as the base address
                  Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");
                  //Create ServiceHost
                  ServiceHost host = new 
                  ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl);
                  //Add a service endpoint
                  host.AddServiceEndpoint
                  (typeof(MyCalculatorService.ISimpleCalculator), new WSHttpBinding(), "");
                  //Enable metadata exchange
                  ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                  host.Description.Behaviors.Add(smb);
                  Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding ();
                  //Adding metadata exchange endpoint
                  host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex");
                  //Start the Service
                  host.Open();
      
                  Console.WriteLine("Service is host at " + DateTime.Now.ToString());
                  Console.WriteLine("Host is running... Press  key to stop");

      HTTP_GET Enabled Metadata

      We will use ServiceBehaviour to publish the metadata using HTTP-GET. This can be configures either administratively or Programmatically. Http and Https can expose by appending "?wsdl" to the end of the service address. For example service address ishttp://localhost:9090/MyCalulatorService , HTTP-Get metadata address is given byhttp://localhost:9090/MyCalulatorService?wsdl.

      Administrative (Configuration file):

      In the below mention configuration information, you can find the behavior section in the ServiceBehavior. You can expose the metadata using ServiceMetadata node with httpGetEnable='True'.
      <system.serviceModel>
         <services>
       <service behaviorConfiguration="ServiceBehavior" name="MyService">
          <endpoint address="http://localhost/IISHostedService/MyService.svc"
           binding="wsHttpBinding" contract="IMyService">
        <identity>
        <dns value="localhost"/>
        </identity>
           </endpoint>
       </service>
        </services>
        <behaviors>
          <serviceBehaviors>
       <behavior name="ServiceBehavior">
         <!-Setting httpGetEnabled you can publish the metadata -->
        <serviceMetadata httpGetEnabled="true"/>
        </behavior>
           </serviceBehaviors>
         </behaviors>
      </system.serviceModel>
      

      Progarmming Model:

      Using ServiceMetadataBehavior you can enable the metadata exchange. In the following code, I have created the ServiceMetadataBehavior object and assigned HttpGetEnabled property to true. Then you have to add the behavior to host description as shown. This set of code will publish the metadata using HTTP-GET.
       //Create a URI to serve as the base address
                  Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");
                  //Create ServiceHost
                  ServiceHost host = new 
                  ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl);
                  //Add a service endpoint
                  host.AddServiceEndpoint
                  (typeof(MyCalculatorService.ISimpleCalculator), new WSHttpBinding(), "");
                  //Enable metadata exchange
                  ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
      
                  //Enable metadata exchange using HTTP-GET
                  smb.HttpGetEnabled = true;
      
                  host.Description.Behaviors.Add(smb);
                  //Start the Service
                  host.Open();
                  Console.WriteLine("Service is host at " + DateTime.Now.ToString());
                  Console.WriteLine("Host is running... Press  key to stop");
                  Console.ReadLine();

      Binding configuration

      Binding can be configured either through configuration file or Programming. Let us see the binding representation in each method.

      Administrative (Configuration file):

      In the configuration file of the hosting application, you can add the <bindings> element inside the <system.serviceModel> element and add the properties to particular binding type. Properties corresponding to the particular binding type can be mentioned below. Name of the binding properties that you are going to use has to be mention in the end point.
      <system.serviceModel>
        <services>
         <service  name="MyService">
       <endpoint address="http://localhost/IISHostedService/MyService.svc" 
       binding="wsHttpBinding" bindingName="wshttpbind" contract="IMyService">
       <identity>
       <dns value="localhost"/>
       </identity>
       </endpoint>
       <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
          </service>
        </services>
        <bindings>
            <wsHttpBinding>
              <binding name="wshttpbind"  allowCookies="true" closeTimeout="00:01:00" 
              receiveTimeout="00:01:00" />
            </wsHttpBinding>
        </bindings>
      </system.serviceModel>
      

      Programming Model:

      In the following code, I have created the WSHttpBinding object and assign the properties which to be configured. This binding object is added to the Service endpoint for client communication. Similarly you can also create any type of binding and add to endpoint.
      //Create a URI to serve as the base address
                  Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");
                  //Create ServiceHost
                  ServiceHost host =
                   new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl);
      
                  //Create Binding to add to end point
                  WSHttpBinding wshttpbind = new WSHttpBinding();
                  wshttpbind.AllowCookies = true;
                  wshttpbind.CloseTimeout = new TimeSpan(0, 1, 0);
                  wshttpbind.ReceiveTimeout  = new TimeSpan(0, 1, 0);
      
                  //Add a service endpoint
                  host.AddServiceEndpoint
                  (typeof(MyCalculatorService.ISimpleCalculator), wshttpbind, "");
                  //Enable metadata exchange
                  ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                  smb.HttpGetEnabled = true;
                  host.Description.Behaviors.Add(smb);
                  //Start the Service
                  host.Open();
      
                  Console.WriteLine("Service is host at " + DateTime.Now.ToString());
                  Console.WriteLine("Host is running... Press  key to stop");
                  Console.ReadLine();
      
      
      Note: It is always good if you configure the binding properties using configuration file, because while moving to the production you no need to change in the code and recompile it. It is always good practice to represent in the configuration file

      Bindings and Channel Stacks

      In WCF all the communication details are handled by channel, it is a stack of channel components that all messages pass through during runtime processing. The bottom-most component is the transport channel. This implements the given transport protocol and reads incoming messages off the wire. The transport channel uses a message encoder to read the incoming bytes into a logical Message object for further processing.
      Figure 1: Bindings and Channel Stacks (draw new diagram)
      After that, the message bubbles up through the rest of the channel stack, giving each protocol channel an opportunity to do its processing, until it eventually reaches the top and WCF dispatches the final message to your service implementation. Messages undergo significant transformation along the way. It is very difficult for the developer to work directly with channel stack architecture. Because you have to be very careful while ordering the channel stack components, and whether or not they are compatible with one other. So WCF provides easy way of achieving this using end point. In end point we will specify address, binding and contract. To know more about end point. Windows Communication Foundation follows the instructions outlined by the binding description to create each channel stack. The binding binds your service implementation to the wire through the channel stack in the middle.

      Windows Service Hosting

      In this tutorial we are going to see the hosting WCF service in Windows service. We will use same set of code used for hosting the WCF service in Console application to this. This is same as hosting the service in IIS without message activated. There is some advantage of hosting service in Windows service.
      • The service will be hosted, when system starts
      • Process life time of the service can be controlled by Service Control Manager for windows service
      • All versions of Windows will support hosting WCF service.
      Step 1: Now let start create the WCF service, Open the Visual Studio 2008 and click New->Project and select Class Library from the template.
      Step 2: Add reference System.ServiceModel to the project. This is the core assembly used for creating the WCF service.
      Step 3: Next we can create the ISimpleCalulator interface as shown below. Add the Service and Operation Contract attribute as shown below. ISimpleCalculator.cs
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.ServiceModel;
      
      namespace WindowsServiceHostedContract
      {
          [ServiceContract]
          public interface ISimpleCalculator
          {
              [OperationContract]
              int Add(int num1, int num2);
      
              [OperationContract]
              int Subtract(int num1, int num2);
      
              [OperationContract]
              int Multiply(int num1,int num2);
      
              [OperationContract]
              double Divide(int num1, int num2);
      
          }
      }
      Step 4: Implement the ISimpleCalculator interface as shown below. SimpleCalulator.cs
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      
      namespace WindowsServiceHostedService
      {
          class SimpleCalculator
              : ISimpleCalculator
          {
       
              public int Add(int num1, int num2)
              {
                  return num1+num2;
              }
      
              public int Subtract(int num1, int num2)
              {
                   return num1-num2;
              }
      
              public int Multiply(int num1, int num2)
              {
                   return num1*num2;
              }
      
              public double Divide(int num1, int num2)
              {
                  if (num2 != 0)
                      return num1 / num2;
                  else
                      return 0;
              }
      
      
          }
      }
      Step 5: Build the Project and get the dll. Now we are ready with WCF service, now we are going to see how to host the WCF Service in Windows service. Note: In this project, I have mention that we are creating both Contract and Service(implementation) are in same project. It is always good practice if you have both in different project.
      Step 6: Open Visual Studio 2008 and Click New->Project and select Windows Service.
      Step 7: Add the 'WindowsServiceHostedService.dll' as reference to the project. This assembly will going to act as service.
      Step 8: OnStart method of the service, we can write the hosting code for WCF. We have to make sure that we are using only one service host object. On stop method you need to close the Service Host. Following code show how to host WCF service in Windows service. WCFHostedWindowsService.cs
      using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.Data;
      using System.Diagnostics;
      using System.Linq;
      using System.ServiceProcess;
      using System.Text;
      using System.ServiceModel;
      using System.ServiceModel.Description;
      
      namespace WCFHostedWindowsService
      {
          partial class WCFHostedWindowsService : ServiceBase
          {
              ServiceHost m_Host;
              
              public WCFHostedWindowsService()
              {
                  InitializeComponent();
              }
      
              protected override void OnStart(string[] args)
              {
                  if (m_Host != null)
                  {
                      m_Host.Close();
                  }
                  //Create a URI to serve as the base address
                  Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");
                  //Create ServiceHost
                  m_Host = new ServiceHost
                  (typeof(WindowsServiceHostedService.SimpleCalculator), httpUrl);
                  //Add a service endpoint
                  m_Host.AddServiceEndpoint
                  (typeof(WindowsServiceHostedService.ISimpleCalculator), new WSHttpBinding(), "");
                  //Enable metadata exchange
                  ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                  smb.HttpGetEnabled = true;
                  m_Host.Description.Behaviors.Add(smb);
                  //Start the Service
                  m_Host.Open();
      
      
              }
      
              protected override void OnStop()
              {
                  if (m_Host != null)
                  {
                      m_Host.Close();
                      m_Host = null;
                  }
              }
              static void Main()
              {
                  ServiceBase[] ServicesToRun;
                  ServicesToRun = new ServiceBase[] 
         { 
          new WCFHostedWindowsService() 
         };
                  ServiceBase.Run(ServicesToRun);
      
              }
          }
      }
      Step 9: In order to install the service we need to have the Installer class for the Windows service. So add new Installer class to the project, which is inherited from the Installer class. Please find the below code for mentioning the Service name, StartUp type etc of the service. ServiceInstaller.cs
      using System;
      using System.Collections.Generic;
      using System.Text;
      using System.ServiceProcess;
      using System.Configuration.Install;
      using System.ComponentModel;
      using System.Configuration;
      
      
      namespace WCFHostedWindowsService
      {
          [RunInstaller(true)]
          public class WinServiceInstaller : Installer
          {
              private ServiceProcessInstaller process;
              private ServiceInstaller service;
      
              public WinServiceInstaller()
              {
                  process = new ServiceProcessInstaller();
                  process.Account = ServiceAccount.NetworkService;
                  service = new ServiceInstaller();
                  service.ServiceName = "WCFHostedWindowsService";
                  service.DisplayName = "WCFHostedWindowsService";
                  service.Description = "WCF Service Hosted";
                  service.StartType = ServiceStartMode.Automatic;
                  Installers.Add(process);
                  Installers.Add(service);
              }
          }
      }
      Step 10: Build the project, we will get the WCFHostedWindowsService.exe. Next we need to install the service using Visual Studio Command Prompt. So open the command prompt by clicking Start->All Programs-> Microsoft Visual Studio 2008-> Visual Studio Tools-> Visual Studio Command Prompt Using installutil utility application, you can install the service as shown below.
      Step 11: Now service is Hosted sucessfully and we can create the proxy class for the service and start using in the client applcaiton.