Monday, April 29, 2013

how to use ViewState In Asp.Net


What is view state

View State is one of the most important and useful client side state management mechanism. It can store the page value at the time of post back (Sending and Receiving information from Server) of your page. ASP.NET pages provide the ViewState property as a built-in structure for automatically storing values between multiple requests for the same page.
View state is the method that the ASP.NET page framework uses by default to preserve page and control values between round trips. When the HTML for the page is rendered, the current state of the page and values that need to be retained during postback are serialized into base64-encoded strings and output in the view state hidden field or fields. You can change the
default behavior and store view state in another location such as a SQL Server database by implementing a custom PageStatePersister class to store page data. For an example of storing page state on a stream rather than in a hidden page field,
see the example for the PageStatePersister class.
Example: If you want to add one variable in View State,

ViewState["Var"]=Count;

For Retrieving information from View State:   

string Test=ViewState["TestVal"];

Advantages of view state

This are the main advantage of using View State:
•           Easy to implement
•           No server resources are required
•           Enhanced security features ,like it can be encoded and compressed.

Disadvantages of view state

This are the main disadvantages of using View State:
•           It can be performance overhead if we are going to store larger amount of data , because it is associated with page only.
•           Its stored in a hidden filed in hashed format (which I have discussed later) still it can be easily trapped.
•           It does not have any support on mobile devices.

When we should use view state

A few point you should remember when you select view state for maintain your page state.
•           Size of data should be small , because data are bind with page controls , so for larger amount of data it can be cause of performance overhead.
•           Try to avoid storing secure data in view state

When we should avoid view state

You won't need view state for a control for following cases,
•           The control never change
•           The control is repopulated on every postback
•           The control is an input control and it changes only of user actions.

Where is view state stored

View State stored the value of page controls as a string which is hashed and encoded in some hashing and encoding technology.
It only contain information about page and its controls. Its does not have any interaction with server. It stays along with the page in the Client Browser. View State use Hidden field to store its information in a encoding format.
Suppose you have written a simple code , to store a value of control:

ViewState["Value"] = MyControl.Text;

Now, Run you application, In Browser, RighClick > View Source , You will get the following section of code

<input type=”hidden” id=”_viewstate” name=”viewstate” value=”dsfefgbgigguwgbdbwqwugyucffvufebcbenhgbc”/>

Now , look at the value. looks likes a encrypted string, This is Base64 Encoded string, this is not a encoded string. So it can easily be decoded. Base64 makes a string suitable for HTTP transfer plus it makes it a little hard to read. Any body can decode that string and read the original value. so be careful about that. There is a security lack of view state.

How to store object in view state

We can store an object easily as we can store string or integer type variable. But what we need? we need to convert it into stream of byte. because as I already said , view state store information in hidden filed in the page. So we need to use Serialization. If object which we are trying to store in view state ,are not serializable , then we will get a error message .
Just take as example,

//Create a simple class and make it as Serializable
[Serializable]
public class student
{
    public int Roll;
    public string Name;
    public void AddStudent(int intRoll,int strName)
      {
        this.Roll=intRoll;
        this.Name=strName;
           }
}

Now we will try to store object of "Student" Class in a view state.

//Store Student Class in View State
student _objStudent = new student();
_objStudent.AddStudent(2, "Abhijit");
ViewState["StudentObject"] = _objStudent;

//Retrieve Student information view state
 student _objStudent;
_objStudent = (student)ViewState["StudentObject"];

How to trace your view state information

If you want to trace your view state information, by just enable "Trace" option of Page Directive

<% Language=”C#” AutoEventWireup=”true”  Trace=”ture” %>

Now Run your web application, You can view the details of View State Size along with control ID inControl Tree Section. Don't worry about "Render Size Byte" , this only the size of rendered control.
Enabling and Disabling View State
You can enable and disable View state for a single control as well as at page level also. To turn off view state for a single control , set EnableViewState Property of that control to false. e.g:

TextBox1.EnableViewState =false;

To turnoff the view state of entire page, we need to set EnableViewState to false of Page Directive as shown bellow.

<% Language=”C#” enbleviewsate=’’false”

Even you disable view state for the entire page , you will see the hidden view state tag with a small amount of information,
ASP.NET always store the controls hierarchy for the page at minimum , even if view state is disabled.For enabling the same, you have to use the same property just set them as True as for example, for a single control we can enabled view state in following way,

TextBox1.EnableViewState =true;

and for a page level, 
<% Language=”C#” enbleviewsate=’’ture”

How to make view state secure

As I already discuss View state information is stored in a hidden filed in a form of Base64 EncodingString, and it looks like:

<input type=”hidden” id=”_viewstate” name=”viewstate” value=”dsfefgbgigguwgbdbwqwugyucffvufebcbenhgbc”/>

Many of ASP.NET Programmers assume that this is an Encrypted format, but I am saying it again, that this is not a encrypted string. It can be break easily. To make your view state secure, There are two option for that,
•           First, you can make sure that the view state information is tamper-proof by using "hash code". You can do this by adding "EnableViewStateMAC=true" with your page directive. MAC Stands for "Message Authentication Code"

<% Language=”C#” enbleviewsate=’’ture” enbleviewsate mac=”true”

A hash code , is a cryptographically strong checksum, which is calculated by ASP.NET and its added with the view state content and stored in hidden filed. At the time of next post back, the checksum data again verified , if there are some mismatch, Post back will be rejected. we can set this property to web.config file also.
•           Second option is to set ViewStateEncryptionMode="Always" with your page directives, which will encrypt the view
state data. You can add this in following way

<% Language=”C#” enbleviewsate=’’ture”  ViewStateEncrypsationMode=”Always”

It ViewStateEncryptionMode has three different options to set:
•           Always
•           Auto
•           Never
 Always, mean encrypt the view state always, Never means, Never encrypt the view state data and AutoSays , encrypt
if any control request specially for encryption. For auto , control must callPage.RegisterRequiresViewStateEncryption() method for request encryption.

•           we can set the Setting for "EnableViewStateMAC" and ViewStateEncryptionMode" in web.configalso.

<System>
<page EnbleViewtateMac=’’true’’ ViewstateEncrypationMode=’’Always’’>
</page></System>

Note : Try to avoid View State Encryption if not necessary , because it cause the performance issue.

Wednesday, April 17, 2013

Why Use WCF


Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for your services, enabling you to expose CLR types as services, and to consume other services as CLR types.

Its forthcoming microsoft technology for service-oriented applications, is designed to address these requirements. WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on operation systems that support it.
Lets me share my project live example scenario to understand WCF working in practical computing world.
To get a sense WHEN to use WCF let me engage you in a problems that WCF addresses, suppose that a car rental firm decides to create a new application for reserving cars. Since this application will run on Windows, the firm chooses to build it on version 2.0 of the .NET Framework. The architects of this rental car reservation application know that the business logic it implements will need to be accessible by other software running both inside and outside their company. Accordingly, its decided to build it in a service-oriented style, with the application’s logic exposed to other software through a well-defined set of services. To implement these services, and thus communicate with other software, the new application will use WCF.
Below is architecture of proposed system. 


Over its lifetime, the rental car reservation application will likely be accessed by a range of other applications. When it’s designed, however,its thought  of the rental car reservation application know that its business logic will be accessed, as shown in the figure above, by three other kinds of software

1) A call center client application running on Windows desktops that will be used by employees in the organization’s call center. Created specifically for the new reservations system, this application will also be built using the .NET Framework and WCF. (In some sense, this application isn’t truly distinct from the new rental car reservation application, since its only purpose is to act as a client for the new system. Still, from a service-oriented perspective, it’s just another client for the reservation system’s business logic.)

2) An existing reservation application built on a J2EE server running on a non-Windows system. Due to a recent merger with another car rental firm, this existing system must be able to access the new application’s logic to provide customers of the merged firms with a unified experience. Partner applications running on a variety of platforms, each located within a company that has a business arrangement with the car rental firm. Partners might include travel agencies, airlines and others that have a business requirement to make car rental reservations.

The diverse communication requirements for the new rental car reservation application aren’t simple. For interactions with the call center client application, for instance, performance is paramount, while interoperability is straightforward, since both are built on the .NET Framework.
For communication with the existing J2EE-based reservation application and with the diverse partner applications, however, interoperability becomes the highest goal. The security requirements are also quite different, varying across local Windows-based applications, a J2EE-based application running on another operating system, and a variety of partner applications coming in across the Internet.
Even transactional requirements might vary, with only the internal applications being allowed to make transactional requests.
So the question is how can we in given  diverse business and technical requirements be met without exposing the creators of the new application to unmanageable complexity? The answer to this question is WCF. Designed for exactly this kind of diverse but realistic scenario, WCF will be the default technology for Windows applications that expose and access services.So here i will introduce to  an introduction to WCF, examining what it provides and showing how it’s used. Throughout this introduction, the scenario just described will serve as an example. The goal is to make clear what WCF is, show what problems it solves, and illustrate how it solves those problems.
Addressing the Problem: WHAT WCF Provides:
The foundation for new Windows-based applications is the .NET Framework. Accordingly, WCF is implemented primarily as a set of classes on top of the .NET Framework’s Common Language Runtime (CLR). Because it extends their familiar environment, WCF allows developers who create object-oriented applications using the .NET Framework today to also build service-oriented applications in a familiar way.


he figure above shows a simple view of a WCF client and service. The two interact via SOAP, WCF’s native protocol, so even though the figure shows both parties built on WCF, this certainly is not required.  WCF addresses a range of problems for communicating applications.
1) Unification of existing .NET Framework communication technologies
2) Support for cross-vendor interoperability, including reliability, security, and transactions.
Let us try to understand each benefit of WCF one by one below;
A) Unification of Microsoft’s Distributed Computing Technologies.
Think about the team of developers implementing the rental car reservation application described earlier. In the absence of WCF, this team would need to choose the right distributed technology from the multiple choices offered by the .NET Framework. Yet given the diverse requirements of this application, no single technology would fit the bill. Instead, the application would probably use multiple existing .NET technologies. For example:

1) ASMX, also called ASP.NET Web Services, would be an option for communicating with the J2EE-based existing reservation application and with the partner applications across the Internet. Given that basic Web services are supported today on most platforms, this would likely be the most direct way to achieve cross-vendor interoperability.

2) .NET Remoting is a natural choice for communication with the call center application, since both are built on the .NET Framework. Remoting is designed expressly for .NET-to-.NET communication, so it would offer the best performance for this situation.

3) Enterprise Services (the successor to COM+) might be used by the rental car reservation application for things such as managing object lifetimes and defining distributed transactions. These functions could be useful in communicating with any of the other applications in this scenario, but Enterprise Services supports only a limited set of communication protocols.

4) Web Services Enhancements (WSE) could be used along with ASMX to communicate with the J2EE-based reservation application and with the partner applications. Because it implements more recently defined Web services agreements, known collectively as the WS-* specifications, WSE can allow better security and more, as long as all applications involved support compatible versions of these new specifications.

5) Microsoft Message Queuing (MSMQ) could be used to communicate with Windows-based partner applications that weren’t always available. The persistent queuing that MSMQ provides is typically the best solution for intermittently connected applications.
If it were built on today’s .NET Framework, the rental car reservation application would need to use more than one of these communication technologies, and maybe even all five, to meet its requirements. Although this is technically possible, the resulting application would be complex to implement and challenging to maintain. A better solution is needed.

With WCF, this solution is at hand. As the figure above shows it also compliments WHY to use it. WCF can be used for all the situations described above. Accordingly, the rental car reservation application can use this single technology for all its application-to-application communication. Here’s how WCF addresses each of these requirements:
1) Because WCF can communicate using Web services, interoperability with other platforms that also support SOAP, such as the leading J2EE-based application servers, is straightforward.

2) To allow optimal performance when both parties in a communication are built on WCF, the wire encoding used in this case is an optimized binary version of SOAP. Messages still conform to the data structure of a SOAP message, referred to as its Infoset, but their encoding uses a binary representation of that Infoset rather than the standard angle-brackets-and-text format of XML. Using this option would make sense for communicating with the call center client application, since it’s also built on WCF, and performance is a paramount concern.

3) Managing object lifetimes, defining distributed transactions, and other aspects of Enterprise Services are now provided by WCF. They are available to any WCF-based application, which means that the rental car reservation application can use them with any of the other applications it communicates with.

4) Because it supports a large set of the WS-* specifications, WCF helps provide reliability, security, and transactions when communicating with any platform that also supports these specifications.

5) WCF’s option for queued messaging, built on MSMQ, allows applications to use persistent queuing without needing to use another set of application programming interfaces.
The result of this unification is greater functionality and significantly reduced complexity. Because WCF allows an application to address all the communication requirements listed earlier, it can easily support scenarios that were difficult (or even impossible) with the collection of technologies that preceded it. While Microsoft will still support these earlier technologies, most new applications that would previously have used any of them will instead be built on WCF.
B) Interoperability with Other Web Services Platforms.
Enterprises today typically have systems and applications that were purchased from a range of vendors. In the rental car application, for instance, communication is required with various other software applications written in various languages and running on various operating systems. This kind of diversity is the reality in most organizations, and it will remain so for the foreseeable future.
Because WCF’s fundamental communication mechanism is SOAP, WCF-based applications can communicate with other software running in a variety of contexts. As shown in the figure below, an application built on WCF can interact with all of the following:

1) WCF-based applications running in a different process on the same Windows machine

2) WCF-based applications running on another Windows machine

3) Applications built on other technologies, such as J2EE application servers, that support standard Web services. These applications can be running on Windows machines or on machines running other operating systems, such as Sun Solaris, IBM z/OS, or Linux.


To allow more than just basic communication, WCF implements Web services technologies defined by the WS-* specifications. All of these specifications were originally defined by Microsoft, IBM, and other vendors working together. As in the figure below, these specifications address several areas, including basic messaging, security, reliability, transactions, and working with a service’s metadata



WCF supports all the specifications shown in this figure. Grouped by function, those specs are:

1) Messaging: SOAP is the foundation protocol for Web services, defining a basic envelope containing a header and a body. WS-Addressing defines additions to the SOAP header for addressing SOAP messages, which frees SOAP from relying on the underlying transport protocol, such as HTTP, to carry addressing information. The Message Transmission Optimization Mechanism (MTOM) defines an optimized transmission format for SOAP messages based on the XML-binary Optimized Packaging (XOP) specification.

2) Metadata: The Web Services Description Language (WSDL) defines a standard language for specifying services and various aspects of how those services can be used. WS-Policy allows specification of more dynamic aspects of a service’s behavior that cannot be expressed in WSDL, such as a preferred security option. WS-MetadataExchange allows a client to directly request descriptive information about a service, such as its WSDL and its policies, via SOAP.

3) Security: WS-Security, WS-Trust and WS-SecureConversation all define additions to SOAP messages for providing authentication, data integrity, data privacy and other security features.

4) Reliability: WS-ReliableMessaging defines additions to the SOAP header that allow reliable end-to-end communication, even when one or more SOAP intermediaries must be traversed.

5) Transactions: Built on WS-Coordination, WS-AtomicTransaction allows using two-phase commit transactions with SOAP-based exchanges
The rental car reservation application would likely use several of these more advanced technologies. For example, WS-Addressing is essential whenever SOAP is running over a protocol other than HTTP, which might be the case for communication with the .NET
Going back to our problem with designing framework-based call center client application, below we see how these specifications addressed the concerns;
WCF relies on WS-Policy and WS-MetadataExchange to discover whether the system it’s communicating with is also using WCF and for other things.
Reliable communication is essential for most situations, so it’s likely that WS-ReliableMessaging would be used to interact with many of the other applications in this scenario.
Similarly, WS-Security and the related specifications might also be used for communication with one or more of the applications, since all would require some kind of security.
For the applications that are allowed to use transactions with the rental car reservation system, WS-AtomicTransaction would be essential. Finally, MTOM could be used whenever an optimized wire format made sense, and both sides of the communication supported this option.

The key point is that WCF implements interoperable Web services, complete with cross-platform security, reliability, transactions, and more. To avoid paying an unnecessary performance penalty, WCF-to-WCF communication is optimized, but all other communication uses standard Web services protocols on the wire.

Friday, April 5, 2013

Difference between Delegate and Interface


1.Delegates can only be methods. Here is an example:
delegate void sampleDelegate();

Interface can include both properties and methods.
Here is an example for an interface:

interface ItestInterface
{
int paraml {
get; set; }
void sampleMethod();
}

2. Delegate can be applied to only one method at a time When a class implements an interface, it can implement all the methods associated with it

3. You can use a delegate that is visible in your scope
You can use an interface only when your class or struct implements it

4. Within a class, you can implement the same delegate any number of times. Assume that either sampleClass1 or sampleClass2 of Examplel includes a method called sampleMethod2( ) with the same signature as that of delegate, then the same delegate can be used to access both sampleMethod() as well as sampleMethod2( )
Within a class, you can implement an interface method only once. In Example2, interface ITestInterface has a method called sampleMethod(). When sampleClass1 implements ITestInterface it implements sampleMethod() only once. If not, then it will end up in error.

5. Delegate can implement any method that shares the same signature as that of the delegate When an interface method is implemented, same method name and signature has to be overridden.

6. Delegate is mainly used for handling events
Interfaces are not used for handling events

7. You need not bother about the other methods available in the class.You are concerned about only the method that matches delegate signature.
When a class implements an interface, though the class requires only one method it has to implement all the methods of the interface

8. To access a method using delegate, you need not require any access to the instance of the class where the method is defined
To access the method, you need an instance of the class which implements the interface or you need an interface reference pointing to the method implemented by the class

9.You can access anonymous methods using delegates
You cannot access anonymous methods.Only named methods declared in interface can be accessed by the implementing class.

10.When you call a method using a delegate, all the method pointers associated with the delegate will be scanned through before the method execution. This is not a direct method call as you assume. It has a considerable performance overhead.
When you are calling a method using interface reference, you are directly accessing the method of the class that implements the interface. This is a direct method call and it doesn't have any overhead.

11. Delegates can wrap methods of sealed classes.Sealed classes are those which cannot be inherited.Accessing sealed types is not permissible in interface.

12. Delegates can wrap any method matching its signature irrespective of which ever class the method belongs to.
Class can implement any number of interfaces and it should override only the methods belonging to those interfaces

13. Delegates can wrap static methods. Examplel discussed above has used the delegate to wrap a static method called sampleMethod()
This provision is not available with interfaces .

14. Delegate cannot involve in inheritance.
Interface can inherit other interfaces. When a class implements that interface, it has to implement all the methods belonging to the interface and its inherited interfaces as well.
Here is an example of an interface inheriting from other interfaces:
interface IInterface: IInterface,1 IInterface2
{
void sampleMethod1();
void sampleMethod2();
}