Tuesday, 5 February 2013

What is state server? how state server will be used in another system?


StateServer is one of the ASP.NET sessionState mode. StateServer mode stores session state in a process, referred to as the ASP.NET state service, that is separate from the ASP.NET worker process or IIS application pool. Using this mode ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
To use StateServer mode, you must first be sure the ASP.NET state service is running on the server used for the session store. The ASP.NET state service is installed as a service when ASP.NET and the .NET Framework are installed. The ASP.Net state service is installed at the following location:
systemroot\Microsoft.NET\Framework\versionNumber\aspnet_state.exe
To configure an ASP.NET application to use StateServer mode, in the application's Web.config file do the following:
Set the mode attribute of the sessionState element to StateServer.
Set the stateConnectionString attribute to tcpip=serverName:42424.
The following example shows a configuration setting for StateServer mode where session state is stored on a remote computer named SampleStateServer:
<configuration>
  <system.web>
    <sessionState mode="StateServer"
      stateConnectionString="tcpip=SampleStateServer:42424"
      cookieless="false"
      timeout="20"/>
  </system.web>
</configuration>

Method Overloading in WebServices

Method Overloading is outside paradigm of SOA as each method within a WSDL must be unique. Hence by default Web Services do not support Method Overloading. Otherwise it leads to WSDL name clashes. 

But .NET provides an alternative way to do it using the MessageName Property of the WebMethod Attribute which changes the method name in the WSDL.

Sample Code:

namespace TestOverloadingWebService
{
    [WebService(Namespace = "http://tempuri.org/")]
    public class OverloadingInWebService : System.Web.Services.WebService
    {
        [WebMethod(MessageName = "AddInt", EnableSession = true)]
        public int Add(int a, int b)
        {
            return (a + b);
        }

        [WebMethod(MessageName = "AddFloat", EnableSession = true)]
        public float Add(float a, float b)
        {
            return (a + b);
        }
    }
}

Method Overloading in WCF

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.
Sample code: 

[ServiceContract]
interface ICalculator
{
 [OperationContract(Name = "AddInt")]
   int Add(int arg1,int arg2);

   [OperationContract(Name = "AddDouble")]
   double Add(double arg1,double arg2);
}

Difference between "throw" and "throw ex" in .NET


When you use the throw with an empty parameter, you are re-throwing the last exception. When you throw the existing exception you are creating a new exception.  
What's the difference? Simple: the stack trace.
The empty parameter re-throw keeps the existing stack list, the parametered version creates a new stack trace to the point of the throw. For debugging, the empty version tells you where the error actually occurred, the parametered version discards that. Exception bubbling means that even though you are catching the exception and doing something with it, you want that exception to "bubble" up from your code to the calling code so it has a chance to do something with that exception. This is a fairly common scenario, but it has the potential to cause some major problems when you are debugging.
   1: try
   2: {
   3:     // do some operation that can fail
   4: }
   5: catch (Exception ex)
   6: {
   7:     // do some local cleanup
   8:     throw ex;
   9: }
This code looks perfectly reasonable and does the job. It properly catches the exception, does some local cleanup and then bubbles the exception up the chain. (A side note here is that you really shouldn't catch a general exception like this. I'm doing this for simplicity in the examples, but you should be catching specific exceptions and only those that you can do something about.)
However, how  many of you have seen code that looks like this
   1: try
   2: {
   3:     // do some operation that can fail
   4: }
   5: catch (Exception ex)
   6: {
   7:     // do some local cleanup
   8:     throw;
   9: }
There is a subtle difference between these two calls that won't be apparent until you are trying to debug the problem. That difference is in the stack trace information that gets sent with the exception.
In the first case, the stack trace is truncated below the method that failed. What this means is that when you look at the stack trace, it will look as if the exception originated in your code. This isn't always the case, particularly if you are bubbling up a CLR generated exception (like a SqlException). This is a problem known as "breaking the stack", because you no longer have the full stack trace information. This happens because you are in essence creating a new exception to throw.
By using "throw" by itself, you preserve the stack trace information. You can confirm this by looking at the IL generated for these two code blocks. This makes the difference very obvious since in the first example the IL instruction called is "throw" while in the second the instruction is called "rethrow".
Before you run and change all of your code, there are still places where "throw ex" is appropriate. There are times when you want to add information to the exception that was caught or change it into a more meaningful exception. In these instances you actually want a new exception to be thrown. Again, there are two ways you can do this. The most common way that I have seen is
   1: try
   2: {
   3:     // do some operation that can fail
   4: }
   5: catch (Exception ex)
   6: {
   7:     // do some local cleanup
   8:     throw new ApplicationException("operation failed!");
   9: }
However, this still suffers the problem of breaking the stack. Here you are generating a completely new exception and loosing any of the stack trace information from the original exception. What you really want to do is
   1: try
   2: {
   3:     // do some operation that can fail
   4: }
   5: catch (Exception ex)
   6: {
   7:     // do some local cleanup
   8:     throw new ApplicationException("operation failed!", ex);
   9: }
By passing the original exception to the ApplicationException you are preserving the original exception, and it's stack trace information, as the inner exception to your ApplicationException.
To wrap everything up
  1. Only catch exceptions if they are important to you and you need to do some sort of cleanup as a result.
  2. If you need to bubble an exception up the chain, use "throw" by itself.
  3. If you need to add information to the exception or repackage it, always pass the original exception as the inner exception.

What are the ways to do security in WCF?

In WCF there are two types of Security, transport level security and message level security.
Transport Security: Transport level security happens at the channel level. Transport level security is the easiest to implement as it happens at the communication level. WCF uses transport protocols like TCP, HTTP, MSMQ etc and every of these protocols have their own security mechanisms. One of the common implementation of transport level security is HTTPS. HTTPS is implemented over HTTP protocols with SSL providing the security mechanism. No coding change is required it’s more of using the existing security mechanism provided by the
protocol.Web config setting like the below example for transport security.See the bold lines:
<services>
            <service behaviorConfiguration="BimaExpress.Services.Service1Behavior"  name="BimaExpress.Services.Service1">
                <endpoint address="https://localhost:58946/myservice.svc" binding="wsHttpBinding"  bindingConfiguration="WSHttpBinding_IChildInsuranceService" contract="BimaExpress.Services.IService1">
               </endpoint>
                <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
           </service>
</services> 
<behaviors>
     <serviceBehaviors>
        <behavior name="BimaExpress.Services.Service1Behavior">
         <serviceMetadata httpsGetEnabled="true" />
         <serviceDebug includeExceptionDetailInFaults="false" />
       </serviceBehaviors> 
        </behavior>
</behaviors>
<bindings>
   <wsHttpBinding>
        <binding name="WSHttpBinding_IChildInsuranceService">
          <security mode="Transport">
               <transport clientCredentialType="none"  />
           </security>
        </binding>
    </wsHttpBinding>
</bindings>

Message Security: Message level security is implemented with message data itself. Due to this it is independent of the protocol. Some of the common ways of implementing message level security is by encrypting data using some standard encryption algorithm.Check the below link for implementation:
http://pratapreddypilaka.blogspot.in/2011/10/wcf-implementing-message-level-security.html

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
“deserialization”.
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.
[Serializable]
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);
stream.Close();
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);
stream.Close();
textBox1.Text = obj.CustomerCode;
textBox2.Text = obj.CustomerName;
}

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.

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.
 
 

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

<system.serviceModel>
<services>
<service name="Samples.StockTickerServ"
behaviorConfiguration="CalculatorServiceBehavior">
...
<!-- Define NetMsmqEndpoint -->
<endpoint address="net.msmq://localhost/private/ServiceModelSamplesVolatile"
binding="netMsmqBinding"
bindingConfiguration="volatileBinding" 
contract="Samples.InterfaceStockTicker" />
...
</service>
</services>

<bindings>
<netMsmqBinding>
<binding name="volatileBinding" 
durable="false"
exactlyOnce="false"/>
</netMsmqBinding>
</bindings>
...
</system.serviceModel>

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) 


event: 

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

 
delegate: 

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. 

event-->delegate-->method 
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.

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.

Example2:

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.

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);

Difference between Abstraction and Encapsulation????


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

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. 

Example: 

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");



            Console.Read();

        }

    }

}

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

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();
stack.Push(3);
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();
stack.Push("SomeName"); 
//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>();
stack.Push(3);
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.
Conclusion
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.