Wednesday, October 6, 2010

Service Design Considerations

 (Excerpts from Application Architecture Guide 2.0a)

Services are flexible by nature and can be used in a wide variety of scenarios and combinations.
The following are key typical scenarios:
• Service exposed over the Internet. This scenario describes a service that is consumed over
the Internet. Decisions on authentication and authorization must be based on Internet trust
boundaries and credentials options. For example, username authentication is more likely in
the Internet scenario than the intranet scenario. This scenario includes business-to-business
(B2B) as well as consumer-focused services. A Web site that allows you to schedule visits to
your family doctor would be an example of this scenario.
• Service exposed over an intranet. This scenario describes a service that is consumed over
an intranet. Decisions on authentication and authorization must be based on intranet trust
boundaries and credentials options. For example, the Microsoft® Active Directory®
directory service is more likely to be the chosen user store in the intranet scenario than in the
Internet scenario. An enterprise Web-mail application would be an example of this scenario.
• Service exposed on the local machine. This scenario describes a service that is consumed
by an application on the local machine. Transport and message-protection decisions must
be based on local machine trust boundaries and users.
• Mixed scenario. This scenario describes a service that is consumed by multiple applications
over the Internet, an intranet, and/or the local machine. A line-of-business (LOB) application
that is consumed internally by a thick client application and over the Internet by a Web
application would be an example of this scenario.

Design Considerations

When designing service-based applications, you should follow the general guidelines that apply
to all services, such as designing for coarse-grained operations, honoring the service contract,
and anticipating invalid requests or invalid request orders. In addition to the general guidelines,
there are specific guidelines that you should follow for different types of services. For example,
with a Service-Oriented Architecture (SOA), you should ensure that the operations are
application-scoped and that the service is autonomous. Alternatively, you might have an
application that provides workflow services, or you might be designing an operational data
store (ODS) that provides a service-based interface.

General Considerations

Design coarse-grained operations. Avoid chatty calls to the service interface, which can
lead to very poor performance. Instead, use the Façade pattern to package smaller fine-grained
operations into single coarse-grained operations.
Design entities for extensibility. Data contracts should be designed so that you can extend
them without affecting consumers of the service.
Compose entities from standard elements. When possible, compose the complex types
used by your service from standard elements.
Design without the assumption that you know who the client is. You should not make
assumptions about the client, and how they plan to use the service you provide.
Design only for the service contract. Do not implement functionality that is not reflected by
the service contract. In addition, the implementation of a service should never be exposed
to external consumers.
Design to assume the possibility of invalid requests. Never assume that all messages
received by the service are valid.
Separate functional business concerns from infrastructure operational concerns. Crosscutting
logic should never be combined with application logic. Doing so can lead to
implementations that are difficult to extend and maintain.
Ensure that the service can detect and manage repeated messages (idempotency). When
designing the service, implement well-known patterns, or take advantage of infrastructure
services, to ensure that duplicate messages are not processed.
Ensure that the service can manage messages arriving out of order (commutativity). If
there is a possibility that messages might arrive out of order, implement a design that will
store messages and then process them in the correct order.


SOA Services Considerations

Design services to be application-scoped and not component-scoped. Service operations
should be coarse-grained and focused on application operations. For example, with
demographics data, you should provide an operation that returns all of the data in one call.
You should not use multiple operations to return subsets of the data with multiple calls.
• Decouple the interface from the implementation. In an SOA application, it is very
important to keep internal business entities hidden from external clients. In other words,
you should never define a service interface that exposes internal business entities. Instead,
the service interface should be based on a contract with which external consumers interact.
Inside the service implementation, you translate between internal business entities and
external contracts.
Design services with explicit boundaries. A services application should be self-contained,
with strict boundaries. Access to the service should only be allowed through the service
interface layer.
Design services to be autonomous. Services should not require anything from consumers of
the service, and should not assume who the consumer is. In addition, you should design
services with the assumption that malformed requests will be sent to it.
Design compatibility based on policy. The service should publish a policy that describes
how consumers can interact with the service. This is more important for public services,
where consumers can examine the policy to determine interaction requirements.

Data Services Considerations

Avoid using services to expose individual tables in a database. This will lead to chatty
service calls and interdependencies between service operations, which can lead to
dependency issues for consumers of the service.
Do not implement business rules with data services. Different consumers of the data will
have unique viewpoints and rules. Attempting to implement rules in data access services
will impose restrictions on the use of that data.

Workflow Services Considerations

Use interfaces supported by your workflow engine. Attempting to create custom interfaces
can restrict the types of operations supported, and will increase the effort required to
extend and maintain the services.
• Design a service that is dedicated to supporting workflow. Instead of adding workflow
services to an existing service application, consider designing an autonomous service that
supports only workflow requirements.

Securing websites from Penentration test

  1. SQL injection
    1.  Use stored procedures , use parameterized dynamic SQL queries
    2. Sanitize input parameters which are coming from UI before feeding them into stored procedures or dynamic SQL statements 
      1. Use stored procedures as you can
      2. Use parametrized in-line SQL query
      3. SQL safe your queries by : Replace("'","''").Replace(";","")
  2.  Cross site scripting 
    1. Securing cookies
    2. Turning off cross site scripting HttpOnly 
    3. HTML encoding all user inputs before storing in DB
  3. Prevent file system traversal
    1. Allowing filenames containing “../..” could allow the hacker to traverse through file system
  4.  IIS 6 vulnerabilities on file extensions 
    1. Filename.asp.jpg is ran as an asp page!
    2. Keep your web servers up-to-date  with OS patches




Related Links:
  1. http://www.owasp.org/index.php/Main_Page
  2. http://msdn.microsoft.com/en-us/library/ff649310.aspx

Tuesday, August 24, 2010

Tour the JQuery Framework


I found an interesting article about JQuery on DevProConnection magazine (below link):

Getting Started with jQuery
The first step in unleashing jQuery's power is to download the beast. You can download jQuery here. Just like any other JavaScript library, jQuery needs to be referenced before it is used. You can set up the reference in a page's head section, as in the following example:
After referring the library, you are now ready to use it. To understand the workings of the library, we'll start with a very simple application that alerts the type of DIV element on screen. The alert will be invoked when the user clicks the button. The following snippet uses the plain-vanilla JavaScript to accomplish the task.
<script language="javascript" type="text/javascript">

function greetings() {
alert($("#display"));
 }
</script><o:p></o:p></pre>
<div style="margin-bottom: 12pt;">

As expected, the alert box in Figure 1 clearly shows that the object is of type HTMLDivElement, which refers to a DIV element in the DOM tree.

Next, we'll implement the same scenario using the jQuery library, as shown in the following code sample, and examine how it differs from the previous one.
<input onclick="greetings()" type="button" value="Greet" />

<div id="display">
</div>
<script language="javascript" type="text/javascript">

 function greetings() {
    alert($("#display"));
}
</script>

Figure 2 shows the result: The object returned is not of the type HTMLDivElement but an object. By investigating further, you'll realize that the object is of type jQuery. This is where the jQuery library really shines. Instead of returning the type of the DOM element that was requested, the jQuery library returns the jQuery object. The jQuery object contains many different functions and attributes that can be used in different scenarios. This also makes it easy to add custom plug-ins to the jQuery library.

jQuery Syntax
jQuery uses a combination of XPath and CSS selector syntax to access elements inside the DOM tree. The selector syntax allows jQuery to manipulate the HTML elements as a group or as an individual element. Take a look at the following selectors in jQuery that are most commonly used in an application.

Fetching by element ID: The hash (#) sign is used to fetch the element using the element ID. This is the equivalent of using the document.getElementById function. For example:
$("#myTextBoxId")  //

returns the control whose ID is myTextBoxId.

Fetching by class name: The period (.) operator is used to retrieve the element by using the class name. For example:
$(".greenColorTextBoxes") //

returns all the controls whose class name is greenColorTextboxes.

Fetching by element type. The element tag name indicates that the element will be fetched by its type. This is equivalent to using the document.getElementsByTagName function. For example:
$("p") //

returns all the p elements on the page.
$("p.display")

returns the
element with the class display.

$("p#display") returns the first
element with the ID display.

jQuery uses the XPath syntax to select elements using their attributes:
•    $("[href]") selects all the elements having the href attribute.
•    $("[href='#']) selects all the elements having the href attribute #.
•    $("[src='.jpg']") selects all the image elements with the source attribute ending in .jpg.

Now that you're familiar with different retrieval strategies using the jQuery library, we'll move on to discussing how to use jQuery effects.

Effects in jQuery
The jQuery framework comes with several built-in effects. If you need to create more advanced effects, you can do so using the jQuery UI library, which you can download at jqueryui.com. The effects that alter the appearance of elements are mostly UI based. The code in Figure 3 uses the built-in effect to show and hide a div element.

Creating animation effects. There are times when jQuery built-in effects are not enough. In such cases, you can use the power of jQuery's animation class, which lets you create custom animations. The animation can be performed on properties consisting of numerical values—for example, width, height, and margin. You can even perform animation on color properties by assigning the color in the color code format. The following example shows how to perform animation on a simple DIV control and change its width property.
  $(document).ready(function() {

        $("#btnAnimate").click(function() {

            $(".block").animate(

            {

                width:"100%"

            }

            );

    });

});

You can even move the DIV across the screen using the marginLeft and marginRight properties, as the following example shows:
  $(document).ready(function() {

        $("#btnAnimate").click(function() {

            $(".block").animate(

            {

                marginLeft:"40%"

            }

            );

    });

});




jQuery can also manipulate color properties of the element if they're used in the form of color codes instead of names, as you can see in the following example. Note that the color animation works only when the jQuery UI reference is added (as mentioned previously).
$(document).ready(function() {

        $("#btnAnimate").click(function() {

            $(".block").animate(

            {

                marginLeft:"40%",

                backgroundColor:'#ffbfff'

            }

            );

    });

});

The previous code also demonstrates the use of multiple properties in the animation function. The animation function provides most of the features to create custom animation, but sometimes we need to plug in our custom animation function in the jQuery framework. In the next section, I'll show you how to extend the existing jQuery functions and how to successfully add your own behavior.

Creating Custom Effects by Extending jQuery
jQuery is an open extension framework that enables developers to easily extend the functionality in the existing the API. For instance, if you're interested in creating a FadeInFadeOut effect, you can easily extend the jQuery.fn class to include new methods and add custom behavior. Take a look at the following code, which demonstrates how to extend jQuery.fn to include FadeInFadeOut effects.
jQuery.fn.fadeInFadeOut = function(speed) {

        return $(this).fadeIn(speed,

        function() {

            return $(this).fadeOut(speed);

         });

    }

Finally, we can use our new function by employing the following code:
$("#divMessage").html("Item has been saved").fadeInFadeOut(3000);

This shows how easy it is to leverage the existing jQuery functionality and create new effects.

Drag-and-Drop Operations Using jQuery
If you've ever written plain old vanilla JavaScript to create drag-and-drop effects, you're aware of the pain you need to go through to make it work. jQuery makes it easy to perform drag-and-drop operations. The drag-and-drop operations are contained in the jQuery.UI framework.

The first task in implementing jQuery drag and drop is to create a draggable item. We will be dragging a simple DIV element. The definition of the DIV element is as follows:

The DIV uses the style "draggableElement" defined by the following code:
  .draggedElement

    {

 

   border: 2px solid #0090DF;

   background-color: #68BFEF;

   width: 100px;

   height: 100px;

   margin: 10px;

   overflow:auto;

   padding:1em 1em 1em 1em;

   z-index:9999;

   cursor:move;



    }

Next, to make the DIV draggable we need to use the jQuery draggable function. Here's the implementation:

And that's it! Now run the application in your browser, and you'll be amazed that by adding a single line of code you can drag the element.

Although we are able to drag the DIV element, we're dragging the original element. In most cases you do not want to drag the original element but the clone. Not to worry, since jQuery provides attributes to add this feature. To make a clone of the dragged element, just use the helper attribute, as in the following example:

This code creates a clone of the dragged element, which is easily visible because of the opacity. Figure 4 shows the clone of the dragged element.

At this point we have implemented only the functionality for the dragged element. But this is only half of the story. The dragged element eventually needs to be dropped. This is where drop zones come into action. A drop zone is an area where a draggable element can be dropped. Creating a drop zone is straightforward, as it can be represented by a simple DIV element:
$(".dropZone").droppable();

The .dropZone class is used to decorate the drop zone with styling features:
  .dropZone

   {

           background-color: #e9b96e;

 border: 3px double #c17d11;

   width: 300px;

   height: 300px;

   margin: 10px;

   overflow:auto;

   position:absolute;

  top: 5px;

  right: 30%;

  padding: 1em 0 0 0;

  

   }

Just as we initialized the draggable element, we need to initialize the drop zone. This is accomplished by using a single line of code:
$(".dropZone").droppable();

Although the drop zone has been initialized, we still need to provide it with additional information so that it knows what kinds of elements are accepted in the drop zone. The following code accomplishes this:
        $(".dropZone").droppable(



        {

            accept: '.draggedElement',

            hoverClass: 'dropZoneHover',

            drop: function(ev, ui) {

            }

        }

        );

The accept attribute represents the class that is accepted by the drop zone. This means any element having class draggedElement can be dropped into the drop zone. The hoverClass attribute represents the class that will become active once the draggable element hovers over the drop zone. Take a look at Figure 5, which shows the drop zone becoming active once the draggable element hovers over it.



Now, let's take a look at the most important feature of the drop zone, the drop function:
$(".dropZone").droppable(



        {

            accept: '.draggedElement',

            hoverClass: 'dropZoneHover',

            drop: function(ev, ui) {

                var droppedItem = ui.draggable.clone().addClass("droppedItemStyle");

                $(this).append(droppedItem);

             }

        }

        );

Inside the droppable function, we have used JavaScript closures to handle the drop event. The $(this) refers to the DIV element that acts as a "DropZone" and is consuming the ".dropZone" class. The dropped item is decorated with droppedItemStyle. Once the dropped element is dropped, it is added to the drop zone element as a child. Figure 6 shows the dropped element added in the drop zone.

The jQuery drag-and-drop API is very useful for creating interactive applications. The ease of use of the drag-and-drop framework lets a developer build complicated client-side applications more quickly.

jQuery AJAX API
jQuery not only provides a strong DOM manipulation library, it also includes a very handy AJAX API. jQuery provides a couple different methods to make an AJAX call, as I'll demonstrate.

The $.ajax function is the most flexible of all jQuery AJAX functions, since it allows a developer to indicate the options manually. Here is a small piece of code that invokes the Greetings web service method and returns a message to the user.
$(document).ready(function() {

        $("#btnGreet").click(function() {

            $.ajax(

            {

                type: "POST",

                contentType: "application/json",

                data: "{}",

                dataType: "json",

                url:"AjaxService.asmx/Greeting",

                success: function(response) {



                    alert(response.d);

                 }

            }

    );

The $.ajax function defined in this code calls the Greeting method contained in the AjaxService.asmx web service. Here's the implementation of the web service:
  [System.Web.Script.Services.ScriptService]

    public class AjaxService : System.Web.Services.WebService

    {

        [WebMethod]

        public string Greeting()

        {

            return "Hello World";

        }

    }

Greeting is a simple method decorated with the [WebMethod] attribute. Another important thing to note about the AjaxService is that it's decorated with the [System.Web.Script.Services.ScriptService] attribute, which allows the web service to be called from the client-side code. Figure 7 shows the result.

You can also return XML just by changing the contentType to support XML, as shown by the following:
$(document).ready(function() {

        $("#btnGreet").click(function() {

            $.ajax(

            {

                type: "POST",

                contentType: "application/xml",

                data: "",

                dataType: "xml",

                url:"AjaxService.asmx/Greeting",

                success: function(response) {

                    alert(response.childNodes\[0].firstChild.textContent);

                 }

            }

    );

It's a good idea to return the result as JSON format. JSON makes it easy to parse the object and usually represents the structure similar to the domain model.

Sending Parameters Using jQuery's AJAX API
In the previous examples, we invoked the methods and returning the results on the client side without sending any input parameters. In real-world applications, our result will depend on the parameters passed to the web method.

In the following example, our result will be based on the parameters sent by the client. We'll use the SQL Server Northwind database, since it's available on most machines. A user will be allowed to select a category from the DropDownList. When the category is selected, the related products are fetched using an AJAX request.

The following code shows the implementation of the GetProductsByCategoryId. The example uses LINQ to SQL as the data access layer, but you may use whatever data access mechanism you want.
 [WebMethod]

        public string GetProductsByCategoryId(int categoryId)

        {

            var json = new JavaScriptSerializer();



            using(var db = new NorthwindDataContext())

            {

                var products = from p in db.Products

                               where p.CategoryID == categoryId

                               select p;



                foreach(var p in products)

                {

                    p.Category = null;  // removing the circular reference!

                }



                return json.Serialize(products);

            }

        }




The JavaScriptSerializer object has a limitation in that it cannot detect and ignore the circular references. For this reason, I've manually eliminated the circular references by setting the Category object to null. You can also return an anonymous type with the required properties to the client.

Figure 8 shows the implementation of the getProducts function, which is used to fire the AJAX request and create the product list display. In the code in Figure 8, note that the name of the parameters matches exactly with the parameter names of the web method. This means that if the web method parameter is called categoryId, then the AJAX call should specify categoryId as the parameter. Additionally, we've used a jQuery plug-in to evaluate the JSON string as an Object. Figure 9 shows the output.

jQuery Support in Visual Studio 2010
The jQuery library is already supported in Visual Studio 2008, but to get the IntelliSense feature working, you need to download a Meta file and place it in a special location. In Visual Studio 2010 jQuery is treated as a first-class citizen, and the IntelliSense support is activated by default. This creates an easy way for developers to discover the jQuery API without having to refer to the documentation.

Wrapping Up
jQuery is a fascinating JavaScript library that has grown exponentially since its inception in 2006. In 2008 Microsoft embraced the popularity of this powerful library by giving it space in Visual Studio. jQuery's ease of use and advanced UI-manipulation features put it at the top of the stack of your choices of a client-side framework for any web application.


Friday, June 4, 2010

Optimizing ASP .NET web application (brief checklist)


Optimizing ASP .NET web application (brief checklist)

1-      Performance Monitor
a.       Add Counters such as ASP .NET set of counters
b.      Requests per session
2-      Key Design considerations
a.       Design with performance in mind
b.      Consider security and performance
c.       Consider n-tier architecture
d.      Use caching (Enterprise library caching application block, ASP .NET caching)
3-      Minimize  database connections
a.       Use built-in connection pooling
b.      Store one connection string in web.config

4-      Turn off view state
5-      Usage of Session state
a.       In-proc  session state: Most efficient
b.      Session state server
c.       SQL session state
6-      Compile with release
Set debug to “false”

Set debug=false> in production, in root webconfig or machine config
You can also use below configuration to override anywhere that set’s :

in configuration
    system.web
          deployment retail=”true”
    system.web
configuration


7-      Use NGen
8-      Use Server.Transfer rather than Response.Redirect


SQL  Server performance tuning

1-      Set proper table indexes
a.       Use SQL profiler index Tuning Wizard
b.      Use SQL query analyzer to check execution plans
2-      Write good queries
a.       Use stored procs. not ad hoc SQL , (parameterized ad-hoc queries are also okay but when you can’t do the job with a proc)
b.      Avoid Distinct, and non-index where clauses
c.       Return only what you need  (avoid select * …)
3-      Performance Monitoring and logging
a.       Create permon logs


Monday, May 24, 2010

Debugging Windows processes


Debugging Windows processes
Last week I had to spend most of my time figuring out why an ASP .NET application CPU utilization hits 100%, I ended up learning how to take memory dumps and how to analyze them. Below is a summary of what I've learned.

Process of debugging using Win Debug/ADPlus( "C:\Program Files\Debugging Tools for Windows (x64)\windbg.exe")
This is for debugging a 64 bit .NET process with .NET CLR version 2.0.
You can also use DebugDiag ("C:\Program Files\DebugDiag\DebugDiag.exe") to take memory dumps and analyzing them in a more user friendly manner.
1-      Attach  to process
-          Attaching to process will cause freezing the process.
You can Use iisapp command line to resolve wpw3 processes and the app pools!threads
-          Hitting “g” for F5 unfreezes the process
-          Detach once you are done
-          Stop will kill the process

2-      Take a memory dump (freezes the process) , There are different types of dumps
1-      Full dump : when process is failed and on 100% CPU
.dump /ma c:\dump_05192010_2PM.dmp
2-      mini dumps: when you want to quickly attach to the process and get a quick memory dump and detach
adpPlus –quick –p process id –o outputPtath
adpPlus is installed with windebug and could be found in
“c:\program files(x86)\windebug” or  "C:\Program Files\Debugging Tools for Windows (x64)\ " folder

3-      Analyze the memory dump

1-      Load up the memory dump
1.       Open dump.
2.       Set symbol path
To : srv*c:\websymbols*http://msdl.microsoft.com/download/symbols
3.       Set image path: this path points to a folder which holds referenced Dll’s , this is usually needed when analyzing a in a mini dump
2-      Load SOS dll
1.       .load C:\WINDOWS\Microsoft.NET\Framework64\v2.0.50727\mscorwks.dll
2.       .loadby sos mscorwks

3-      Analyze by querying the memory dump
Things to look for in a memory dump analysis, all we have is call stacks and objects in memory (stack/heap).Stacks and memory objects could be viewed in two ways .NET CLR view of unmanaged view, most of below commands have an unmanaged version which outputs more detailed information regarding either call stack or objects.

1-      Threads
a.       List of Threads: command for this is !threads
b.      to find out exactly what the CPU-usage was at the time the dump was taken !threadpool
c.       This is a nice command that will list all running threads and their CPU-usage. It's your best friend when troubleshooting a high CPU hang issue.  !runaway

2-      Call stack(s):
 you can view call stack of a particular thread or all call stacks of the process
To view call stack of a thread:
1-      Go to the thread by command: ~[threaded]s : example : ~20s
2-      Run: !clrstack or !clrstack -p
kb is its native  version run  ~* kb 2000 to get all native stacks
                                       To view call stack of all threads:
~*e !clrstack (~*e kb is the unmanaged version)
3-      Memory objects:

1-      Content of heap memory :  !dumpheap
2-      View list of objects that are used by call stack: !dumpstackobjects
3-      To view content/value of a object in heap or stack object run: !do [memory address]

4-      Determine the ID of the thread owning the lock
!syncblk

Quick reference list of Windbg commands :
•    .cls : clear screen
•    ~*:  Native threadlist
•    ~* kb: Native call stack
•    !clrstack –a:
•    Analyze –v
•    Symbol : srv*c:\websymbols*http://msdl.microsoft.com/download/symbols
•    .load C:\WINDOWS\Microsoft.NET\Framework64\v2.0.50727\mscorwks.dll
•    .loadby sos mscorwks
•    !threads
    Get on a thread: ~threadIds : eg. ~20s
•    ~*e !clrstack
•    !dumpheap
•    !dumpheap -stat
•    !dumpstackobjects == !dso


Links:



Friday, April 9, 2010

Exceptions


Exception throwing guidelines described in this section require a good definition of the meaning of execution failure. Execution failure occurs whenever a member cannot do what it was designed to do (what the member name implies). For example, if OpenFile method cannot return an opened file handle to the caller, it would be considered an execution failure.
Most developers have become comfortable with using exceptions for hard error cases such as division by zero or null references. In the Framework, exceptions are used for both hard errors and logical errors. At first, it can be difficult to embrace exception handling as the means of reporting all functional failures. However, it is important to design all public methods of a framework to report method-failures by throwing an exception.
There are a variety of excuses for not using exceptions, but most boil down to the two perceptions that exception handling syntax is undesirable, so returning an error code is somehow preferable, or that a thrown exception does not perform as well as returning an error code. The performance concerns are addressed in the performance section below. The concern over syntax is largely a matter of familiarity and should not be a consideration. As an API designer we should not make assumptions about the familiarity of the application developers consuming our code. 
Do not return error codes. Exceptions are the primary means of reporting errors in frameworks.
Do report execution failures by throwing exceptions. If a member cannot successfully do what is designed to do, it should be considered an execution failure and an exception should be thrown.
Consider terminating the process by calling System.Environment.FailFast (.NET Framework 2.0 feature) instead of throwing an exception, if your code encounters a situation where it is unsafe for further execution.
Do not use exceptions for normal flow of control. Except for system failures, there should generally be a way to write code that avoids exceptions being thrown. For example, you can provide a way to check preconditions before calling a member to allow users to write code that does not throw exceptions.
ICollection collection = …
if(!collection.IsReadOnly){
    collection.Add(additionalNumber);
}
The member used to check preconditions of another member is often referred to as a tester and the member that actually does the work is called a doer. See performance section below for more information on the Tester-Doer Pattern.
There are cases when the Tester-Doer pattern may have an unacceptable performance overhead. In such cases the so called TryParse Pattern (see section below) should be used.
Consider performance implications of throwing exceptions. See section below for details.
Do document all exceptions thrown by publicly callable members because of a violation of the member contract (rather than a system failure) and treat them as part of your contract. Exceptions that are a part of the contract should not change from one version to the next.
Do not have public members that can either throw or not based on some option.
Type GetType(string name, bool throwOnError)
Do not have public members that return exceptions as the return value or an out parameter.
Do set all the relevant properties of the exception you throw.
Consider using exception builder methods. It is common to throw the same exception from different places. To avoid code bloat, use helper methods that create exceptions and initialize their properties. For example:
class File{
   string fileName;

   public byte[] Read(int bytes){
      if (!ReadFile(handle, bytes))
            throw NewFileIOException(...);
   }

   FileException NewFileException(...){
      string description = // build localized string
      return new FileException(description);
   }
}
Do not throw exceptions from exception filter blocks. When an exception filter raises an exception, the exception is caught by the CLR, and the filter returns false. This behavior is indistinguishable from the filter executing and returning false explicitly and is therefore very difficult to debug.
Avoid explicitly throwing exceptions from finally blocks. Implicitly thrown exceptions resulting from calling methods that throw are acceptable. 



Designing Custom Exceptions
In some cases, it will not be possible to use existing exceptions. In those cases, you’ll need to define custom exceptions. The guidelines in this section provide help on doing that.
Avoid deep exception hierarchies. 
Do derive exceptions from System.Exception or one of the other common base Exceptions.
Do end exception class names with the ‘Exception’ suffix.
Do make exceptions serializable. An exception must be serializable to work correctly across application domain and remoting boundaries.
Do provide (at least) these common constructors on all exceptions. Make sure the names and types of the parameters are exactly as in the example below.
public class SomeException: Exception, ISerializable {
   public SomeException();
  public SomeException(string message);
  public SomeException(string message, Exception inner);

  // this constructor is needed for serialization.
   protected SomeException(SerializationInfo info, StreamingContext context);
}
Do report security sensitive information through an override of ToString only after demanding an appropriate permission.
If the permission demand fails, return a string excluding the security sensitive information.
Annotation (Rico Mariani):
Do not store the results of ToString in any generally accessible data structure unless that data structure suitably secures the string from untrusted code.  This advice applies to all strings but since exception strings frequently contain sensitive information (such a file paths) I reiterate the advice here.
Do store useful security sensitive information in private exception state. Ensure only trusted code can get the information.
Consider providing exception properties for programmatic access to extra information (besides the message string) relevant to the exception.


Application Exception :