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.