Thursday, December 31, 2009

Generics and other microsoft .net interview question

Introduction

The support for something like 'Templates' found in the good old(?) C++. The support for the concept of type parameters, which makes it possible to design classes which take in a generic type and determine the actual type later on.

This means that by using a generic type parameter T, you can write a single class MyList and the client code can use it as MyList, MyList or MyList without any risk of runtime casts or boxing operations.

Version 2.0 of the .NET Framework introduces a new namespace viz. System.Collections.Generic, which contains the classes that support this concept, like the List, Queue, Stack, LinkedList and many more which you can use effectively in your programs.

Advantages of Generics
In the earlier versions, before .NET 2.0, generalization was accomplished by casting types to and from the universal base type System.Object. Generics provide a solution to this limitation in the common language runtime and the C# language. This limitation can be demonstrated with the help of the ArrayList collection class from the .NET Framework base class library. ArrayList is a highly convenient collection class that can be used without any modifications to store any reference or value type.
// The .NET Framework 1.1 way of creating a list
ArrayList list1 = new ArrayList();
list1.Add(3);
list1.Add(105);
//...
ArrayList list2 = new ArrayList();
list2.Add("First item.");
list2.Add("Second item");
//...


But this convenience comes at a cost. Any reference or value type that is added to an ArrayList is implicitly typecast to System.Object. If the items are value types, they must be boxed when added to the list, and unboxed when they are retrieved. The casting, boxing and unboxing operations degrade performance; the effect of boxing and unboxing can be quite significant in scenarios where you must iterate through large collections.
So, what we need is, flexibility of the ArrayList but it should be more efficient and should provide some ways of type checking by the compiler, without sacrificing on the reusability of that class with different data types. An ArrayList with a type parameter? That is precisely what generics provide. Generics would eliminate the need for all items to be type cast to Object and would also enable the compiler to do some type checking.
In the generic List collection, in System.Collections.Generic namespace, the same operation of adding items to the collection looks like this:
// The .NET Framework 2.0 way of creating a list
List list1 = new List();
list1.Add(3); // No boxing, no casting
list1.Add("First item"); // Compile-time error

For the client code, the only added syntax with List compared to ArrayList is the type argument in the declaration and in instantiation. In return for this slightly greater coding complexity, you can create a list that is not only safer than ArrayList, but also significantly faster, especially when the list items are value types.

Generic Classes
Generic classes encapsulate operations that are not specific to any particular data type. The most common use for generic classes is with the collections like linked lists, hash tables, stacks, queues, trees and so on where operations such as adding and removing items from the collection are performed in more or less the same way regardless of the type of the data being stored.
public class Node
{
T head;
T next;
}
Here, T is the type parameter. We can pass any data type as parameter.
This class can be instantiated like this:
Node node = new Node();
This will tell the compiler that the properties, head and next are of type string. Instead of string, you can substitute this with any data type.

Generic Methods
A generic method is a method that is declared with a type parameter.
void Swap( ref T left, ref T right)
{
T temp;
temp = left;
left = right;
right = temp;
}

The following code example shows how to call the above method:
int a = 1;
int b = 2;
Swap (a, b);
You can also omit the type parameter because the compiler will automatically identify it for you. The following is also a valid call to the same method:
Swap (a, b);


Write your own Generic class
The following example demonstrates how you can write your own generic classes.
The example shown below is a simple generic linked list class for demonstration purpose:
using System;
using System.Collections.Generic;
public class MyList //type parameter T in angle brackets
{
private Node head;

// The nested class is also generic on T.
private class Node
{
private Node next;
//T as private member data type:
private T data;
//T used in non-generic constructor:

public Node(T t)
{
next = null;
data = t;
}


public Node Next
{
get { return next; }
set { next = value; }
}

//T as return type of property:
public T Data
{
get { return data; }
set { data = value; }
}
}

public MyList()
{
head = null;
}

//T as method parameter type:
public void AddHead(T t)
{
Node n = new Node(t);
n.Next = head;
head = n;
}

public IEnumerator GetEnumerator()
{
Node current = head;
while (current != null)
{
yield return current.Data;
current = current.Next;
}
}

}
Notice the declaration of the above class :
public class MyList
T is the parameter type. Throughout the above code, the data type for the Node is T rather than any specific types like int or string or any other class. This gives flexibility to the programmer to use this class with any data type he wishes to use.
The following code example shows how the client code uses the generic MyList class to create a list of integers. Simply by changing the type argument, the code below can be easily modified to create lists of strings or any other custom type:

class Program
{
static void Main(string[] args)
{
//int is the type argument.
MyList list = new MyList();

for (int x = 0; x < 10; x++)
list.AddHead(x);
 foreach (int i in list)
Console.WriteLine(i);
Console.WriteLine("Done");
 }
}

How generics are handled by the .NET runtime
When a generic type or method is compiled into MSIL, it contains metadata that identifies it as having type parameters. How this MSIL which contains generic type is used is different based on whether or not the supplied type parameter is a value or reference type. When a generic type is first constructed with a value type as parameter, the runtime creates a specialized generic type with the supplied parameter or parameters substituted in the appropriate places in the MSIL. Specialized generic types are created once for each of the unique value type used as parameter. For example, suppose your program code declared a Stack constructed of integers, like this: Stack stack;
At this point, the runtime generates a specialized version of the Stack class with the integer substituted appropriately as its parameter. Now, whenever your program code uses a stack of integers, the runtime reuses the generated specialized Stack class. In the following example, two instances of a stack of integers are created, and they share a single instance of the Stack code:
Stack stackOne = new Stack();
Stack stackTwo = new Stack();
However, if at another point in your program code another Stack class is created but with a different value type such as a long or a user-defined structure as its parameter, then the runtime generates another version of the generic type, this time substituting a long in the appropriate places in the MSIL. Conversions are no longer necessary because each specialized generic class natively contains the value type.
Generics work a bit differently for reference types. The first time a generic type is constructed with any reference type, the runtime creates a specialized generic type with the object references substituted for the parameters in the MSIL. Then, each time a constructed type is instantiated with a reference type as its parameter, regardless of its type, the runtime reuses the previously created specialized version of the generic type. This is possible because all references are the same size.
For example, suppose you had two reference types, a Customer class and an Order class, and that you created a stack of Customer types:
Stack customers;
At this point, the runtime generates a specialized version of the Stack class that, instead of storing data, stores object references that will be filled in later. Suppose the next line of code creates a stack of another reference type, called Order:
Stack orders = new Stack();
Unlike the value types, another specialized version of the Stack class is not created for the Order type. Rather, an instance of the specialized version of the Stack class is created and the orders variable is set to reference it. Suppose you then encountered a line of code to create a stack of a Customer type:
customers = new Stack();
As with the previous use of the Stack class created with the Order type, another instance of the specialized Stack class is created, and the pointers contained therein are set to reference an area of memory the size of a Customer type. The C# implementation of generics greatly reduces code bloat by reducing the number of specialized classes created by the compiler for generic classes of reference types to just one.
C# Generics is language features that provide support for parameterized types. C# generic type substitutions are performed at runtime and generic type information is preserved for the instantiated objects.

Conclusion
Generics are a great way of writing classes that combine reusability, type safety and efficiency. Generics are commonly used with collections. .NET 2.0 has introduced a new namespace called System.Collections.Generic which contains classes that support generics.

Which Versions of the .NET Framework Support Generics?
Generics are only supported on version 2.0 and above of the Microsoft .NET framework, as well as version 2.0 of the compact framework.

Can I Use Generics in Web Services?
Unfortunately, no. Web services have to expose a WSDL-based contract. Such contracts are always limited by the expressiveness of the message format being used. For example, HTTP-GET based web services only support primitive types such as int or string, but not complex types like a DataSet. SOAP-based web services are more capable, but SOAP has no ability to represent generic type parameters. As a result, at present, you cannot define web services that rely on generic types. That said, you can define .NET web services that rely on closed constructed generic types, for example: \

[C#]
public class MyWebService
{
[WebMethod]
public List GetCities()
{
List cities = new List();
cities.Add("New York");
cities.Add("San Francisco");
cities.Add("London");
return cities;
}
}
In the above example, List will be marshaled as an array of strings.

Can I Use Generics in Enterprise Services?
Unfortunately, no. All methods and interfaces on a ServicedComponent-derived class must be COM-visible. The COM type system is IDL, and IDL does not support type parameters.

Can I Use Generics in Indigo?
Unfortunately, no. SOAP has no ability to represent generic type parameters, and so all methods and interfaces on an indigo service contract or service class can only use primitive types such as integers or strings, or specific known types that provide a data contract. As a result, at present, you cannot define Indigo services that rely on generic types, that is, services that leave it up to the service consumer to specify the types to use when invoking the service.

Can I Use Generics in .NET Remoting?
Yes. You can expose generic types as remote objects

Where Does the .NET Framework Itself Use Generics?
Version 2.0 of the .NET Framework makes use of generics in three main areas: The System namespace added a large set of static generic methods to the Array type. These methods automate and streamline common manipulations of and interactions with arrays. The System namespace also defined a number of generic utility delegates, which are used by the Array type and the List class, but can be used freely in other contexts as well. In addition, System provides support for nullable types. The System namespace defines the IComparable interface and the EventHandler delegate, both generic reincarnations of their non-generic predecessors. The System namespace also defines the IEquatable interface, used to check for equality of two values. The System namespace defines the ArraySegment used to allocate a strongly typed portion of an array.
The System.Collections.Generic namespace defines generic collection interfaces, collections and iterator classes, similar to the old, non generic ones available in the System.Collections namespace. The System.Collections.Generic namespace also defines a few generic helper classes and structures.
The System.ComponentModel namespace defines the class BindingList. A binding list is used very similar to a mere generic list, except it can fire events notifying interested parties about changes to its state.
The System.Collections.ObjectModel namespace defines a few types such as Collection that can be used as base types for custom collections.
Finally, all the types that supported IComparable in .NET 1.1 support IComparable and IEquatable in .NET 2.0. This enables you to use common types for keys, such as int, string, Version, Guid, DateTime, and so on.

What Are the Generic Collection Classes?
The System.Collections.Generic namespace contains the majority of the new generic collections. These collections are by and large the generic reincarnation of the collections available in the System.Collections namespace. For example, there is a generic Stack and a generic Queue classes. The collections in System.Collections.Generic are used in much the same way as their predecessors. In addition, some of the collections where renamed in the process. The Dictionary data structure is equivalent to the non-generic HashTable, and the class List is analogous to the non-generic ArrayList. System.Collections.Generic also defines new types that have no equivalent in System.Collections, such as LinkedList and KeyValuePair. In addition, The System.Collections.Generic namespace defines generic interfaces such as ICollection and IList. To support generic-based iterators, System.Collections.Generic defines the IEnumerable and IEnumerator interfaces, and these interfaces are supported by all the generic collections. It is important to note that the generic collections can be used by clients that do not rely on generics, because all the generic collections also support the non-generic collection and iteration interfaces (IList, ICollection, IEnumerable). For example, here is the definition of the List class:
[C#]
public class List : IList,IList
{...}

What Are the Generic Methods of System.Array?
The System.Array type is extended with many generic static methods. The generic static methods are designed to automate and streamline common tasks of working with arrays, such as iterating over the array and performing an action on each element, scanning the array looking for a value that matches a certain criteria (a predicate), converting and sorting the array, and so on. Below is a partial listing of these static methods:
[C#]
public abstract class Array
{
//Partial listing of the static methods:
public static ReadOnlyCollection AsReadOnly(T[] array);
public static int BinarySearch(T[] array,T value);
public static int BinarySearch(T[] array,T value,
IComparer comparer);
public static U[] ConvertAll(T[] array,
Converter converter);
public static bool Exists(T[] array,Predicate match);
public static T Find(T[] array,Predicate match);
public static T[] FindAll(T[] array,Predicate match);
public static int FindIndex(T[] array,Predicate match);
public static void ForEach(T[] array,Action action);
public static int IndexOf(T[] array,T value);
public static void Sort(T[] array,IComparer comparer);
public static void Sort(T[] array,Comparison comparison);
}

What Are the Generic Methods of List?
Besides implementing IList, the List type contains many generic helper methods. These methods are designed to automate and streamline common tasks of working with the list, such as iterating over the list and performing a task on each element, scanning the list looking for a value that matches a certain criteria (a predicate), or just searching for a particular value, converting and sorting the list, and so on. Below is a partial listing of these generic methods:
[C#]
public class List : IList,
{
//Partial listing of the generic helper methods:
public List ConvertAll(Converter converter);
public bool Exists(Predicate match);
public T Find(Predicate match);
public List FindAll(Predicate match);
public int FindIndex(Predicate match);
public T FindLast(Predicate match);
public void ForEach(Action action);
public int LastIndexOf(T item);
public void Sort(Comparison comparison);
public T[] ToArray();
//More members
}


What Are Nullable Types?
Unlike reference types, you cannot assign a null into a value type. This is often a problem when interacting with code that interprets a null as having no value, rather than no-reference. The canonical example is database null values in columns that have representation as types such as int or DateTime. To address that, the System namespace provides the structure Nullable defined as:
[C#]
public interface INullableValue
{
bool HasValue{get;}
object Value{get;}
}
[Serializable]
public struct Nullable : INullableValue,IEquatable>,... where T : struct
{
public Nullable(T value);
public bool HasValue{get;}
public T Value{get;}
public T GetValueOrDefault();
public T GetValueOrDefault(T defaultValue);
public bool Equals(Nullable other);
public static implicit operator Nullable(T value);
public static explicit operator T(Nullable value);

//More members
}

What do you mean by Function Overloading
When more than one function is created with the same name, but different is of there arguments . In other words, function names can be overloaded. A function may also have the same name as an attribute. In the case that there is an ambiguity between a function on a complex type and an attribute of the complex type, the attribute will always be used.

Can you give an example of when it would be appropriate to use a web service as opposed to a nonserviced dot NET component
When to Use Asp Net Web Services: (i)Communicating through a Firewall When building a distributed application with 100s/1000s of users spread over multiple locations, there is always the problem of communicating between client and server because of firewalls and proxy servers. Exposing your middle tier components as Web Services and invoking the directly from a Windows UI is a very valid option. (ii)Application Integration When integrating applications
written in various languages and running on disparate systems. Or even applications running on the same platform that have been written by separate vendors. (iii)Business-to-Business Integration This is an enabler for B2B intergtation which allows one to expose vital business processes to authorized supplier and customers. An example would be exposing electronic ordering and invoicing, allowing customers to send you purchase orders and suppliers to send you invoices electronically. (iv)Software Reuse This takes place at multiple levels. Code Reuse at the Source code level or binary componet-based resuse. The limiting factor here is that you can reuse the code but not the data behind it. Webservice overcome this limitation. A scenario could be when you are building an app that aggregates the functionality of serveral other Applicatons. Each of these functions could be performed by individual apps, but there is value in perhaps combining the the multiple apps to present a unifiend view in a Portal or Intranet.

Can you define basic element of WebServices and explain any one from them
These are as follows SOAP, WSDL and UDDI. And I am explaining about the SOAP(Simple Object Access Protocol) it is a communication protocol it is for communication between application it is platform and language independent.It is based on XML and also help to get from Firewall.

Explain functioning of Web Services Protocols
Http-Get:- This is standard protocol that helps client to communicate with server with HTTP.When client send a request to server via HTTP request and reuired parameter are attached with the querystring.Example:- http://www.dotnetquestion.info/dotnet/interview.aspx?id=pervej&cast=munjal and we get the value from querystring. Request.querystring("id") Request.querystring("cast"). Http-Post:-This is same as Http-Get but the diffrence is that in place of
sending parameters onto the URL information is send with HTTP request message with some extra information which contains Parameters and their values.This Protocols is limited to sending name/value pairs. SOAP:-The only diffrence is that its relies on the XML as compares to Http-Get,Http-Post.SOAP can send not only the name/value pairs but also some complex object also as for example datatypes,class,objects.SOAP can also uses request/reponse model as Http-Get,Http-post but it is not limited to Request/Response it can also send types of message.Because its uses XML that is pure text so firewalls not created so much problem because its easily converted in to HTML.

Which one is better Remoting or WebServices
Remoting involves efficient communication or exchange of data when we have control on both ends of the application involved in the communication process. Web Services is open-protocol-based exchange of informaion. Web Services play there role when we need to communicataion with external organization or whicj doesnot have .NET technology.

How .NET and non .NET component communicate with each other when they are on different platform
In past when we have to communicate .NET with non .NET component we are using COM component this component helps in doing this. At the moment we are using in both apps a COM component that has an intermediary Windows service running on one machine. But this component is quite old and not in use now because it will create a problem when we are using firewall. So to handle this we use Web-Services which really have a solution for Firewall.

What is WSDL
WSDL is an XML format for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information. The operations and messages are described abstractly, and then bound to a concrete network protocol and message format to define an endpoint. Related concrete endpoints are combined into abstract endpoints (services).

What is the standard you use to wrap up a call to a Web service
HTTP with SOAP.

What is Asp Net Web Services
Web services are programmable business logic components that provide access to functionality through the Internet. Standard protocols like HTTP can be used to access them. Web services are based on the Simple Object Access Protocol (SOAP), which is an application of XML. Web services are given the .asmx extension.

Define Protocols that helps Web Services in Asp Net
Web Services used three protocols for interacting with the clients:-
Http-Post
Http-Get
SOAP

What are VSDISCO files
VSDISCO files are DISCO files that enable dynamic discovery of Web Services. ASP.NET links the VSDISCO to a HTTP handler that scans the host directory and subdirectories for ASMX and DISCO files and returns a dynamically generated DISCO document. A client who requests a VSDISCO file gets back what appears to be a static DISCO document.

What is UDDI
UDDI stands for Universal Description, Discovery, and Integration. It is like an "Yellow Pages" for Web Services. It is maintained by Microsoft, IBM, and Ariba, and is designed to provide detailed information regarding registered Web Services for all vendors. The UDDI can be queried for specific Web Services.


How to Create Virtual Directory
1. Click ?Start೥ttings࣯ntrol Panel ?ministrative Toolsą©®ternet information services?
2. Expand Internet Information Server.
3. Expand the server name.
4. In the left pane, right-click Default Web Site, point to New, and then click Virtual Directory.
5. In the first screen of the New Virtual Directory Wizard, type an alias, or name, for the virtual directory (SiteName), and then click Next.
6. In the second screen, click Browse. Locate the content folder that you created to hold the Web content. Click Next.
7. In the third screen, click to select Read and Run scripts (such as ASP). Make sure that the other check boxes are cleared. Click Finish to complete the wizard.

Diffrence between Viewstate and Session
View State are valid mainly during postbacks and information is stored in client only. Viewstate are valid for serializable data only. Moreover Viewstate are not secured as data is exposed to client. although we can configure page directive and machine key to make view state encrypted. Where in case of session this is user specific data that is stored in server memory . Session state is valid for any type of objects. We can take help of session  through different web pages also


Is it possible to get vale of viewstate value on next page
View state is page specific; it contains information about controls embedded on the particular page. ASP.NET 2.0 resolves this by embedding a hidden input field name,__POSTBACK . This field is embedded only when there is an IButtonControl on the page and its PostBackUrl property is set to a non-null value. This field contains the view state information of the poster page. To access the view state of the poster page, you can use the new PreviousPage property of the page:

Page poster = this.PreviousPage;
we can find any control from the previous page and read its state:
Label posterLabel = poster.findControl("myLabel");
string lbl = posterLabel.Text;
Cross-page post back feature also solves the problem of posting a Form to multiple pages, because each control, in theory, can point to different post back URL

How to create and removethat cookies in asp.net
This is the syntax for creating a cookies.
HttpCookie SiteCookies = new HttpCookie("UserInfo");
SiteCookies["UserName"] = "Pervej";
SiteCookies["sitename"] = "dotnetRed";
SiteCookies["Expire"] = "5 Days";
SiteCookies= DateTime.Now.AddDays(5);
Response.Cookies.Add(SiteCookies);
Now syntax to remove this cookie:-
HttpCookie SiteCookies= new HttpCookie("UserInfo");
siteCookies= DateTime.Now.A
ddDays(-1);
Response.Cookies.AddSiteCookies

Server Control and User Control
An ASP.NET control (sometimes called a server control) is a server-side component that is shipped with .NET Framework.A server control is a compiled DLL file and cannot be edited. It can, however, be manipulated through its public properties at design-time or runtime. It is possible to build a custom server control (sometimes called a customcontrol or composite control). (We will build these in part 2 of this article).
In contrast, a user control will consist of previously built server controls (called constituent controls when used within a user control). It has an interface that can be completely edited and changed. It can be manipulated at design-time and runtime via properties that you are responsible for creating. While there will be a multitude of controls for every possible function built by third-party vendors for ASP.NET, they will exist in the form of compiled server controls, as mentioned above. Custom server controls may be the .NET answer to ActiveX Web controls.



Can we update table from View that we are using
No view are only virtual table so cannot update table.

How to change the Page Title dynamically
//Declare
protected System.Web.UI.HtmlControls.HtmlGenericControl Title1 ;
//In Page_Load
Title1.InnerText ="Page 1" ;

Explain session and its type
Sessions can be managed by two ways in case of webfarms:
1. Using SQL server or any other database for storing sessions regarding current logged in user.
2. Using State Server, as one dedicated server for managing sessions. State Server will run as service on web server having dotnet installed.
In ASP.NET there is three ways to manage session objects. one support the in-proc mechanism and other two's support the out-proc machanism.
1)In-Proc (By Default)
2) SQL-Server (Out-proc)
3) State-Server (Out-Proc)

Something about Session or Session Management and Application
Sessions can stored in cookies . cookieless session is also available.for cookie less session it wil create unique session id for each session. it wil be automatically retrieved in URL.state management can be like, user sessions can be stored in 3 ways .
Inproc - stored in asp.net worker process
stateserver- stored in window service .
sqlserver- user sessions can be stored in sqlserver also.Application Start This Event is fired when t
he server which holding application starts whereas Session Start event is fired when any User has access that page or Session has been created. Suppose we want to track that how many users have accessed our sites today then Application Start is the best place to do so or we want to give some personalised view to User than Session is the best place.

Which file is taken by compiler when we have both file Application and Server Configguration file
Application Configuration File Values will over ride the values of server configuration file. But only when we allow override set as True, if we does not allow override then Application Configuration file variables cannot override the values of server configuration file.


what is the difference between serializable and MarshalByRefObject
In .net Remoting if ypu want your class to be participated in remoting it has to inherit from MarshalByRefObject class so that class definition can be passed by reference Where as [seraliazable] attribute is preceded before class that is can be seralized but this is used in conjuction with MarshalByValue class. Because when we pass by value then only we require this attribute.

What is serialization in .NET and What are the ways to control serialization
Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of creating an object from a stream of bytes. Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database)Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class,including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created. Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the clipboard. You can serialize an object to a stream,disk,memory,over the network,and so forth.Remoting uses serializatn.to pass objects "by value" from one computer or application domain to another. XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data.Because XML is an open standard,it is an attractive choice for sharing data across the Web. SOAP is an open standard,which makes it an attractive choice. There are two separate mechanisms provided by the .NET class library


1.XmlSerializer
2.SoapFormatter/BinaryFormatter.

Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.

Diffrence Between ServerSide and ClientSideCode
server side code is responsible to execute and provide the executed code to the browser at the client side. the executed code may be either in XML or Plain HTML. the executed code only have the values or the results that are executed on the server. The clients browser executes the HTML code and displays the result.
where as the client side code executes at client side and displays the result in its browser. it the client side core consist of certain functions that are to be executed on server then it places request to the server and the server responses as the result in form of HTML.



How do I make a reference type parameter as a readonly parameter
Assuming that it is, and that all the data fields are only accessible via parameters, then you can create an interface for the class that only allows access to the parameters via a get. Add this interface to the class definition, then where you need the instance of the class to be read only, access it through the interface.

How to check querystring is null or not
string queryStringVal = Request.QueryString["field"];
if (string.IsNullOrEmpty(queryStringValue))
{
}
else
{
}

What is Pull and Push Model in ado.net
Answer:- Pull model is used to pick out the element or we can also say objects from Database tabel.
Push model is used to insert the element only at the top position in table to database with the help of object. But when we have to delete the top most record pull method is used over push. Similar to stack operation

What is Property
A property is a thing that describes the features of an object. A property is a piece of data contained within class that has an exposed interface for reading/writing. Looking at that definition, you might think you could declare a public variable in a class and call it a property. While this assumption is somewhat valid, the true technical term for a public variable in a class is a field. The key difference between a field and a property is in the inclusion of an interface.
We make use of Get and Set keywords while working with properties.
We prefix the variables used within this code block with an underscore. Value is a keyword, that holds the value which is being retrieved or set.
Private _Color As String
Public Property Color()
Get
Return _Color
End Get
Set(ByVal Value)
_Color = Value
End Set
End Property

What is PostBack and Callback
One technique that current ASP.NET 1.0/1.1 developers use to overcome this postback problem is to use the Microsoft XMLHTTP ActiveX object to send requests to server-side methods from client-side JavaScript. In ASP.NET 2.0, this process has been simplified and encapsulated within the function known as the Callback Manager.
The ASP.NET 2.0 Callback Manager uses XMLHTTP behind the scenes to encapsulate the complexities in sending data to and from the servers and clients. And so, in order for the Callback Manager to work, you need a web browser that supports XMLHTTP. Microsoft Internet Explorer is, obviously, one of them.


What is the diffrence between Pivot an Unpivot
These tow are th opertor in Sql Server 2005 these are used to manupulate a expression from one table into another table but both are opposite of each other Pivot take rows and put them into the column but on the other hand Unpivot take column and put them into the row.Pivots helps in rotating unique in one column from mutliple columns.

Can you explain difference between .Net framework and .Net Compact Framework
As the name suggest to us that .Net compact framework has been created with enabling managed code on devices just like PDAs,mobiles etc. These are compact devices for which a .NET compact framework is used.This is main diffrence between these two.

What are Namespaces
The namespace keyword is used to declare a scope. This namespace scope lets you organize code and gives you a way to create globally-unique types. Even if you do not explicitly declare one, a default namespace is created.This unnamed namespace, sometimes called the global namespace, is present in every file. Any identifier in the global namespace is available for use in a named namespace. Namespaces implicitly have public access and this is not modifiable.

How can we load multiple tables in to Dataset
Write the select queries required in fill statement.
e.g.
Adp.Fill("Select * from Table1;Select * from Table2;Select * from Table3",DS)
This statement wil generate Dataset with 3 datatables.
How to display alert on post back from javascript
string strScript = " ";
if ((!Page.IsStartupScriptRegistered("clientScript")))
{
Page.RegisterStartupScript("clientScript", strScript);
}

What is Machine.config File
As web.config file is used to configure one asp .net web application, same way Machine.config file is used to configure application according to a particular machine. That is, configuration done in machine.config file is affected on any application that runs on a particular machine. Usually, this file is not altered and only web.config is used which configuring applications.
What is a LiveLock
A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely.
what is a jitter and how many types of jitters are there
JIT is just in time complier.it categorized into three:-
1 Standard JIT : prefered in webApp-----on diamand
2 Pre JIT : only one time------only use for window App
3 Economic JIT : use in mobile App


What are the different IIS level
There are mainly three level of ISS these are as follows.
(1)Low ; (2)Medium ; (3)High
(1)Low(IIS Process):-In this all the main process of IIS and ASP.NET application runs in the same process . But here is some disadvantage of this if one of process is failed whole the process failed.Its required low resources as compare to other.
(2)Medium(Pooled):-In this IIS process and application runs in different process.Let there are two proces
s process1 and process2 then in process one IIS process is running and in process2 application is run.
(3)High(Isolated):-In this all the process running in there own process. One process for one application.But it is one costly things because too much memory needed for this.

Isolation levels in SQL SERVER
Isolation level get the condition to which data is isolated for use by one process and secured against interference from other processes.
Read Committed -
SQL Server applied a share lock while reading a row into a cursor but frees the lock immediately after reading the row. Because a shared lock request is blocked by an exclusive lock, a cursor is prevented from reading a row that another task has updated but not yet committed. Read commi
tted is the default isolation level setting for both SQL Server and ODBC.
Read Uncommitted -
When no locks while reading a row into a cursor and honors no exclusive locks. Cursors can be populated with values that have already been updated but not yet committed. The user is bypassing all of SQL Server?s locking transaction control mechanisms.
Repeatable Read or Serializable -
SQL Server requests a shared lock on each row as it is read into the cursor as in READ COMMITTED, but if the cursor is opened within a transaction, the shared locks are held until the end of the transaction instead of being freed after the row is read. This has the same effect as specifying HOLDLOCK on a SELECT statement.

What does the term immutable mean
It means to create a view of data that is not modifiable and is temporary of data that is modifiable.Immutable means you can't change the currrent data,but if you perform some operation on that data, a new copy is created. The operation doesn't change the data itself. Like let's say you have a string object having "hello" value. Now if you say
temp = temp + "new value"
a new object is created, and values is saved in that. The temp object is im
mutable, and can't be changed. An object qualifies as being called immutable if its value cannot be modified once it has been created. For example, methods that appear to modify a String actually return a new String containing the modification. Developers are modifying strings all the time in their code. This may appear to the developer as mutable - but it is not. What actually happens is your string variable/object has been changed to reference a new string value containing the results of your new string value. For this very reason .NET has the System.Text.StringBuilder class. If you find it necessary to modify the actual contents of a string-like object heavily, such as in a for or foreach loop, use the System.Text.StringBuilder class.

which dll handles the request of .aspx page
When the Internet Information Service process (inetinfo.exe) receives an HTTP request, it uses the filename extension of the requested resource to determine which Internet Server Application Programming Interface (ISAPI) program to run to process the request. When request is for an ASP.NET page (.aspx file), IIS passes the request to the ISAPI DLL capable of handling the request for ASP.NET pages, which is aspnet_isapi.dll.

ASP.NET Globalization and Localization
Globalization is the process of designing and developing applications that function for multiple cultures, and localization is the process of customizing your application for a given culture and locale. The topics in this section describe how to create ASP.NET Web applications that can be adapted to different languages and cultures.

Type of garbage collector
There are two types of Garbage Collector
managed garbage collector
see we will declaring variable ,object in our programes once this kind of variable,object goes out of the scope ,they are put into the heap and they are checked for the further existence.once its beeing no longer used garbage collector wil deallcate mem for that variable and objects.
Umanaged garbage collector
this was done mannually and u will be happen to open a conn
ection with database,will be open the file etc. while this kind of the thing goes out of the scope we have to explicitly call the garage colector by calling the closecommand of the datbase once the connection is closed it puts this memmory ino the heep and process follws the same

Diffrence between function and StoreProcedure
Both functions and stored procedures can be custom defined and part of any application.Functions, on the other hand, are designed to send their output to a query or T-SQL statement. For example, User Defined Functions (UDFs) can run an executable file from SQL SELECT or an action query,while Stored Procedures (SPROC) use EXECUTE or EXEC to run. Both are instantiated using CREATE FUNCTION.stored procedures are designed to return its output to the application. A UDF returns table variables,while SPROC can't return a table variable although it can create a table. Another significant difference between them is that UDFs can't change server environment or your operating system environment, while a SPROC can. Operationally, when T-SQL encounters an error the function stops, while T-SQL will ignore an error in a SPROC and proceed to the next statement in your code (provided you've included error handling support). You'll also find that although a SPROC can be used in an XML FOR clause, a UDF cannot be.
How to get number of control on web page
foreach (Control ctrl in Page.Form.Controls)
{
Response.Write(ctrl.ID);
}

Why it is preferred not to use finalize for cleanup
Answer:-There is problem with the finalize regards to object when we use finalize to destroy the object it will take two round to remove the objects.To understand it we will take a simple example let there are three objects obj1,obj2,obj3 we use finalize for obj2.Now when garbage collector is run first time it will only clean obj1,obj3 becuase obj2 is pushes to the finalization queue. Now when garbage collector runs second time it will take if any object is pending for finalization then it will check the finalization queue if any item it will destroy that one.
What is exception handling
When an exception occurs, the system searches for the nearest catch clause that can handle the exception, as determined by the run-time type of the exception. First, the current method is searched for a lexically enclosing try statement, and the associated catch clauses of the try statement are considered in order. If that fails, the method that called the current method is searched for a lexically enclosing try statement that encloses the point of the call to the current method.This search continues until a catch clause is found that can handle the current exception, by naming an exception class that is of the same class, or a base class, of the run-time type of the exception being thrown. A catch clause that doesn't name an exception class can handle any exception.Once a matching catch clause is found, the system prepares to transfer control to the first statement of the catch clause. Before execution of the catch clause begins, the system first executes, in order, any finally clauses that were associated with try statements more nested that than the one that caught the exception.Exceptions that occur during destructor execution are worth special mention. If an exception occurs during destructor execution, and that exception is not caught, then the execution of that destructor is terminated and the destructor of the base class (if any) is called. If there is no base class or if there is no base class destructor, then the exception is discarded.



What is event bubbling
Event Bubbling is nothing but events raised by child controls is handled by the parent control. Example: Suppose consider datagrid as parent control in which there are several child controls.There can be a column of link buttons right.Each link button has click event.Instead of writing event routine for each link button write one routine for parent which will handlde the click event of the child link button events.Parent can know which child actaully triggered the event.That thru arguments passed to event routine.


Types of Directive
Directives in ASP.NET control the settings and properties of page and user control compilers. They can be included anywhere on a page, although it is standard to place them at the beginning. Directives are used in both .aspx files (ASP.NET pages) and .ascx files (user control pages). ASP.NET pages actually support eight different directives.
@ Page
@ Control
@ Import
@ Implements
@ Register
@ Assembly
@ OutputCache
@ Reference

What is correlated SubQuery
A correlated sub-query is dependent upon the outer query. The outer query and the sub-query are related typically through a WHERE statement located in the sub-query. The way acorrelated sub-query works is when a reference to the outer query is found in the sub-query, the outer query will be executed and the results returned to the sub-query.The sub-query is executed for every row that is selected by the outer query.

How to create cookies in asp.net

VB.NET
C#
HttpCookie cookie;
String UserID = "dotnetquestion";
cookie = new HttpCookie("ID");
cookie.Values.Add("ID", ID);
Response.Cookies.Add(cookie);

How many cookies can a application use
Most probaly 20 cookies are used but some browser can use even more.

What is the difference between ToString and Convert.ToString
The difference is quite simple Convert can handle the NULLS values but on the other side ToString produce error like NULL reference exception error.

BLOB Datatype in ASP.NET
BLOB data type is used to store any data that a program can generate: graphic images, satellite images, video clips, audio clips, or formatted documents saved by any word processor or spreadsheet. The database server permits any kind of data of any length in a BLOB column.
Like CLOB objects, BLOB objects are stored in whole disk pages in separate disk areas from normal row data.The advantage of the BLOB data type, as opposed to CLOB, is that it
accepts any data. Otherwise, the advantages and disadvantages of the BLOB data type are the same as for the CLOB data type.

What is AUTOEVENTWIREUP
AutoEventWireup is a Boolean attribute that indicates whether the ASP.NET pages events are auto-wired.
Note: In the above case, ASP.NET compiles the code-behind page on the fly. We have to note that this compilation step only occurs when the code-behind file is updated. Whether the file has been updated or not, well this is detected through a timestamp change.The AutoEventWireup attribute may have a value of true or false. When an ASP.NET Web Application is created by using Microsoft Visual Studio .NET, the value of the AutoEventWireup attribute is set as false.

We can specify the default value of the AutoEventWireup attribute in the following locations:
The Machine.config file.
The Web.config file.
Individual Web Forms (.aspx files).
Web User Controls (.ascx files)
The value of the AutoEventWireup attribute can be declared in the section in the Machine.config file or the Web.config file.We must not set the value of the AutoEventWireup attribute to true if performance is key consideration.If we set the value of the AutoEventWireup attribute to true, the ASP.NET page framework must make a call to the CreateDelegate method for every Web Form (.aspx page), and instead of relying on the automatic hookup, manually override the events from the page.

ArrayList in asp.net
(1)Its capacity is increased if required as objects are added to it. So it frees programmer from the worries of array overflow.
(2)Provides methods to perform common operations -- append, insert, remove, replace etc.
(3)There is no restriction on the type of objects which can be added to an arraylist. First object could be a
(4)string, second a double, third a user defined object and so on.
(5)ArrayList can be made read only after adding elements to prevent unintentional modifications.
(6)It provides an overloaded method to perform binary search on its objects.

Difference between = and ==
= is used for assignment to assign some value for example
int i

i=9;
on the other hand == is used for comparing some values

if(i==9)
























































Sub Select_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Select.Click
Dim newCookie As HttpCookie = New HttpCookie("dotnetBooks")
newCookie.Values.Add("Name", TxtBox.Text)
newCookie.Values.Add("Publisher", RadioButtonList1.SelectedItem.Text)
newCookie.Expires = #12/31/2008#
Response.Cookies.Add(newCookie)
Label3.Text = "Cookie Created"
Select.Visible = False
TxtBox.Visible = False
Label1.Visible = False
Label2.Visible = False
RadioButtonList1.Visible = False
End Sub

Sunday, December 27, 2009

WPF

csharpwithdj.blogspot.com

Introduction

WPF offers a new way to build Windows applications that offer the user a richer experience. WPF applications offer the user advanced graphical features, animation, multimedia components, a better look and integration with documents, among other features.

Developers of WPF applications can now declaratively define the appearance of an application with Extensible Application Markup Language (XAML), and can implement the mechanics of an application in a code-behind file, separating presentation from logic in a way similar to what is done in ASP.NET. This approach also makes applications easier to divide up: designers can work with the visual half of the application using tools such as Microsoft Expression, and developers can work with the programming half using Visual Studio. The two halves can then be easily combined to form a visually pleasing product.

Moreover, while WPF provides a way to create traditional Windows applications, many users may prefer a browser-based experience. Because of this, WPF also offers a way to create browser-hosted applications, where the application will open in the user's browser rather than a traditional desktop window. Furthermore, Silverlight is compatible with WPF, and so knowledge of WPF in building Windows applications will carry over to building Silverlight applications.

Creating a WPF Project

• Open up Visual Studio 2008 and open the New Project dialog.

• There are two main WPF project templates:

o WPF Application

o WPF Browser Application.

The WPF Application template is used for standard desktop applications, and it's what we'll be using here. C# project named WpfToDo.

The WPF Browser Application is used for browser-hosted applications. Creating a browser application isn't much different from creating a desktop application.

Creating WPF Application

When the project is created and loaded, you should immediately see a split-view in the workspace. On the top will be a visual representation of the application's default window, and on the bottom will be the corresponding XAML. The visual part will probably be bigger, but you may want to click the Swap Panes button in order to enlarge the XAML view.

For now, though, leave the workspace area alone and take a look at the Solution Explorer. You should see two files, App.xaml and Window1.xaml. As the extensions give away, these contain the application's XAML. If you expand the two files, you should see something like this:



Under the XAML files are the code-behind files, whose names are created simply by appending “.cs” to the XAML file names. The -.xaml files of WPF are analogous to the -.aspx files of ASP.NET, and the code-behind files simply tack on the appropriate language extension.

The App files aren't very important to us right now. They deal with the application as a whole. For example, if we had a resource that we needed to share across the entire application, then we'd probably deal with that in the App files. But we don't. The only thing worth mentioning right now is one attribute in App.xaml:

<="" p="" x:class="WpfToDo.App">

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

StartupUri="Window1.xaml">

The attribute in bold specifies what the starting window is. In this case, it's Window1.xaml. With that, turn your attention to the Window1 files. Window1 is going to be the main window for our application.

Creating the basic UI with XAML

WPF applications are, just like Windows Form applications and ASP.NET applications, event-driven. So, before we start working with code, we need to create the basic user interface of our application using XAML. Then, we can work on responding to events raised through user interaction with the interface. The initial contents of Window1.xaml should look like this:

<="" p="" x:class="WpfToDo.Window1">

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="Window1" Height="300" Width="300">

Right now, there's just a Window tag which contains an empty Grid tag. Let's take a look at the Window tag first. In the first line, we define the Class attribute. This attribute points to the class associated with the window as defined in XAML. The next two lines aren't important—leave them be. Then, there are the Title, Height and Width attributes. These attributes specify the title, initial height and initial width of the window. Go ahead and change the title to something more appropriate, such as “To-Do List.”

Speaking of height and width, there is one important thing to be mentioned here. WPF doesn't use standard pixels. Instead, it uses “device independent pixels.” The goal with the device independent pixel is to provide consistent sizing across different devices and video settings. So 96 device independent pixels make up 1 inch. This makes since, since 96 dots per inch is common.

Inside the Window is a Grid. WPF offers numerous ways to control the layout of a window. The default method is through a Grid, which, as its name implies, arranges controls in a grid, with rows and columns whose sizes are specified by the developer. Another layout control is the StackPanel, which simply arranges controls from left to right or from top to bottom. There are, of course, a number of other layout controls, but we won't need them for our application. We'll be using a Grid for the main window, since it fits the desired layout.

The layout of the application doesn't have to be very complicated. A long, rectangular window will do. Inside the window will be a list of tasks, and below the list of tasks will be two buttons. One button will be for adding a new task to the list, and the other button will be for deleting a task from the list. Let's start by modifying the window's dimensions. Set the height of the window to 480 (5 inches) and the width of the window to 384 (4 inches).

Creating the Grid

In order to lay out the controls as described above, we need two columns (since there are two buttons below the task list, each of which will need its own column) and two rows (since, vertically, there's one list and one group of buttons). The columns need to be of equal width, since the buttons will need to be of equal width, but the rows will need to be of very different heights, since the buttons will naturally occupy less vertical space than the list. The list will span across two columns.

Setting the height of each row and the width of each column (and, thus, the size of each individual cell) isn't very difficult. It involves simply adding some tags within the Grid tag:

The above XAML is pretty straightforward. First, we define the columns of the grid, and then we define the rows, exactly as described earlier, with two columns of equal width and two rows of unequal width. Grid columns are defined using the ColumnDefinition tag, and column definitions are all wrapped inside of a Grid.ColumnDefinitions tag. Rows are defined the exact same way, except with RowDefinition and Grid.RowDefinitions.

Notice that the dimensions of the grid are considerably less than the dimensions of the window. Some difference is to be expected, since the border and title bar of the window will take up some space, but I've subtracted even more space from the grid in order to create some empty space between the controls and the border of the window. If we add controls to the grid as-is, though, the empty space will only be to the right and to the bottom of the grid. That is, everything will be crammed to the top left. To fix this, we need to center the the columns and rows within the grid. This isn't very hard. Only the Grid tag needs to be modified:

Above, we add a HorizontalAlignment attribute along with a VerticalAlignment tag. Now, all of the controls will be centered in the window, with a margin between the controls and the edge of the window. Note, though, that there is also a Margin attribute for controls, which we'll take a look at shortly.

Using XAML, we've declaratively created a layout for our application's controls, and, so far, the XAML has been rather uncomplicated and uncluttered, just as it should be. In the next article, we'll start by placing the controls inside the cells of the Grid.

















WCF Tutorial - Basic Interprocess Communication

csharpwithdj.blogspot.com

WCF Tutorial - Basic Interprocess Communication

Related Posts

• WCF Tutorial - Events and Callbacks

• WCF Tip: Using Properties in Service Contracts

• WCF Callbacks Hanging WPF Applications

• .NET 3.5 Adds Named Pipes Support

What the heck is WCF?

At its core, WCF is a mechanism that facilitates communication between processes - either on the same machine or separate machines. Part of the confusion I had when trying to understand WCF was the almost limitless ways WCF can accomplish this. We're not going to worry about all of that though. We're going to strip out everything except the bare essentials required to get a client/server system up and running - and it's actually very little code.

What we're building today will look a lot like a simple remote procedure call. We'll be building a server that exposes a function that can be called by a client. Just to show how easy it is to change the transport layer, the client will connect to the server through two different mechanisms - http and named pipe.

The first thing we need to do is define what the client will have access to. We do this by defining an interface in C# and giving it a few attributes for WCF. The server will create a class that implements the interface to actually do the work. The client will just be provided the interface so it knows which functions are available.

using System;

using System.ServiceModel;

[ServiceContract]

public interface IStringReverser

{

[OperationContract]

string ReverseString(string value);

}

Here's my simple interface. It provides a function that takes a string and returns a new string with all of the characters reversed. The ServiceContract attribute tells WCF that this interface can be exposed for client use. The OperationContract attributes tells WCF that ReverseString is part of this service contract and can be used by clients. There are lots of optional settings that can be applied to both of these attributes, but this is all that's required to get things up and running. The System.ServiceModel namespace is available by adding a reference to the System.ServiceModel assembly to your project, which is available in the default installation of .NET 3.5.

Starting with the server, the first thing we need to do is create a class that implements this interface and provides the functionality behind ReverseString.

using System;

using System.ServiceModel;

[ServiceContract]

public interface IStringReverser

{

[OperationContract]

string ReverseString(string value);

}


public class StringReverser : IStringReverser

{

public string ReverseString(string value)

{

char[] retVal = value.ToCharArray();

int idx = 0;

for (int i = value.Length - 1; i >= 0; i--)

retVal[idx++] = value[i];

return new string(retVal);

}

}

Pretty simple, right? There might be more elegant ways to reverse a string, but we're not here to criticize the implementation of this function. It's actually not required to use the interface method for defining service contracts (i.e. you could stick the attributes directly on the class), but it's the recommended way, and it makes client applications much easier to implement if they can simply share the same interfaces.

Surprisingly, there's actually very little code required to make the server fully functional. We'll begin by creating a ServiceHost, which is responsible for most of the work behind exposing the service to clients.

class Program

{

static void Main(string[] args)

{

using (ServiceHost host = new ServiceHost(

typeof(StringReverser),

new Uri[]{

new Uri("http://localhost:8000"),

new Uri("net.pipe://localhost")

}))

{


}

}

}

The most difficult thing here is the array of Uri objects. These are our base addresses that clients can use to connect to this WCF server. Like I said before, we're exposing two ways to connect to this service: http and named pipe. How the address is formatted depends on the type of Binding it represents.

Now that we've got our ServiceHost created, we need to configure some endpoints. These will actually enable the http and named pipe bindings and give them the address required by the client.

class Program

{

static void Main(string[] args)

{

using (ServiceHost host = new ServiceHost(

typeof(StringReverser),

new Uri[]{

new Uri("http://localhost:8000"),

new Uri("net.pipe://localhost")

}))

{

host.AddServiceEndpoint(typeof(IStringReverser),

new BasicHttpBinding(),

"Reverse");

host.AddServiceEndpoint(typeof(IStringReverser),

new NetNamedPipeBinding(),

"PipeReverse");

host.Open();

Console.WriteLine("Service is available. " +

"Press to exit.");

Console.ReadLine();

host.Close();

}

}

}

Here we're adding two endpoints - one for http and one for named pipe. The address that's passed in is what appears after the base address specified in the ServiceHost constructor (e.g. for http it would be: "http://localhost:8000/Reverse"). We have to specify a base address for each endpoint we're configuring. So if the net.pipe base address was not present in the ServiceHost constructor, the server would throw an exception when it attempted to create the named pipe endpoint. After the endpoints are configured, we simply call Open on the ServiceHost to enable it.

Believe or not, that's it for a fully functional WCF server. Below is all of the code put together.

using System;

using System.ServiceModel;

namespace WCFServer

{

[ServiceContract]

public interface IStringReverser

{

[OperationContract]

string ReverseString(string value);

}

public class StringReverser : IStringReverser

{

public string ReverseString(string value)

{

char[] retVal = value.ToCharArray();

int idx = 0;

for (int i = value.Length - 1; i >= 0; i--)

retVal[idx++] = value[i];

return new string(retVal);

}

}

class Program

{

static void Main(string[] args)

{

using (ServiceHost host = new ServiceHost(

typeof(StringReverser),

new Uri[]{

new Uri("http://localhost:8000"),

new Uri("net.pipe://localhost")

}))

{

host.AddServiceEndpoint(typeof(IStringReverser),

new BasicHttpBinding(),

"Reverse");

host.AddServiceEndpoint(typeof(IStringReverser),

new NetNamedPipeBinding(),

"PipeReverse");

host.Open();

Console.WriteLine("Service is available. " +

"Press to exit.");

Console.ReadLine();

host.Close();

}

}

}

}

Now we can move on to the client. The first thing we'll need in the client code is the same interface, with the same attributes, that we defined in the server. If this were being used in a production environment, these interfaces would probably be created in a dedicated library that could be easily distributed. For now, I just copied and pasted the code into another project.

We have to first establish a channel between the client and a server. A channel is basically a connection that allows the client and server to send messages to each other. Fortunately, WCF provides something called a ChannelFactory that makes creating these very simple.

using System;

using System.ServiceModel;

using System.ServiceModel.Channels;


namespace WCFClient

{

[ServiceContract]

public interface IStringReverser

{

[OperationContract]

string ReverseString(string value);

}


class Program

{

static void Main(string[] args)

{

ChannelFactory httpFactory =

new ChannelFactory(

new BasicHttpBinding(),

new EndpointAddress(

http://localhost:8000/Reverse));


ChannelFactory pipeFactory =

new ChannelFactory(

new NetNamedPipeBinding(),

new EndpointAddress(

"net.pipe://localhost/PipeReverse"));



IStringReverser httpProxy =

httpFactory.CreateChannel();



IStringReverser pipeProxy =

pipeFactory.CreateChannel();

}

}

}

We're building two proxies here - one for http and one for named pipe. The addresses passed into the ChannelFactory constructor are the same as those configured on the server. We also have to pass in the specific bindings we want: BasicHttpBinding and NetNamedPipeBinding. Lastly we call CreateChannel on each channel factory, which returns an IStringReverser interface. Now we can call functions on those interfaces and WCF makes a remote call through the channel to our server to get the result.

string str = Console.ReadLine();

Console.WriteLine("http: " + httpProxy.ReverseString(str));

Console.WriteLine("pipe: " + pipeProxy.ReverseString(str));

Incredibly, we're now done with the client. Here's the client program in its entirety:

using System;

using System.ServiceModel;

using System.ServiceModel.Channels;



namespace WCFClient

{

[ServiceContract]

public interface IStringReverser

{

[OperationContract]

string ReverseString(string value);

}



class Program

{

static void Main(string[] args)

{

ChannelFactory httpFactory =

new ChannelFactory(

new BasicHttpBinding(),

new EndpointAddress(

"http://localhost:8000/Reverse"));



ChannelFactory pipeFactory =

new ChannelFactory(

new NetNamedPipeBinding(),

new EndpointAddress(

"net.pipe://localhost/PipeReverse"));



IStringReverser httpProxy =

httpFactory.CreateChannel();



IStringReverser pipeProxy =

pipeFactory.CreateChannel();



while (true)

{

string str = Console.ReadLine();

Console.WriteLine("http: " +

httpProxy.ReverseString(str));

Console.WriteLine("pipe: " +

pipeProxy.ReverseString(str));

}

}

}

}

It's amazing when you think about the amount of stuff happening behind the scenes that developers no longer have to worry about. Basically, all developers have to do is define interfaces and objects and WCF takes care of the rest. The server side and client side code can be drastically reduced by using configuration files to replace the setup we did in code, but for the purpose of understanding, explicitly setting it is a good way to know what's behind configuration settings.

I think that about wraps it up for this introduction to WCF. There's an immense amount of configuration and customization supported by WCF, and volumes could be dedicated to it. Hopefully we'll slowly unravel WCF's complexity and introduce new concepts in following tutorials. You

Saturday, December 26, 2009

WCF Interview Question

When not to use Design Patterns
Do not use design patterns in any of the following situations.

• When the software being designed would not change with time.
• When the requirements of the source code of the application are unique.

If any of the above applies in the current software design, there is no need to apply design patterns in the current design and increase unnecessary complexity in the design.

What do you mean by three-tier architecture?
The three-tier architecture was comes into existence to improve management of code and contents and to improve the performance of the web based applications. There are mainly three layers in three-tier architecture. the are define as follows
(1)Presentation
(2)Business Logic
(3)Database

(1)First layer Presentation contains mainly the interface code, and this is shown to user. This code could contain any technology that can be used on the client side like HTML, JavaScript or VBScript etc.

(2)Second layer is Business Logic which contains all the code of the server-side .This layer have code to interact with database and to query, manipulate, pass data to user interface and handle any input from the UI as well.

(3)Third layer Data represents the data store like MS Access, SQL Server, an XML file, an Excel file or even a text file containing data also some additional database are also added to that layers.


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. *Step-by-step instructions carefully walk you through the most common questions, issues, and tasks. *The Q&A sections, quizzes, and exercises help you build and test your knowledge. *By the Way notes present interesting pieces of information. *Did You Know? Tips offer advice or teach an easier way to do something. *Watch Out! Cautions advise you about potential problems and help you steer clear of disaster. Learn how to... *Use XAML to build user interfaces *Leverage data binding to minimize tedious code *Create visually engaging applications *Architect and design WPF applications using proven patterns such as MVP *Incorporate audio and video into your applications *Customize controls with styles, templates, and animation *Apply best practices for developing software with WPF *Deploy WPF applications to the desktop and Web *Take advantage of WPF¡¯s advanced printing capabilities *Grow as a developer by improving your overall software design skills.

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

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

What are the various ways of hosting a WCF service?
Self hosting the service in his own application domain. 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.


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.



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.
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


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.

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)

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.

Sunday, December 20, 2009

Windows Communication Foundation Architecture Overview

Summary: Get a high-level view of the Windows Communication Foundation (WCF) architecture and its key concepts. Code examples demonstrate WCF contracts, endpoints, and behaviors. (17 printed pages)

Contents

Introduction

WCF Fundamentals

Code Examples

Summary

Introduction

This document provides a high-level view of the Windows Communication Foundation (WCF) architecture. It is intended to explain key concepts in WCF and how they fit together. There are a few code examples to further illustrate the concepts, but code is not the emphasis of this document.

The rest of this document is organized in two main sections:

• WCF Fundamentals: Covers key concepts in WCF, terms, and architectural components.

• Code Examples: Provides a few short code examples intended to illustrate and reify the concepts covered in WCF Fundamentals.

WCF Fundamentals

A WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.

A Client is a program that exchanges messages with one or more Endpoints. A Client may also expose an Endpoint to receive Messages from a Service in a duplex message exchange pattern.

The following sections describe these fundamentals in more detail.

Endpoints

A Service Endpoint has an Address, a Binding, and a Contract.

The Endpoint's Address is a network address where the Endpoint resides. The EndpointAddress class represents a WCF Endpoint Address.

The Endpoint's Binding specifies how the Endpoint communicates with the world including things like transport protocol (e.g., TCP, HTTP), encoding (e.g., text, binary), and security requirements (e.g., SSL, SOAP message security). The Binding class represents a WCF Binding.

The Endpoint's Contract specifies what the Endpoint communicates and is essentially a collection of messages organized in operations that have basic Message Exchange Patterns (MEPs) such as one-way, duplex, and request/reply. The ContractDescription class represents a WCF Contract.

The ServiceEndpoint class represents an Endpoint and has an EndpointAddress, a Binding, and a ContractDescription corresponding to the Endpoint's Address, Binding, and Contract, respectively (see Figure 1).



Figure 1. Each Service's Endpoint contains an EndpointAddress, a Binding and a Contract represented by ContractDescription.

EndpointAddress

An EndpointAddress is basically a URI, an Identity, and a collection of optional headers as shown in Figure2.

An Endpoint's security identity is normally its URI; however, in advanced scenarios the identity can be explicitly set independent of the URI using the Identity address property.

The optional headers are used to provide additional addressing information beyond the Endpoint's URI. For example, address headers are useful for differentiating between multiple Endpoints that share the same address URI.




Figure 2. EndpointAddress contains a URI and AddressProperties contains an Identity and a collection of AddressHeaders.

Bindings

A Binding has a name, a namespace, and a collection of composable binding elements (Figure 3). The Binding's name and namespace uniquely identify it in the service's metadata. Each binding element describes an aspect of how the Endpoint communicates with the world.




Figure 3. Binding class and its members

For example, Figure 4 shows a binding element collection containing three binding elements. The presence of each binding element describes part of the how of communicating with the Endpoint. The TcpTransportBindingElement indicates that the Endpoint will communicate with the world using TCP as the transport protocol. ReliableSessionBindingElement indicates that the Endpoint uses reliable messaging to provide message delivery assurances. SecurityBindingElement indicates that the Endpoint uses SOAP message security. Each binding element usually has properties that further describe the specifics of the how of communicating with the Endpoint. For example, the ReliableSessionBindingElement has an Assurances property that specifies the required message delivery assurances, such as none, at least once, at most once, or exactly once.




Figure 4. An example Binding with three binding elements

The order and types of binding elements in Bindings are significant: The collection of binding elements is used to build a communications stack ordered according to the order of binding elements in the binding elements collection. The last binding element to be added to the collection corresponds to the bottom component of the communications stack, while the first one corresponds to the top component. Incoming messages flow through the stack from the bottom upwards, while outgoing messages flow from the top downwards. Therefore the order of binding elements in the collection directly affects the order in which communications stack components process messages. Note that WCF provides a set of pre-defined bindings that can be used in the majority of scenarios instead of defining custom bindings.

Contracts

A WCF Contract is a collection of Operations that specifies what the Endpoint communicates to the outside world. Each operation is a simple message exchange, for example one-way or request/reply message exchange.

The ContractDescription class is used to describe WCF Contracts and their operations. Within a ContractDescription, each Contract operation has a corresponding OperationDescription that describes aspects of the operation such as whether the operation is one-way or request/reply. Each OperationDescription also describes the messages that make up the operation using a collection of MessageDescriptions.

A ContractDescription is usually created from an interface or class that defines the Contract using the WCF programming model. This type is annotated with ServiceContractAttribute and its methods that correspond to Endpoint Operations are annotated with OperationContractAttribute. You can also build a ContractDescription by hand without starting with a CLR type annotated with attributes.

A duplex Contract defines two logical sets of operations: A set that the Service exposes for the Client to call and a set that the Client exposes for the Service to call. The programming model for defining a duplex Contract is to split each set in a separate type (each type must be a class or an interface) and annotate the contract that represents the service's operations with ServiceContractAttribute, referencing the contract that defines the client (or callback) operations. In addition, ContractDescription contains a reference to each of the types thereby grouping them into one duplex Contract.

Similar to Bindings, each Contract has a Name and Namespace that uniquely identify it in the Service's metadata.

Each Contract also has a collection of ContractBehaviors that are modules that modify or extend the contract's behavior. The next section covers behaviors in more detail.




Figure 5. ContractDescription class describes a WCF contract

Behaviors

Behaviors are types that modify or extend Service or Client functionality. For example, the metadata behavior that ServiceMetadataBehavior implemented controls whether the Service publishes metadata. Similarly, the security behavior controls impersonation and authorization, while the transactions behavior controls enlisting in and auto-completing transactions.

Behaviors also participate in the process of building the channel and can modify that channel based on user-specified settings and/or other aspects of the Service or Channel.

A Service Behavior is a type that implements IServiceBehavior and applies to Services. Similarly, a Channel Behavior is a type that implements IChannelBehavior and applies to Client Channels.

Service and Channel Descriptions

The ServiceDescription class is an in-memory structure that describes a WCF Service including the Endpoints exposed by the Service, the Behaviors applied to the Service, and the type (a class) that implements the Service (see Figure 6). ServiceDescription is used to create metadata, code/config, and channels.

You can build this ServiceDescription object by hand. You can also create it from a type annotated with certain WCF attributes, which is the more common scenario. The code for this type can be written by hand or generated from a WSDL document using a WCF tool called svcutil.exe.

Although ServiceDescription objects can be created and populated explicitly, they are often created behind the scenes as part of running the Service.




Figure 6. ServiceDescription object model

Similarly on the client side, a ChannelDescription describes a WCF Client's Channel to a specific Endpoint (Figure 7). The ChannelDescription class has a collection of IchannelBehaviors, which are Behaviors applied to the Channel. It also has a ServiceEndpoint that describes the Endpoint with which the Channel will communicate.


Note that, unlike ServiceDescription, ChannelDescription contains only one ServiceEndpoint that represents the target Endpoint with which the Channel will communicate.



Figure 7. ChannelDescription object model

WCF Runtime

The WCF Runtime is the set of objects responsible for sending and receiving messages. For example, things like formatting messages, applying security, and transmitting and receiving messages using various transport protocols, as well as dispatching received messages to the appropriate operation, all fall within the WCF runtime. The following sections explain the key concepts of the WCF runtime.

Message

The WCF Message is the unit of data exchange between a Client and an Endpoint. A Message is essentially an in-memory representation of a SOAP message InfoSet. Note that Message is not tied to text XML. Rather, depending on which encoding mechanism is used, a Message can be serialized using the WCF binary format, text XML, or any other custom format.

Channels

Channels are the core abstraction for sending Messages to and receiving Messages from an Endpoint. Broadly speaking, there are two categories of Channels: Transport Channels handle sending or receiving opaque octet streams using some form of transport protocol such as TCP, UDP, or MSMQ. Protocol Channels, on the other hand, implement a SOAP-based protocol by processing and possibly modifying messages. For example, the security Channel adds and processes SOAP message headers and may modify the body of the message by encrypting it. Channels are composable such that a Channel may be layered on top of another Channel that is in turn layered on top of a third Channel.

EndpointListener

An EndpointListener is the runtime equivalent of a ServiceEndpoint. The EndpointAddress, Contract, and Binding of ServiceEndpoint (representing where, what and how), correspond to the EndpointListener's listening address, message filtering and dispatch, and channel stack, respectively. The EndpointListener contains the Channel stack that is responsible for sending and receiving messages.

ServiceHost and ChannelFactory

The WCF Service runtime is usually created behind the scenes by calling ServiceHost.Open. ServiceHost (Figure 6) drives the creation of a ServiceDescription from on the Service type and populates the ServiceDescription's ServiceEndpoint collection with Endpoints defined in config or code, or both. ServiceHost then uses the ServiceDescription to create the channel stack in the form of an EndpointListener object for each ServiceEndpoint in the ServiceDescription.



Figure 8. ServiceHost object model

Similarly, on the client side, the Client runtime is created by a ChannelFactory, which is the Client's equivalent of ServiceHost.

ChannelFactory drives the creation of a ChannelDescription based on a Contract type, a Binding, and an EndpointAddress. It then uses this ChannelDescription to create the Client's channel stack.

Unlike the Service runtime, the Client runtime does not contain EndpointListeners because a Client always initiates connection to the Service, so there is no need to "listen" for incoming connections.

Code Examples

This section provides code examples that show how Services and Clients are built. These examples are intended to reify the above concepts and not to teach WCF programming.

Defining and Implementing a Contract

As mentioned above, the easiest way to define a contract is creating an interface or a class and annotating it with ServiceContractAttribute, allowing the system to easily create from it a ContractDescription.

When using interfaces or classes to define contracts, each interface or class method that is a member of the contract must be annotated with OperationContractAttribute. For example:





using System.ServiceModel;



//a WCF contract defined using an interface

[ServiceContract]

public interface IMath

{

[OperationContract]

int Add(int x, int y);

}

Implementing the contract in this case is simply a matter of creating a class that implements IMath. That class becomes the WCF Service class. For example:





//the service class implements the interface

public class MathService : IMath

{

public int Add(int x, int y)

{ return x + y; }

}

Defining Endpoints and Starting the Service

Endpoints can be defined in code or in config. In the example below, the DefineEndpointImperatively method shows the easiest way to define Endpoints in code and start the service.

DefineEndpointInConfig method shows the equivalent endpoint defined in config (config example follows the code below).


public class WCFServiceApp

{

public void DefineEndpointImperatively()

{

//create a service host for MathService

ServiceHost sh = new ServiceHost(typeof(MathService));


//use the AddEndpoint helper method to

//create the ServiceEndpoint and add it

//to the ServiceDescription

sh.AddServiceEndpoint(

typeof(IMath), //contract type

new WSHttpBinding(), //one of the built-in bindings

"http://localhost/MathService/Ep1"); //the endpoint's address



//create and open the service runtime

sh.Open();



}



public void DefineEndpointInConfig()

{

//create a service host for MathService

ServiceHost sh = new ServiceHost (typeof(MathService));



//create and open the service runtime

sh.Open();



}

}





xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">













address="http://localhost/MathService/Ep1"

binding="wsHttpBinding"

contract="IMath"/>









Sending Messages to an Endpoint

The code below shows two ways to send a message to the IMath endpoint. SendMessageToEndpoint hides the Channel creation, which happens behind the scenes while the SendMessageToEndpointUsingChannel example does it explicitly.

The first example in SendMessageToEndpoint uses a tool named svcutil.exe and the Service's metadata to generate a Contract (IMath in this example), a proxy class (MathProxy in this example) that implements the Contract, and associated config (not shown here). Again, the Contract defined by IMath specifies the what (i.e., the operations that can be performed), while the generated config contains a Binding (the how) and an address (the where).

Using this proxy class is simply a matter of instantiating it and calling the Add method. Behind the scenes, the proxy class will create a Channel and use that to communicate with the Endpoint.

The second example in SendMessageToEndpointsUsingChannel below shows communicating with an Endpoint using ChannelFactory directly. In this example, instead of using a proxy class and config, a Channel is created directly using ChannelFactory.CreateChannel. Also, instead of using config to define the Endpoint's address and Binding, the ChannelFactory constructor takes those two pieces of information as parameters. The third piece of information required to define an Endpoint, namely the Contract, is passed in as the type T.

using System.ServiceModel;

//this contract is generated by svcutil.exe

//from the service's metadata

public interface IMath

{

[OperationContract]

public int Add(int x, int y)

{ return x + y; }

}





//this class is generated by svcutil.exe

//from the service's metadata

//generated config is not shown here

public class MathProxy : IMath

{

...

}



public class WCFClientApp

{

public void SendMessageToEndpoint()

{

//this uses a proxy class that was

//created by svcutil.exe from the service's metadata

MathProxy proxy = new MathProxy();



int result = proxy.Add(35, 7);

}

public void SendMessageToEndpointUsingChannel()

{

//this uses ChannelFactory to create the channel

//you must specify the address, the binding and

//the contract type (IMath)

ChannelFactory factory=new ChannelFactory(

new WSHttpBinding(),

new EndpointAddress("http://localhost/MathService/Ep1"));

IMath channel=factory.CreateChannel();

int result=channel.Add(35,7);

factory.Close();



}

}

Defining a Custom Behavior

Defining a custom Behavior is a matter of implementing IServiceBehavior (or IChannelBehavior for client-side behaviors). The code below shows an example behavior that implements IServiceBehavior. In IServiceBehavior.ApplyBehavior, the code inspects the ServiceDescription and writes out the Address, Binding, and Contract of each ServiceEndpoint, as well as the name of each Behavior in the ServiceDescription.

This particular behavior is also an attribute (inherits from System.Attribute), making it possible to apply declaratively as will be shown below. However, behaviors are not required to be attributes.


[AttributeUsageAttribute(

AttributeTargets.Class,

AllowMultiple=false,

Inherited=false)]

public class InspectorBehavior : System.Attribute,

System.ServiceModel.IServiceBehavior

{

public void ApplyBehavior(

ServiceDescription description,

Collection behaviors)

{

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

foreach (ServiceEndpoint endpoint in description.Endpoints)

{

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

Console.WriteLine("Endpoint Address: {0}",

endpoint.Address);

Console.WriteLine("Endpoint Binding: {0}",

endpoint.Binding.GetType().Name);

Console.WriteLine("Endpoint Contract: {0}",

endpoint.Contract.ContractType.Name);

Console.WriteLine();

}

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

foreach (IServiceBehavior behavior in description.Behaviors)

{

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

Console.WriteLine("Behavior: {0}", behavior.GetType().Name);

Console.WriteLine();

}

}

}

Applying a Custom Behavior

All behaviors can be applied imperatively by adding an instance of the behavior to the ServiceDescription (or the ChannelDescription on the client side). For example, to apply the InspectorBehavior imperatively you would write:


ServiceHost sh = new ServiceHost(typeof(MathService));

sh.AddServiceEndpoint(

typeof(IMath),

new WSHttpBinding(),

"http://localhost/MathService/Ep1");

//Add the behavior imperatively

InspectorBehavior behavior = new InspectorBehavior();

sh.Description.Behaviors.Add(behavior);

sh.Open();

Additionally, behaviors that inherit from System.Attribute may be applied declaratively to the service. For example, because InspectorBehavior inherits from System.Attribute, it can be applied declaratively like this:


[InspectorBehavior]

public class MathService : IMath

{

public int Add(int x, int y)

{ return x + y; }

}

Summary

WCF Services expose a collection of Endpoints where each Endpoint is a portal for communicating with the world. Each Endpoint has an Address, a Binding, and a Contract (ABC). The Address is where the Endpoint resides, the Binding is how the Endpoint communicates, and the Contract is what the Endpoint communicates.

On the Service, a ServiceDescription holds the collection of ServiceEndpoints each describing an Endpoint that the Service exposes. From this description, ServiceHost creates a runtime that contains an EndpointListener for each ServiceEndpoint in the ServiceDescription. The Endpoint's address, Binding, and Contract (representing the where, what, and how) correspond to the EndpointListener's listening address, message filtering and dispatch, and channel stack, respectively.

Similarly, on the Client, a ChannelDescription holds the one ServiceEndpoint with which the Client communicates. From this ChannelDescription, ChannelFactory creates the channel stack that can communicate with the Service's Endpoint.