जगदीश खोलिया: 2012

Friday, December 14, 2012

Delegate with example

Delegate is a type which  holds the method(s) reference in an object. It is also referred to as a type safe function pointer.


  • Encapsulating the method's call from caller
  • Effective use of delegate improves the performance of application
  • Used to call a method asynchronously


public delegate type_of_delegate delegate_name()

public delegate int mydelegate(int delvar1,int delvar2)


  • You can use delegates without parameters or with parameter list
  • You should follow the same syntax as in the method
    (If you are referring to the method with two int parameters and int return type, the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer.) 
 Sample program using delegate :

public delegate double Delegate_MyFirst(int Num1,int Num2);
class Class1
    static double AddVal(int val1,int val2)
        return val1 + val2;
    static void Main(string[] args)
        //Creating the Delegate Instance
        Delegate_MyFirst Objdel = new Delegate_MyFirst(AddVal);
        Console.Write("Please Enter Values");
        int v1 = Int32.Parse(Console.ReadLine());
        int v2 = Int32.Parse(Console.ReadLine());
        //use delegate for processing
        double dblResult = Objdel(v1,v2);
        Console.WriteLine ("Result :"+dblResult);

Multicast Delegate

What is Multicast Delegate?

It is a delegate which holds the reference of more than one method.
Multicast delegates must contain only methods that return void, else there is a run-time exception.

Simple Program using Multicast Delegate

delegate void Delegate_Multicast(int x, int y);
Class Class2
    static void Method1(int x, int y)
        Console.WriteLine("You r in Method 1");

    static void Method2(int x, int y)
        Console.WriteLine("You r in Method 2");

    public static void Main()
        Delegate_Multicast func = new Delegate_Multicast(Method1);
        func += new Delegate_Multicast(Method2);
        func(1,2);             // Method1 and Method2 are called
        func -= new Delegate_Multicast(Method1);
        func(2,3);             // Only Method2 is called
Delegate is added using the += operator and removed 
using the -= operator.  

Thursday, October 25, 2012


The CHARINDEX and PATINDEX functions return the starting position of a pattern you specify.
Both functions take 2 parameters.For CHARINDEX, the pattern cannot include wildcard characters. 
With PATINDEX, you must include percent signs before and after the pattern, unless you are looking for the pattern as the first (omit the first %) or last (omit the last %) characters in a column.  The second argument is a character expression  in which searches for the specified pattern.
Retrive File Extension from given File Name  using charindex and patindex :
Example of CHARINDEX:

SET @FileName='jagdish.doc'
SELECT SUBSTRING(@FileName,charindex('.', @FileName)+1 ,LEN(@FileName)) AS Extention


Examples of PATINDEX:

SET @FileName='jagdish.doc'
SELECT SUBSTRING(@FileName,patindex('%.%', @FileName)+1 ,LEN(@FileName)) AS Extention

Thursday, August 16, 2012

Post data to external URL

 Java script code for posting data to external URL:
 There are 2 Methods of doing this:
1)  <script language="javascript" type="text/javascript">    
        function submitForm(formName, formAction, newWindow) {
            var arrayStr = document.getElementById('<%= hdnData.ClientID %>').value;           
            var frm = createForm(formName, formAction, newWindow);
            var inputArray = arrayStr.split('&');
            for (var j = 0; j < inputArray.length; j++) {
                var temp = inputArray[j].split('=');
                if (isArray(temp) && temp.length == 2) {
                    createfrmInuput(frm, temp[0], temp[1])
        //Check whether variable is array
        function isArray(obj) {
            if (obj.constructor.toString().indexOf('Array') == -1)
                return false;
                return true;
        function createForm(name, action, newWindow) {
            var frmJagdish= document.createElement('FORM');
            frmJagdish.method = 'POST';
            frmJagdish.name = name;
            frmJagdish.action = action;
            //if (newWindow)
            //frmJagdish.target = '_blank';
            return frmJagdish;
        function createfrmInuput(parentForm, name, value) {
            var inuptVar = document.createElement('INPUT');
            inuptVar.type = 'hidden';
            inuptVar.name = name;
            inuptVar.value = value;

ASP.Net design :
<body onload="submitForm('PostedData','http://jagdishkholiya.blogspot.com',true);return false;">
    <form id="frmJagdish" runat="server">
    <asp:HiddenField ID="hdnData" runat="server" />

Code behind :
hdnData.Value = "firstname=jagdish&lastname=kholiya&mobileno=9999999999"

2) <html xmlns="http://www.w3.org/1999/xhtml">
    <head >
    <form id="frmTest" method="post" action="http://jagdishkholiya.blogspot.in"
    <asp:HiddenField ID="firstname" runat="server" />
    <asp:HiddenField ID="lastname" runat="server" />
    <asp:HiddenField ID="mobilenumber" runat="server" />
    <asp:HiddenField ID="city" runat="server" />
    <asp:HiddenField ID="email" runat="server" />  
    <script language="javascript" type="text/javascript">

Code Behind:

  firstname.Value ="Jagdish";
  lastname.Value = "Kholiya";
  mobilenumber.Value ="9999999999";                  
  city.Value = "Gurgaon";
  email.Value = "jagdish.kholiya@gmail.com";

Thursday, July 12, 2012

What's the Difference between WCF and Web Services?

Web Service in ASP.NET

A Web Service is programmable application logic accessible via standard Web protocols. One of these Web protocols is the Simple Object Access Protocol (SOAP). SOAP is a W3C submitted note (as of May 2000) that uses standards based technologies (XML for data description and HTTP for transport) to encode and transmit application data.
Consumers of a Web Service do not need to know anything about the platform, object model, or programming language used to implement the service; they only need to understand how to send and receive SOAP messages (HTTP and XML).

WCF Service

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or word sent as XML, or as complex as a stream of binary data.
In what scenarios must WCF be used
  • A secure service to process business transactions.
  • A service that supplies current data to others, such as a traffic report or other monitoring service.
  • A chat service that allows two people to communicate or exchange data in real time.
  • A dashboard application that polls one or more services for data and presents it in a logical presentation.
  • Exposing a workflow implemented using Windows Workflow Foundation as a WCF service.
  • A Silverlight application to poll a service for the latest data feeds.

Features of WCF

  • Service Orientation
  • Interoperability
  • Multiple Message Patterns
  • Service Metadata
  • Data Contracts
  • Security
  • Multiple Transports and Encodings
  • Reliable and Queued Messages
  • Durable Messages
  • Transactions
  • AJAX and REST Support
  • Extensibility

Difference between Web Service in ASP.NET & WCF Service

WCF is a replacement for all earlier web service technologies from Microsoft. It also does a lot more than what is traditionally considered as "web services".
WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.
ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities.
Web Services can be accessed only over HTTP & it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. Common scenarios for hosting WCF services are IIS,WAS, Self-hosting, Managed Windows Service.
The major difference is that Web Services Use XmlSerializer. But WCF Uses DataContractSerializer which is better in Performance as compared to XmlSerializer.

Key issues with XmlSerializer to serialize .NET types to XML

  • Only Public fields or Properties of .NET types can be translated into XML
  • Only the classes which implement IEnumerable interface
  • Classes that implement the IDictionary interface, such as Hash table cannot be serialized

Important difference between DataContractSerializer and XMLSerializer

  • A practical benefit of the design of the DataContractSerializer is better performance overXmlserializer.
  • XML Serialization does not indicate which fields or properties of the type are serialized into XML whereasDataCotractSerializer
  • Explicitly shows the which fields or properties are serialized into XML
  • The DataContractSerializer can translate the HashTable into XML

Using the Code

The development of web service with ASP.NET relies on defining data and relies on the XmlSerializer to transform data to or from a service.

Key issues with XmlSerializer to serialize .NET types to XML

  • Only Public fields or Properties of .NET types can be translated into XML
  • Only the classes which implement IEnumerable interface
  • Classes that implement the IDictionary interface, such as Hash table cannot be serialized
The WCF uses the DataContractAttribute and DataMemeberAttribute to translate .NET FW types into XML.

public class Item 

    public string ItemID; 
    public decimal ItemQuantity; 
    public decimal ItemPrice;

The DataContractAttribute can be applied to the class or a strcture. DataMemberAttribute can be applied to field or a property and theses fields or properties can be either public or private.
Important difference between DataContractSerializer and XMLSerializer.
  • A practical benefit of the design of the DataContractSerializer is better performance over XML serialization.
  • XML Serialization does not indicate which fields or properties of the type are serialized into XML whereasDataContractSerializer explicitly shows which fields or properties are serialized into XML.
  • The DataContractSerializer can translate the HashTable into XML.

Developing Service

To develop a service using ASP.NET, we must add the WebService attribute to the class andWebMethodAttribute to any of the class methods.

public class Service : System.Web.Services.WebService 
      public string Test(string strMsg) 
          return strMsg; 

To develop a service in WCF, we will write the following code:

public interface ITest 
       string ShowMessage(string strMsg); 
public class Service : ITest 
       public string ShowMessage(string strMsg) 
          return strMsg; 

The ServiceContractAttribute specifies that an interface defines a WCF service contract,
OperationContract attribute indicates which of the methods of the interface defines the operations of the service contract.
A class that implements the service contract is referred to as a service type in WCF.

Hosting the Service

ASP.NET web services are compiled into a class library assembly and a service file with an extension .asmx will have the code for the service. The service file is copied into the root of the ASP.NET application and Assembly will be copied to the bin directory. The application is accessible using URL of the service file.
WCF Service can be hosted within IIS or WindowsActivationService.
  • Compile the service type into a class library
  • Copy the service file with an extension .SVC into a virtual directory and assembly into bin sub directory of the virtual directory.
  • Copy the web.config file into the virtual directory.

Client Development

Clients for the ASP.NET Web services are generated using the command-line tool WSDL.EXE.
WCF uses the ServiceMetadata tool (svcutil.exe) to generate the client for the service.

Message Representation

The Header of the SOAP Message can be customized in ASP.NET Web service.
WCF provides attributes MessageContractAttributeMessageHeaderAttribute andMessageBodyMemberAttribute to describe the structure of the SOAP Message.

Service Description

Issuing a HTTP GET Request with query WSDL causes ASP.NET to generate WSDL to describe the service. It returns the WSDL as a response to the request.
The generated WSDL can be customized by deriving the class of ServiceDescriptionFormatExtension.
Issuing a Request with the query WSDL for the .svc file generates the WSDL. The WSDL that generated by WCF can be customized by using ServiceMetadataBehavior class.

Exception Handling

In ASP.NET Web services, unhandled exceptions are returned to the client as SOAP faults.
In WCF Services, unhandled exceptions are not returned to clients as SOAP faults. A configuration setting is provided to have the unhandled exceptions returned to clients for the purpose of debugging.

Wednesday, June 6, 2012

Few important C# question...

1.C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write? 
Ans.  Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.

2.Can you declare the override method static while the original method is non-static?
 Ans. No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

3.Can you prevent your class from being inherited and becoming a base class for some other classes? Ans. Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class Whatever Base Class Name is.

4. When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)? 
Ans. When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.

5. What’s the difference between System.String and System.StringBuilder classes?
Ans. System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

6. What is the use of private constructor ?
Ans. When we declare a class constructor as private , we can not do 2 things:-
  • We can not create a object of the class.
  • We can not inherit the class.

Now the next question which the interviewer will ask , whats the use of such kind of class which can not be inherited neither instantiated.
Many times we do not want to create instances of certain classes like utility , common routine classes. Rather than calling as shown below

7.Who is faster hashtable or dictionary ?
Ans.Dictionary is faster than hashtable as dictionary is a generic strong type. Hashtable is slower as it takes object as data type which leads to boxing and unboxing.

8. What is the difference between const and readonly?

public class Const_V_Readonly
  public const int I_CONST_VALUE = 2;
  public readonly int I_RO_VALUE;
  public Const_V_Readonly()
     I_RO_VALUE = 3;

AssemblyB references AssemblyA and uses these values in code. When this is compiled,
  • in the case of the const value, it is like a find-replace, the value 2 is 'baked into' the AssemblyB's IL. This means that tomorrow if I update I_CONST_VALUE to 20 in the future. Assembly B would still have 2 till I recompile it.
  • in the case of the readonly value, it is like a ref to a memory location. The value is not baked into AssemblyB's IL. This means that if the memory location is updated, Assembly B gets the new value without recompilation. So if I_RO_VALUE is updated to 30, you only need to build AssemblyA. All clients do not need to be recompiled.

9.I want to force the data reader to return only schema of the data store rather than data.
Ans. PobjDataReader = pobjCommand.ExecuteReader (CommandBehavior.SchemaOnly)

10. What are the various methods provided by the dataset object to generate XML?

 XML is one of the most important leap between classic ADO and ADO.NET. So this question is normally asked more generally how can we convert any data to XML format. Best answer is convert in to dataset and use the below methods.
• ReadXML
Read’s a XML document in to Dataset.
• GetXML
This is a function, which returns the string containing XML document.
• Writexml
This writes a XML data to disk.

11.What is the difference between “Dataset” and “Data Reader” ?

Ans.Following are the major differences between “Dataset” and “Data Reader”:-
• “Dataset” is a disconnected architecture, while “Data Reader” has live connection while reading data. If we want to cache data and pass to a different tier “Dataset” forms the best choice and it has decent XML support.

• When application needs to access data from more than one table “Dataset” forms the best choice. 

• If we need to move back while reading records, “data reader” does not support this functionality.

• However, one of the biggest drawbacks of Dataset is speed. As “Dataset” carry considerable overhead because of relations, multiple table’s etc speed is slower than “Data Reader”. Always try to use “Data Reader” wherever possible, as it is meant especially for speed performance.

12. What’s difference between “Optimistic” and “Pessimistic” locking ?

In pessimistic locking when user wants to update data it locks the record and till then no one can update data. Other user’s can only view the data when there is pessimistic locking.
In optimistic locking multiple users can open the same record for updating, thus increase maximum concurrency. Record is only locked when updating the record. This is the most preferred way of locking practically. Now a days in browser based application it is very common and having pessimistic locking is not a practical solution.

13.How many ways are there to implement locking in ADO.NET?

Following are the ways to implement locking using ADO.NET:-
• When we call “Update” method of Data Adapter it handles locking internally. If the Dataset values are not matching with current data in Database, it raises concurrency exception error. We can easily trap this error using Try. Catch block and raise appropriate error message to the user.
• Define a Date time stamp field in the table. When actually you are firing the UPDATE SQL statements, compare the current timestamp with one existing in the database. Below is a sample SQL which checks for timestamp before updating and any mismatch in timestamp it will not update the records. This I the best practice used by industries for locking.

Update table1 set field1=@test where Last Timestamp=@Current Timestamp

• Check for original values stored in SQL SERVER and actual changed values. In stored procedure check before updating that the old data is same as the current Example in the below shown SQL before updating field1 we check that is the old field1 value same. If not then some one else has updated and necessary action has to be taken.

Update table1 set field1=@test where field1 = @oldfield1value
Locking can be handled at ADO.NET side or at SQL SERVER side i.e. in stored procedures. For more details of how to implementing locking in SQL SERVER read “What are different locks in SQL SERVER?” in SQL SERVER chapter.

14.How can we perform transactions in .NET?

The most common sequence of steps that would be performed while developing a transactional application is as follows:
• Open a database connection using the Open method of the connection object.
• Begin a transaction using the Begin Transaction method of the connection object. This method provides us with a transaction object that we will use later to commit or rollback the transaction. Note that changes caused by any queries executed before calling the Begin Transaction method will be committed to the database immediately after they execute. Set the Transaction property of the command object to the above mentioned transaction object.
• Execute the SQL commands using the command object. We may use oneormorecommand objects for this purpose, as long as the Transaction property of all the objects is set to a valid transaction object.
• Commit or roll back the transaction using the Commit or Rollback method of the transaction object.
• Close the database connection.

15.What is difference between Dataset? Clone and Dataset. Copy?

Clone: - It only copies structure, does not copy data.
Copy: - Copies both structure and data.

16. What is Maximum Pool Size in ADO.NET Connection String?

Maximum pool size decides the maximum number of connection objects to be pooled. If the maximum pool size is reached and there is no usable connection available the request is queued until connections are released back in to pool. So it’s always a good habit to call the close or dispose method of the connection as soon as you have finished work with the connection object.

17. How to enable and disable connection pooling?
For .NET it is enabled by default but if you want to just make sure set Pooling=true in the connection string. To disable connection pooling set Pooling=false in connection string if it is an ADO.NET Connection. If it is an OLEDBConnection object set OLE DB Services=-4 in the connection string.

Tuesday, June 5, 2012

APPLY operator (CROSS Apply and OUTER Apply) in SQL Server

The APPLY operator let's you join a table to a table-valued-function.UDFs can be used in queries at column level, table levels and on column definition while creating tables.
They can also be joined with other tables, but not by simple joins. They have special joins called APPLY operator.There are 2 types of APPLY:
- CROSS APPLY acts as INNER JOIN, returns only rows from the outer table that produce a result set from the table-valued function.
- OUTER APPLY acts as OUTER JOIN, returns both rows that produce a result set, and rows that do not, with NULL values in the columns produced by the table-valued function.
CREATE Procedure [dbo].[Test_Apply]
 ContactId varchar(50)
SELECT name.Customer_Id,name.CustomerName,name.Email,name.MobileNo
FROM Test_Lead lead
INNER JOIN customer cust ON cust.CustomerId = lead.CustomerID
outer apply dbo.fn_Test_GetLatestResponse_Customerwise(lead.Customer_ID) sales
cross apply dbo.fn_Test_GetCustomerDetails(lead.Customer_ID) name
inner join LMS_UserDetails agent on agent.ID = lead.Allocated_To
WHERE lead.ProductId = name.ProductID

Monday, June 4, 2012

Generics in C#

Parametric Polymorphism is a well-established programming language feature. Generics offers this feature to C#.
The best way to understand generics is to study some C# code that would benefit from generics. The code stated below is about a simple Stack class with two methods: Push () and Pop (). First, without using generics example you can get a clear idea about two issues: a) Boxing and unboxing overhead and b) No strong type information at compile type. After that the same Stack class with the use of generics explains how these two issues are solved.
Example Code
Code without using generics:
public class Stack
object[] store; int size; public void Push(object x) {...} public object Pop() {...}

Boxing and unboxing overhead:
You can push a value of any type onto a stack. To retrieve, the result of the Pop method must be explicitly cast back. For example if an integer passed to the Push method, it is automatically boxed. While retrieving, it must be unboxed with an explicit type cast.
Stack stack = new Stack();
int i = (int)stack.Pop(); //unboxing with explicit int casting
Such boxing and unboxing operations add performance overhead since they involve dynamic memory allocations and run-time type checks.
No strong Type information at Compile Time
Another issue with the Stack class: It is not possible to enforce the kind of data placed on a stack. For example, a string can be pushed on a stack and then accidentally cast to the wrong type like integer after it is retrieved:
Stack stack = new Stack();
//pushing the stringint i = (int)stack.Pop(); //run-time exception will be thrown at this point
The above code is technically correct and you will not get any compile time error. The problem does not become visible until the code is executed; at that point an InvalidCastException is thrown.
Code with generics
In C# with generics, you declare class Stack <T> {...}, where T is the type parameter. Within class Stack <T> you can use T as if it were a type. You can create a Stack as Integer by declaring Stack <int> or Stack as Customer object by declaring Stack<Customer>. Simply your type arguments get substituted for the type parameter. All of the Ts become ints or Customers, you don't have to downcast, and there is strong type checking everywhere.
public class Stack<T>
// items are of type T, which is kown when you create the objectT[] items; int count; public void Push(T item) {...}//type of method pop will be decided when you creat the object public T Pop()
In the following example, int is given as the type argument for T:
Stack<int> stack = new Stack<int>();
int i = stack.Pop();
The Stack<int> type is called a constructed type. In the Stack<int> type, every occurrence of T is replaced with the type argument int. The Push and Pop methods of a Stack<int> operate on int values, making it a compile-time error to push values of other types onto the stack, and eliminating the need to explicitly cast values back to their original type when they are retrieved.
You can use parameterization not only for classes but also for interfaces, structs, methods and delegates.
//For Interfaces interface IComparable <T>//for structs struct HashBucket <K,D>//for methods static void Reverse <T> (T[] arr)//for delegates delegate void Action <T> (T arg)

What you can get with Generics
Generics can make the C# code more efficient, type-safe and maintainable.
Efficiency: Following points states that how performance is boosted.
  1. Instantiations of parameterized classes are loaded dynamically and the code for their methods is generated on demand [Just in Time].
  2. Where ever possible, compiled code and data representations are shared between different instantiations.
  3. Due to type specialization, the implementation never needs to box values of primitive types.
Safety: Strong type checking at compile time, hence more bugs caught at compile time itself.
Maintainability: Maintainability is achieved with fewer explicit conversions between data types and code with generics improves clarity and expressively.
Generics gives better performance, type safety and clarity to the C# programs. Generics will increase program reliability by adding strong type checking. Learning how to use generics is straightforward, hopefully this article has inspired you to look deeper into how you can use them.

Schemabinding View

Schemabinding View Restirct you to made any change in tables you used in your View.

Suppose I have an table Employee(EmpID,EmpName, DOJ,Managerid,DepartID)

Now am Creating a view

Create View EmployeeDetails
with Schemabinding
Select EmPid, EmpName,DOj,ManagerId,DepartID from Employee

after it just try to execute delete table and alter table and delete column of employee table.

Sql server will not allow to change table schema. Because you are having Schema dependency.First you need to delete View then only database will allow to modify table.

If you are using Normal View. Sytem will Allow you to delete or modify table but when you run your View next time it will display error.

Chain constructor or constructor chaining

We can chain the call of constructor from child class to base class depending on our requirement. This concept makes sure that the matching base class constructor must be called based on the parameter passed to the child class constructor.


namespace ConsoleApplication1


    class A


        public A(){

            Console.WriteLine("Constructor A.");


        public A(string s){

            Console.WriteLine("Constructor A with parameter = {0}",s);


        public A(string s,string t){

            Console.WriteLine("Constructor A with parameter = {0} & {1}", s,t);



    class B:A


        public B():base(){

            Console.WriteLine("Constructor B.");


        public B(string s):base(s){

            Console.WriteLine("Constructor B with parameter = {0}", s);


        public B(string s, string t):base(s,t){

            Console.WriteLine("Constructor B with parameter = {0} & {1}", s, t);



    class Program


        static void Main(string[] args)


            B b1 = new B();

            B b2 = new B("First Parameter ", "Second Parameter");





Constructor A.
Constructor B.
Constructor A with parameter = First Parameter & Second Parameter
Constructor B with parameter = First Parameter & Second Parameter

Difference between Abstraction and Encapsulation????

1. Abstraction solves the problem in the design level.

1. Encapsulation solves the problem in the implementation level.

2. Abstraction is used for hiding the unwanted data and giving relevant data.

2. Encapsulation means hiding the code and data into a single unit to protect the data from outside world.

3. Abstraction lets you focus on what the object does instead of how it does it

3. Encapsulation means hiding the internal details or mechanics of how an object does something.

4. Abstraction- Outer layout, used in terms of design.
For Example:-
 Outer Look of a Mobile Phone, like it has a display screen and keypad buttons to dial a number.

4. Encapsulation- Inner layout, used in terms of implementation.
For Example:- Inner Implementation detail of a Mobile Phone, how keypad button and Display Screen are connect with each other using circuits.

"Encapsulation is accomplished by using Class. - Keeping data and methods that accesses that data into a single unit" 
"Abstraction is accomplished by using Interface. - Just giving the abstract information about what it can do without specifying the back ground details" 
"Information/Data hiding is accomplished by using Modifiers - By keeping the instance variables private or protected."

Address header in WCF

Address Header contains the information which is sent with every request, it can be used by either end point service or any intermediate device for determining any routing logic or processing logic.

WCF provides AddressHeader class for this purpose.

Example :

AddressHeader addressHeader= AddressHeader.CreateAddressHeader("Name of the header", "Information included in header ");

Once the AddressHeader instance is created, it can be associated with end point instance as follows :

EndpointAddress endpoint = new EndpointAddress(new Uri("http://myserver/myservice"), addressHeader);

Isolation levels in Sql Server

An isolation levels mechanism is used to isolate a resource each transaction in a multi-user
environment. Isolation can be set by obtaining locks on objects.  The correct use of the isolation levels mechanism prevents applications from introducing errors that can occur from the following situations.

1. Lost Updates: This situation occurs when two transactions attempt to update the same data. Consider the following example:
Transaction A reads row 1.
Transaction B reads row 1.
Transaction A updates row 1.
Transaction B updates row 1, overlaying changes applied by Transaction A.

In the above situation, updates performed by Transaction A are lost.

This problem could be avoided if the second Transaction could not make changes until the first Transaction had finished.

2. Dirty Reads: This situation occurs when transactions read data that has not been committed. Consider the following example:
Transaction A inserts row 1 without committing.
Transaction B reads row 1.
Transaction A rolls back row 1.
Transaction B now has a row that physically does not exist.

This problem could be avoided if no one could read the changes until the first Transaction determined that the changes were final.

3. Nonrepeatable Reads: This situation occurs when a transaction reads the same query multiple times and results are not the same each time. Consider the following example:
Transaction A reads a row of data.
Transaction B modifies this row and commits.
Transaction A re-reads the same row and sets back different data values.  (When the record was read for the second time by Transaction A, it has changed).

This problem could be avoided if the Transaction A could read the row only after the Transaction B has finished writing it.

4. Phantom reads: This situation occurs when a row of data matches the first time but does not match subsequent times. Consider the following example:
Transaction A reads two rows based on a Query A where clause.
Transaction B inserts a new row that happens to fall under Transaction A Query A's where clause.
Transaction A runs Query A again and now gets back three rows.


Phantom reads occur when an insert or delete action is performed against a row that belongs to a range of rows being read by a transaction. The transaction's first read of the range of rows shows a row that no longer exists in the second or succeeding read, as a result of a deletion by a different transaction. Similarly, as the result of an insert by a different transaction, the transaction's second or succeeding read shows a row that did not exist in the original read.

The above four phenomenon demonstrate that there is a need to utilize a mechanism called ISOLATION LEVELS.

Difference between event and delegate

Class1 c = new Class1();
c.MyDeleageteCallback = new Class1.DomSomethingDelegate(this.Calculate);

This piece of code will work just fine with class1, but if we were to try to use it on class2, where there is the event keyword declared, we would get a compilation error.

In conclusion: an event declaration adds a layer of protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list, and only allows adding or removing targets from the invocation list.

Three main differences:
events can be included in interfaces
events can only be invoked by the containing class
events' signatures are constrained (depends on language and CLS compliance)


1) It is a data member of a type(class/structure)

2)It is declared inside a type(class/structure)

3) It is used to generate notifications which are then passed to methods though


1)It is a datatype(reference type) that holds references of methods with
some signatures.also called as function pointer.

2)It may or may not be declared inside a class.

3)It is used as the return type of an event and used in passing messages from event to methods.

example: 1
namespace dd
//delegate declaration
delegate void first();
class cc
//event declaration
public first myevent;

example 2:
button1.Click+=new EventHandler(this.button1_Click);

Click is the event that returns an instance of the EventHandler delegate.
EventHandler delegate has the reference of button1_Click event and that
helps in the communication betwen the Click event and button1_Click method.

Dead letter queues in WCF

The main use of queue is that you do not need the client and the server running at one time. Therefore, it is possible that a message will lie in queue for long time until the server or client picks it up. But there are scenarios where a message is of no use after a certain time. Therefore, these kinds of messages if not delivered within that time span it should not be sent to the user.
Below is the config snippet, which defines for how much time the message should be in queue.
<binding name="MyBindings"

Volatile queues in WCF

There are scenarios in the project when you want the message to deliver in proper time. The timely delivery of message is more important than losing message. In these scenarios, Volatile queues are used.
Below is the code snippet, which shows how to configure Volatile queues. You can see the binding Configuration property set to Volatile Binding. This code will assure that message will deliver on time but there is a possibility that you can lose data.

<!-- use appSetting to configure MSMQ queue name -->
<add key="queueName" value=".\private$\ServiceModelSamplesVolatile" />

<service name="Samples.StockTickerServ"
<!-- Define NetMsmqEndpoint -->
<endpoint address="net.msmq://localhost/private/ServiceModelSamplesVolatile"
contract="Samples.InterfaceStockTicker" />

<binding name="volatileBinding" 

Friday, June 1, 2012

Type of serialization

.NET provides 2 ways for serializtion 1) XmlSerializer and 2) BinaryFormatter/SoapFormatter

XmlSerializer is used for Web Services. The BinaryFormatter & SoapFormatter is used for Remoting. While using XmlSerializer, it is required that the target class has parameter less constructors, has public read-write properties and has fields that can be serialized. The XmlSerializer has good support for XML documents. It can be used to construct objects from existing XML documents. The XmlSerializer enables us to serialize and deserialize objects to an XML format.

SoapFormatter enables us to serialize & deserialize objects to SOAP format. They can serialize private and public fields of a class. The target class must be marked with the Serializable attribute. On deserialization, the constructor of the new object is not invoked.

BinaryFormatter has the same features as the SoapFormatter except that it formats data into binary format. The BinaryForamatter (and the SoapFormatter) has two main methods. Serialize and Deserialize. To serialize an object, we pass an instance of the stream and the object to the Serialize method. To Deserialize an object, you pass an instance of a stream to the Deserialize method.

You can use the BinaryFormatter to serialize many, but not all, classes in the .NET Framework. For example, you can serialize ArrayLists, DataSets, and Arrays but not other objects, such as DataReaders or TextBox controls. To serialize a class, the class must have the Serializable attribute or implement the ISerializable interface.

Note that the XmlSerializer captures only the public members of the class, whereas the BinaryFormatter & the SoapFormatter captures both the public & private members of the class. The output using the BinaryFormatter is quite compact, as the information is in binary format, whereas the XmlSerializer format is filled with XML tags.

Serialization and Deserialization

Serialization: -“Serialization” is a process of converting an object into a stream of bytes.

Deserialization: – “Deserialization” is reverse of “serialization”, where stream of bytes are converted back in to an object.
Let’s see a simple example how exactly we can do “serialization” and
It’s very simple four steps procedure as follows.
Step1: – create a new “window application” like below diagram.

Step2: – Now create a customer class in “Form1.cs” file.
public class Customer
public string CustomerCode;
public string CustomerName;
Step3: – Now, we will see how exactly “serialization” is done.
Import the following namespace 
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

private void Serialize_Click(object sender, EventArgs e)
Customer obj = new Customer();// created instance of the customer class
obj.CustomerCode = textBox1.Text;
obj.CustomerName = textBox2.Text;
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("E:\\Customer.bin", FileMode.Create,
 FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
textBox1.Text = "";
textBox2.Text = "";
Step4: – Similarly, we will do for “deserialization”.
private void Deserialize_Click(object sender, EventArgs e)
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("E:\\Customer.bin", FileMode.Open, 
FileAccess.Read, FileShare.Read);
Customer obj = (Customer)formatter.Deserialize(stream);
textBox1.Text = obj.CustomerCode;
textBox2.Text = obj.CustomerName;