<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-30591913</id><updated>2024-09-01T22:55:41.823+05:30</updated><title type='text'>Tech Articles</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><link rel='next' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default?start-index=26&amp;max-results=25&amp;redirect=false'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>46</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-30591913.post-55882068069984951</id><published>2011-12-21T13:24:00.002+05:30</published><updated>2011-12-21T13:24:40.612+05:30</updated><title type='text'>Using WS-Discovery in WCF 4.0</title><content type='html'>Runtime endpoint discovery is one of the most challenging capabilities to implement in service oriented systems. Dynamically resolving service’s endpoints based on predefined criteria is a necessary functionality to interact with services which endpoint addresses change frequently. WS-Discovery is an OASIS Standard that defines a lightweight discovery mechanism for discovering services based on multicast messages. Essentially, WS-Discovery enables a service to send a Hello announcement message when it is initialized and a Bye message when is removed from the network. Clients can discover services by multicasting a Probe message to which a service can reply with a ProbeMatch message containing the information necessary to contact the service. Additionally, clients can find services that have changed endpoint by issuing a Resolve message to which respond with a ResolveMatch message. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg3lOA9QNpPIz1H264mnQ_-SB-di5q0-BfGaEMrs3m2HdMCZlPBuvwZq3z5zg-Xt7x3O_HvLoWlxlHhPGbpzLsHsbdSka15VYa700ttS98Qd4KgFhTK4vZmHsZdjijz-DQX0Hkg/s1600/image_thumb.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;253&quot; oda=&quot;true&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg3lOA9QNpPIz1H264mnQ_-SB-di5q0-BfGaEMrs3m2HdMCZlPBuvwZq3z5zg-Xt7x3O_HvLoWlxlHhPGbpzLsHsbdSka15VYa700ttS98Qd4KgFhTK4vZmHsZdjijz-DQX0Hkg/s320/image_thumb.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
Contrary to other WS-* protocols, WS-Discovery has found a great adoption among the network device builders as it allows to streamline the interactions between these type of devices. For instance, a printer can use WS-Discovery to announce its presence on a network so that it can be discovered by the different applications that require printing documents. Windows Vista&#39;s contact location system is another example of a technology based on WS-Discovery. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The 4.0 release of Windows Communication Foundation includes an implementation of WS-Discovery that enables service’s endpoints as runtime discoverable artifacts. WCF enables the WS-Discovery capabilities in two fundamental models: Managed and Ad-Hoc. The managed mode assumes a centralized component called service proxy that serves as a persistent repository for all the services in a network. When a service is initialized it publishes its details to the discovery proxy so that it becomes accessible the the different clients in the network. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Contrary to the managed model, the Ad-Hoc mechanism does not rely on a centralized discovery proxy. In this model, services publish their presence in a network by multicasting announcement message that can be processed by the interested consumers. Additionally, clients can also multicast discover messages through the network in order to find a service that matches predefined criteria. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
WCF&#39;s WS-Discovery managed mode will be the subject on a future post. Today we would like to illustrate the details of enabling dynamic discovery using the WS-Discovery &#39;s Ad-Hoc model in WCF 4.0. This model is traditionally simpler to implement than the managed model although it can introduce some challenges from the management standpoint. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
WCF 4.0 abstracts the WS-Discovery Ad-Hoc model using the ServiceDiscoveryBehavior which indicates that a service can be discoverable and the UdpDiscoveryEndpoint that instantiates a service endpoint that can listen for discovery requests. The remaining of this post will provide a practical example of the use of the WS-Discovery Ad-Hoc model in WCF 4.0 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let’s start with the following WCF service. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
1: public class SampleService: ISampleService &lt;br /&gt;
2: { &lt;br /&gt;
3: public string Echo(string msg) &lt;br /&gt;
4: { &lt;br /&gt;
5: return msg; &lt;br /&gt;
6: } &lt;br /&gt;
7: }&lt;br /&gt;
&amp;nbsp;8:&lt;br /&gt;
&amp;nbsp;9: [ServiceContract]&lt;br /&gt;
&amp;nbsp;10: public interface ISampleService &lt;br /&gt;
11: { &lt;br /&gt;
12: [OperationContract]&lt;br /&gt;
&amp;nbsp;13: string Echo(string msg); &lt;br /&gt;
14: }&lt;br /&gt;
Figure: Sample WCF Service&lt;br /&gt;
&lt;br /&gt;
In order to make the service discoverable we first need to add the ServiceDiscoveryBehavior to the service behavior’s collection. As explained previously, this behavior indicates to the WCF runtime that the service supports the WS-Discovery protocol. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
1: using (ServiceHost host = new ServiceHost(typeof(SampleService), new Uri(base uri...))) &lt;br /&gt;
2: { &lt;br /&gt;
3: ... &lt;br /&gt;
4: &lt;br /&gt;
host.AddServiceEndpoint(typeof(ISampleService), new BasicHttpBinding(), String.Empty);&lt;br /&gt;
5: ServiceDiscoveryBehavior discoveryBehavior= new ServiceDiscoveryBehavior(); &lt;br /&gt;
6: host.Description.Behaviors.Add(discoveryBehavior); &lt;br /&gt;
7: ...&lt;br /&gt;
&amp;nbsp;8: }&lt;br /&gt;
&lt;br /&gt;
Figure: Adding the service discovery behavior &lt;br /&gt;
The next step is to add the UdpDiscoveryEndpoint to the list of service endpoints so that our service can start listening for WS-Discovery messages. &lt;br /&gt;
&lt;br /&gt;&lt;br /&gt;
1: host.AddServiceEndpoint(new UdpDiscoveryEndpoint());Figure: Adding an UDP discovery endpoint&lt;br /&gt;
&lt;br /&gt;
At this point our service is ready to receive and interpret WS-Discovery messages from the different clients on the network. However those clients are not yet aware of the existence of the service given that this one hasn’t published the Hello announcement message. We can accomplish this by simply adding a new UdpAnnoucement endpoint to the list of service endpoints. &lt;br /&gt;
&lt;br /&gt;
1: discoveryBehavior.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint());&lt;br /&gt;
&lt;br /&gt;
Figure: Adding an UDP announcement endpoint &lt;br /&gt;
&lt;br /&gt;
In order to dynamically discover services using the Ad-Hoc model, a WCF client instantiates a DiscoveryClient that uses discovery endpoint specifying where to send Probe or Resolve messages. The client then calls Find that specifies search criteria within a FindCriteria instance. If matching services are found, Find returns a collection of EndpointDiscoveryMetadata. The following code illustrates that concept. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
1: DiscoveryClient discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint()); &lt;br /&gt;
2: FindResponse discoveryResponse= discoveryClient.Find(new FindCriteria(typeof(ISampleService))); &lt;br /&gt;
3: EndpointAddress address = discoveryResponse.Endpoints[0].Address;&lt;br /&gt;
4:&lt;br /&gt;
5: SampleServiceClient service = new SampleServiceClient(new BasicHttpBinding(), address); &lt;br /&gt;
6: service.Echo(&quot;WS-Discovery test&quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Figure: WCF WS-Discovery client&lt;br /&gt;
&lt;br /&gt;
The WCF implementation of the WS-Discovery Ad-Hoc model presents various aspects that I think are worth highlighting. First, WCF uses specialized discovery and announcement endpoints to process WS-Discovery messages isolating them from the service’s messages. Additionally, the use of service behaviors allow developers to incorporate the WS-Discovery capabilities as they are required without interfering with the normal service functioning. Finally, WCF clients can simply use the discovery client to dynamically resolve the service endpoint without having to make major modifications to its business logic. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/55882068069984951/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/55882068069984951' title='27 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/55882068069984951'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/55882068069984951'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2011/12/using-ws-discovery-in-wcf-40.html' title='Using WS-Discovery in WCF 4.0'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg3lOA9QNpPIz1H264mnQ_-SB-di5q0-BfGaEMrs3m2HdMCZlPBuvwZq3z5zg-Xt7x3O_HvLoWlxlHhPGbpzLsHsbdSka15VYa700ttS98Qd4KgFhTK4vZmHsZdjijz-DQX0Hkg/s72-c/image_thumb.png" height="72" width="72"/><thr:total>27</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-1431372694714585965</id><published>2011-11-21T13:19:00.001+05:30</published><updated>2011-11-21T13:24:17.154+05:30</updated><title type='text'>Introduction to jQuery for ASP.NET</title><content type='html'>If you are keeping yourself updated with the latest in the .NET sphere, you are probably aware that Microsoft has provided an inbuilt support for jQuery in Visual Studio 2010. Though it was possible to use jQuery with ASP.NET even before VS 2010, formally including jQuery as a part of website created using VS2010 means that more and more developers are going to learn and use it. If you haven&#39;t tried jQuery yet this article series will teach you everything needed to master jQuery and use it in ASP.NET applications.
What is jQuery?
&lt;br /&gt;
&lt;br /&gt;
The official website for jQuery defines jQuery as follows:

&quot;jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.&quot;

Let&#39;s try to understand this description of jQuery in a bit detail.

&lt;br /&gt;
&lt;br /&gt;
jQuery is a JavaScript library

As a ASP.NET developer you must have used JavaScript in one way or the other. The standard JavaScript no doubt helps you code rich and responsive web pages but the amount of code that you need to write is often too much. For example, if you wish to write a fancy popup menu from ground up using JavaScript it might be a time consuming task. To simplify such development and make you more productive several JavaScript libraries are available and jQuery is one of them. There are others such as Mootools, Prototype and Dojo. The fact that Microsoft is supporting jQuery in its products and investing resources into it clearly indicates its popularity. As you would expect jQuery is cross-browser and supports all leading browsers including IE 6+, FF 2+, Chrome, Safari 3+ and Opera 9+.

jQuery is fast and concise
&lt;br /&gt;
&lt;br /&gt;
jQuery is highly optimized library. Moreover it is compact. The production version of jQuery 1.4.3 is just 26 KB and development version 179 KB. This compactness means less data to be downloaded at client side without compromising stunning UI effects.

Scope of jQuery

jQuery simplifies HTML DOM navigation considerably. For example, document.getElementById(&quot;Text1&quot;) becomes just $(&quot;#Text1&quot;). Simple. Isn&#39;t it? Most of the JavaScript functionality goes in client side event handlers. jQuery is handy when it comes to event handling. If you are thinking about your AJAX functionality don&#39;t worry. jQuery allows you to make AJAX calls to ASP.NET Web Services, WCF services or even page methods.&lt;br /&gt;
&lt;br /&gt;
 If needed jQuery can be used along with ASP.NET AJAX.

jQuery is designed to change the way that you write JavaScript

That&#39;s true! jQuery dramatically changes the way you write JavaScript code. Initially you may find syntax of jQuery bit odd but once you get hang of it you will probably never look at any other library (or at least to the traditional way of writing JavaScript).&lt;br /&gt;
&lt;br /&gt;
For example, a common JavaScript file contains too many small to huge functions and you keep calling them individually whenever required. With jQuery the &quot;chain&quot; of operations makes your code compact and handy. 

Ok. Enough of introduction. Now, let&#39;s complete the &quot;hello world&quot; ritual :-) In next section you will build a simple ASP.NET webform with some server controls on it that perform a trivial job of displaying &quot;Hello world&quot;.
Download jQuery

Before you start any development with jQuery you need to download its latest version. You can do so by visiting http://jquery.com and then downloading &quot;Development&quot; version.&lt;br /&gt;
&lt;br /&gt;
 If you are using VS2010 then you need not download anything because when you create a new website by default jQuery library is already added for you (see screenshot below)

In the above screenshot jquery-1.4.1.js is the development version, jquery-1.4.1.min.js is minified production version and jquery-1.4.1-vsdoc.js is the VS2010 IntelliSense file that enables IntelliSense for jQuery (see below).

In the remainder of this article I will be using VS2008. If you are using VS2010 then just cleanup the default website by removing master page and other unwanted stuff.
Design a simple web form

Create a new website in VS2008 and create a new folder named Scripts. Copy the downloaded jQuery file in the Scripts folder. Though you can place it anywhere inside your website it is recommended to keep all JavaScript files under one folder typically named Scripts. The default name for the jQuery file is jquery-1.4.3.js but you can change it to something else if you so wish.

Now open the default web form and add a &lt;script&gt;
 tag in its &lt;head&gt; section as shown below :

&lt;script src=&quot;Scripts/jquery-1.4.3.js&quot; type=&quot;text/javascript&quot;&gt;
&lt;/script&gt;

Now place a TextBox and a Button web control on the web form. Switch back to HTML source view and add another &lt;script&gt;
 block as shown below:
&lt;br&gt;
&lt;br&gt;
&lt;script type=&quot;text/javascript&quot;&gt;

$(document).ready(OnPageReady);

function OnPageReady() 
{
  $(&quot;#Button1&quot;).click(OnButtonClick)
}

function OnButtonClick(event) 
{
  alert(&quot;Hello world from jQuery!&quot;);
  event.preventDefault();
}
&lt;/script&gt;

The first line is where jQuery magic starts. The $ sign is a shortcut to base object jQuery. So, $(...) is actually same as jQuery(...).&lt;br /&gt;
&lt;br /&gt;
If you ever coded in ASP.NET AJAX this concept should be familiar to you. The ready() is an event that fires when the wen page under consideration is fully loaded and its various elements are ready to be accessed. The event handler for ready event is supplied in the parenthesis as OnPageReady. OnPageReady() is a normal JavaScript function that wires an event handler for the client side click event of the button. It does so again by using $ shortcut. This time, however, ID of the button control is specified prefixing it with #. The click is an event and you specify its handler as OnButtonClick. The event handler receives an event object giving more information about the event. The OnButtonClick() is another function that simply displays &quot;Hello World from jQuery!&quot; using JavaScript alert. The OnButtonClick function also calls event.preventDefault() method so as to prevent web form postback that normally would have happened due to Button web server control.

Ok.&lt;br /&gt;
If you run the web form you should see something like this :

Easy! Isn&#39;t it?

Now let&#39;s modify the above code as shown below:&lt;br /&gt;
&lt;br /&gt;
$(document).ready(
 function()&lt;br /&gt; {
   $(&quot;#Button1&quot;).click(function(event)&lt;br /&gt; {
    alert(&quot;Hello world from jQuery!&quot;);&lt;br /&gt;
event.preventDefault();
   }
  )
 }&lt;br /&gt;

)&lt;br /&gt;&lt;br /&gt;


This is a compact version of the code that achieves the same functionality. Here, instead of defining separate functions you have written all the code there itself. You may compare this code with anonymous methods of C#.
Adding something more...

Now that the &quot;Hello world&quot; ritual is over let&#39;s add some extra features to our code. Begin by defining the following CSS class in your web form:

    &lt;style type=&quot;text/css&quot;&gt;
        .NoFocus
        {
            background-color:White;
            border:solid 1px gray;
        }

        .Focus
        {
            background-color:silver;
            border:solid 3px gray;
        }

    
&lt;/style&gt;

The CSS class NoFocus will be applied to the textbox when it doesn&#39;t have focus whereas CSS class Focus will be applied when the textbox receives the focus. To accomplish this change the preceding code (compact version) as shown below:&lt;br /&gt;
&lt;br /&gt;


        $(document).ready
        (
            function()&lt;br /&gt;
{
                $(&quot;#Button1&quot;).click(
                function(event)&lt;br /&gt;
 
                {
                    alert($(&quot;#TextBox1&quot;).val());
                    return false;
                }
                )
                
                ,&lt;br /&gt;
                $(&quot;#TextBox1&quot;).addClass(&quot;NoFocus&quot;)
                ,&lt;br /&gt;
                $(&quot;#TextBox1&quot;).focus(
                function(event)
                {
                   $(&quot;#TextBox1&quot;).removeClass(&quot;NoFocus&quot;);
                   $(&quot;#TextBox1&quot;).addClass(&quot;Focus&quot;);
                }
                ),
                
                $(&quot;#TextBox1&quot;).blur(
                function(event)
                {
                   $(&quot;#TextBox1&quot;).removeClass(&quot;Focus&quot;);
                   $(&quot;#TextBox1&quot;).addClass(&quot;NoFocus&quot;);
                }
                )
            }
        )&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;


Notice the lines marked in bold letters. The click event handler of the button now displays whatever has been entered in the textbox. To retrieve textbox value you use val() method. Initially the textbox won&#39;t have focus and its CSS class should be NoFocus. This is done using addClass() method. The focus() and blur() event handlers simply add and remove the appropriate classes using addClass() and removeClass() methods respectively.</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/1431372694714585965/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/1431372694714585965' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/1431372694714585965'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/1431372694714585965'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2011/11/introduction-to-jquery-for-aspnet.html' title='Introduction to jQuery for ASP.NET'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-3572901832151901440</id><published>2011-11-16T13:35:00.001+05:30</published><updated>2011-11-16T13:44:00.497+05:30</updated><title type='text'>Entity FrameWork in DAL</title><content type='html'>The data access layer provides a centralized location for all calls into the database, and thus makes it easier to port the application to other database systems. There are many different options to get the Data Access Layer built quickly.

In my effort to build the DAL, I would have chosen from many different model providers, for example:

    NHibernate
    LINQ to SQL

Or else I would have chosen any other model provider, possibly:

    SubSonic
    LLBLGen Pro
    LightSpeed
    ..or who knows

This means that we will be using an ORM (Object Relational Mapping) tool to generate our Data Access Layer. As you can see, there are many tools, but all having their advantages and disadvantages. In order to select the right tool, you need consider your project requirements, the skills of the development team, and if an organization has standardized on a specific tool etc.

However, I am not going to use the tools listed above, instead decided to use Microsoft Entity Framework (EF), which is something Microsoft has newly introduced. The ADO.NET Entity Framework (EF) is an object-relational mapping (ORM) framework for the .NET Framework. ADO.NET Entity Framework (EF) abstracts the relational (logical) schema of the data that is stored in a database and presents its conceptual schema to the application. However the conceptual model that EF created fail to meet my requirements. Therefore I had to find a work around to create the right conceptual model for this design. You will see few adjustments that I have made to achieve my requirement in later part of this Article.

The selection of EF (Entity Framework) for my ASP.NET MVC front end is not a blindfolded decision. I do have few affirmations...

    ASP.NET MVC Framework is Microsoft, so as ADO.NET Entity Framework. They tend to work well together than any other tool.
    Latest version of EF (Entity Framework) has many promising features, and has addressed many issue had in its initial version.
    In general Microsoft seems serious about EF. That made me thinks that EF would have a significant share in the future of ORM tools.

The community has raised concerns over what has been promised and is being delivered with EF. You can read this ADO .NET Entity Framework Vote of No Confidence for more details about it. Microsoft and the Entity Framework team have received a tremendous amount of feedback from experts in entity-based applications and software architectures on the .NET platform. While Microsoft’s announcement of its intention to provide framework support for entity architectures was received with enthusiasm, the Entity Framework itself has consistently proved to be cause for significant concern. However the second version of Entity Framework (known, somewhat confusingly, as &#39;Entity Framework v4&#39; because it forms part of .NET 4.0) is available in Beta form as part of Visual Studio 2010, and has addressed many of the criticisms made of version 1.

The Entity data model (which is also called the conceptual model of the database), which ADO.NET Entity Framework auto created for our DMS is given below. This has a 1:1 (one to one) mapping between the database tables and the so called conceptual models. These models or objects can be used to communicate with the respective physical data source or the tables of the database. I hope you can understand my conceptual model quite easily.
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhq0105KCT3ig5zFs2QT438LW4GzZWSLPDADXIHrde-lt23L1y-_-UbvH-z4qtMcMbcRSML1OmKkKbKKUk-aJ5XMwbcYJVirPZZhJiYIHvOgrAnpnOvFIrbh56n9sKvxORHRCsE/s1600/EntityDesignerDiagram.jpg&quot; imageanchor=&quot;1&quot; style=&quot;clear:left; float:left;margin-right:1em; margin-bottom:1em&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;247&quot; width=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhq0105KCT3ig5zFs2QT438LW4GzZWSLPDADXIHrde-lt23L1y-_-UbvH-z4qtMcMbcRSML1OmKkKbKKUk-aJ5XMwbcYJVirPZZhJiYIHvOgrAnpnOvFIrbh56n9sKvxORHRCsE/s320/EntityDesignerDiagram.jpg&quot; /&gt;&lt;/a&gt;&lt;/div&gt;




The Data Access Layer project, which is given below, has three folders namely Models, Infrastructure and Interfaces (You will later notice that this project template is being reused in other projects of this system too). Outside of those folders, you find few classes such as one base class and two concrete classes. These are the main operational classes of the data access layer (DAL) project. This project template made it possible to directly access all commonly used main operational classes without worrying about navigating in to directories.

&quot;The inherent complexity of a software system is related to the problem it is trying to solve. The actual complexity is related to the size and structure of the software system as actually built. The difference is a measure of the inability to match the solution to the problem.&quot;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgWmYY1QcEdw7B60BnB5MvG5PI3yf9Ok16qOPVrDbs-Cgeo-38fuu50csDEOdegu5EucpLKzseU9KHRxPuWdCZncv1mOnfDYwCa1WSJ-NtSKzDlEyrxqjmk8NCxttCtgPFNaDDr/s1600/DalDesingView1.jpg&quot; imageanchor=&quot;1&quot; style=&quot;clear:left; float:left;margin-right:1em; margin-bottom:1em&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;200&quot; width=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgWmYY1QcEdw7B60BnB5MvG5PI3yf9Ok16qOPVrDbs-Cgeo-38fuu50csDEOdegu5EucpLKzseU9KHRxPuWdCZncv1mOnfDYwCa1WSJ-NtSKzDlEyrxqjmk8NCxttCtgPFNaDDr/s320/DalDesingView1.jpg&quot; /&gt;&lt;/a&gt;&lt;/div&gt;




In the Data Access Layer (DAL) design, I thought of using a variant of repository pattern. The Repository pattern is commonly used by many enterprise designers. It is a straight forward design that gives you testable &amp; reusable code modules. Furthermore it gives flexibility and separation of concerns between the conceptual model and business logics too. In my design there are two Repositories namely ‘DocumentRepository’ and ‘FileRepository’, which will mediates between the domain (also called Business Logic Layer) and data mapping layers (also called Data Access Layer) using domain objects (also called Business Objects or Models).

In general it is recommended having one repository class for every business object of the system.

Among the few folders that you see in that project, the folder named &#39;Interfaces&#39; is important. So let&#39;s check inside the &#39;Interfaces&#39; folder and see what interfaces that we have in it...

    IRepository&lt;T&gt; - The generic interface that abstractly defines the behavior of all the repositories of our system. This is the super repository. This is what extends to create the abstract repository with the name &#39;RepositoryBase&lt;T&gt;&#39;.
    IDocumentRepository – This is a specialized repository, which defines the behavior specific to &#39;Document&#39;.
    IFileRepository – Just like it was with &#39;IDocumentRepository&#39;, this defines the behavior of the &#39;File&#39; repository.
    IRepositoryContext - This defines the behavior of the context of our repositories.
    IPagination - This defined the definition for pagination related operations.
    &#39;IUnitOfWork&#39; and &#39;IUnitOfWorkFactory&#39; were there but removed from the design later. Initially, I was planning to write some codes for dependency injection (DI) too. But later I found that Microsoft enterprise library has everything done for us. They have an application block called &#39;UnityApplicaitonBlock&#39;, which does what I was initiated with those two interfaces. Therefore I removed unity and inversion of control related implementations from the project. Now the source code you download now will not have those implementations.

I have used interfaces in the DAL design, and that might made you ask questions like &#39;why we need these interfaces?&#39; and &#39;why not just have the concrete implementation alone?&#39;. There are many reasons for having interfaces in a design. They allow implementation to be interchangeable (One common scenario is, when unit testing, you can replace the actual repository implementation with a fake one). Additionally, when carefully used, they help to better organize your design.

The interface is the bare minimum needed to explain what a function or class will do. It&#39;s the lease amount of code you can write for a full declaration of functionality and usability. For this reason, it&#39;s (more) clearer for a user of your function or class to understand how the object works. The user shouldn&#39;t have to look through all of your implementations to understand what the object does. So, again defining interfaces is the more organized approach.

In some instances, I have seen designers add interfaces for every class, which I thought is a too extreme design practice. In my design I have used interfaces not only to organize the design but also to interchange implementation too. Later in the article you will see how these interfaces are being used to assist &#39;unity application block&#39; to inject dependencies too.

You can see in the screen above that I have set of interfaces define for pagination too. The pagination (of business objects/ entities) is something that developers code in many different layers. Some code it in the UI (User Interface) layer, while others do it in BLL (Business Logic Layer) or DAL (Data Access Layer). I thought of implementing it inside DAL to avoid unwanted network round trips that would occurred otherwise in a distributed multi-tier deployment setup. Additionally when keep it inside DAL, I will have the option of using some of the built-in EF (Entity Framework) functions for pagination works.

The figure below summarizes the overall DAL design with its main components and their relations. I think it is clear how the three interfaces and their concrete implementations are being defined.

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiATfNbUPaVj3jikK9NzGfCN3ltE_PtAXqyjnhkV2W1DCykJ1cJhug1QenoI7f1Z0Fpm6tjSNNRPP_uwTyIHdFRr6IjZ9syc9xB0VDh5TpNVi6-Zi-9ET_JKi4LzQnNf6ERYN4/s1600/ClassDiagram.Dal1.png&quot; imageanchor=&quot;1&quot; style=&quot;clear:left; float:left;margin-right:1em; margin-bottom:1em&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;232&quot; width=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiATfNbUPaVj3jikK9NzGfCN3ltE_PtAXqyjnhkV2W1DCykJ1cJhug1QenoI7f1Z0Fpm6tjSNNRPP_uwTyIHdFRr6IjZ9syc9xB0VDh5TpNVi6-Zi-9ET_JKi4LzQnNf6ERYN4/s320/ClassDiagram.Dal1.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;


I think it is important for you to know how this design evolves. So let me talk about that here. Initially, I had the &#39;IRepository&lt;T&gt;&#39; interface. That was used to implement the two specialized &#39;Document&#39; and &#39;File&#39; repositories. That time I noticed that the two was having many common operations. So I thought of abstractly define them with a abstract class. Thus, decided to add a new generic abstract class called &#39;RepositoryBase&lt;T&gt;&#39;. Once all these were done, the final system had the generic &#39;IRepository&lt;T&gt;&#39; interface right at the top, then the abstract &#39;RepositoryBase&lt;T&gt;&#39; class, and then two concrete implementations of &#39;File&#39; and &#39;Document&#39; repositories. I thought it is done, and had a final look before closing-up the design, but that made me realized that the design is still having issues. So let me talk about that in the next paragraph.

The design I had made it impossible to interchange implementation of either of the specialized repository. As an example, if I have a test/ fake version of the &#39;DocumentRepository&#39; implemented with the name &#39;TestDocumentRepository&#39; and wanted to interchange that with the &#39;DocumentRepository&#39;, then it is not possible with my design. So I decided to do few more adjustment to the design by introducing two specialized interfaces called &#39;IDocumentRepository&#39; and &#39;IFileRepository&#39;. This made it possible to fully hide the special implementations, hence gain the required interchangeability. That final change concludes my DAL design.</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/3572901832151901440/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/3572901832151901440' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/3572901832151901440'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/3572901832151901440'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2011/11/entity-framework-in-dal.html' title='Entity FrameWork in DAL'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhq0105KCT3ig5zFs2QT438LW4GzZWSLPDADXIHrde-lt23L1y-_-UbvH-z4qtMcMbcRSML1OmKkKbKKUk-aJ5XMwbcYJVirPZZhJiYIHvOgrAnpnOvFIrbh56n9sKvxORHRCsE/s72-c/EntityDesignerDiagram.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-2577473633911776562</id><published>2011-10-31T18:15:00.001+05:30</published><updated>2011-10-31T18:17:40.027+05:30</updated><title type='text'>Embedding RavenDB into an ASP.NET MVC 3 Application</title><content type='html'>RavenDB Embedded and MVC&lt;br /&gt;RavenDB can be run in three different modes:&lt;br /&gt;&lt;br /&gt;1.As a Windows service&lt;br /&gt;2.As an IIS application&lt;br /&gt;3.Embedded in a .NET application&lt;br /&gt;The first two have a fairly simple setup process, but come with some implementation strategy overhead. The third option, embedded, is extremely easy to get up and running. In fact, there’s a NuGet package available for it. A call to the following command in the Package Manager Console in Visual Studio 2010 (or a search for the term “ravendb” in the Manage NuGet Packages dialog) will deliver all of the references needed to start working with the embedded version of RavenDB:&lt;br /&gt;&lt;br /&gt;Install-Package RavenDB-EmbeddedDetails of the package can be found on the NuGet gallery site at bit.ly/ns64W1.&lt;br /&gt;&lt;br /&gt;Adding the embedded version of RavenDB to an ASP.NET MVC 3 application is as simple as adding the package via NuGet and giving the data store files a directory location. Because ASP.NET applications have a known data directory in the framework named App_Data, and most hosting companies provide read/write access to that directory with little or no configuration required, it’s a good place to store the data files. When RavenDB creates its file storage, it builds a handful of directories and files in the directory path provided to it. It won’t create a top-level directory to store everything. Knowing that, it’s worthwhile to add the ASP.NET folder named App_Data via the Project context menu in Visual Studio 2010 and then create a subdirectory in the App_Data directory for the RavenDB data (see Figure 1).&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Figure 1 App_Data Directory Structure&lt;br /&gt;&lt;br /&gt;A document data store is schema-less by nature, hence there’s no need to create an instance of a database or set up any tables. Once the first call to initialize the data store is made in code, the files required to maintain the data state will be created.&lt;br /&gt;&lt;br /&gt;Working with the RavenDB Client API to interface with the data store requires an instance of an object that implements the Raven.Client.IDocumentStore interface to be created and initialized. The API has two classes, DocumentStore and EmbeddedDocumentStore, that implement the interface and can be used depending on the mode in which RavenDB is running. There should only be one instance per data store during the lifecycle of an application. I can create a class to manage a single connection to my document store that will let me access the instance of the IDocumentStore object via a static property and have a static method to initialize the instance (see Figure 2).&lt;br /&gt;&lt;br /&gt;Figure 2 Class for DocumentStore&lt;br /&gt;&lt;br /&gt;public class DataDocumentStore&lt;br /&gt;{&lt;br /&gt;  private static IDocumentStore instance;&lt;br /&gt; &lt;br /&gt;  public static IDocumentStore Instance&lt;br /&gt;  {&lt;br /&gt;    get&lt;br /&gt;    {&lt;br /&gt;      if(instance == null)&lt;br /&gt;        throw new InvalidOperationException(&lt;br /&gt;          &quot;IDocumentStore has not been initialized.&quot;);&lt;br /&gt;      return instance;&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt; &lt;br /&gt;  public static IDocumentStore Initialize()&lt;br /&gt;  {&lt;br /&gt;    instance = new EmbeddableDocumentStore { ConnectionStringName = &quot;RavenDB&quot; };&lt;br /&gt;    instance.Conventions.IdentityPartsSeparator = &quot;-&quot;;&lt;br /&gt;    instance.Initialize();&lt;br /&gt;    return instance;&lt;br /&gt;  }&lt;br /&gt;}The static property getter checks a private static backing field for a null object and, if null, it throws an InvalidOperationException. I throw an exception here, rather than calling the Initialize method, to keep the code thread-safe. If the Instance property were allowed to make that call and the application relied upon referencing the property to do the initialization, then there would be a chance that more than one user could hit the application at the same time, resulting in simultaneous calls to the Initialize method. Within the Initialize method logic, I create a new instance of the Raven.Client.Embedded.EmbeddableDocumentStore and set the ConnectionStringName property to the name of a connection string that was added to the web.config file by the install of the RavenDB NuGet package. In the web.config, I set the value of the connection string to a syntax that RavenDB understands in order to configure it to use the embedded local version of the data store. I also map the file directory to the Database directory I created in the App_Data directory of the MVC project:&lt;br /&gt;&lt;br /&gt;&lt;connectionStrings&gt;&lt;br /&gt;  &lt;add name=&quot;RavenDB &quot; connectionString=&quot;DataDir = ~\App_Data\Database&quot; /&gt;&lt;br /&gt;&lt;/connectionStrings&gt;The IDocumentStore interface contains all of the methods for working with the data store. I return and store the EmbeddableDocumentStore object as an instance of the interface type IDocumentStore so I have the flexibility of changing the instantiation of the EmbeddedDocumentStore object to the server version (DocumentStore) if I want to move away from the embedded version. This way, all of my logic code that will handle my document object management will be decoupled from the knowledge of the mode in which RavenDB is running.&lt;br /&gt;&lt;br /&gt;RavenDB will create document ID keys in a REST-like format by default. An “Item” object would get a key in the format “items/104.” The object model name is converted to lowercase and is pluralized, and a unique tracking identity number is appended after a forward slash with each new document creation. This can be problematic in an MVC application, as the forward slash will cause a new route parameter to be parsed. The RavenDB Client API provides a way to change the forward slash by setting the IdentityPartsSeparator value. In my DataDocumentStore.Initialize method, I’m setting the IdentityPartsSeparator value to a dash before I call the Initialize method on the EmbeddableDocumentStore object, to avoid the routing issue.&lt;br /&gt;&lt;br /&gt;Adding a call to the DataDocumentStore.Initialize static method from the Application_Start method in the Global.asax.cs file of my MVC application will establish the IDocumentStore instance at the first run of the application, which looks like this:&lt;br /&gt;&lt;br /&gt;protected void Application_Start()&lt;br /&gt;{&lt;br /&gt;  AreaRegistration.RegisterAllAreas();&lt;br /&gt;  RegisterGlobalFilters(GlobalFilters.Filters);&lt;br /&gt;  RegisterRoutes(RouteTable.Routes);&lt;br /&gt; &lt;br /&gt;  DataDocumentStore.Initialize();&lt;br /&gt;}From here I can make use of the IDocumentStore object with a static call to the DataDocumentStore.Instance property to work on document objects from my embedded data store within my MVC application.&lt;br /&gt;&lt;br /&gt;RavenDB Objects&lt;br /&gt;To get a better understanding of RavenDB in action, I’ll create a prototype application to store and manage bookmarks. RavenDB is designed to work with Plain Old CLR Objects (POCOs), so there’s no need to add property attributes to guide serialization. Creating a class to represent a bookmark is pretty straightforward. Figure 3 shows the Bookmark class.&lt;br /&gt;&lt;br /&gt;Figure 3 Bookmark Class&lt;br /&gt;&lt;br /&gt;public class Bookmark&lt;br /&gt;{&lt;br /&gt;  public string Id { get; set; }&lt;br /&gt;  public string Title { get; set; }&lt;br /&gt;  public string Url { get; set; }&lt;br /&gt;  public string Description { get; set; }&lt;br /&gt;  public List&lt;string&gt; Tags { get; set; }&lt;br /&gt;  public DateTime DateCreated { get; set; }&lt;br /&gt; &lt;br /&gt;  public Bookmark()&lt;br /&gt;  {&lt;br /&gt;    this.Tags = new List&lt;string&gt;();&lt;br /&gt;  }&lt;br /&gt;}RavenDB will serialize the object data into a JSON structure when it goes to store the document. The well-known “Id” named property will be used to handle the document ID key. RavenDB will create that value—provided the Id property is empty or null when making the call to create the new document—and will store it in a @metadata element for the document (which is used to handle the document key at the data-store level). When requesting a document, the RavenDB Client API code will set the document ID key to the Id property when it loads the document object.&lt;br /&gt;&lt;br /&gt;The JSON serialization of a sample Bookmark document is represented in the following structure:&lt;br /&gt;&lt;br /&gt;{&lt;br /&gt;  &quot;Title&quot;: &quot;The RavenDB site&quot;,&lt;br /&gt;  &quot;Url&quot;: &quot;http://www.ravendb.net&quot;,&lt;br /&gt;  &quot;Description&quot;: &quot;A test bookmark&quot;,&lt;br /&gt;  &quot;Tags&quot;: [&quot;mvc&quot;,&quot;ravendb&quot;],&lt;br /&gt;  &quot;DateCreated&quot;: &quot;2011-08-04T00:50:40.3207693Z&quot;&lt;br /&gt;}The Bookmark class is primed to work well with the document store, but the Tags property is going to pose a challenge in the UI layer. I’d like to let the user enter a list of tags separated by commas in a single text box input field and have the MVC model binder map all of the data fields without any logic code seeping into my views or controller actions. I can tackle this by using a custom model binder for mapping a form field named “TagsAsString” to the Bookmark.Tags field. First, I create the custom model binder class (see Figure 4).&lt;br /&gt;&lt;br /&gt;Figure 4 BookmarkModelBinder.cs&lt;br /&gt;&lt;br /&gt;public class BookmarkModelBinder : DefaultModelBinder&lt;br /&gt;{&lt;br /&gt;  protected override void OnModelUpdated(ControllerContext controllerContext,&lt;br /&gt;    ModelBindingContext bindingContext)&lt;br /&gt;  {&lt;br /&gt;    var form = controllerContext.HttpContext.Request.Form;&lt;br /&gt;    var tagsAsString = form[&quot;TagsAsString&quot;];&lt;br /&gt;    var bookmark = bindingContext.Model as Bookmark;&lt;br /&gt;    bookmark.Tags = string.IsNullOrEmpty(tagsAsString)&lt;br /&gt;      ? new List&lt;string&gt;()&lt;br /&gt;      : tagsAsString.Split(&#39;,&#39;).Select(i =&gt; i.Trim()).ToList();&lt;br /&gt;  }&lt;br /&gt;}Then I update the Globals.asax.cs file to add the BookmarkModelBinder to the model binders at application startup:&lt;br /&gt;&lt;br /&gt;protected void Application_Start()&lt;br /&gt;{&lt;br /&gt;  AreaRegistration.RegisterAllAreas();&lt;br /&gt;  RegisterGlobalFilters(GlobalFilters.Filters);&lt;br /&gt;  RegisterRoutes(RouteTable.Routes);&lt;br /&gt; &lt;br /&gt;  ModelBinders.Binders.Add(typeof(Bookmark), new BookmarkModelBinder());&lt;br /&gt;  DataDocumentStore.Initialize();&lt;br /&gt;}To handle populating an HTML text box with the current tags in the model, I’ll add an extension method to convert a List&lt;string&gt; object to a comma-separated string:&lt;br /&gt;&lt;br /&gt;public static string ToCommaSeparatedString(this List&lt;string&gt; list)&lt;br /&gt;{&lt;br /&gt;  return list == null ? string.Empty : string.Join(&quot;, &quot;, list);&lt;br /&gt;}Unit of Work&lt;br /&gt;The RavenDB Client API is based on the Unit of Work pattern. To work on documents from the document store, a new session needs to be opened; work needs to be done and saved; and the session needs to close. The session handles change tracking and operates in a manner that’s similar to a data context in the EF. Here’s an example of creating a new document:&lt;br /&gt;&lt;br /&gt;using (var session = documentStore.OpenSession())&lt;br /&gt;{&lt;br /&gt;  session.Store(bookmark);&lt;br /&gt;  session.SaveChanges();&lt;br /&gt;}It’s optimal to have the session live throughout the HTTP request so it can track changes, use the first-level cache and so on. I’ll create a base controller that will use the DocumentDataStore.Instance to open a new session on action executing, and on action executed will save changes and then dispose of the session object (see Figure 5). This allows me to do all of the work desired during the execution of my action code with a single open session instance.&lt;br /&gt;&lt;br /&gt;Figure 5 BaseDocumentStoreController&lt;br /&gt;&lt;br /&gt;public class BaseDocumentStoreController : Controller&lt;br /&gt;{&lt;br /&gt;  public IDocumentSession DocumentSession { get; set; }&lt;br /&gt; &lt;br /&gt;  protected override void OnActionExecuting(ActionExecutingContext filterContext)&lt;br /&gt;  {&lt;br /&gt;    if (filterContext.IsChildAction)&lt;br /&gt;      return;&lt;br /&gt;    this.DocumentSession = DataDocumentStore.Instance.OpenSession();&lt;br /&gt;    base.OnActionExecuting(filterContext);&lt;br /&gt;  }&lt;br /&gt; &lt;br /&gt;  protected override void OnActionExecuted(ActionExecutedContext filterContext)&lt;br /&gt;  {&lt;br /&gt;    if (filterContext.IsChildAction)&lt;br /&gt;      return;&lt;br /&gt;    if (this.DocumentSession != null &amp;&amp; filterContext.Exception == null)&lt;br /&gt;      this.DocumentSession.SaveChanges();&lt;br /&gt;    this.DocumentSession.Dispose();&lt;br /&gt;    base.OnActionExecuted(filterContext);&lt;br /&gt;  }&lt;br /&gt;}MVC Controller and View Implementation&lt;br /&gt;The BookmarksController actions will work directly with the IDocumentSession object from the base class and manage all of the Create, Read, Update and Delete (CRUD) operations for the documents. Figure 6 shows the code for the bookmarks controller.&lt;br /&gt;&lt;br /&gt;Figure 6 BookmarksController Class&lt;br /&gt;&lt;br /&gt;public class BookmarksController : BaseDocumentStoreController&lt;br /&gt;{&lt;br /&gt;  public ViewResult Index()&lt;br /&gt;  {&lt;br /&gt;    var model = this.DocumentSession.Query&lt;Bookmark&gt;()&lt;br /&gt;      .OrderByDescending(i =&gt; i.DateCreated)&lt;br /&gt;      .ToList();&lt;br /&gt;    return View(model);&lt;br /&gt;  }&lt;br /&gt; &lt;br /&gt;  public ViewResult Details(string id)&lt;br /&gt;  {&lt;br /&gt;    var model = this.DocumentSession.Load&lt;Bookmark&gt;(id);&lt;br /&gt;    return View(model);&lt;br /&gt;  }&lt;br /&gt; &lt;br /&gt;  public ActionResult Create()&lt;br /&gt;  {&lt;br /&gt;    var model = new Bookmark();&lt;br /&gt;    return View(model);&lt;br /&gt;  }&lt;br /&gt; &lt;br /&gt;  [HttpPost]&lt;br /&gt;  public ActionResult Create(Bookmark bookmark)&lt;br /&gt;  {&lt;br /&gt;    bookmark.DateCreated = DateTime.UtcNow;&lt;br /&gt;    this.DocumentSession.Store(bookmark);&lt;br /&gt;    return RedirectToAction(&quot;Index&quot;);&lt;br /&gt;  }&lt;br /&gt;   &lt;br /&gt;  public ActionResult Edit(string id)&lt;br /&gt;  {&lt;br /&gt;    var model = this.DocumentSession.Load&lt;Bookmark&gt;(id);&lt;br /&gt;    return View(model);&lt;br /&gt;  }&lt;br /&gt; &lt;br /&gt;  [HttpPost]&lt;br /&gt;  public ActionResult Edit(Bookmark bookmark)&lt;br /&gt;  {&lt;br /&gt;    this.DocumentSession.Store(bookmark);&lt;br /&gt;    return RedirectToAction(&quot;Index&quot;);&lt;br /&gt;  }&lt;br /&gt; &lt;br /&gt;  public ActionResult Delete(string id)&lt;br /&gt;  {&lt;br /&gt;    var model = this.DocumentSession.Load&lt;Bookmark&gt;(id);&lt;br /&gt;    return View(model);&lt;br /&gt;  }&lt;br /&gt; &lt;br /&gt;  [HttpPost, ActionName(&quot;Delete&quot;)]&lt;br /&gt;  public ActionResult DeleteConfirmed(string id)&lt;br /&gt;  {&lt;br /&gt;    this.DocumentSession.Advanced.DatabaseCommands.Delete(id, null);&lt;br /&gt;    return RedirectToAction(&quot;Index&quot;);&lt;br /&gt;  }&lt;br /&gt;}The IDocumentSession.Query&lt;T&gt; method in the Index action returns a result object that implements the IEnumerable interface, so I can use the OrderByDescending LINQ expression to sort the items and call the ToList method to capture the data to my return object. The IDocumentSession.Load method in the Details action takes in a document ID key value and de-serializes the matching document to an object of type Bookmark.&lt;br /&gt;&lt;br /&gt;The Create method with the HttpPost verb attribute sets the CreateDate property on the bookmark item and calls the IDocumentSession.Store method off of the session object to add a new document record to the document store. The Update method with the HttpPost verb can call the IDocumentSession.Store method as well, because the Bookmark object will have the Id value already set. RavenDB will recognize that Id and update the existing document with the matching key instead of creating a new one. The DeleteConfirmed action calls a Delete method off of the IDocumentSession.Advanced.DatabaseCommands object, which provides a way to delete a document by key without having to load the object first. I don’t need to call the IDocumentSession.SaveChanges method from within any of these actions, because I have the base controller making that call on action executed.&lt;br /&gt;&lt;br /&gt;All of the views are pretty straightforward. They can be strongly typed to the Bookmark class in the Create, Edit and Delete markups, and to a list of bookmarks in the Index markup. Each view can directly reference the model properties for display and input fields. The one place where I’ll need to vary on object property reference is with the input field for the tags. I’ll use the ToCommaSeparatedString extension method in the Create and Edit views with the following code:&lt;br /&gt;&lt;br /&gt;@Html.TextBox(&quot;TagsAsString&quot;, Model.Tags.ToCommaSeparatedString())This will allow the user to input and edit the tags associated with the bookmark in a comma-delimited format within a single text box.&lt;br /&gt;&lt;br /&gt;Searching Objects&lt;br /&gt;With all of my CRUD operations in place, I can turn my attention to adding one last bit of functionality: the ability to filter the bookmark list by tags. In addition to implementing the IEnumerable interface, the return object from the IDocumentSession.Query method also implements the IOrderedQueryable and IQueryable interfaces from the .NET Framework. This allows me to use LINQ to filter and sort my queries. For example, here’s a query of the bookmarks created in the past five days:&lt;br /&gt;&lt;br /&gt;var bookmarks = session.Query&lt;Bookmark&gt;()&lt;br /&gt;  .Where( i=&gt; i.DateCreated &gt;= DateTime.UtcNow.AddDays(-5))&lt;br /&gt;  .OrderByDescending(i =&gt; i.DateCreated)&lt;br /&gt;  .ToList();Here’s one to page through the full list of bookmarks:&lt;br /&gt;&lt;br /&gt;var bookmarks = session.Query&lt;Bookmark&gt;()&lt;br /&gt;  .OrderByDescending(i =&gt; i.DateCreated)&lt;br /&gt;  .Skip(pageCount * (pageNumber – 1))&lt;br /&gt;  .Take(pageCount)&lt;br /&gt;  .ToList();RavenDB will build dynamic indexes based on the execution of these queries that will persist for “some amount of time” before being disposed of. When a similar query is rerun with the same parameter structure, the temporary dynamic index will be used. If the index is used enough within a given period, the index will be made permanent. These will persist beyond the application lifecycle.&lt;br /&gt;&lt;br /&gt;I can add the following action method to my BookmarksController class to handle getting bookmarks by tag:&lt;br /&gt;&lt;br /&gt;public ViewResult Tag(string tag)&lt;br /&gt;{&lt;br /&gt;  var model = new BookmarksByTagViewModel { Tag = tag };&lt;br /&gt;  model.Bookmarks = this.DocumentSession.Query&lt;Bookmark&gt;()&lt;br /&gt;    .Where(i =&gt; i.Tags.Any(t =&gt; t == tag))&lt;br /&gt;    .OrderByDescending(i =&gt; i.DateCreated)&lt;br /&gt;    .ToList();&lt;br /&gt;  return View(model);&lt;br /&gt;}I expect this action to be hit on a regular basis by users of my application. If that’s indeed the case, this dynamic query will get turned into a permanent index by RavenDB with no additional work needed on my part.</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/2577473633911776562/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/2577473633911776562' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/2577473633911776562'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/2577473633911776562'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2011/10/embedding-ravendb-into-aspnet-mvc-3.html' title='Embedding RavenDB into an ASP.NET MVC 3 Application'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-1123626128009602215</id><published>2010-04-06T13:34:00.007+05:30</published><updated>2010-04-06T13:55:56.050+05:30</updated><title type='text'>WCF Service For HTTP Get Request</title><content type='html'>In my last article I talked about how you can put a hook by implementing some interface of WCF. In this article I am talking about how you can define one method which will act as a controller and control all the income request.&lt;br /&gt;&lt;br /&gt;In WCF when you define the ServiceContract you can also define what will be the action which will trigger that particular method.So basically I am talking about OperationContract where you can define the Action and ReplyAction attributes.&lt;br /&gt;&lt;br /&gt;So we will see a very small example how we can handle the Http get request.&lt;br /&gt;&lt;br /&gt;I have one Service Contract where I have define one method call Process which take message as a input parameter and the operation contract of this method define Action and ReplyAction as * it a wild card character which will invoke this method for all the request.&lt;br /&gt;&lt;br /&gt;[OperationContract(Action=&quot;*&quot;, ReplyAction=&quot;*&quot;)]&lt;br /&gt;void Process(Message msg);&lt;br /&gt;&lt;br /&gt;When you implements this service contract into you actual class message parameter of this class will give you the income request object and you can extract out different information from this message object.&lt;br /&gt;&lt;br /&gt;public void Process(Message request)&lt;br /&gt;{&lt;br /&gt;HttpRequestMessageProperty rp = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];&lt;br /&gt;if (rp.Method.Equals(&quot;Get&quot;, StringComparison.InvariantCultureIgnoreCase))&lt;br /&gt;HttpContext.Current.Response.Write(Get(request));&lt;br /&gt;} &lt;br /&gt;so you can see In this code I am checking the request whether it&#39;s Get or POST and do my action on the basis of that.&lt;br /&gt;&lt;br /&gt;In this case I don&#39;t need to create any class inherited by IServiceBehaviour or some other interface this method will be called for all hit whether some body is hitting by creating a proxy of your service which is POST or just directly typing into URL which is GET.</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/1123626128009602215/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/1123626128009602215' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/1123626128009602215'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/1123626128009602215'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2010/04/wcf-service-for-http-get-request.html' title='WCF Service For HTTP Get Request'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-1427780214299225283</id><published>2010-03-30T19:07:00.002+05:30</published><updated>2010-03-30T19:16:23.091+05:30</updated><title type='text'>Property Handling in WCF</title><content type='html'>In this article I am talking about how you can define OperationContract for your properties of Service Contract.&lt;br /&gt;&lt;br /&gt;As you know you can&#39;t put [OperationContract] attribute on your Properties it will give you an compile time error because this attribute is only valid for method declaration. &lt;br /&gt;&lt;br /&gt;In this case you can define this attribute on you get and set of property and these get and set will treat as normal method so for example I am define one property called CustomerId I have to define like this.&lt;br /&gt;&lt;br /&gt;int CustomerId&lt;br /&gt;{&lt;br /&gt;&lt;br /&gt;[OperationContract]&lt;br /&gt;get;&lt;br /&gt;[OperationContract]&lt;br /&gt;set;&lt;br /&gt;}&lt;br /&gt;After doing this you will get set_CustomerId and get_CustomerId as normal method in your WCF proxy class.</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/1427780214299225283/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/1427780214299225283' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/1427780214299225283'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/1427780214299225283'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2010/03/property-handling-in-wcf.html' title='Property Handling in WCF'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-3840193588308021666</id><published>2010-03-29T20:07:00.002+05:30</published><updated>2010-03-29T20:24:48.041+05:30</updated><title type='text'>Hooking Your class into WCF</title><content type='html'>In this article I am talking about how you can intercept the SOAP Calling and handling of non existences message of service contract. In this example Add is a dummy method which is not a part of service contract I just mimic the web service request and response handling.&lt;br /&gt;&lt;br /&gt;You can create you class which will be inherited from IServiceBehavior and then use ApplyDispatchBehavior of this interface to set you hook as message inspector.&lt;br /&gt;&lt;br /&gt;  void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)&lt;br /&gt;        {&lt;br /&gt;           //ApplyDispatchBehavior&lt;br /&gt;&lt;br /&gt;            foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)&lt;br /&gt;            {&lt;br /&gt;                ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher;&lt;br /&gt;                if (channelDispatcher != null)&lt;br /&gt;                {&lt;br /&gt;                    foreach (EndpointDispatcher endpoint in channelDispatcher.Endpoints)&lt;br /&gt;                    {&lt;br /&gt;                        //endpoint.DispatchRuntime.OperationSelector = this;&lt;br /&gt;                        endpoint.DispatchRuntime.MessageInspectors.Add(new PrintMessageInterceptor());&lt;br /&gt;                    }&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;In this method PrintMessageInterceptor is an instance of another class which is inherited from IDispatchMessageInspector which provide us two method AfterReceiveRequest and BeforeSendReply&lt;br /&gt;&lt;br /&gt;In AfterReceiveRequest you can take out body of SOAP and then you can set you parameter and in BeforeSendReply you can check this parameter and modified the response message.&lt;br /&gt;&lt;br /&gt;public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request,&lt;br /&gt;IClientChannel channel, InstanceContext instanceContext)&lt;br /&gt;{&lt;br /&gt;&lt;br /&gt;XmlNodeReader reader;&lt;br /&gt;XmlDocument document = new XmlDocument();&lt;br /&gt;document.Load(request.GetReaderAtBodyContents());&lt;br /&gt;//Get the body element operation &lt;br /&gt;string bodyElement = document.DocumentElement.LocalName;&lt;br /&gt;switch(bodyElement)&lt;br /&gt;{&lt;br /&gt;case &quot;Add&quot; :&lt;br /&gt;strAction = Action.Add;&lt;br /&gt;break;&lt;br /&gt;} &lt;br /&gt;return null;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply,&lt;br /&gt;object correlationState)&lt;br /&gt;{&lt;br /&gt;MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);&lt;br /&gt;reply = buffer.CreateMessage();&lt;br /&gt;//Get the body element operation &lt;br /&gt;XmlDocument document;&lt;br /&gt;string bodyElement;&lt;br /&gt;&lt;br /&gt;document = new XmlDocument();&lt;br /&gt;document.Load(reply.GetReaderAtBodyContents());&lt;br /&gt;//Get the body element operation &lt;br /&gt;bodyElement = document.DocumentElement.LocalName;&lt;br /&gt;switch (strAction.ToString())&lt;br /&gt;{&lt;br /&gt;case &quot;Add&quot;:&lt;br /&gt;Add(document);&lt;br /&gt;reply = Message.CreateMessage(reply.Version, null, localReader);&lt;br /&gt;break;&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Now in this case Add method will take the body of the SOAP and modified that one and send the same body to the calling method.localReader is of XmlNodeReader which I have set to create the response message.&lt;br /&gt;&lt;br /&gt;private void Add(XmlDocument passedValue)&lt;br /&gt;{&lt;br /&gt;&lt;br /&gt;if (passedValue.DocumentElement.Name.Equals(&quot;Add&quot;))&lt;br /&gt;{&lt;br /&gt;using (var passedReader = XmlReader.Create(new System.IO.MemoryStream(System.Text.Encoding.ASCII.GetBytes(passedValue.InnerXml))))&lt;br /&gt;//using (var writer = XmlWriter.Create(new System.IO.MemoryStream(System.Text.Encoding.ASCII.GetBytes(reader.ReadInnerXml())), settings))&lt;br /&gt;{&lt;br /&gt;while (passedReader.Read())&lt;br /&gt;{&lt;br /&gt;switch (passedReader.NodeType)&lt;br /&gt;{&lt;br /&gt;case XmlNodeType.Element:&lt;br /&gt;break;&lt;br /&gt;&lt;br /&gt;case XmlNodeType.Text:&lt;br /&gt;Sum += Convert.ToInt32(passedReader.Value);&lt;br /&gt;break;&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;newNode = passedValue.CreateElement(&quot;AddResponse&quot;, &quot;http://tempuri.org/&quot;);&lt;br /&gt;childNode = passedValue.CreateElement(&quot;AddResult&quot;, &quot;http://tempuri.org/&quot;);&lt;br /&gt;childNode.InnerText = Sum.ToString();&lt;br /&gt;newNode.AppendChild(childNode);&lt;br /&gt;passedValue.RemoveChild(passedValue.DocumentElement);&lt;br /&gt;passedValue.InnerXml = (newNode.OuterXml);&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Let me know your feedback.</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/3840193588308021666/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/3840193588308021666' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/3840193588308021666'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/3840193588308021666'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2010/03/hooking-your-class-into-wcf.html' title='Hooking Your class into WCF'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-2651600199763933670</id><published>2010-03-11T19:24:00.003+05:30</published><updated>2010-03-11T19:41:23.975+05:30</updated><title type='text'>How to Run the WCF Service on local system</title><content type='html'>For making WCF service to work you need to add the services end point and you can also define the binding with different transporter for e.g net.tcp, http&lt;br /&gt;Below is the code how you can define these bindings.&lt;br /&gt;&lt;br /&gt;1.First you need to define the ServiceHost which will take type of your class which inherited the service contract.&lt;br /&gt;&lt;br /&gt;using System.ServiceModel; &lt;br /&gt;ServiceHost selfHost = new ServiceHost(typeof(&quot;Type of your class&quot;), baseAddress);&lt;br /&gt;&lt;br /&gt;2. Second you need to Add service point to this service host which will take type of you service contract and also the name of class which inherited this service contract.&lt;br /&gt;&lt;br /&gt;selfHost.AddServiceEndpoint(&lt;br /&gt;typeof(IUploadInterface),&lt;br /&gt;new WSHttpBinding(),&lt;br /&gt;&quot;UploadClass&quot;);&lt;br /&gt;3. You need to create the service meta behaviour and need to set HttpGetEnable to true so that it will enabled Http request on your service and you also need to define the url of your service which include the port number and the class name.&lt;br /&gt;&lt;br /&gt;ServiceMetadataBehavior smb = new ServiceMetadataBehavior();&lt;br /&gt;smb.HttpGetEnabled = true;&lt;br /&gt;smb.HttpGetUrl = new Uri(&quot;http://localhost:8000/UploadClass&quot;);&lt;br /&gt;selfHost.Description.Behaviors.Add(smb);&lt;br /&gt;&lt;br /&gt;4. You need to open the service host &lt;br /&gt;selfHost.Open();</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/2651600199763933670/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/2651600199763933670' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/2651600199763933670'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/2651600199763933670'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2010/03/how-to-run-wcf-service-on-local-system.html' title='How to Run the WCF Service on local system'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-2361895292682539492</id><published>2010-03-08T15:04:00.003+05:30</published><updated>2010-03-08T15:30:52.681+05:30</updated><title type='text'>XML with Linq</title><content type='html'>&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgHAOnWXKsyljuu7kbHCBH78_Qev-piT6f172NNPDjXDyCh8QW4jY8iuLw9EmeOxA-CqmorBwpGmll6wovt0x7fDzl-Sl-ZGPb0dSY0E2EslPxBj2q3nAkUcyscV9Fi9D-KvKjX/s1600-h/Generated+XML.bmp&quot;&gt;&lt;img style=&quot;float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 320px; height: 49px;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgHAOnWXKsyljuu7kbHCBH78_Qev-piT6f172NNPDjXDyCh8QW4jY8iuLw9EmeOxA-CqmorBwpGmll6wovt0x7fDzl-Sl-ZGPb0dSY0E2EslPxBj2q3nAkUcyscV9Fi9D-KvKjX/s320/Generated+XML.bmp&quot; border=&quot;0&quot; alt=&quot;&quot;id=&quot;BLOGGER_PHOTO_ID_5446199384313329938&quot; /&gt;&lt;/a&gt;&lt;br /&gt;System.Xml.Linq namespace provide good way of working with XML you don&#39;t need to create a DOM object you can smiply create a object of XElement object and then define you XML and after defining the complete XML you can save this XML by smiply calling Save method of XElement object.&lt;br /&gt;&lt;br /&gt;For e.g &lt;br /&gt;If I want to generate one XML through XML.Linq first I need to create an object of XElement for root tag  and inside that define the nested object of XElement which will become child elements of the root XElement.&lt;br /&gt;&lt;br /&gt;  xlElement = new XElement(&quot;configuration&quot;,&lt;br /&gt;                new XElement(&quot;configSections&quot;,&lt;br /&gt;                  new XElement(&quot;section&quot;, new XAttribute(&quot;name&quot;, &quot;log4net&quot;),&lt;br /&gt;                                          new XAttribute(&quot;type&quot;, &quot;log4net.Config.Log4                                         NetConfigurationSectionHandler, log4net&quot;))),&lt;br /&gt;                new XElement(&quot;log4net&quot;, new XAttribute(&quot;debug&quot;, &quot;true&quot;)),&lt;br /&gt;                  new XElement(&quot;appender&quot;, new XAttribute                 (&quot;name&quot;, &quot;AppTraceFileAppender&quot;), new XAttribute(&quot;type&quot;, &quot;log4net.Appender.FileAppender&quot;)),&lt;br /&gt;                 new XElement(&quot;param&quot;, new XAttribute(&quot;name&quot;, &quot;File&quot;), new XAttribute&lt;br /&gt;(&quot;value&quot;, &quot;&quot;)));&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;In this case it will create an XML object with root element as Configuration and inside that we have neseted childs,In above senario we have define attribute of an elements with the help of XAttribute calss.&lt;br /&gt;&lt;br /&gt;After defining this simply call xlElement.Save(filePath);</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/2361895292682539492/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/2361895292682539492' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/2361895292682539492'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/2361895292682539492'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2010/03/xml-with-linq.html' title='XML with Linq'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgHAOnWXKsyljuu7kbHCBH78_Qev-piT6f172NNPDjXDyCh8QW4jY8iuLw9EmeOxA-CqmorBwpGmll6wovt0x7fDzl-Sl-ZGPb0dSY0E2EslPxBj2q3nAkUcyscV9Fi9D-KvKjX/s72-c/Generated+XML.bmp" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-687028927377279223</id><published>2010-03-04T10:27:00.002+05:30</published><updated>2010-03-04T10:33:53.672+05:30</updated><title type='text'>Adding file as Link</title><content type='html'>Whenever you have files/dll which is going to refer from more that one project of a common solution you can put that in common location and add that dll/files as link. Benefit of adding a file as a link is one copy of that dll/file will be shared by all the project and whenever you change something in shared dll/file it will reflect in all the link refrence.&lt;br /&gt;&lt;br /&gt;How to Add dll/file as link.&lt;br /&gt;&lt;br /&gt;1. Right click on project choose add existing item&lt;br /&gt;2. file add dialog box apprear.&lt;br /&gt;3. Choose the file and click on combobox showing in Add button of file add dialog    box.&lt;br /&gt;4. Choose add as a link.</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/687028927377279223/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/687028927377279223' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/687028927377279223'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/687028927377279223'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2010/03/adding-file-as-link.html' title='Adding file as Link'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-3766598203419879342</id><published>2010-03-03T10:06:00.007+05:30</published><updated>2010-03-03T10:22:46.905+05:30</updated><title type='text'>Using XPathDocument in place of DataSet</title><content type='html'>//Create object of XPathDocument&lt;br /&gt;   XPathDocument docNav = new XPathDocument(strPath);&lt;br /&gt;   //Create the XPathNavigator&lt;br /&gt;   XPathNavigator nav = docNav.CreateNavigator();&lt;br /&gt;   //Set the pointer at ShoppingRule node&lt;br /&gt;   expr = nav.Compile(&quot;/Rule/ShoppingRule&quot;);&lt;br /&gt;   //Get all the ShoppingRule node from the XML.&lt;br /&gt;   XPathNodeIterator parentIterator = nav.Select(expr);&lt;br /&gt;     //Treverse on all the shoppingRules node    &lt;br /&gt;     while(parentIterator.MoveNext()&lt;br /&gt;     {&lt;br /&gt;        if (parentIterator.Current.HasChildren)&lt;br /&gt;           {&lt;br /&gt;             //Move to the first child node of the ShoppingRules&lt;br /&gt;             parentIterator.Current.MoveToChild(XPathNodeType.Element); &lt;br /&gt;             strTransactionCode = parentIterator.Current.Value;&lt;br /&gt;           }&lt;br /&gt;       //Get all the childs of ShoppingRules node&lt;br /&gt;       XPathNodeIterator children = childNode.SelectChildren(XPathNodeType.Element);&lt;br /&gt;       //Traverse on all the child node of the ShoppingRules nodes.&lt;br /&gt;       while (children.MoveNext())&lt;br /&gt;       {&lt;br /&gt;       }&lt;br /&gt;     }</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/3766598203419879342/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/3766598203419879342' title='31 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/3766598203419879342'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/3766598203419879342'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2010/03/using-xpathdocument-in-place-of-dataset.html' title='Using XPathDocument in place of DataSet'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>31</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-3840459140458432149</id><published>2008-12-17T11:11:00.001+05:30</published><updated>2011-11-16T13:47:08.753+05:30</updated><title type='text'>The MRU List</title><content type='html'>One of the truisms of search is that if you search for something once, you’re likely to search for it again. In addition, some things are searched for much more often than others. It makes sense, then to cache the results for the most common searches so that you don’t have to query the database or other backing store in order to return results. That way you can satisfy the most common requests very quickly, reducing the load on your back-end database.
&lt;br /&gt;
&lt;br /&gt;The problem, of course, is that you can’t cache all search results. If you could, you wouldn’t need a database to hold the information. The question becomes one of how to determine which results you should store in memory. One method that works very well is the Most Recently Used (MRU) list.
&lt;br /&gt;
&lt;br /&gt;The idea is to keep some small number of the most recently requested results in memory. When somebody performs a search, the program checks the MRU list first. If the results are found in the MRU list, then those results moved to the front of the list. If the requested results are not in the list, then the program queries the database to obtain the results, places those new results at the front of the list, and removes the results from the back of the list--the least recently used results.
&lt;br /&gt;
&lt;br /&gt;Because items are moved back to the front of the list each time they’re requested, the most frequently requested results will remain in the list, and things that are requested infrequently will fall off the back of the list.
&lt;br /&gt;
&lt;br /&gt;This technique works well when searches follow the common pattern: a few terms being much more frequently requested than others. If searches are randomly distributed, the MRU list is not at all affected, because it’s likely that the requested results won’t be in the cache.
&lt;br /&gt;
&lt;br /&gt;The .NET LinkedList class is an excellent choice for implementing an MRU list because moving things around in the list is a constant-time operation. That is, it takes the same amount of time to insert or remove an item in a list of 10,000 items as it does in a list of 10 items.
&lt;br /&gt;
&lt;br /&gt;The MRU List interface requires a way to determine if an item is in the list, and a way to add something to the list. Also, the constructor should let you say how many items the list should hold. That’s really all there is to it, but implementation is just a little bit tricky.
&lt;br /&gt;
&lt;br /&gt;We can build the MRU list as a generic class with two type parameters: the type of object to be stored in the linked list, and the type of key used to search for items. The key is important because the LinkedList.Find method searches the list looking for a particular object reference, rather than a key value. We’ll have to implement our own key search.
&lt;br /&gt;
&lt;br /&gt;The constructor requires two parameters: an integer that specifies the maximum number of items that the MRU list can hold, and a comparison function that can compare a key value against a list object to determine if the object matches the key. The final interface looks like this:
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;using System;
&lt;br /&gt;using System.Collections.Generic;
&lt;br /&gt;using System.Text;
&lt;br /&gt;
&lt;br /&gt;namespace MostRecentlyUsedList
&lt;br /&gt;{
&lt;br /&gt;    public delegate bool MruEqualityComparer&lt;K, T&gt;(K key, T item);
&lt;br /&gt;
&lt;br /&gt;    public class MruList &lt;K, T&gt;
&lt;br /&gt;    {
&lt;br /&gt;        private LinkedList&lt;T&gt; items;
&lt;br /&gt;        private int maxCapacity;
&lt;br /&gt;        private MruEqualityComparer&lt;K, T&gt; compareFunc;
&lt;br /&gt;
&lt;br /&gt;        public MruList(int maxCap, MruEqualityComparer&lt;K, T&gt; compFunc)
&lt;br /&gt;        {
&lt;br /&gt;            maxCapacity = maxCap;
&lt;br /&gt;            compareFunc = compFunc;
&lt;br /&gt;            items = new LinkedList&lt;T&gt;();
&lt;br /&gt;        }
&lt;br /&gt;
&lt;br /&gt;        public T Find(K key)
&lt;br /&gt;        {
&lt;br /&gt;            LinkedListNode&lt;T&gt; node = FindNode(key);
&lt;br /&gt;            if (node != null)
&lt;br /&gt;            {
&lt;br /&gt;                items.Remove(node);
&lt;br /&gt;                items.AddFirst(node);
&lt;br /&gt;                return node.Value;
&lt;br /&gt;            }
&lt;br /&gt;            return default(T);
&lt;br /&gt;        }
&lt;br /&gt;
&lt;br /&gt;        private LinkedListNode&lt;T&gt; FindNode(K key)
&lt;br /&gt;        {
&lt;br /&gt;            LinkedListNode&lt;T&gt; node = items.First;
&lt;br /&gt;            while (node != null)
&lt;br /&gt;            {
&lt;br /&gt;                if (compareFunc(key, node.Value))
&lt;br /&gt;                    return node;
&lt;br /&gt;                node = node.Next;
&lt;br /&gt;            }
&lt;br /&gt;            return null;
&lt;br /&gt;        }
&lt;br /&gt;
&lt;br /&gt;        public void Add(T item)
&lt;br /&gt;        {
&lt;br /&gt;            // remove items until the list is no longer full.
&lt;br /&gt;            while (items.Count &gt;= maxCapacity)
&lt;br /&gt;            {
&lt;br /&gt;                items.RemoveLast();
&lt;br /&gt;            }
&lt;br /&gt;            items.AddFirst(item);
&lt;br /&gt;        }
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;    }
&lt;br /&gt;}
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;static class Program
&lt;br /&gt;    {
&lt;br /&gt;        static private MruList&lt;string, SearchResult&gt; mru;
&lt;br /&gt;        /// &lt;summary&gt;
&lt;br /&gt;        /// The main entry point for the application.
&lt;br /&gt;        /// &lt;/summary&gt;
&lt;br /&gt;        [STAThread]
&lt;br /&gt;        static void Main()
&lt;br /&gt;        {
&lt;br /&gt;
&lt;br /&gt;            mru = new MruList&lt;string, SearchResult&gt;(1000, KeyCompare);
&lt;br /&gt;
&lt;br /&gt;            for (int count = 0; count &lt; 1000; count++)
&lt;br /&gt;            {
&lt;br /&gt;                mru.Add(new SearchResult(&quot;Jim&quot; + count, count));
&lt;br /&gt;            }
&lt;br /&gt;            FindItem(&quot;Jim999&quot;);
&lt;br /&gt;           
&lt;br /&gt;        }
&lt;br /&gt;
&lt;br /&gt;        static private bool KeyCompare(string key, SearchResult item)
&lt;br /&gt;        {
&lt;br /&gt;            return key.Equals(item.Name);
&lt;br /&gt;        }
&lt;br /&gt;
&lt;br /&gt;        static private void FindItem(string key)
&lt;br /&gt;        {
&lt;br /&gt;            SearchResult rslt = mru.Find(key);
&lt;br /&gt;            if (rslt == null)
&lt;br /&gt;            {
&lt;br /&gt;                Console.WriteLine(&quot;’{0}’ not found&quot;, key);
&lt;br /&gt;            }
&lt;br /&gt;            else
&lt;br /&gt;            {
&lt;br /&gt;                Console.WriteLine(&quot;’{0}’ is {1}&quot;, rslt.Name, rslt.Age);
&lt;br /&gt;            }
&lt;br /&gt;            
&lt;br /&gt;        }
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;    }
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;    class SearchResult
&lt;br /&gt;    {
&lt;br /&gt;        private string _name;
&lt;br /&gt;        private int _age;
&lt;br /&gt;
&lt;br /&gt;        public SearchResult(string n, int a)
&lt;br /&gt;        {
&lt;br /&gt;            _name = n;
&lt;br /&gt;            _age = a;
&lt;br /&gt;        }
&lt;br /&gt;
&lt;br /&gt;        public string Name
&lt;br /&gt;        {
&lt;br /&gt;            get { return _name; }
&lt;br /&gt;        }
&lt;br /&gt;
&lt;br /&gt;        public int Age
&lt;br /&gt;        {
&lt;br /&gt;            get { return _age; }
&lt;br /&gt;        }
&lt;br /&gt;    }
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/3840459140458432149/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/3840459140458432149' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/3840459140458432149'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/3840459140458432149'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2008/12/mru-list_17.html' title='The MRU List'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-4986357681932235785</id><published>2008-12-17T11:11:00.000+05:30</published><updated>2008-12-17T11:13:30.131+05:30</updated><title type='text'>The MRU List</title><content type='html'>One of the truisms of search is that if you search for something once, you’re likely to search for it again. In addition, some things are searched for much more often than others. It makes sense, then to cache the results for the most common searches so that you don’t have to query the database or other backing store in order to return results. That way you can satisfy the most common requests very quickly, reducing the load on your back-end database.&lt;br /&gt;&lt;br /&gt;The problem, of course, is that you can’t cache all search results. If you could, you wouldn’t need a database to hold the information. The question becomes one of how to determine which results you should store in memory. One method that works very well is the Most Recently Used (MRU) list.&lt;br /&gt;&lt;br /&gt;The idea is to keep some small number of the most recently requested results in memory. When somebody performs a search, the program checks the MRU list first. If the results are found in the MRU list, then those results moved to the front of the list. If the requested results are not in the list, then the program queries the database to obtain the results, places those new results at the front of the list, and removes the results from the back of the list--the least recently used results.&lt;br /&gt;&lt;br /&gt;Because items are moved back to the front of the list each time they’re requested, the most frequently requested results will remain in the list, and things that are requested infrequently will fall off the back of the list.&lt;br /&gt;&lt;br /&gt;This technique works well when searches follow the common pattern: a few terms being much more frequently requested than others. If searches are randomly distributed, the MRU list is not at all affected, because it’s likely that the requested results won’t be in the cache.&lt;br /&gt;&lt;br /&gt;The .NET LinkedList class is an excellent choice for implementing an MRU list because moving things around in the list is a constant-time operation. That is, it takes the same amount of time to insert or remove an item in a list of 10,000 items as it does in a list of 10 items.&lt;br /&gt;&lt;br /&gt;The MRU List interface requires a way to determine if an item is in the list, and a way to add something to the list. Also, the constructor should let you say how many items the list should hold. That’s really all there is to it, but implementation is just a little bit tricky.&lt;br /&gt;&lt;br /&gt;We can build the MRU list as a generic class with two type parameters: the type of object to be stored in the linked list, and the type of key used to search for items. The key is important because the LinkedList.Find method searches the list looking for a particular object reference, rather than a key value. We’ll have to implement our own key search.&lt;br /&gt;&lt;br /&gt;The constructor requires two parameters: an integer that specifies the maximum number of items that the MRU list can hold, and a comparison function that can compare a key value against a list object to determine if the object matches the key. The final interface looks like this:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;using System;&lt;br /&gt;using System.Collections.Generic;&lt;br /&gt;using System.Text;&lt;br /&gt;&lt;br /&gt;namespace MostRecentlyUsedList&lt;br /&gt;{&lt;br /&gt;    public delegate bool MruEqualityComparer&lt;K, T&gt;(K key, T item);&lt;br /&gt;&lt;br /&gt;    public class MruList &lt;K, T&gt;&lt;br /&gt;    {&lt;br /&gt;        private LinkedList&lt;T&gt; items;&lt;br /&gt;        private int maxCapacity;&lt;br /&gt;        private MruEqualityComparer&lt;K, T&gt; compareFunc;&lt;br /&gt;&lt;br /&gt;        public MruList(int maxCap, MruEqualityComparer&lt;K, T&gt; compFunc)&lt;br /&gt;        {&lt;br /&gt;            maxCapacity = maxCap;&lt;br /&gt;            compareFunc = compFunc;&lt;br /&gt;            items = new LinkedList&lt;T&gt;();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public T Find(K key)&lt;br /&gt;        {&lt;br /&gt;            LinkedListNode&lt;T&gt; node = FindNode(key);&lt;br /&gt;            if (node != null)&lt;br /&gt;            {&lt;br /&gt;                items.Remove(node);&lt;br /&gt;                items.AddFirst(node);&lt;br /&gt;                return node.Value;&lt;br /&gt;            }&lt;br /&gt;            return default(T);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private LinkedListNode&lt;T&gt; FindNode(K key)&lt;br /&gt;        {&lt;br /&gt;            LinkedListNode&lt;T&gt; node = items.First;&lt;br /&gt;            while (node != null)&lt;br /&gt;            {&lt;br /&gt;                if (compareFunc(key, node.Value))&lt;br /&gt;                    return node;&lt;br /&gt;                node = node.Next;&lt;br /&gt;            }&lt;br /&gt;            return null;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void Add(T item)&lt;br /&gt;        {&lt;br /&gt;            // remove items until the list is no longer full.&lt;br /&gt;            while (items.Count &gt;= maxCapacity)&lt;br /&gt;            {&lt;br /&gt;                items.RemoveLast();&lt;br /&gt;            }&lt;br /&gt;            items.AddFirst(item);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;static class Program&lt;br /&gt;    {&lt;br /&gt;        static private MruList&lt;string, SearchResult&gt; mru;&lt;br /&gt;        /// &lt;summary&gt;&lt;br /&gt;        /// The main entry point for the application.&lt;br /&gt;        /// &lt;/summary&gt;&lt;br /&gt;        [STAThread]&lt;br /&gt;        static void Main()&lt;br /&gt;        {&lt;br /&gt;&lt;br /&gt;            mru = new MruList&lt;string, SearchResult&gt;(1000, KeyCompare);&lt;br /&gt;&lt;br /&gt;            for (int count = 0; count &lt; 1000; count++)&lt;br /&gt;            {&lt;br /&gt;                mru.Add(new SearchResult(&quot;Jim&quot; + count, count));&lt;br /&gt;            }&lt;br /&gt;            FindItem(&quot;Jim999&quot;);&lt;br /&gt;           &lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        static private bool KeyCompare(string key, SearchResult item)&lt;br /&gt;        {&lt;br /&gt;            return key.Equals(item.Name);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        static private void FindItem(string key)&lt;br /&gt;        {&lt;br /&gt;            SearchResult rslt = mru.Find(key);&lt;br /&gt;            if (rslt == null)&lt;br /&gt;            {&lt;br /&gt;                Console.WriteLine(&quot;’{0}’ not found&quot;, key);&lt;br /&gt;            }&lt;br /&gt;            else&lt;br /&gt;            {&lt;br /&gt;                Console.WriteLine(&quot;’{0}’ is {1}&quot;, rslt.Name, rslt.Age);&lt;br /&gt;            }&lt;br /&gt;            &lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    class SearchResult&lt;br /&gt;    {&lt;br /&gt;        private string _name;&lt;br /&gt;        private int _age;&lt;br /&gt;&lt;br /&gt;        public SearchResult(string n, int a)&lt;br /&gt;        {&lt;br /&gt;            _name = n;&lt;br /&gt;            _age = a;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public string Name&lt;br /&gt;        {&lt;br /&gt;            get { return _name; }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public int Age&lt;br /&gt;        {&lt;br /&gt;            get { return _age; }&lt;br /&gt;        }&lt;br /&gt;    }</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/4986357681932235785/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/4986357681932235785' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/4986357681932235785'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/4986357681932235785'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2008/12/mru-list.html' title='The MRU List'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-2927748326853720601</id><published>2008-12-16T16:52:00.002+05:30</published><updated>2008-12-16T17:05:01.889+05:30</updated><title type='text'>Factory Method</title><content type='html'>&lt;strong&gt;Definition&lt;/strong&gt;&lt;br /&gt;Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.&lt;br /&gt;&lt;br /&gt;using System;&lt;br /&gt;using System.Collections;&lt;br /&gt;&lt;br /&gt;namespace GangOfFour.Factory&lt;br /&gt;{&lt;br /&gt;    /// &lt;summary&gt;&lt;br /&gt;    /// MainApp startup class for Real-World &lt;br /&gt;    /// Factory Method Design Pattern.&lt;br /&gt;    /// &lt;/summary&gt;&lt;br /&gt;    class MainApp&lt;br /&gt;    {&lt;br /&gt;        /// &lt;summary&gt;&lt;br /&gt;        /// Entry point into console application.&lt;br /&gt;        /// &lt;/summary&gt;&lt;br /&gt;        static void Main()&lt;br /&gt;        {&lt;br /&gt;            // Note: constructors call Factory Method&lt;br /&gt;            Document[] documents = new Document[2];&lt;br /&gt;            documents[0] = new Resume();&lt;br /&gt;            documents[1] = new Report();&lt;br /&gt;&lt;br /&gt;            // Display document pages&lt;br /&gt;            foreach (Document document in documents)&lt;br /&gt;            {&lt;br /&gt;                Console.WriteLine(&quot;\n&quot; + document.GetType().Name+ &quot;--&quot;);&lt;br /&gt;                foreach (Page page in document.Pages)&lt;br /&gt;                {&lt;br /&gt;                    Console.WriteLine(&quot; &quot; + page.GetType().Name);&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            // Wait for user&lt;br /&gt;            Console.Read();        &lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // &quot;Product&quot;&lt;br /&gt;&lt;br /&gt;    abstract class Page&lt;br /&gt;    {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // &quot;ConcreteProduct&quot;&lt;br /&gt;&lt;br /&gt;    class SkillsPage : Page&lt;br /&gt;    {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // &quot;ConcreteProduct&quot;&lt;br /&gt;&lt;br /&gt;    class EducationPage : Page&lt;br /&gt;    {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // &quot;ConcreteProduct&quot;&lt;br /&gt;&lt;br /&gt;    class ExperiencePage : Page&lt;br /&gt;    {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // &quot;ConcreteProduct&quot;&lt;br /&gt;&lt;br /&gt;    class IntroductionPage : Page&lt;br /&gt;    {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // &quot;ConcreteProduct&quot;&lt;br /&gt;&lt;br /&gt;    class ResultsPage : Page&lt;br /&gt;    {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // &quot;ConcreteProduct&quot;&lt;br /&gt;&lt;br /&gt;    class ConclusionPage : Page&lt;br /&gt;    {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // &quot;ConcreteProduct&quot;&lt;br /&gt;&lt;br /&gt;    class SummaryPage : Page&lt;br /&gt;    {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // &quot;ConcreteProduct&quot;&lt;br /&gt;&lt;br /&gt;    class BibliographyPage : Page&lt;br /&gt;    {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // &quot;Creator&quot;&lt;br /&gt;&lt;br /&gt;    abstract class Document&lt;br /&gt;    {&lt;br /&gt;        private ArrayList pages = new ArrayList();&lt;br /&gt;&lt;br /&gt;        // Constructor calls abstract Factory method&lt;br /&gt;        public Document()&lt;br /&gt;        {&lt;br /&gt;            this.CreatePages();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public ArrayList Pages&lt;br /&gt;        {&lt;br /&gt;            get{ return pages; }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Factory Method&lt;br /&gt;        public abstract void CreatePages();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // &quot;ConcreteCreator&quot;&lt;br /&gt;&lt;br /&gt;    class Resume : Document&lt;br /&gt;    {&lt;br /&gt;        // Factory Method implementation&lt;br /&gt;        public override void CreatePages()&lt;br /&gt;        {&lt;br /&gt;            Pages.Add(new SkillsPage());&lt;br /&gt;            Pages.Add(new EducationPage());&lt;br /&gt;            Pages.Add(new ExperiencePage());&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // &quot;ConcreteCreator&quot;&lt;br /&gt;&lt;br /&gt;    class Report : Document&lt;br /&gt;    {&lt;br /&gt;        // Factory Method implementation&lt;br /&gt;        public override void CreatePages()&lt;br /&gt;        {&lt;br /&gt;            Pages.Add(new IntroductionPage());&lt;br /&gt;            Pages.Add(new ResultsPage());&lt;br /&gt;            Pages.Add(new ConclusionPage());&lt;br /&gt;            Pages.Add(new SummaryPage());&lt;br /&gt;            Pages.Add(new BibliographyPage());&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Factory Method:when and where use it&lt;/strong&gt;: &lt;br /&gt;Class constructors exist so that clients can create an instance of a class. There are situations however, where the client does not, or should not, know which of several possible classes to instantiate. The Factory Method allows the client to use an interface for creating an object while still retaining control over which class to instantiate.&lt;br /&gt;The key objective of the Factory Method is extensibility. Factory Methods are frequently used in applications that manage, maintain, or manipulate collections of objects that are different but at the same time have many characteristics in common. A document management system for example is more extensible if you reference your documents as a collections of IDocuments. These documents may be Text files, Word documents, Visio diagrams, or legal papers. They all have an author, a title, a type, a size, a location, a page count, etc. If a new type of document is introduced it simply has to implement the IDocument interface and it will fit in with the rest of the documents. To support this new document type the Factory Method code may or may not have to be adjusted (depending on how it was implemented - with or without parameters).&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Factory Method in .NET Framework&lt;/strong&gt;&lt;br /&gt;The Factory Method is commonly used in .NET. An example is the System.Convert class which exposes many static methods that, given an instance of a type, returns another new type. For example, Convert.ToBoolean accepts a string and returns&lt;br /&gt;boolean with value true or false depending on the string value (“true” or “false”).&lt;br /&gt;In .NET the Factory Method is typically implemented as a static method which creates an instance of a particular type determined at compile time. In other words, these methods don’t return base classes or interface types of which the true type is only known at runtime. This is exactly where Abstact Factory and Factory Method differ; Abstract Factory methods are virtual or abstract and return abstract classes or interfaces. Factory Methods are abstract and return class types.</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/2927748326853720601/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/2927748326853720601' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/2927748326853720601'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/2927748326853720601'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2008/12/factory-method.html' title='Factory Method'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-3473449874115784504</id><published>2008-12-12T17:04:00.002+05:30</published><updated>2008-12-12T17:28:55.754+05:30</updated><title type='text'>Abstract Facotry</title><content type='html'>&lt;strong&gt;Definition&lt;/strong&gt;&lt;br /&gt;Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&lt;br /&gt;Frequency of use: high&lt;br /&gt;&lt;br /&gt;using System;&lt;br /&gt;&lt;br /&gt;namespace DoFactory.GangOfFour.Adapter&lt;br /&gt;{&lt;br /&gt;    &lt;br /&gt;    class MainApp&lt;br /&gt;    {&lt;br /&gt;        /// &lt;summary&gt;&lt;br /&gt;        /// Entry point into console application.&lt;br /&gt;        /// &lt;/summary&gt;&lt;br /&gt;        static void Main()&lt;br /&gt;        {&lt;br /&gt;            // Non-adapted chemical compound&lt;br /&gt;            Compound unknown = new Compound(Chemical.Unknown);&lt;br /&gt;            unknown.Display();&lt;br /&gt;&lt;br /&gt;            // Adapted chemical compounds&lt;br /&gt;            Compound water = new RichCompound(Chemical.Water);&lt;br /&gt;            water.Display();&lt;br /&gt;&lt;br /&gt;            Compound benzene = new RichCompound(Chemical.Benzene);&lt;br /&gt;            benzene.Display();&lt;br /&gt;&lt;br /&gt;            Compound alcohol = new RichCompound(Chemical.Alcohol);&lt;br /&gt;            alcohol.Display();&lt;br /&gt;&lt;br /&gt;            // Wait for user&lt;br /&gt;            Console.Read();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // &quot;Target&quot;&lt;br /&gt;&lt;br /&gt;    class Compound&lt;br /&gt;    {&lt;br /&gt;        private Chemical name;&lt;br /&gt;        private float boilingPoint;&lt;br /&gt;        private float meltingPoint;&lt;br /&gt;        private double molecularWeight;&lt;br /&gt;        private string molecularFormula;&lt;br /&gt;&lt;br /&gt;        // Constructor&lt;br /&gt;        public Compound(Chemical name)&lt;br /&gt;        {&lt;br /&gt;            this.name = name;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public virtual void Display()&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(&quot;\nCompound: {0} -- &quot;, Name);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Properties&lt;br /&gt;        public Chemical Name&lt;br /&gt;        {&lt;br /&gt;            get{ return name; }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public float BoilingPoint&lt;br /&gt;        {&lt;br /&gt;            get{ return boilingPoint; }&lt;br /&gt;            set{ boilingPoint = value; }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public float MeltingPoint&lt;br /&gt;        {&lt;br /&gt;            get{ return meltingPoint; }&lt;br /&gt;            set{ meltingPoint = value; }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public double MolecularWeight&lt;br /&gt;        {&lt;br /&gt;            get{ return molecularWeight; }&lt;br /&gt;            set{ molecularWeight = value; }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public string MolecularFormula&lt;br /&gt;        {&lt;br /&gt;            get{ return molecularFormula; }&lt;br /&gt;            set{ molecularFormula = value; }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // &quot;Adapter&quot;&lt;br /&gt;&lt;br /&gt;    class RichCompound : Compound&lt;br /&gt;    {&lt;br /&gt;        private ChemicalDatabank bank;&lt;br /&gt;&lt;br /&gt;        // Constructor&lt;br /&gt;        public RichCompound(Chemical name) : base(name)&lt;br /&gt;        {    &lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public override void Display()&lt;br /&gt;        {&lt;br /&gt;            // Adaptee&lt;br /&gt;            bank = new ChemicalDatabank();&lt;br /&gt;&lt;br /&gt;            // Adaptee request methods&lt;br /&gt;            BoilingPoint = bank.GetCriticalPoint(Name, State.Boiling);&lt;br /&gt;            MeltingPoint = bank.GetCriticalPoint(Name, State.Melting);&lt;br /&gt;            MolecularWeight  = bank.GetMolecularWeight(Name);&lt;br /&gt;            MolecularFormula = bank.GetMolecularStructure(Name);&lt;br /&gt;&lt;br /&gt;            base.Display();&lt;br /&gt;            Console.WriteLine(&quot; Formula: {0}&quot;, MolecularFormula);&lt;br /&gt;            Console.WriteLine(&quot; Weight : {0}&quot;, MolecularWeight);&lt;br /&gt;            Console.WriteLine(&quot; Melting Pt: {0}&quot;, MeltingPoint);&lt;br /&gt;            Console.WriteLine(&quot; Boiling Pt: {0}&quot;, BoilingPoint);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // &quot;Adaptee&quot;&lt;br /&gt;&lt;br /&gt;    class ChemicalDatabank&lt;br /&gt;    {&lt;br /&gt;        // The Databank &#39;legacy API&#39;&lt;br /&gt;        public float GetCriticalPoint(Chemical compound, State point)&lt;br /&gt;        {&lt;br /&gt;            float temperature = 0.0F;&lt;br /&gt;&lt;br /&gt;            // Melting Point&lt;br /&gt;            if (point == State.Melting)&lt;br /&gt;            {&lt;br /&gt;                switch (compound)&lt;br /&gt;                {&lt;br /&gt;                    case Chemical.Water   : temperature = 0.0F;    break;&lt;br /&gt;                    case Chemical.Benzene : temperature = 5.5F;    break;&lt;br /&gt;                    case Chemical.Alcohol : temperature = -114.1F; break;&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;                // Boiling Point&lt;br /&gt;            else if (point == State.Boiling)&lt;br /&gt;            {&lt;br /&gt;                switch (compound)&lt;br /&gt;                {&lt;br /&gt;                    case Chemical.Water   : temperature = 100.0F; break;&lt;br /&gt;                    case Chemical.Benzene : temperature = 80.1F;  break;&lt;br /&gt;                    case Chemical.Alcohol : temperature = 78.3F;  break;&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;            return temperature;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public string GetMolecularStructure(Chemical compound)&lt;br /&gt;        {&lt;br /&gt;            string structure = &quot;&quot;;&lt;br /&gt;&lt;br /&gt;            switch (compound)&lt;br /&gt;            {&lt;br /&gt;                case Chemical.Water   : structure = &quot;H20&quot;;    break;&lt;br /&gt;                case Chemical.Benzene : structure = &quot;C6H6&quot;;   break;&lt;br /&gt;                case Chemical.Alcohol : structure = &quot;C2H6O2&quot;; break;&lt;br /&gt;            }&lt;br /&gt;            return structure;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public double GetMolecularWeight(Chemical compound)&lt;br /&gt;        {&lt;br /&gt;            double weight = 0.0;&lt;br /&gt;            switch (compound)&lt;br /&gt;            {&lt;br /&gt;                case Chemical.Water   : weight = 18.015;  break;&lt;br /&gt;                case Chemical.Benzene : weight = 78.1134; break;&lt;br /&gt;                case Chemical.Alcohol : weight = 46.0688; break;&lt;br /&gt;            }&lt;br /&gt;            return weight;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Enumerations&lt;br /&gt;&lt;br /&gt;    public enum Chemical&lt;br /&gt;    {&lt;br /&gt;        Unknown,&lt;br /&gt;        Water,&lt;br /&gt;        Benzene,&lt;br /&gt;        Alcohol&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public enum State&lt;br /&gt;    {&lt;br /&gt;        Boiling,&lt;br /&gt;        Melting&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;&lt;br /&gt;.NET optimized sample code&lt;/strong&gt;&lt;br /&gt;The .NET optimized code demonstrates the same code as above but uses more modern, built-in .NET features. In this example, abstract classes have been replaced by interfaces because the abstract classes do not contain implementation code. Continents are represented as enumerations. The AnimalWorld constructor dynamically creates the desired abstract factory using the Continent enumerated values.&lt;br /&gt;Code in project: DoFactory.GangOfFour.Abstract.NetOptimized&lt;br /&gt;Abstract Factory: when and where use it&lt;br /&gt;The Abstract Factory pattern provides a client with a class that creates objects that are related by a common theme. The classic example is that of a GUI component factory which creates UI controls for different windowing systems, such as, Windows, Motif, or MacOS. If you’re familiar with Java Swing you’ll recognize it as a good example of the use of the Abstract Factory pattern to build UI interfaces that are independent of their hosting platform. From a design pattern perspective, Java Swing succeeded, but applications built on this platform perform poorly and are not very interactive or responsive compared to native Windows or native Motif applications.&lt;br /&gt;Over time the meaning of the Abtract Factory pattern has changed somewhat compared to the original GoF definition. Today, when developers talk about the Abstract Factory pattern they do not only mean the creation of a ‘family of related or dependent’ objects but also include the creation of individual object instances.&lt;br /&gt;Next are some reasons and benefits for creating objects using an Abstract Factory rather than calling constructors directly:&lt;br /&gt;Constructors are limited in their control over the overall creation process. If your application needs more control consider using a Factory. These include scenarios that involve object caching, sharing or re-using of objects, and applications that maintain object and type counts.&lt;br /&gt;&lt;br /&gt;There are times when the client does not know exactly what type to construct. It is easier to code against a base type or interface and a factory can take parameters or other context-based information to make this decision for the client. An example of this are the provider specific ADO.NET objects (DbConnection, DbCommand, DbDataAdapter, etc).&lt;br /&gt;Constructors don’t communicate their intention very well because they must be named after their class (or Sub New in VB.NET). Having numerous overloaded constructors may make it hard for the client developer to decide which constructor to use. Replacing constructors with intention-revealing creation methods are sometimes preferred. An example follows:&lt;br /&gt;Several overloaded constructors. Which one should you use?&lt;br /&gt;&lt;br /&gt;// C#&lt;br /&gt;public Vehicle (int passengers)&lt;br /&gt;public Vehicle (int passengers, int horsePower)&lt;br /&gt;public Vehicle (int wheels, bool trailer)&lt;br /&gt;public Vehicle (string type)&lt;br /&gt;&#39; VB.NET&lt;br /&gt;public Sub New (Byval passengers As Integer)&lt;br /&gt;public Sub New (Byval passengers As Integer, _&lt;br /&gt;Byval horsePower As Integer)&lt;br /&gt;public Sub New (Byval wheels As Integer wheels, _&lt;br /&gt;Byval trailer As Boolean)&lt;br /&gt;public Sub New (Byval type As String)&lt;br /&gt;The Factory pattern makes code more expressive and developers more productive&lt;br /&gt;// C#&lt;br /&gt;public Vehicle CreateCar (int passengers)&lt;br /&gt;public Vehicle CreateSuv (int passengers, int horsePower)&lt;br /&gt;public Vehicle CreateTruck (int wheels, bool trailer)&lt;br /&gt;public Vehicle CreateBoat ()&lt;br /&gt;public Vehicle CreateBike ()&lt;br /&gt;&#39; VB.NET&lt;br /&gt;public Function CreateCar (Byval passengers As Integer) As Vehicle&lt;br /&gt;public Function CreateSuv (Byval passengers As Integer, _&lt;br /&gt;Byval horsePower As Integer) As Vehicle&lt;br /&gt;public Function CreateTruck (Byval wheels As Integer, _&lt;br /&gt;Byval trailer As Boolean) As Vehicle&lt;br /&gt;public Function CreateBoat () As Vehicle&lt;br /&gt;public Function CreateBike () As Vehicle&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Abstract Factory in the .NET Framework&lt;/strong&gt;&lt;br /&gt;ADO.NET 2.0 includes two new Abstract Factory classes that offer provider independent data access techniques. They are: DbProviderFactory and DbProviderFactories. The DbProviderFactory class creates the ‘true’ (i.e. the database specific) classes you need, such as SqlClientConnection, SqlClientCommand, and SqlClientDataAdapter. Each managed provider (such as SqlClient, OleDb, ODBC, and Oracle) has its own DbProviderFactory class. DbProviderFactory objects are created by the DbProviderFactories class, which itself is a factory class. In fact, it is a factory of factories -- it manufactures different factories, one for each provider.&lt;br /&gt;When Microsoft talks about Abstract Factories they mean types that expose factory methods as virtual or abstract instance functions and return an abstract class or interface. Below is an example from .NET:&lt;br /&gt;// C#&lt;br /&gt;public abstract class StreamFactory&lt;br /&gt;{&lt;br /&gt;public abstract Stream CreateStream();&lt;br /&gt;}&lt;br /&gt;&#39; VB.NET&lt;br /&gt;Public MustInherit Class StreamFactory&lt;br /&gt;Public MustOverride Function CreateStream() As Stream&lt;br /&gt;End Class&lt;br /&gt;In this scenario your factory type inherits from StreamFactory and is used to dynamically select the actual Stream type being created:&lt;br /&gt;// C#&lt;br /&gt;public class MemoryStreamFactory : StreamFactory&lt;br /&gt;{&lt;br /&gt;...&lt;br /&gt;}&lt;br /&gt;&#39; VB.NET&lt;br /&gt;Public Class MemoryStreamFactory&lt;br /&gt;Inherits StreamFactory&lt;br /&gt;...&lt;br /&gt;End Class&lt;br /&gt;&lt;br /&gt;The naming convention in .NET is to appends the word ‘Factory’ to the name of&lt;br /&gt;that is being created. For example, a class that manufactures widget objects would&lt;br /&gt;named WidgetFactory. A search through the libraries for the word ‘Factory’ reveals numerous classes that are implementations of the Factory design pattern.</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/3473449874115784504/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/3473449874115784504' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/3473449874115784504'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/3473449874115784504'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2008/12/abstract-facotry.html' title='Abstract Facotry'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-5134814213615706629</id><published>2008-06-18T12:14:00.003+05:30</published><updated>2008-06-18T12:17:38.387+05:30</updated><title type='text'>Using SQL Management Objects to create.</title><content type='html'>SQL Management Objects (SMO) is a new set of programming objects that expose the management functionalities of the SQL Server Database. In simpler terms, with the help of SMO objects and their associated methods/attributes/functionalities we can automate SQL Server tasks which can range from &lt;br /&gt;&lt;br /&gt;Administrative Tasks - Retrieval of Database Server Settings, creating new databases Etc. &lt;br /&gt;Application Oriented Task - Applying T-SQL Scripts &lt;br /&gt;Scheduling Tasks - Creation of new Jobs, Running and maintenance of existing Jobs via SQL Server Agent. &lt;br /&gt;SMO is also an upgraded version of SQL-DMO (Database Management Objects) which came along earlier versions of SQL Server. Even the SQL Management Studios is utilizes SMO, therefore in theory one should be able to replicate any function which can be performed with the help of SQL Management Studios.&lt;br /&gt;&lt;br /&gt;Scope of the Article&lt;br /&gt;The scope of this document is to explain the use of SMO dynamic linked assembly for creation and restoration of databases .This involves creating copies of databases from an existing database template backup (.bak).&lt;br /&gt;&lt;br /&gt;Possible Applications&lt;br /&gt;Such an approach to database creation can be made to effective use in scenarios such as: &lt;br /&gt;&lt;br /&gt;Automated Database creation and Restoration:&lt;br /&gt;If a need arises to create &#39;N&#39; number of database and restore them from a common database backup (.bak). &lt;br /&gt;Creation of a new database. &lt;br /&gt;Overwriting an existing database. &lt;br /&gt;&lt;br /&gt;I would elaborate on the first application, creation of copies of databases from a common database backup. Below is a list of the implementation in detail:&lt;br /&gt;&lt;br /&gt;Reference SMO&lt;br /&gt;For us to make use of the builtin functionality that SMO objects offer we have to refer the SMO assemblies via a .Net application. This can be done by adding via the Visual Studios 2005 by browsing to, Project -&gt;Add Reference Tab and adding the following.&lt;br /&gt;&lt;br /&gt;- Microsoft.SqlServer.ConnectionInfo &lt;br /&gt;- Microsoft.SqlServer.Smo &lt;br /&gt;- Microsoft.SqlServer.SmoEnum &lt;br /&gt;- Microsoft.SqlServer.SqlEnum&lt;br /&gt;&lt;br /&gt;Also include the following in the code editor of your Visual Studios 2005 project&lt;br /&gt;&lt;br /&gt;Using Microsoft.SqlServer.Management.Smo;&lt;br /&gt;The Configurable Values which are required are:&lt;br /&gt;- Server Name -Name of the Server which you want to connect to and restore the &lt;br /&gt;databases at.&lt;br /&gt;- User Name and Password in case of SQL Authentication&lt;br /&gt;- Name of the Database&lt;br /&gt;- Data File Path of the Database - By default it will be stored under SQL Server Directory.&lt;br /&gt;- Log File Path of the Database - By default it will be stored under SQL Server Directory.&lt;br /&gt;&lt;br /&gt;Step1: Connecting to the Server&lt;br /&gt;This can be done either by using SQL authentication or by using the built in NT authentication depending upon your usage and application.&lt;br /&gt;&lt;br /&gt;a) SQL Authentication&lt;br /&gt;&lt;br /&gt;ServerConnection conn = new ServerConnection();&lt;br /&gt;//Windows Authentication is False conn.LoginSecure = false;&lt;br /&gt;//Specify the UserName conn.Login = &lt;UserName&gt; //Specify the Password conn.Password = &lt;Password&gt;&lt;br /&gt;//Specify the Server Name to be connected conn.ServerInstance = &lt;ServerName&gt;; Server svr = new Server(conn);&lt;br /&gt;//Connect to the server using the configured Connection  //String svr.ConnectionContext.Connect();&lt;br /&gt;&lt;br /&gt;--------------------------------------------------------------------------------&lt;br /&gt;&lt;br /&gt;b) Windows Authentication:&lt;br /&gt;&lt;br /&gt;ServerConnection conn = new ServerConnection();&lt;br /&gt;//Windows Authentication is True conn.LoginSecure = true;&lt;br /&gt;//Specify the Server Name to be connected conn.ServerInstance = &lt;ServerName&gt;; Server svr = new Server(conn); //Connect to the server using the configured Connection  //String svr.ConnectionContext.Connect();&lt;br /&gt;&lt;br /&gt;--------------------------------------------------------------------------------&lt;br /&gt;&lt;br /&gt;Step2: Obtaining Information of the New Database to be Restored&lt;br /&gt;&lt;br /&gt;a) Use Restore object to facilitate the restoration of the new Database. Specify the name of the New Database to be restored.&lt;br /&gt;&lt;br /&gt;Restore res = new Restore(); res.Database = &lt;New DataBase Name&gt; ;&lt;br /&gt;&lt;br /&gt;--------------------------------------------------------------------------------&lt;br /&gt;&lt;br /&gt;b) Specify the location of the Backup file from which the new database is to be restored.&lt;br /&gt;&lt;br /&gt;//Restore from an already existing database backup&lt;br /&gt;res.Action = RestoreActionType.Database; res.Devices.AddDevice(&lt;Location of the BackUp File&gt;,  DeviceType.File); res.ReplaceDatabase = true;&lt;br /&gt;//Data Table to obtain the values of the Data Files of  // the database. DataTable dt; dt = res.ReadFileList(svr);&lt;br /&gt;//Obtaining the existing Logical Name and Log Name of  //the database backup string TemplateDBName = dt.Rows[0][&quot;LogicalName&quot;].ToString(); string TemplateLogName = dt.Rows[1][&quot;LogicalName&quot;].ToString();&lt;br /&gt;&lt;br /&gt;--------------------------------------------------------------------------------&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;c) Specify the new location of the database files which with the relocate property.(This is similar to the restoration of a database from SQL Server Script with the help of WITH MOVE option&lt;br /&gt;&lt;br /&gt;// Now relocate the data and log files // RelocateFile reloData = new RelocateFile(TemplateDBName, @&quot;D:\&quot; + &lt;New Database Name&gt; +  &quot;_data.mdf&quot;); RelocateFile reloLog = new RelocateFile(TemplateLogName, @&quot;D:\&quot; + &lt;New Database Name&gt; +  &quot;_log.ldf&quot;); res.RelocateFiles.Add(reloData); res.RelocateFiles.Add(reloLog);&lt;br /&gt;&lt;br /&gt;--------------------------------------------------------------------------------&lt;br /&gt;&lt;br /&gt;d) Restore the Database. This will restore an exact replica of the database backup file which was specified.&lt;br /&gt;&lt;br /&gt;//Restore the New Database File res.SqlRestore(svr); //Close connection svr.ConnectionContext.Disconnect();&lt;br /&gt;&lt;br /&gt;--------------------------------------------------------------------------------&lt;br /&gt;&lt;br /&gt;Conclusion&lt;br /&gt;Such an implementation of SMO for automated database restore can be put to use by a Database administrator for ease of use and customization.&lt;br /&gt;&lt;br /&gt;Another possible utilization which i had implemented was to improve the efficiency of a data intensive operation .This was done by automating the restoration of multiple copies of the database. A real time scenario where such an approach can be made use of is to process bulk data with the help of staging databases. A particular data intensive operation was spilt across similar databases to process individual units of data and split the load.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Find out more information on http://www.sqlservercentral.com/</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/5134814213615706629/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/5134814213615706629' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/5134814213615706629'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/5134814213615706629'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2008/06/using-sql-management-objects-to-create.html' title='Using SQL Management Objects to create.'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-8751583213632041516</id><published>2008-02-27T09:49:00.001+05:30</published><updated>2008-02-27T09:51:44.210+05:30</updated><title type='text'>Smart Client Architecture</title><content type='html'>&lt;strong&gt;From thick clients to thin clients to Smart Clients&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;We are all accustomed to desktop applications of the past that were designed and developed for the Windows environments. These applications have had a rich user interface but had their limitations too. This section drills down at what these limitations were and how and why Smart Clients came into being. &lt;br /&gt;&lt;br /&gt;As far as the client applications of the past are concerned, we have had an increased demand for client applications that can be executed in the Windows environments. We have an increased demand for rich client applications that could be developed with ease using some powerful tools like Microsoft&#39;s VB, VC++, etc. Using these developer tools, one could develop applications that could create executables that would run on any Windows environments, provided the necessary runtime libraries or DLLs were available. We could design and develop applications that had rich UIs too. These applications however suffered from a major drawback in their deployment (commonly known as the DLL Hell problem). They were quite difficult to deploy and maintain. &lt;br /&gt;&lt;br /&gt;With these hindrances in mind, client browser applications which could be deployed and updated from a central location emerged. This reduced the cost involved in deploying and maintaining these applications. These applications had their drawbacks too. They were devoid of the rich UI that the rich client applications provided and had to be connected at all times for their operation. However, they were a good choice especially for their ease of deployment and management. Contrary to this, the rich client applications had their deployment and management drawbacks associated. Hence, the thin client applications continued to dominate the software development community for years. &lt;br /&gt;&lt;br /&gt;The increasing demand by the global businesses worldwide for fast, flexible, efficient and responsive applications and the increasing demand for applications that support mobility, Smart Client Applications emerged. These applications provide a rich user experience, ease of deployment and ability to be updated from a centralized location. They can work in both online and offline modes and provide a fast and responsive UI. &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Smart Clients -- combining the best of both worlds&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Smart Clients provide a much rich user interface much like a traditional two tier application, with a seamless offline operation which was missing with these traditional applications. Smart Client Applications combine the best of both worlds. They combine the best of both fat and thin client applications. They use local resources, local processing, web services for communication and are flexible and can be deployed and updated from a centralized server seamlessly. Typically we could have a Web Service to hold all with the Smart Clients consuming this service. The Patterns and Practices group from Microsoft has come out with the Smart Client Architecture and Design Guide which &quot;gives you prescriptive guidance on how to overcome architectural challenges and design issues when building smart client solutions. It also provides guidance on how to combine the benefits of traditional rich client applications with the manageability of thin client applications.&quot; You can take a look at this guide here. &lt;br /&gt;&lt;br /&gt;The following are the basic characteristics of Smart Client.&lt;br /&gt;&lt;br /&gt;Use of local resources and processing &lt;br /&gt;Support for both online and offline operations &lt;br /&gt;Ease of deployment and configuration &lt;br /&gt;Use of Web services for communication purposes &lt;br /&gt;Support for hot updates &lt;br /&gt;&lt;br /&gt;Microsoft .NET provides ample support for designing and developing Smart Client applications in more ways then one. It solves the version conflicts (using assembly metadata, etc.) involved in storing multiple assemblies side - by - side. This allows the applications to be executed with the version of an assembly with which you had built and tested your applications. It also provides No-Touch deployment, hot updates features and high flexibility in securing assemblies (using cryptography, etc.) and providing specific permissions to an assembly; hence facilitating application stability. Further, you can leverage the rich UI of the .NET Windows applications to provide a powerful user experience, use SOAP based Web Services. Finally, you have Service Oriented architecture and with the introduction of .NET 2.0, you have more power, flexibility, management and deployment features than you can even think of.</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/8751583213632041516/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/8751583213632041516' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/8751583213632041516'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/8751583213632041516'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2008/02/smart-client-architecture.html' title='Smart Client Architecture'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-5860885872563231194</id><published>2007-08-17T09:15:00.000+05:30</published><updated>2007-08-17T09:39:36.779+05:30</updated><title type='text'>Query Performance Tuning (SQL Server Compact Edition)</title><content type='html'>You can improve your SQL Server 2005 Compact Edition (SQL Server Compact Edition) application performance by optimizing the queries you use. The following sections outline techniques you can use to optimize query performance.&lt;br /&gt;&lt;br /&gt;Improve Indexes&lt;br /&gt;&lt;br /&gt;Creating useful indexes is one of the most important ways to achieve better query performance. Useful indexes help you find data with fewer disk I/O operations and less system resource usage.&lt;br /&gt;&lt;br /&gt;To create useful indexes, you much understand how the data is used, the types of queries and the frequencies they are run, and how the query processor can use indexes to find your data quickly.&lt;br /&gt;&lt;br /&gt;When you choose what indexes to create, examine your critical queries, the performance of which will affect user experience most. Create indexes to specifically aid these queries. After adding an index, rerun the query to see if performance is improved. If it is not, remove the index.&lt;br /&gt;&lt;br /&gt;As with most performance optimization techniques, there are tradeoffs. For example, with more indexes, SELECT queries will potentially run faster. However, DML (INSERT, UPDATE, and DELETE) operations will slow down significantly because more indexes must be maintained with each operation. Therefore, if your queries are mostly SELECT statements, more indexes can be helpful. If your application performs many DML operations, you should be conservative with the number of indexes you create.&lt;br /&gt;&lt;br /&gt;SQL Server Compact Edition includes support for showplans, which help assess and optimize queries. SQL Server Compact Edition uses the same showplan schema as SQL Server 2005 except SQL Server Compact Edition uses a subset of the operators. For more information, see the Microsoft Showplan Schema at http://schemas.microsoft.com/sqlserver/2004/07/showplan/.&lt;br /&gt;&lt;br /&gt;The next few sections provide additional information about creating useful indexes.&lt;br /&gt;&lt;br /&gt;Create Highly-Selective Indexes&lt;br /&gt;Indexing on columns used in the WHERE clause of your critical queries frequently improves performance. However, this depends on how selective the index is. Selectivity is the ratio of qualifying rows to total rows. If the ratio is low, the index is highly selective. It can get rid of most of the rows and greatly reduce the size of the result set. It is therefore a useful index to create. By contrast, an index that is not selective is not as useful.&lt;br /&gt;&lt;br /&gt;A unique index has the greatest selectivity. Only one row can match, which makes it most helpful for queries that intend to return exactly one row. For example, an index on a unique ID column will help you find a particular row quickly.&lt;br /&gt;&lt;br /&gt;You can evaluate the selectivity of an index by running the sp_show_statistics stored procedures on SQL Server Compact Edition tables. For example, if you are evaluating the selectivity of two columns, &quot;Customer ID&quot; and &quot;Ship Via&quot;, you can run the following stored procedures:&lt;br /&gt;&lt;br /&gt;sp_show_statistics_steps &#39;orders&#39;, &#39;customer id&#39;; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;RANGE_HI_KEY RANGE_ROWS EQ_ROWS DISTINCT_RANGE_ROWS &lt;br /&gt;&lt;br /&gt;------------------------------------------------------------ &lt;br /&gt;&lt;br /&gt;ALFKI               0            7                   0 &lt;br /&gt;&lt;br /&gt;ANATR               0            4                   0 &lt;br /&gt;&lt;br /&gt;ANTON               0           13                   0 &lt;br /&gt;&lt;br /&gt;AROUT               0           14                   0 &lt;br /&gt;&lt;br /&gt;BERGS               0           23                   0 &lt;br /&gt;&lt;br /&gt;BLAUS               0            8                   0 &lt;br /&gt;&lt;br /&gt;BLONP               0           14                   0 &lt;br /&gt;&lt;br /&gt;BOLID               0            7                   0 &lt;br /&gt;&lt;br /&gt;BONAP               0           19                   0 &lt;br /&gt;&lt;br /&gt;BOTTM               0           20                   0 &lt;br /&gt;&lt;br /&gt;BSBEV               0           12                   0 &lt;br /&gt;&lt;br /&gt;CACTU               0            6                   0 &lt;br /&gt;&lt;br /&gt;CENTC               0            3                   0 &lt;br /&gt;&lt;br /&gt;CHOPS               0           12                   0 &lt;br /&gt;&lt;br /&gt;COMMI               0            5                   0 &lt;br /&gt;&lt;br /&gt;CONSH               0            4                   0 &lt;br /&gt;&lt;br /&gt;DRACD               0            9                   0 &lt;br /&gt;&lt;br /&gt;DUMON               0            8                   0 &lt;br /&gt;&lt;br /&gt;EASTC               0           13                   0 &lt;br /&gt;&lt;br /&gt;ERNSH               0           33                   0 &lt;br /&gt;&lt;br /&gt;(90 rows affected) &lt;br /&gt;&lt;br /&gt;And&lt;br /&gt;&lt;br /&gt;sp_show_statistics_steps &#39;orders&#39;, &#39;reference3&#39;; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;RANGE_HI_KEY RANGE_ROWS EQ_ROWS DISTINCT_RANGE_ROWS &lt;br /&gt;&lt;br /&gt;------------------------------------------------------------ &lt;br /&gt;&lt;br /&gt;1               0            320                   0 &lt;br /&gt;&lt;br /&gt;2               0            425                   0 &lt;br /&gt;&lt;br /&gt;3               0            333                   0 &lt;br /&gt;&lt;br /&gt;(3 rows affected) &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The results show that the &quot;Customer ID&quot; column has a much lower degree of duplication. This means an index on it will be more selective than an index on the &quot;Ship Via&quot; column. &lt;br /&gt;&lt;br /&gt;For more information about using these stored procedures, see sp_show_statistics (SQL Server Compact Edition), sp_show_statistics_steps (SQL Server Compact Edition), and sp_show_statistics_columns (SQL Server Compact Edition).&lt;br /&gt;&lt;br /&gt;Create Multiple-Column Indexes&lt;br /&gt;Multiple-column indexes are natural extensions of single-column indexes. Multiple-column indexes are useful for evaluating filter expressions that match a prefix set of key columns. For example, the composite index CREATE INDEX Idx_Emp_Name ON Employees (&quot;Last Name&quot; ASC, &quot;First Name&quot; ASC) helps evaluate the following queries:&lt;br /&gt;&lt;br /&gt;... WHERE &quot;Last Name&quot; = &#39;Doe&#39;&lt;br /&gt;&lt;br /&gt;... WHERE &quot;Last Name&quot; = &#39;Doe&#39; AND &quot;First Name&quot; = &#39;John&#39;&lt;br /&gt;&lt;br /&gt;... WHERE &quot;First Name&quot; = &#39;John&#39; AND &quot;Last Name&quot; = &#39;Doe&#39;&lt;br /&gt;&lt;br /&gt;However, it is not useful for this query:&lt;br /&gt;&lt;br /&gt;... WHERE &quot;First Name&quot; = &#39;John&#39;&lt;br /&gt;&lt;br /&gt;When you create a multiple-column index, you should put the most selective columns leftmost in the key. This makes the index more selective when matching several expressions.&lt;br /&gt;&lt;br /&gt;Avoid Indexing Small Tables&lt;br /&gt;A small table is one whose contents fit in one or just a few data pages. Avoid indexing very small tables because it is typically more efficient to do a table scan. This saves the cost of loading and processing index pages. By not creating an index on very small tables, you remove the chance of the optimizer selecting one.&lt;br /&gt;&lt;br /&gt;SQL Server Compact Edition stores data in 4 Kb pages. The page count can be approximated by using the following formula, although the actual count might be slightly larger because of the storage engine overhead.&lt;br /&gt;&lt;br /&gt;&lt;sum of sizes of columns in bytes&gt; * &lt;# of rows&gt;&lt;br /&gt;&lt;br /&gt;&lt;# of pages&gt; = -----------------------------------------------------------------&lt;br /&gt;&lt;br /&gt;4096&lt;br /&gt;&lt;br /&gt;For example, suppose a table has the following schema:&lt;br /&gt;&lt;br /&gt;Column Name  Type (size)  &lt;br /&gt;Order ID&lt;br /&gt; INTEGER (4 bytes)&lt;br /&gt; &lt;br /&gt;Product ID&lt;br /&gt; INTEGER (4 bytes)&lt;br /&gt; &lt;br /&gt;Unit Price&lt;br /&gt; MONEY (8 bytes)&lt;br /&gt; &lt;br /&gt;Quantity&lt;br /&gt; SMALLINT (2 bytes)&lt;br /&gt; &lt;br /&gt;Discount&lt;br /&gt; REAL (4 bytes)&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;The table has 2820 rows. According to the formula, it takes about 16 pages to store its data:&lt;br /&gt;&lt;br /&gt;&lt;# of pages&gt; = ((4 + 4 + 8 + 2 + 4) * 2820) / 4096 = 15.15 pages&lt;br /&gt;&lt;br /&gt;Choose What to Index&lt;br /&gt;&lt;br /&gt;We recommend that you always create indexes on primary keys. It is frequently useful to also create indexes on foreign keys. This is because primary keys and foreign keys are frequently used to join tables. Indexes on these keys lets the optimizer consider more efficient index join algorithms. If your query joins tables by using other columns, it is frequently helpful to create indexes on those columns for the same reason.&lt;br /&gt;&lt;br /&gt;When primary key and foreign key constraints are created, SQL Server Compact Edition automatically creates indexes for them and takes advantage of them when optimizing queries. Remember to keep primary keys and foreign keys small. Joins run faster this way.&lt;br /&gt;&lt;br /&gt;Use Indexes with Filter Clauses&lt;br /&gt;Indexes can be used to speed up the evaluation of certain types of filter clauses. Although all filter clauses reduce the final result set of a query, some can also help reduce the amount of data that must be scanned. &lt;br /&gt;&lt;br /&gt;A search argument (SARG) limits a search because it specifies an exact match, a range of values, or a conjunction of two or more items joined by AND. It has one of the following forms:&lt;br /&gt;&lt;br /&gt;Column operator &lt;constant or variable&gt;&lt;br /&gt;&lt;br /&gt;&lt;constant or variable&gt; operator Column&lt;br /&gt;&lt;br /&gt;SARG operators include =, &gt;, &lt;, &gt;=, &lt;=, IN, BETWEEN, and sometimes LIKE (in cases of prefix matching, such as LIKE &#39;John%&#39;). A SARG can include multiple conditions joined with an AND. SARGs can be queries that match a specific value, such as:&lt;br /&gt;&lt;br /&gt;&quot;Customer ID&quot; = &#39;ANTON&#39;&lt;br /&gt;&lt;br /&gt;&#39;Doe&#39; = &quot;Last Name&quot;&lt;br /&gt;&lt;br /&gt;SARGs can also be queries that match a range of values, such as:&lt;br /&gt;&lt;br /&gt;&quot;Order Date&quot; &gt; &#39;1/1/2002&#39;&lt;br /&gt;&lt;br /&gt;&quot;Customer ID&quot; &gt; &#39;ABCDE&#39; AND &quot;Customer ID&quot; &lt; &#39;EDCBA&#39;&lt;br /&gt;&lt;br /&gt;&quot;Customer ID&quot; IN (&#39;ANTON&#39;, &#39;AROUT&#39;)&lt;br /&gt;&lt;br /&gt;An expression that does not use SARG operators does not improve performance, because the SQL Server Compact Edition query processor has to evaluate every row to determine whether it meets the filter clause. Therefore, an index is not useful on expressions that do not use SARG operators. Non-SARG operators include NOT, &lt;&gt;, NOT EXISTS, NOT IN, NOT LIKE, and intrinsic functions.&lt;br /&gt;&lt;br /&gt;Use the Query Optimizer&lt;br /&gt;&lt;br /&gt;When determining the access methods for base tables, the SQL Server Compact Edition optimizer determines whether an index exists for a SARG clause. If an index exists, the optimizer evaluates the index by calculating how many rows are returned. It then estimates the cost of finding the qualifying rows by using the index. It will choose indexed access if it has lower cost than table scan. An index is potentially useful if its first column or prefix set of columns are used in the SARG, and the SARG establishes a lower bound, upper bound, or both, to limit the search. &lt;br /&gt;&lt;br /&gt;Understand Response Time vs. Total Time&lt;br /&gt;&lt;br /&gt;Response time is the time it takes for a query to return the first record. Total time is the time it takes for the query to return all records. For an interactive application, response time is important because it is the perceived time for the user to receive visual affirmation that a query is being processed. For a batch application, total time reflects the overall throughput. You have to determine what the performance criteria are for your application and queries, and then design accordingly.&lt;br /&gt;&lt;br /&gt;For example, suppose the query returns 100 records and is used to populate a list with the first five records. In this case, you are not concerned with how long it takes to return all 100 records. Instead, you want the query to return the first few records quickly, so that you can populate the list.&lt;br /&gt;&lt;br /&gt;Many query operations can be performed without having to store intermediate results. These operations are said to be pipelined. Examples of pipelined operations are projections, selections, and joins. Queries implemented with these operations can return results immediately. Other operations, such as SORT and GROUP-BY, require using all their input before returning results to their parent operations. These operations are said to require materialization. Queries implemented with these operations typically have an initial delay because of materialization. After this initial delay, they typically return records very quickly.&lt;br /&gt;&lt;br /&gt;Queries with response time requirements should avoid materialization. For example, using an index to implement ORDER-BY yields better response time than does using sorting. The following section describes this in more detail.&lt;br /&gt;&lt;br /&gt;Index the ORDER-BY / GROUP-BY / DISTINCT Columns for Better Response Time&lt;br /&gt;The ORDER-BY, GROUP-BY, and DISTINCT operations are all types of sorting. The SQL Server Compact Edition query processor implements sorting in two ways. If records are already sorted by an index, the processor needs to use only the index. Otherwise, the processor has to use a temporary work table to sort the records first. Such preliminary sorting can cause significant initial delays on devices with lower power CPUs and limited memory, and should be avoided if response time is important.&lt;br /&gt;&lt;br /&gt;In the context of multiple-column indexes, for ORDER-BY or GROUP-BY to consider a particular index, the ORDER-BY or GROUP-BY columns must match the prefix set of index columns with the exact order. For example, the index CREATE INDEX Emp_Name ON Employees (&quot;Last Name&quot; ASC, &quot;First Name&quot; ASC) can help optimize the following queries:&lt;br /&gt;&lt;br /&gt;... ORDER BY / GROUP BY &quot;Last Name&quot; ...&lt;br /&gt;&lt;br /&gt;... ORDER BY / GROUP BY &quot;Last Name&quot;, &quot;First Name&quot; ...&lt;br /&gt;&lt;br /&gt;It will not help optimize:&lt;br /&gt;&lt;br /&gt;... ORDER BY / GROUP BY &quot;First Name&quot; ...&lt;br /&gt;&lt;br /&gt;... ORDER BY / GROUP BY &quot;First Name&quot;, &quot;Last Name&quot; ...&lt;br /&gt;&lt;br /&gt;For a DISTINCT operation to consider a multiple-column index, the projection list must match all index columns, although they do not have to be in the exact order. The previous index can help optimize the following queries:&lt;br /&gt;&lt;br /&gt;... DISTINCT &quot;Last Name&quot;, &quot;First Name&quot; ...&lt;br /&gt;&lt;br /&gt;... DISTINCT &quot;First Name&quot;, &quot;Last Name&quot; ...&lt;br /&gt;&lt;br /&gt;It will not help optimize:&lt;br /&gt;&lt;br /&gt;... DISTINCT &quot;First Name&quot; ...&lt;br /&gt;&lt;br /&gt;... DISTINCT &quot;Last Name&quot; ...&lt;br /&gt;&lt;br /&gt;Note:  &lt;br /&gt;If your query always returns unique rows on its own, avoid specifying the DISTINCT keyword, because it only adds overhead&lt;br /&gt;&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Rewrite Subqueries to Use JOIN&lt;br /&gt;&lt;br /&gt;Sometimes you can rewrite a subquery to use JOIN and achieve better performance. The advantage of creating a JOIN is that you can evaluate tables in a different order from that defined by the query. The advantage of using a subquery is that it is frequently not necessary to scan all rows from the subquery to evaluate the subquery expression. For example, an EXISTS subquery can return TRUE upon seeing the first qualifying row.&lt;br /&gt;&lt;br /&gt;Note:  &lt;br /&gt;The SQL Server Compact Edition query processor always rewrites the IN subquery to use JOIN. You do not have to try this approach with queries that contain the IN subquery clause.&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;For example, to determine all the orders that have at least one item with a 25 percent discount or more, you can use the following EXISTS subquery:&lt;br /&gt;&lt;br /&gt;SELECT &quot;Order ID&quot; FROM Orders O &lt;br /&gt;&lt;br /&gt;WHERE EXISTS (SELECT &quot;Order ID&quot; &lt;br /&gt;&lt;br /&gt;FROM &quot;Order Details&quot; OD &lt;br /&gt;&lt;br /&gt;WHERE O.&quot;Order ID&quot; = OD.&quot;Order ID&quot; &lt;br /&gt;&lt;br /&gt;AND Discount &gt;= 0.25) &lt;br /&gt;&lt;br /&gt;You can also rewrite this by using JOIN:&lt;br /&gt;&lt;br /&gt;SELECT DISTINCT O.&quot;Order ID&quot; FROM Orders O INNER JOIN &quot;Order Details&quot; &lt;br /&gt;&lt;br /&gt;OD ON O.&quot;Order ID&quot; = OD.&quot;Order ID&quot; WHERE Discount &gt;= 0.25 &lt;br /&gt;&lt;br /&gt;Limit Using Outer JOINs&lt;br /&gt;OUTER JOINs are treated differently from INNER JOINs in that the optimizer does not try to rearrange the join order of OUTER JOIN tables as it does to INNER JOIN tables. The outer table (the left table in LEFT OUTER JOIN and the right table in RIGHT OUTER JOIN) is accessed first, followed by the inner table. This fixed join order could lead to execution plans that are less than optimal.&lt;br /&gt;&lt;br /&gt;For more information about a query that contains INNER JOIN, see Microsoft Knowledge Base.&lt;br /&gt;&lt;br /&gt;Use Parameterized Queries&lt;br /&gt;&lt;br /&gt;If your application runs a series of queries that are only different in some constants, you can improve performance by using a parameterized query. For example, to return orders by different customers, you can run the following query:&lt;br /&gt;&lt;br /&gt;SELECT &quot;Customer ID&quot; FROM Orders WHERE &quot;Order ID&quot; = ? &lt;br /&gt;&lt;br /&gt;Parameterized queries yield better performance by compiling the query only once and executing the compiled plan multiple times. Programmatically, you must hold on to the command object that contains the cached query plan. Destroying the previous command object and creating a new one destroys the cached plan. This requires the query to be re-compiled. If you must run several parameterized queries in interleaved manner, you can create several command objects, each caching the execution plan for a parameterized query. This way, you effectively avoid re-compilations for all of them.&lt;br /&gt;&lt;br /&gt;Query Only When You Must&lt;br /&gt;&lt;br /&gt;The SQL Server Compact Edition query processor is a powerful tool for querying data stored in your relational database. However, there is an intrinsic cost associated with any query processor. It must compile, optimize, and generate an execution plan before it starts doing the real work of performing the plan. This is particularly true with simple queries that finish quickly. Therefore, implementing the query yourself can sometimes provide vast performance improvement. If every millisecond counts in your critical component, we recommend that you consider the alternative of implementing the simple queries yourself. For large and complex queries, the job is still best left to the query processor.&lt;br /&gt;&lt;br /&gt;For example, suppose you want to look up the customer ID for a series of orders arranged by their order IDs. There are two ways to accomplish this. First, you could follow these steps for each lookup:&lt;br /&gt;&lt;br /&gt;Open the Orders base table&lt;br /&gt;&lt;br /&gt;Find the row, using the specific &quot;Order ID&quot;&lt;br /&gt;&lt;br /&gt;Retrieve the &quot;Customer ID&quot;&lt;br /&gt;&lt;br /&gt;Or you could issue the following query for each lookup:&lt;br /&gt;&lt;br /&gt;SELECT &quot;Customer ID&quot; FROM Orders WHERE &quot;Order ID&quot; = &lt;the specific order id&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The query-based solution is simpler but slower than the manual solution, because the SQL Server Compact Edition query processor translates the declarative SQL statement into the same three operations that you could implement manually. Those three steps are then performed in sequence. Your choice of which method to use will depend on whether simplicity or performance is more important in your application.</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/5860885872563231194/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/5860885872563231194' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/5860885872563231194'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/5860885872563231194'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2007/08/query-performance-tuning-sql-server.html' title='Query Performance Tuning (SQL Server Compact Edition)'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-7669002976279466039</id><published>2007-08-06T10:05:00.000+05:30</published><updated>2007-08-06T10:06:49.504+05:30</updated><title type='text'>Participating in Transactions in XML Web Services Created Using ASP.NET</title><content type='html'>The transaction support for XML Web services leverages the support found in the common language runtime, which is based on the same distributed transaction model found in Microsoft Transaction Server (MTS) and COM+ Services. The model is based on declaratively deciding whether an object participates in a transaction, rather than writing specific code to handle committing and rolling back a transaction. For an XML Web service created using ASP.NET, you can declare an XML Web service&#39;s transactional behavior by setting the TransactionOption property of the WebMethod attribute applied to an XML Web service method. If an exception is thrown while the XML Web service method is executing, the transaction is automatically aborted; conversely, if no exception occurs, the transaction is automatically committed.&lt;br /&gt;&lt;br /&gt;The TransactionOption property of the WebMethod attribute specifies how an XML Web service method participates in a transaction. Although this declarative level represents the logic of a transaction, it is one step removed from the physical transaction. A physical transaction occurs when a transactional object accesses a data resource, such as a database or message queue. The transaction associated with the object automatically flows to the appropriate resource manager. A .NET Framework data provider, such as the .NET Framework Data Provider for SQL Server or the .NET Framework Data Provider for OLE DB, looks up the transaction in the object&#39;s context and enlists in the transaction through the Distributed Transaction Coordinator (DTC). The entire transaction occurs automatically.&lt;br /&gt;&lt;br /&gt;XML Web service methods can only participate in a transaction as the root of a new transaction. As the root of a new transaction, all interactions with resource managers, such as servers running Microsoft SQL Server, Microsoft Message Queuing (also known as MSMQ), and Microsoft Host Integration Server maintain the ACID properties required to run robust distributed applications. XML Web service methods that call other XML Web service methods participate in different transactions, as transactions do not flow across XML Web service methods.&lt;br /&gt;&lt;br /&gt;The following code example shows an XML Web service that exposes a single XML Web service method, called DeleteDatabase. This XML Web service method performs a database operation that is scoped within a transaction. If the database operation does throw an exception, the transaction is automatically stopped; otherwise, the transaction is automatically committed.&lt;br /&gt;&lt;br /&gt;&lt;%@ WebService Language=&quot;C#&quot; Class=&quot;Orders&quot; %&gt;&lt;br /&gt;&lt;%@ Assembly name=&quot;System.EnterpriseServices,Version=1.0.3300.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a&quot; %&gt;&lt;br /&gt;&lt;br /&gt;using System;&lt;br /&gt;using System.Data;&lt;br /&gt;using System.Data.SqlClient;&lt;br /&gt;using System.Web.Services;&lt;br /&gt;using System.EnterpriseServices;&lt;br /&gt;&lt;br /&gt;public class Orders : WebService&lt;br /&gt;{&lt;br /&gt;   [ WebMethod(TransactionOption=TransactionOption.RequiresNew)]&lt;br /&gt;   public int DeleteAuthor(string lastName)  &lt;br /&gt;   {&lt;br /&gt;      String deleteCmd = &quot;DELETE FROM authors WHERE au_lname=&#39;&quot; + &lt;br /&gt;                          lastName + &quot;&#39;&quot; ;&lt;br /&gt;      String exceptionCausingCmdSQL = &quot;DELETE FROM NonExistingTable WHERE&lt;br /&gt;                                       au_lname=&#39;&quot; + lastName + &quot;&#39;&quot; ;&lt;br /&gt;&lt;br /&gt;      SqlConnection sqlConn = new SqlConnection(&lt;br /&gt;        &quot;Persist Security Info=False;Integrated Security=SSPI;database=pubs;server=myserver&quot;);&lt;br /&gt;&lt;br /&gt;      SqlCommand deleteCmd = new SqlCommand(deleteCmdSQL,sqlConn);&lt;br /&gt;      SqlCommand exceptionCausingCmd = new&lt;br /&gt;                 SqlCommand(exceptionCausingCmdSQL,sqlConn);&lt;br /&gt;   &lt;br /&gt;      // This command should execute properly.&lt;br /&gt;      deleteCmd.Connection.Open();&lt;br /&gt;      deleteCmd.ExecuteNonQuery();&lt;br /&gt;&lt;br /&gt;      // This command results in an exception, so the first command is&lt;br /&gt;      // automatically rolled back.  Since the XML Web service method is&lt;br /&gt;      // participating in a transaction, and an exception occurs, ASP.NET&lt;br /&gt;      // automatically aborts the transaction.  The deleteCmd that&lt;br /&gt;      // executed properly is rolled back.&lt;br /&gt;&lt;br /&gt;      int cmdResult = exceptionCausingCmd.ExecuteNonQuery();&lt;br /&gt;&lt;br /&gt;      sqlConn.Close();&lt;br /&gt;       &lt;br /&gt;      return cmdResult;&lt;br /&gt;   }&lt;br /&gt;}</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/7669002976279466039/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/7669002976279466039' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/7669002976279466039'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/7669002976279466039'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2007/08/participating-in-transactions-in-xml.html' title='Participating in Transactions in XML Web Services Created Using ASP.NET'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-2901869396834693466</id><published>2007-08-06T09:59:00.000+05:30</published><updated>2007-08-06T10:02:16.615+05:30</updated><title type='text'>Managing State in XML Web Services Created Using ASP.NET</title><content type='html'>XML Web services have access to the same state management options as other ASP.NET applications when the class implementing the XML Web service derives from the WebService class. The WebService class contains many of the common ASP.NET objects, including the Session and Application objects.&lt;br /&gt;&lt;br /&gt;The Application object provides a mechanism for storing data that is accessible to all code running within the Web application, whereas the Session object allows data to be stored on a per-client session basis. If the client supports cookies, a cookie can identify the client session. Data stored in the Session object is available only when the EnableSession property of the WebMethod attribute is set to true for a class deriving from WebService. A class deriving from WebService automatically has access to the Application object.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt; To access and store state specific to a particular client session &lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Declare an XML Web service method, setting the EnableSession property of the WebMethod attribute to true. &lt;br /&gt;&lt;br /&gt;[ WebMethod(EnableSession=true) ]&lt;br /&gt;public int PerSessionServiceUsage()&lt;br /&gt;&lt;br /&gt;The following code example is an XML Web service with two XML Web service methods: ServerUsage and PerSessionServerUage. ServerUsage is a hit counter for every time the ServerUsage XML Web service method is accessed, regardless of the client communicating with the XML Web service method. For instance, if three clients call the ServerUsage XML Web service method consecutively, the last one receives a return value of 3. PerSessionServiceUsage, however, is a hit counter for a particular client session. If three clients access PerSessionServiceUsage consecutively, each will receive the same result of 1 on the first call.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;%@ WebService Language=&quot;C#&quot; Class=&quot;ServerUsage&quot; %&gt;&lt;br /&gt;using System.Web.Services;&lt;br /&gt;&lt;br /&gt;public class ServerUsage : WebService {&lt;br /&gt;   [ WebMethod(Description=&quot;Number of times this service has been accessed.&quot;) ]&lt;br /&gt;   public int ServiceUsage() {&lt;br /&gt;     // If the XML Web service method hasn&#39;t been accessed,&lt;br /&gt;     // initialize it to 1.&lt;br /&gt;     if (Application[&quot;appMyServiceUsage&quot;] == null) &lt;br /&gt;     {&lt;br /&gt;       Application[&quot;appMyServiceUsage&quot;] = 1;&lt;br /&gt;     }&lt;br /&gt;     else&lt;br /&gt;     {&lt;br /&gt;     // Increment the usage count.&lt;br /&gt;       Application[&quot;appMyServiceUsage&quot;] = ((int) Application[&quot;appMyServiceUsage&quot;]) + 1;&lt;br /&gt;     }&lt;br /&gt;     return  (int) Application[&quot;appMyServiceUsage&quot;];&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   [ WebMethod(Description=&quot;Number of times a particualr client session has accessed this XML Web service method.&quot;,EnableSession=true) ]&lt;br /&gt;   public int PerSessionServiceUsage() {&lt;br /&gt;     // If the XML Web service method hasn&#39;t been accessed, initialize&lt;br /&gt;     // it to 1.&lt;br /&gt;     if (Session[&quot;MyServiceUsage&quot;] == null) &lt;br /&gt;     {&lt;br /&gt;       Session[&quot;MyServiceUsage&quot;] = 1;&lt;br /&gt;     }&lt;br /&gt;     else&lt;br /&gt;     {&lt;br /&gt;     // Increment the usage count.&lt;br /&gt;       Session[&quot;MyServiceUsage&quot;] = ((int) Session[&quot;MyServiceUsage&quot;]) + 1;&lt;br /&gt;     }&lt;br /&gt;     return  (int) Session[&quot;MyServiceUsage&quot;];&lt;br /&gt;   }&lt;br /&gt;}</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/2901869396834693466/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/2901869396834693466' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/2901869396834693466'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/2901869396834693466'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2007/08/managing-state-in-xml-web-services.html' title='Managing State in XML Web Services Created Using ASP.NET'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-6352329613932122349</id><published>2007-08-01T18:20:00.000+05:30</published><updated>2007-08-01T18:28:59.625+05:30</updated><title type='text'>Post data to other Web pages with ASP.NET 2.0</title><content type='html'>ASP.NET 2.0&#39;s PostBackUrl attribute allows you to designate where a Web form and its data is sent when submitted.&lt;br /&gt;&lt;br /&gt;Standard HTML forms allow you to post or send data to another page or application via the method attribute of the form element. In ASP.NET 1.x, Web pages utilise the postback mechanism where the page&#39;s data is submitted back to the page itself. ASP.NET 2.0 provides additional functionality by allowing a Web page to be submitted to another page. This week, I examine this new feature.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The old approach&lt;br /&gt;&lt;br /&gt;I want to take a minute to cover the older HTML approach to gain perspective. The HTML form element contains the action attribute to designate what server side resource will handle the submitted data. The following code provides an example.&lt;br /&gt;&lt;br /&gt;&amp;lt html &amp;gt&lt;br /&gt;&amp;lt head &amp;gt&lt;br /&gt;&amp;lt title &amp;gt Sample HTML form&amp;lt/title&amp;gt&amp;lt/head&amp;gt&lt;br /&gt;&amp;ltbody&amp;gt&lt;br /&gt;&amp;ltform name=&quot;frmSample&quot; method=&quot;post&quot; action=&quot;target_url&quot;&amp;gt&lt;br /&gt;&amp;ltinput type=&quot;text&quot; name=&quot;fullname&quot; id=&quot;fullname&quot; /&amp;gt&lt;br /&gt;&amp;ltinput type=&quot;button&quot; name=&quot;Submit&quot; value=&quot;submit&quot; /&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lt/form&amp;gt&lt;br /&gt;&amp;lt/body&amp;gt&amp;lt/html&amp;gtThe value entered in the text field (fullname) is submitted to the page or program specified in the form element&#39;s action attribute. For ASP.NET developers, standard HTML forms are seldom, if ever, used.&lt;br /&gt;&lt;br /&gt;ASP.NET developers have plenty of options when faced with the task of passing values from page to page. This includes session variables, cookies, querystring variables, caching, and even Server.Transfer, but ASP.NET 2.0 adds another option.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;ASP.NET 2.0 alternative&lt;br /&gt;&lt;br /&gt;When designing ASP.NET 2.0, Microsoft recognised the need to easily cross post data between Web forms. With that in mind, the PostBackUrl attribute was added to the ASP.NET button control. It allows you to designate where the form and its data are sent when submitted (via the URL assigned to the PostBackUrl attribute). Basically, cross posting is a client side transfer that uses JavaScript behind the scenes.&lt;br /&gt;&lt;br /&gt;The ASP.NET Web form in Listing A has two text fields (name and e-mail address) and a button to submit the data. The PostBackUrl attribute of the submit button is assigned to another Web form, so the data is sent to that page when the form is submitted. Note: The form is set up to post the data when it is submitted via the method attribute of the form element, but this is unnecessary since all cross postbacks utilise post by design.&lt;br /&gt;&lt;br /&gt;Listing A&lt;br /&gt;&lt;br /&gt;&amp;lt%@ Page language=&quot;vb&quot; %&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lt!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot; &amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lthtml&amp;gt&amp;lthead&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lttitle&amp;gtCross Postback Example&amp;lt/title&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lt/head&amp;gt&amp;ltbody&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;ltform id=&quot;frmCrossPostback1&quot; method=&quot;post&quot; runat=&quot;server&quot;&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;ltasp:Label ID=&quot;lblName&quot; runat=&quot;server&quot; Text=&quot;Name:&quot;&amp;gt&amp;lt/asp:Label&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;ltasp:TextBox ID=&quot;txtName&quot; runat=&quot;server&quot;&amp;gt&amp;lt/asp:TextBox&amp;gt&amp;ltbr /&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;ltasp:Label ID=&quot;lblE-mailAddress&quot; runat=&quot;server&quot; Text=&quot;E-mail:&quot;&amp;gt&amp;lt/asp:Label&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;ltasp:TextBox ID=&quot;txtE-mailAddress&quot; runat=&quot;server&quot;&amp;gt&amp;lt/asp:TextBox&amp;gt&amp;ltbr /&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;ltasp:Button ID=&quot;btnSubmit&quot; runat=&quot;server&quot; Text=&quot;Submit&quot; PostBackUrl=&quot;CrossPostback2.aspx&quot; /&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lt/form&amp;gt&amp;lt/body&amp;gt&amp;lt/html&amp;gt&lt;br /&gt;Working with previous pages&lt;br /&gt;&lt;br /&gt;The IsPostBack property of an ASP.NET Page object is not triggered when it is loaded via a cross postback call. However, a new property called PreviousPage allows you to access and work with pages utilising cross postbacks.&lt;br /&gt;&lt;br /&gt;When a cross page request occurs, the PreviousPage property of the current Page class holds a reference to the page that caused the postback. If the page is not the target of a cross-page posting, or if the pages are in different applications, the PreviousPage property is not initialised.&lt;br /&gt;&lt;br /&gt;You can determine if a page is being loaded as a result of a cross postback by checking the PreviousPage object. A null value indicates a regular load, while a null value signals a cross postback. Also, the Page class contains a new method called IsCrossPagePostBack to specifically determine whether the page is loading as the result of a cross postback.&lt;br /&gt;&lt;br /&gt;Once you determine that a cross postback has occurred, you can access controls on the calling page via the PreviousPage object&#39;s FindControl method. The code in Listing B is the second page in our example; it is called by the page in the previous listing.&lt;br /&gt;&lt;br /&gt;Listing B&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&amp;lt%@ Page language=&quot;vb&quot; %&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lt!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot; &amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lthtml&amp;gt&amp;lthead&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lttitle&amp;gtCross Postback Example 2&amp;lt/title&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lt/head&amp;gt&amp;ltbody&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;ltscript language=&quot;vb&quot; runat=&quot;server&quot;&amp;gt&lt;br /&gt;&lt;br /&gt;Sub Page_Load()&lt;br /&gt;&lt;br /&gt;If Not (Page.PreviousPage Is Nothing) Then&lt;br /&gt;&lt;br /&gt;If Not (Page.IsCrossPagePostBack) Then&lt;br /&gt;Response.Write(&quot;Name:&quot; + CType(PreviousPage.FindControl(&quot;txtName&quot;), TextBox).Text + &quot;&amp;ltBR&amp;gt&quot;)&lt;br /&gt;Response.Write(&quot;E-mail:&quot; + CType(PreviousPage.FindControl(&quot;txtE-mailAddress&quot;), TextBox).Text + &quot;&amp;ltBR&amp;gt&quot;)&lt;br /&gt;&lt;br /&gt;End If&lt;br /&gt;&lt;br /&gt;End If&lt;br /&gt;&lt;br /&gt;End Sub&lt;br /&gt;&lt;br /&gt;&amp;lt/script&amp;gt&amp;lt/body&amp;gt&amp;lt/html&amp;gt&lt;br /&gt;The page determines if it is being called via a cross postback. If so, the values from the calling page are accessed using the FindControl method and converting the controls returned by this method to TextBox controls and displaying their Text properties.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;You can convert the entire PreviousPage object to the type of the page initiating the cross postback. This approach allows you to access the public properties and methods of a page. Before I offer an example of this technique, I must rewrite the first example to include public properties. Listing C is the first listing with two properties added to give access to field values.&lt;br /&gt;&lt;br /&gt;Listing C&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&amp;lt%@ Page language=&quot;vb&quot; %&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lt!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot; &amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lthtml&amp;gt&amp;lthead&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lttitle&amp;gtCross Postback Example&amp;lt/title&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;ltscript language=&quot;vb&quot; runat=&quot;server&quot;&amp;gt&lt;br /&gt;&lt;br /&gt;Public ReadOnly Property Name&lt;br /&gt;&lt;br /&gt;Get&lt;br /&gt;&lt;br /&gt;Return Me.txtName.Text&lt;br /&gt;&lt;br /&gt;End Get&lt;br /&gt;&lt;br /&gt;End Property&lt;br /&gt;&lt;br /&gt;Public ReadOnly Property E-mailAddress&lt;br /&gt;&lt;br /&gt;Get&lt;br /&gt;&lt;br /&gt;Return Me.txtE-mailAddress.Text&lt;br /&gt;&lt;br /&gt;End Get&lt;br /&gt;&lt;br /&gt;End Property&lt;br /&gt;&lt;br /&gt;&amp;lt/script&amp;gt&amp;lt/head&amp;gt&amp;ltbody&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;ltform id=&quot;frmCrossPostback1&quot; method=&quot;post&quot; runat=&quot;server&quot;&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;ltasp:Label ID=&quot;lblName&quot; runat=&quot;server&quot; Text=&quot;Name:&quot;&amp;gt&amp;lt/asp:Label&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;ltasp:TextBox ID=&quot;txtName&quot; runat=&quot;server&quot;&amp;gt&amp;lt/asp:TextBox&amp;gt&amp;ltbr /&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;ltasp:Label ID=&quot;lblE-mailAddress&quot; runat=&quot;server&quot; Text=&quot;E-mail:&quot;&amp;gt&amp;lt/asp:Label&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;ltasp:TextBox ID=&quot;txtE-mailAddress&quot; runat=&quot;server&quot;&amp;gt&amp;lt/asp:TextBox&amp;gt&amp;ltbr /&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;ltasp:Button ID=&quot;btnSubmit&quot; runat=&quot;server&quot; Text=&quot;Submit&quot; PostBackUrl=&quot;CrossPostback2.aspx&quot; /&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lt/form&amp;gt&amp;lt/body&amp;gt&amp;lt/html&amp;gt&lt;br /&gt;Now that the properties have been established, you can easily access them. One caveat is that the Page class&#39;s PreviousPage object must be converted to the appropriate type to properly work with the properties. This is accomplished by converting it to the necessary page level object.&lt;br /&gt;&lt;br /&gt;Listing D illustrates this point by referencing the calling page in the top of the page, so it can be used in the code. Once it is referenced, the actual VB.NET code converts the PreviousPage object to the appropriate type using the CType function. At this point, the properties may be used as the code demonstrates.&lt;br /&gt;&lt;br /&gt;Listing D&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&amp;lt%@ Page language=&quot;vb&quot;&lt;br /&gt;%&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lt%@ Reference Page=&quot;~/CrossPostback1.aspx&quot; %&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lt!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot; &amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lthtml&amp;gt&amp;lthead&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lttitle&amp;gtCross Postback Example 3&amp;lt/title&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;lt/head&amp;gt&amp;ltbody&amp;gt&lt;br /&gt;&lt;br /&gt;&amp;ltscript language=&quot;vb&quot; runat=&quot;server&quot;&amp;gt&lt;br /&gt;&lt;br /&gt;Sub Page_Load()&lt;br /&gt;&lt;br /&gt;Dim cppPage As CrossPostback1_aspx&lt;br /&gt;&lt;br /&gt;If Not (Page.PreviousPage Is Nothing) Then&lt;br /&gt;&lt;br /&gt;If Not (Page.IsCrossPagePostBack) Then&lt;br /&gt;&lt;br /&gt;If (Page.PreviousPage.IsValid) Then&lt;br /&gt;cppPage = CType(PreviousPage, CrossPostBack1_aspx)&lt;br /&gt;Response.Write(&quot;Name:&quot; + cppPage.Name + &quot;&amp;ltbr&amp;gt&quot;)&lt;br /&gt;Response.Write(&quot;E-mail:&quot; + cppPage.E-mailAddress)&lt;br /&gt;&lt;br /&gt;End If&lt;br /&gt;&lt;br /&gt;End If&lt;br /&gt;&lt;br /&gt;End If&lt;br /&gt;&lt;br /&gt;End Sub&lt;br /&gt;&lt;br /&gt;&amp;lt/script&amp;gt&amp;lt/body&amp;gt&amp;lt/html&amp;gt&lt;br /&gt;&lt;br /&gt;A note about the use of the IsValid method of the PreviousPage object in the previous listing: The IsValid property of a previous page allows you to ensure a page passed all validation tests before working with it.&lt;br /&gt;&lt;br /&gt;Summary&lt;br /&gt;&lt;br /&gt;Passing data values between Web pages has many applications, including maintaining personal user information. Legacy Web solutions, like using the querystring and cookies, allows you to pass and maintain values, and you can easily direct one page to another when submitted. ASP.NET 1.1 supported these solutions as well as additional ones, but ASP.NET 2.0 addresses the issue head on by supporting cross page postbacks. This makes it easy for one Web page to process data from another. Take advantage of this new concept when you&#39;re working on your next ASP.NET 2.0 application.</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/6352329613932122349/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/6352329613932122349' title='7 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/6352329613932122349'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/6352329613932122349'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2007/08/post-data-to-other-web-pages-with.html' title='Post data to other Web pages with ASP.NET 2.0'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>7</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-2163447003121347822</id><published>2007-07-31T09:11:00.000+05:30</published><updated>2007-07-31T09:23:40.162+05:30</updated><title type='text'>Generic Classes</title><content type='html'>Many developers will view themselves primarily as consumers of generics. However, as you get more comfortable with generics, you&#39;re likely to find yourself introducing your own generic classes and frameworks. Before you can make that leap, though, you&#39;ll need to get comfortable with all the syntactic mutations that come along with creating your own generic classes. Fortunately, you&#39;ll notice that the syntax rules for defining generic classes follow many of the same patterns you&#39;ve already grown accustomed to with non-generic types. So, although there are certainly plenty of new generic concepts you&#39;ll need to absorb, you&#39;re likely to find it quite easy to make the transition to writing your own generic types. &lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Parameterizing Types &lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;In a very general sense, a generic class is really just a class that accepts parameters. As such, a generic class really ends up representing more of an abstract blueprint for a type that will, ultimately, be used in the construction of one or more specific types at run-time. This is one area where, I believe, the C++ term templates actually provides developers with a better conceptual model. This term conjures up a clearer metaphor for how the type parameters of a generic class serve as placeholders that get replaced by actual data types when a generic class is constructed. Of course, as you might expect, this same term also brings with it some conceptual inaccuracies that don&#39;t precisely match generics. &lt;br /&gt;&lt;br /&gt;The idea of parameterizing your classes shouldn&#39;t seem all that foreign. In reality, the mindset behind parameterizing a class is not all that different than the rationale you would use for parameterizing a method in one of your existing classes. The goals in both scenarios are conceptually very similar. For example, suppose you had the following method in one of your classes that was used to locate all retired employees that had an age that was greater than or equal to the passed-in parameter (minAge):&lt;br /&gt;&lt;br /&gt;[C# code]&lt;br /&gt;public IList LookupRetiredEmployees(int minAge) {&lt;br /&gt;    IList retVal = new ArrayList();&lt;br /&gt;    foreach (Employee emp in masterEmployeeCollection) {&lt;br /&gt;        if ((emp.Age &gt;= minAge) &amp;&amp; (emp.Status == EmpStatus.Retired))&lt;br /&gt;            retVal.Add(emp);&lt;br /&gt;        }&lt;br /&gt;        return retVal;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;Now, at some point, you happen to identify a handful of additional methods that are providing similar functionality. Each of these methods only varies based on the status (Retired, Active, and so on) of the employees being processed. This represents an obvious opportunity to refactor through parameterization. By adding status as a parameter to this method, you can make it much more versatile and eliminate the need for all the separate implementations. This is something you&#39;ve likely done. It&#39;s a simple, common flavor of refactoring that happens every day. &lt;br /&gt;&lt;br /&gt;So, with this example in mind, you can imagine applying this same mentality to your classes. Classes, like methods, can now be viewed as being further generalized through the use of type parameters. To better grasp this concept, let&#39;s go ahead and build a non-generic class that will be your candidate for further generalization: &lt;br /&gt;&lt;br /&gt;[C# code]&lt;br /&gt;public class CustomerStack {&lt;br /&gt;    private Customer[] _items;&lt;br /&gt;    private int _count;&lt;br /&gt;&lt;br /&gt;    public void Push(Customer item) {...}&lt;br /&gt;    public Customer Pop() {...}&lt;br /&gt;}&lt;br /&gt;This is the classic implementation of a type-safe stack that has been created to contain collections of Customers. There&#39;s nothing spectacular about it. But, as should be apparent by now, this class is the perfect candidate to be refactored with generics. To make your stack generic, you simply need to add a type parameter (T in this example) to your type and replace all of your references to the Customer with the name of your generic type parameter. The result would appear as follows:&lt;br /&gt;&lt;br /&gt;[C# code]&lt;br /&gt;public class Stack&lt;T&gt; {&lt;br /&gt;    private T[] _items;&lt;br /&gt;    private int _count;&lt;br /&gt;&lt;br /&gt;    public void Push(T item) {...}&lt;br /&gt;    public T Pop() {...}&lt;br /&gt;}&lt;br /&gt;Pretty simple. It&#39;s really not all that different than adding a parameter to a method. It&#39;s as if generics have just allowed you to widen the scope of what can be parameterized to include classes.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt; Type Parameters &lt;/strong&gt;&lt;br /&gt;By now, you should be comfortable with the idea of type parameters and how they serve as a type placeholder for the type arguments that will be supplied when your generic class is constructed. Now let&#39;s look at what, precisely, can appear in a type parameter list for a generic class. &lt;br /&gt;&lt;br /&gt;First, let&#39;s start with the names that can be assigned to type parameters. The rules for naming a type parameter are similar to the rules used when defining any identifier. That said, there are guidelines that you should follow in the naming of your type parameters to improve the readability and maintainability of your generic class. These guidelines, and others, are discussed in Chapter 10, &quot;Generics Guidelines&quot; of Professional .NET 2.0 Generics.&lt;br /&gt;&lt;br /&gt;A generic class may also accept multiple type parameters. These parameters are provided as a delimited list of identifiers:&lt;br /&gt;&lt;br /&gt;[C# code]&lt;br /&gt;public class Stack&lt;T, U, V&gt; &lt;br /&gt;As you might suspect, each type parameter name must be unique within the parameter list as well as within the scope of the class. You cannot, for example, have a type parameter T along with a field that is also named T. You are also prevented from having a type parameter and the class that accepts that parameter share the same name. Fortunately, the names you&#39;re likely to use for type parameters and classes will rarely cause collisions.&lt;br /&gt;&lt;br /&gt;In terms of scope, a type parameter can only be referenced within the scope of the generic class that declared it. So, if you have a child generic class B that descends from generic class A, class B will not be able to reference any type parameters that were declared as part of class A.&lt;br /&gt;&lt;br /&gt;The list of type parameters may also contain constraints that are used to further qualify what type arguments can be supplied of a given type parameter. Chapter 7, &quot;Generic Constraints&quot; (Professional .NET 2.0 Generics) looks into the relevance and application of constraints in more detail.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt; Overloaded Types &lt;/strong&gt;&lt;br /&gt;The .NET implementation of generics allows programmers to create overloaded types. This means that types, like methods, can be overloaded based on their type parameter signature. Consider the declarations of the following types:&lt;br /&gt;[C# Code]&lt;br /&gt;public class MyType {&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class MyType&lt;T&gt; {&lt;br /&gt;    ...&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class MyType&lt;T, U&gt; {&lt;br /&gt;    ...&lt;br /&gt;} &lt;br /&gt;Three types are declared here and they all have the same name and different type parameter lists. At first glance, this may seem invalid. However, if you look at it from an overloading perspective, you can see how the compiler would treat each of these three types as being unique. This can introduce some level of confusion for clients, and this is certainly something you&#39;ll want to factor in as you consider building your own generic types. That said, this is still a very powerful concept that, when leveraged correctly, can enrich the power of your generic types.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt; Static Constructors &lt;/strong&gt;&lt;br /&gt;All classes support the idea of a static (shared) constructor. As you might expect, a static constructor is a constructor that can be called without requiring clients to create an instance of a given class. These constructors provide a convenient mechanism for initializing classes that leverage static types. &lt;br /&gt;&lt;br /&gt;Now, when it comes to generics, you have to also consider the accessibility of your class&#39;s type parameters within the scope of your static constructor. As it turns out, static constructors are granted full access to any type parameters that are associated with your generic classes. Here&#39;s an example of a static constructor in action:&lt;br /&gt;&lt;br /&gt;[C# code]&lt;br /&gt;using System.Collections.Generic;&lt;br /&gt;&lt;br /&gt;public class &lt;b&gt;MySampleClass&lt;/b&gt;&lt;T&gt; {&lt;br /&gt;    private static &lt;b&gt;List&lt;/b&gt;&lt;T&gt; _values;&lt;br /&gt;&lt;br /&gt;    static &lt;b&gt;MySampleClass&lt;/b&gt;() {&lt;br /&gt;        if (typeof(T).IsAbstract == false)&lt;br /&gt;            throw new &lt;b&gt;Exception&lt;/b&gt;(&quot;T must not be abstract&quot;);&lt;br /&gt;        else&lt;br /&gt;            _values = new &lt;b&gt;List&lt;/b&gt;&lt;T&gt;();&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;This example creates a class that accepts a single type parameter, T. The class has a data member that is used to hold a static collection of items of type T. However, you want to be sure, as part of initialization, that T is never abstract. In order to enforce this constraint, this example includes a static constructor that examines the type information about T and throws an exception if the type of T is abstract. If it&#39;s not abstract, the constructor proceeds with the initialization of its static collection. &lt;br /&gt;&lt;br /&gt;This is just one application of static constructors and generic types. You should be able to see, from this example, how static constructors can be used as a common mechanism for initializing any generic class that has static data members.</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/2163447003121347822/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/2163447003121347822' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/2163447003121347822'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/2163447003121347822'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2007/07/generic-classes.html' title='Generic Classes'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-7630581923015477224</id><published>2007-07-23T09:39:00.000+05:30</published><updated>2007-07-23T09:46:18.675+05:30</updated><title type='text'>A Preview of What&#39;s New in C# 3.0</title><content type='html'>This article discusses the following major new enhancements expected in C# 3.0:&lt;br /&gt;&lt;br /&gt;Implicitly typed local variables &lt;br /&gt;Anonymous types &lt;br /&gt;Extension methods &lt;br /&gt;Object and collection initializers &lt;br /&gt;Lambda expressions &lt;br /&gt;Query expressions &lt;br /&gt;Expression Trees &lt;br /&gt;&lt;br /&gt;&lt;strong&gt; Implicitly Typed Local Variables &lt;/strong&gt;&lt;br /&gt;C# 3.0 introduces a new keyword called &quot;var&quot;. Var allows you to declare a new variable, whose type is implicitly inferred from the expression used to initialize the variable. In other words, the following is valid syntax in C# 3.0:&lt;br /&gt;&lt;br /&gt;var i = 1;&lt;br /&gt;The preceding line initializes the variable i to value 1 and gives it the type of integer. Note that &quot;i&quot; is strongly typed to an integer—it is not an object or a VB6 variant, nor does it carry the overhead of an object or a variant.&lt;br /&gt;&lt;br /&gt;To ensure the strongly typed nature of the variable that is declared with the var keyword, C# 3.0 requires that you put the assignment (initializer) on the same line as the declaration (declarator). Also, the initializer has to be an expression, not an object or collection initializer, and it cannot be null. If multiple declarators exist on the same variable, they must all evaluate to the same type at compile time.&lt;br /&gt;&lt;br /&gt;Implicitly typed arrays, on the other hand, are possible using a slightly different syntax, as shown below:&lt;br /&gt;&lt;br /&gt;var intArr = new[] {1,2,3,4} ;&lt;br /&gt;The above line of code would end up declaring intArr as int[].&lt;br /&gt;&lt;br /&gt;The var keyword allows you to refer to instances of anonymous types (described in the next section) and yet the instances are statically typed. So, when you create instances of a class that contain an arbitrary set of data, you don&#39;t need to predefine a class to both hold that structure and be able to hold that data in a statically typed variable.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt; Anonymous types &lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;C# 3.0 gives you the flexibility to create an instance of a class without having to write code for the class beforehand. So, you now can write code as shown below:&lt;br /&gt;&lt;br /&gt;new {hair=&quot;black&quot;, skin=&quot;green&quot;, teethCount=64}&lt;br /&gt;The preceding line of code, with the help of the &quot;new&quot; keyword, gives you a new type that has three properties: hair, skin, and teethCount. Behind the scenes, the C# compiler would create a class that looks as follows:&lt;br /&gt;&lt;br /&gt;class __Anonymous1&lt;br /&gt;{&lt;br /&gt;   private string _hair = &quot;black&quot;;&lt;br /&gt;   private string _skin = &quot;green&quot;;&lt;br /&gt;   private int _teeth   = 64;&lt;br /&gt;   public string hair {get { return _hair; } set { _hair = value; }}&lt;br /&gt;   public string skin {get { return _skin; } set { _skin = value; }}&lt;br /&gt;   public int teeth {get { return _teeth; } set { _teeth = value; }}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;In fact, if another anonymous type that specified the same sequence of names and types were created, the compiler would be smart enough to create only a single anonymous type for both instances to use. Also, because the instances are, as you may have guessed, simply instances of the same class, they can be exchanged because the types are really the same.&lt;br /&gt;&lt;br /&gt;Now you have a class, but you still need something to hold an instance of the above class. This is where the &quot;var&quot; keyword comes in handy; it lets you hold a statically typed instance of the above instance of the anonymous type. Here is a rather simple and easy use of an anonymous type:&lt;br /&gt;&lt;br /&gt;var frankenstein = new {hair=&quot;black&quot;, skin=&quot;green&quot;, teethCount=64}&lt;br /&gt;&lt;br /&gt;&lt;strong&gt; Extension methods  &lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Extension methods enable you to extend various types with additional static methods. However, they are quite limited and should be used as a last resort—only where instance methods are insufficient.&lt;br /&gt;&lt;br /&gt;Extension methods can be declared only in static classes and are identified by the keyword &quot;this&quot; as a modifier on the first parameter of the method. The following is an example of a valid extension method:&lt;br /&gt;&lt;br /&gt;public static int ToInt32(this string s)&lt;br /&gt;{&lt;br /&gt;   return Convert.ToInt32(s) ;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;If the static class that contains the above method is imported using the &quot;using&quot; keyword, the ToInt32 method will appear in existing types (albeit in lower precedence to existing instance methods), and you will be able to compile and execute code that looks as follows:&lt;br /&gt;&lt;br /&gt;string s = &quot;1&quot;;&lt;br /&gt;int i    = s.ToInt32();&lt;br /&gt;&lt;br /&gt;This allows you to take advantage of the extensible nature of various built-in or defined types and add newer methods to them.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt; Object and collection initializers    &lt;/strong&gt;&lt;br /&gt;C# 3.0 is expected to allow you to include an initializer that specifies the initial values of the members of a newly created object or collection. This enables you to combine declaration and initialization in one step.&lt;br /&gt;&lt;br /&gt;For instance, if you defined a CoOrdinate class as follows:&lt;br /&gt;&lt;br /&gt;public class CoOrdinate&lt;br /&gt;{&lt;br /&gt;   public int x ;&lt;br /&gt;   public int y;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;You then could declare and initialize a CoOrdinate object using an object initializer, like this:&lt;br /&gt;&lt;br /&gt;var myCoOrd = new CoOrdinate{ x = 0, y= 0} ;&lt;br /&gt;The above code may have made you raise your eyebrows and ask, &quot;Why not just write the following:&quot;&lt;br /&gt;&lt;br /&gt;var myCoOrd = new CoOrdinate(0, 0) ;&lt;br /&gt;Note: I never declared a constructor that accepted two parameters in my class. In fact, initializing the object using an object initializer essentially is equivalent to calling a parameterless (default) constructor of the CoOrdinate object and then assigning the relevant values.&lt;br /&gt;Similarly, you should easily be able to give values to collections in a rather concise and compact manner in C# 3.0. For instance, the following C# 2.0 code:&lt;br /&gt;&lt;br /&gt;List&lt;string&gt; animals = new List&lt;string&gt;();&lt;br /&gt;animals.Add(&quot;monkey&quot;);&lt;br /&gt;animals.Add(&quot;donkey&quot;);&lt;br /&gt;animals.Add(&quot;cow&quot;);&lt;br /&gt;animals.Add(&quot;dog&quot;);&lt;br /&gt;animals.Add(&quot;cat&quot;);&lt;br /&gt;&lt;br /&gt;Now can be shortened to simply:&lt;br /&gt;&lt;br /&gt;List&lt;string&gt; animals = new List&lt;string&gt; {&lt;br /&gt;   &quot;monkey&quot;, &quot;donkey&quot;, &quot;cow&quot;, &quot;dog&quot;, &quot;cat&quot; } ;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt; Lambda expressions  &lt;/strong&gt;&lt;br /&gt;C# 1.x allowed you to write code blocks in methods, which you could invoke easily using delegates. Delegates are definitely useful, and they are used throughout the framework, but in many instances you had to declare a method or a class just to use one. Thus, to give you an easier and more concise way of writing code, C# 2.0 allowed you to replace standard calls to delegates with anonymous methods. The following code may have been written in .NET 1.1 or earlier:&lt;br /&gt;&lt;br /&gt;class Program&lt;br /&gt;{&lt;br /&gt;   delegate void DemoDelegate();&lt;br /&gt;   static void Main(string[] args)&lt;br /&gt;   {&lt;br /&gt;      DemoDelegate myDelegate = new DemoDelegate(SayHi);&lt;br /&gt;      myDelegate(); &lt;br /&gt;   }&lt;br /&gt;   void SayHi()&lt;br /&gt;   {&lt;br /&gt;      Console.Writeline(&quot;Hiya!!&quot;) ;&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;In C# 2.0, using anonymous methods, you could rewrite the code as follows:&lt;br /&gt;&lt;br /&gt;class Program&lt;br /&gt;{&lt;br /&gt;   delegate void DemoDelegate();&lt;br /&gt;   static void Main(string[] args)&lt;br /&gt;   {&lt;br /&gt;      DemoDelegate myDelegate = delegate()&lt;br /&gt;         {&lt;br /&gt;            Console.Writeline(&quot;Hiya!!&quot;);&lt;br /&gt;         };&lt;br /&gt;      myDelegate();&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Whereas anonymous methods are a step above method-based delegate invocation, lambda expressions allow you to write anonymous methods in a more concise, functional syntax.&lt;br /&gt;&lt;br /&gt;You can write a lambda expression as a parameter list, followed by the =&gt; token, followed by an expression or statement block. The above code can now be replaced with the following code:&lt;br /&gt;&lt;br /&gt;class Program&lt;br /&gt;{&lt;br /&gt;   delegate void DemoDelegate();&lt;br /&gt;   static void Main(string[] args)&lt;br /&gt;   {&lt;br /&gt;      DemoDelegate myDelegate = () =&gt; Console.WriteLine(&quot;Hiya!!&quot;) ;&lt;br /&gt;      myDelegate();&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Although Lambda expressions may appear to be simply a more concise way of writing anonymous methods, in reality they also are a functional superset of anonymous methods. Specifically, Lambda expressions offer the following additional functionality:&lt;br /&gt;&lt;br /&gt;They permit parameter types to be inferred. Anonymous methods will require you to explicitly state each and every type. &lt;br /&gt;They can hold either query expressions (described in the following section) or C# statements. &lt;br /&gt;They can be treated as data using expression trees (described later). This cannot be done using Anonymous methods. &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt; Query expressions  &lt;/strong&gt;&lt;br /&gt;Even though further enhancements may be introduced in the coming months as C# 3.0 matures, the new features described in the preceding sections make it a lot easier to work with data inside C# in general. This feature, also known as LINQ (Language Integrated Query), allows you to write SQL-like syntax in C#.&lt;br /&gt;&lt;br /&gt;For instance, you may have a class that describes your data as follows:&lt;br /&gt;&lt;br /&gt;public class CoOrdinate&lt;br /&gt;{&lt;br /&gt;   public int x ;&lt;br /&gt;   public int y;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;You now could easily declare the logical equivalent of a database table inside C# as follows:&lt;br /&gt;&lt;br /&gt;// Use Object and collection initializers&lt;br /&gt;List&lt;CoOrdinate&gt; coords = ... ;&lt;br /&gt;&lt;br /&gt;And now that you have your data as a collection that implements IEnumerable&lt;T&gt;, you easily can query this data as follows:&lt;br /&gt;&lt;br /&gt;var filteredCoords =&lt;br /&gt;   from c in coords&lt;br /&gt;   where x == 1&lt;br /&gt;   select (c.x, c.y)&lt;br /&gt;&lt;br /&gt;In the SQL-like syntax above, &quot;from&quot;, &quot;where&quot;, and &quot;select&quot; are query expressions that take advantage of C# 3.0 features such as anonymous types, extension methods, implicit typed local variables, and so forth. This way, you can leverage SQL-like syntax and work with disconnected data easily.&lt;br /&gt;&lt;br /&gt;Each query expression is actually translated into a C#-like invocation behind the scenes. For instance, the following:&lt;br /&gt;&lt;br /&gt;where x == 1&lt;br /&gt;Translates to this:&lt;br /&gt;&lt;br /&gt;coords.where(c =&gt; c.x == 1)&lt;br /&gt;As you can see, the above looks an awful lot like a lambda expression and extension method. C# 3.0 has many other query expressions and rules that surround them.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;   Expression Trees &lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;C# 3.0 includes a new type that allows expressions to be treated as data at runtime. This type, System.Expressions.Expression&lt;T&gt;, is simply an in-memory representation of a lambda expression. The end result is that your code can modify and inspect lambda expressions at runtime.&lt;br /&gt;&lt;br /&gt;The following is an example of an expression tree:&lt;br /&gt;&lt;br /&gt;Expression&lt;DemoDelegate&gt; filter = () =&gt; Console.WriteLine(&quot;Hiya!!&quot;) ;&lt;br /&gt;With the above expression tree setup, you easily can inspect the contents of the tree by using various properties on the filter variable.</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/7630581923015477224/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/7630581923015477224' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/7630581923015477224'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/7630581923015477224'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2007/07/preview-of-whats-new-in-c-30.html' title='A Preview of What&#39;s New in C# 3.0'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-9184722240353189036</id><published>2007-07-18T09:22:00.000+05:30</published><updated>2007-07-18T09:26:11.823+05:30</updated><title type='text'>FileSystemWatcher in .Net</title><content type='html'>Use FileSystemWatcher to watch for changes in a specified directory. You can watch for changes in files and subdirectories of the specified directory. The component can watch files on a local computer, a network drive, or a remote computer&lt;br /&gt;&lt;br /&gt;The .NET FileSystemWatcher class makes it possible to quickly and easily launch business processes when certain files or directories are created, modified, or deleted. The FileSystemWatcher class, for example, can be quite useful in application integration, by way of monitoring incoming data files and processing it once an event is raised. It listens to the file system change notifications and raises events when a directory, or file(s) in a directory, changes. &lt;br /&gt;&lt;br /&gt;I&#39;ve come to realize that it does need some understanding of this class to make it work efficiently. For example, a denial-of-service attack is possible if a malicious program gains access to a directory the FileSystemWatcher component is monitoring, and which thereby generates so many changes that the component cannot manage them and can cause a buffer overflow or other drastic effects. Following are some tips and notes on how to use the FileSystemWatcher class to build a more robust solution:&lt;br /&gt;&lt;br /&gt;1. Events being raised twice - An event will be raised twice if an event handler (AddHander FSW.Created, AddressOf FSW_Created) is explicitly specified. This is because, by default, the public events automatically call the respective protected methods (OnChanged, OnCreated, OnDeleted, OnRenamed). To correct this problem, simply remove the explicit event handler (AddHandler ...).&lt;br /&gt;&lt;br /&gt;2. Events being raised multiple times - In some cases a single event can generate multiple events that are handled by the component. Because FileSystemWatcher monitors the operating system activities, all events that applications fire will be picked up. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Such multiple events can be correctly handled and processed by using a simple boolean flag check (for a first-come-first-serve approach) or by setting the FileSystemWatcher.NotifyFilter property to one of the NotifyFilters values.&lt;br /&gt;&lt;br /&gt;3. Thread Safety - Any public static (Shared in VB) members of this class type are thread safe. Any instance members are not guaranteed to be thread safe.&lt;br /&gt;&lt;br /&gt;4. File System Type - The FileSystemWatcher does not raise events for CDs and DVDs, because time stamps and properties cannot change for such media types.&lt;br /&gt;&lt;br /&gt;5. Filter - The Filter property can be used to watch for changes in a certain type(s) of file(s) (eg: &quot;*.txt&quot;). To watch for changes in all files, set the Filter property to an empty string (&quot;&quot;). Hidden files are also monitored by the FileSystemWatcher.&lt;br /&gt;&lt;br /&gt;6. Internal Buffer - The FileSytemWatcher component uses an internal buffer to keep track of file system actions. You should set the buffer to an appropriate size for the approximate number of events you expect to receive. By default, the buffer is set to a size of 4 KB. A 4 KB buffer can track changes on approximately 80 files in a directory. Each event takes up 16 bytes in the buffer, plus enough bytes to store the name of the file, in Unicode (2 bytes per character), that the event occurred on. You can use this information to approximate the buffer size you will need. You (re)set the buffer size by setting the InternalBufferSize property. If there are many changes in a short time, the buffer can overflow. This causes the component to lose track of changes in the directory, and it will only provide blanket notification. Increasing the size of the buffer is expensive, as it comes from non-paged memory that cannot be swapped out to disk, so keep the buffer as small as possible. Setting the Filter does not decrease what goes into the buffer. If you are using Microsoft Windows 2000, you should increase the buffer size in increments of 4 KB, because this corresponds to the operating system&#39;s default page size. With any other operating system, you should increase the buffer size in increments that correspond to the operating system&#39;s default page size. If you are unsure of the default page size for the operating system you are using, the safest way to proceed is to just double the original size of the buffer. This will maintain the original interval needed for your operating system.&lt;br /&gt;&lt;br /&gt;7. Directories - Changing a file within a directory you are monitoring with a FileSystemWatcher component generates not only a Changed event on the file but also a similar event for the directory itself. This is because the directory maintains several types of information for each file it contains - the names and sizes of files, their modification dates, attributes, and so on. Use the IncludeSubdirectories property to indicate whether or not you want to include the subdirectories of the directory you are watching. If you turn this off when you do not need it, you will receive fewer events than when it is turned on.&lt;br /&gt;&lt;br /&gt;8. Stop Watching - When file system monitoring is not needed anymore, you should set the EnableRaisingEvents property to False to disable the component, otherwise the component will continue listening.&lt;br /&gt;&lt;br /&gt;The FileSystemWatcher class provides a useful feature but it should be implemented along with a thorough examination.&lt;br /&gt;&lt;br /&gt;public class Watcher&lt;br /&gt;{&lt;br /&gt;&lt;br /&gt;    public static void Main()&lt;br /&gt;    {&lt;br /&gt;&lt;br /&gt;        string[] args = System.Environment.GetCommandLineArgs();&lt;br /&gt; &lt;br /&gt;        // If a directory is not specified, exit program.&lt;br /&gt;        if(args.Length != 2)&lt;br /&gt;        {&lt;br /&gt;            // Display the proper way to call the program.&lt;br /&gt;            Console.WriteLine(&quot;Usage: Watcher.exe (directory)&quot;);&lt;br /&gt;            return;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Create a new FileSystemWatcher and set its properties.&lt;br /&gt;        FileSystemWatcher watcher = new FileSystemWatcher();&lt;br /&gt;        watcher.Path = args[1];&lt;br /&gt;        /* Watch for changes in LastAccess and LastWrite times, and &lt;br /&gt;           the renaming of files or directories. */&lt;br /&gt;        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite &lt;br /&gt;           | NotifyFilters.FileName | NotifyFilters.DirectoryName;&lt;br /&gt;        // Only watch text files.&lt;br /&gt;        watcher.Filter = &quot;*.txt&quot;;&lt;br /&gt;&lt;br /&gt;        // Add event handlers.&lt;br /&gt;        watcher.Changed += new FileSystemEventHandler(OnChanged);&lt;br /&gt;        watcher.Created += new FileSystemEventHandler(OnChanged);&lt;br /&gt;        watcher.Deleted += new FileSystemEventHandler(OnChanged);&lt;br /&gt;        watcher.Renamed += new RenamedEventHandler(OnRenamed);&lt;br /&gt;&lt;br /&gt;        // Begin watching.&lt;br /&gt;        watcher.EnableRaisingEvents = true;&lt;br /&gt;&lt;br /&gt;        // Wait for the user to quit the program.&lt;br /&gt;        Console.WriteLine(&quot;Press \&#39;q\&#39; to quit the sample.&quot;);&lt;br /&gt;        while(Console.Read()!=&#39;q&#39;);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Define the event handlers.&lt;br /&gt;    private static void OnChanged(object source, FileSystemEventArgs e)&lt;br /&gt;    {&lt;br /&gt;        // Specify what is done when a file is changed, created, or deleted.&lt;br /&gt;       Console.WriteLine(&quot;File: &quot; +  e.FullPath + &quot; &quot; + e.ChangeType);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private static void OnRenamed(object source, RenamedEventArgs e)&lt;br /&gt;    {&lt;br /&gt;        // Specify what is done when a file is renamed.&lt;br /&gt;        Console.WriteLine(&quot;File: {0} renamed to {1}&quot;, e.OldFullPath, e.FullPath);&lt;br /&gt;    }&lt;br /&gt;}</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/9184722240353189036/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/9184722240353189036' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/9184722240353189036'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/9184722240353189036'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2007/07/filesystemwatcher-in-net.html' title='FileSystemWatcher in .Net'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-30591913.post-1680674347833240233</id><published>2007-07-12T09:33:00.000+05:30</published><updated>2007-07-12T09:47:50.993+05:30</updated><title type='text'>Performance Modeling</title><content type='html'>&lt;strong&gt;Objectives&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Engineer for performance up front. &lt;br /&gt;Manage performance risks. &lt;br /&gt;Map business requirements to performance objectives. &lt;br /&gt;Balance performance against other quality-of-service requirements. &lt;br /&gt;Identify and analyze key performance scenarios. &lt;br /&gt;Identify and allocate budgets. &lt;br /&gt;Evaluate your model to ensure you meet your performance objectives. &lt;br /&gt;Identify metrics and test cases. &lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Overview&lt;/strong&gt;&lt;br /&gt;This chapter presents performance modeling based on approaches used by Microsoft teams. Similar approaches are recommended elsewhere, including in the book Performance Solutions by Connie U. Smith and Lloyd G. Williams. You and your organization will need to adapt the process for your environment.&lt;br /&gt;&lt;br /&gt;Performance modeling is a structured and repeatable approach to modeling the performance of your software. It begins during the early phases of your application design and continues throughout the application life cycle.&lt;br /&gt;&lt;br /&gt;Performance is generally ignored until there is a problem. There are several problems with this reactive approach: &lt;br /&gt;&lt;br /&gt;Performance problems are frequently introduced early in the design. &lt;br /&gt;Design issues cannot always be fixed through tuning or more efficient coding. &lt;br /&gt;Fixing architectural or design issues later in the cycle is not always possible. At best, it is inefficient, and is usually very expensive. &lt;br /&gt;When you create performance models, you identify application scenarios and your performance objectives. Your performance objectives are your measurable criteria, such as response time, throughput (how much work in how much time), and resource utilization (CPU, memory, disk I/O, and network I/O). You break down your performance scenarios into steps and assign performance budgets. Your budget defines the resources and constraints across your performance objectives.&lt;br /&gt;&lt;br /&gt;Performance modeling provides several important benefits: &lt;br /&gt;&lt;br /&gt;Performance becomes part of your design. &lt;br /&gt;Modeling helps answer the question &quot;Will your design support your performance objectives?&quot; By building and analyzing models, you can evaluate tradeoffs before you actually build the solution. &lt;br /&gt;You know explicitly what design decisions are influenced by performance and the constraints performance puts on future design decisions. Frequently, these decisions are not captured and can lead to maintenance efforts that work against your original goals. &lt;br /&gt;&lt;br /&gt;You avoid surprises in terms of performance when your application is released into production. &lt;br /&gt;&lt;br /&gt;You end up with a document of itemized scenarios that help you quickly see what is important. That translates to where to instrument, what to test for, and how to know whether you are on or off track for meeting your performance goals. &lt;br /&gt;Upfront performance modeling is not a replacement for scenario-based load testing or prototyping to validate your design. In fact, you have to prototype and test to determine what things cost and to see if your plan makes sense. Data from your prototypes can help you evaluate early design decisions before implementing a design that will not allow you to meet your performance goals.&lt;br /&gt;&lt;br /&gt;An information structure to help you capture performance-related information. This information can be filled out partially with assumptions and requirements, and it can get more comprehensively filled out according to your needs. &lt;br /&gt;A process that helps you incrementally define and capture the information that helps the teams working on your solution to focus on using, capturing, and sharing the appropriate information. &lt;br /&gt;&lt;br /&gt;To use this performance model, do the following: &lt;br /&gt;&lt;br /&gt;Set goals. Capture whatever partial performance-related information you have, including your application prototype&#39;s metrics, important scenarios, workloads, goals, or budgets. The performance model presented in this chapter is designed to use the partial information you might have in these areas as input. You do not have to completely fill out the data or have a complete understanding of your own requirements and solutions. &lt;br /&gt;Measure. Execute the suggested tasks in the process to iteratively set goals and measure the result of your action, by using the partially completed model as a guide of what to focus on. This allows you add and refine the information in your model. The new data will inform the next round of goal setting and measurement. &lt;br /&gt;Why Model Performance?&lt;br /&gt;A performance model provides a path to discover what you do not know. The benefits of performance modeling include the following: &lt;br /&gt;&lt;br /&gt;Performance becomes a feature of your development process and not an afterthought. &lt;br /&gt;You evaluate your tradeoffs earlier in the life cycle based on measurements. &lt;br /&gt;Test cases show you whether you are trending toward or away from the performance objectives throughout your application life cycle. &lt;br /&gt;Modeling allows you to evaluate your design before investing time and resources to implement a flawed design. Having the processing steps for your performance scenarios laid out enables you to understand the nature of your application&#39;s work. By knowing the nature of this work and the constraints affecting that work, you can make more informed decisions.&lt;br /&gt;&lt;br /&gt;Your model can reveal the following about your application: &lt;br /&gt;&lt;br /&gt;What are the relevant code paths and how do they affect performance? &lt;br /&gt;Where do the use of resources or computations affect performance? &lt;br /&gt;Which are the most frequently executed code paths? This helps you identify where to spend time tuning. &lt;br /&gt;What are the key steps that access resources and lead to contention? &lt;br /&gt;Where is your code in relation to resources (local, remote)? &lt;br /&gt;What tradeoffs have you made for performance? &lt;br /&gt;Which components have relationships to other components or resources? &lt;br /&gt;Where are your synchronous and asynchronous calls? &lt;br /&gt;What is your I/O-bound work and what is your CPU-bound work? &lt;br /&gt;And the model can reveal the following about your goals: &lt;br /&gt;&lt;br /&gt;What is the priority and achievability of different performance goals? &lt;br /&gt;Where have your performance goals affected design? &lt;br /&gt;&lt;strong&gt;&lt;br /&gt;Risk Management&lt;/strong&gt;&lt;br /&gt;The time, effort, and money you invest up front in performance modeling should be proportional to project risk. For a project with significant risk, where performance is critical, you may spend more time and energy up front developing your model. For a project where performance is less of a concern, your modeling approach might be as simple as white-boarding your performance scenarios.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Budget&lt;/strong&gt;&lt;br /&gt;Performance modeling is essentially a &quot;budgeting&quot; exercise. Budget represents your constraints and enables you to specify how much you can spend (resource-wise) and how you plan to spend it. Constraints govern your total spending, and then you can decide where to spend to get to the total. You assign budget in terms of response time, throughput, latency, and resource utilization.&lt;br /&gt;&lt;br /&gt;Performance modeling does not need to involve a lot of up-front work. In fact, it should be part of the work you already do. To get started, you can even use a whiteboard to quickly capture the key scenarios and break them down into component steps.&lt;br /&gt;&lt;br /&gt;If you know your goals, you can quickly assess if your scenarios and steps are within range, or if you need to change your design to accommodate the budget. If you do not know your goals (particularly resource utilization), you need to define your baselines. Either way, it is not long before you can start prototyping and measuring to get some data to work with.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;What You Must Know&lt;/strong&gt;&lt;br /&gt;Performance models are created in document form by using the tool of your choice (a simple Word document works well). The document becomes a communication point for other team members. The performance model contains a lot of key information, including goals, budgets (time and resource utilization), scenarios, and workloads. Use the performance model to play out possibilities and evaluate alternatives, before committing to a design or implementation decision. You need to measure to know the cost of your tools. For example, how much does a certain API cost you?&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Best Practices&lt;/strong&gt;&lt;br /&gt;Consider the following best practices when creating performance models: &lt;br /&gt;&lt;br /&gt;Determine response time and resource utilization budgets for your design. &lt;br /&gt;Identify your target deployment environment. &lt;br /&gt;Do not replace scenario-based load testing with performance modeling, for the following reasons: &lt;br /&gt;Performance modeling suggests which areas should be worked on but cannot predict the improvement caused by a change. &lt;br /&gt;Performance modeling informs the scenario-based load testing by providing goals and useful measurements. &lt;br /&gt;Modeled performance may ignore many scenario-based load conditions that can have an enormous impact on overall performance. &lt;br /&gt;Information in the Performance Model&lt;br /&gt;The information in the performance model is divided into different areas. Each area focuses on capturing one perspective. Each area has important attributes that help you execute the process. &lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Information in the Performance Model&lt;/strong&gt;&lt;br /&gt;Category Description &lt;br /&gt;Application Description The design of the application in terms of its layers and its target infrastructure. &lt;br /&gt;Scenarios Critical and significant use cases, sequence diagrams, and user stories relevant to performance. &lt;br /&gt;Performance Objectives Response time, throughput, resource utilization. &lt;br /&gt;Budgets Constraints you set on the execution of use cases, such as maximum execution time and resource utilization levels, including CPU, memory, disk I/O, and network I/O. &lt;br /&gt;Measurements Actual performance metrics from running tests, in terms of resource costs and performance issues. &lt;br /&gt;Workload Goals Goals for the number of users, concurrent users, data volumes, and information about the desired use of the application. &lt;br /&gt;Baseline Hardware Description of the hardware on which tests will be run — in terms of network topology, bandwidth, CPU, memory, disk, and so on. &lt;br /&gt;&lt;br /&gt;&lt;strong&gt; Additional Information You Might Need&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Category Description &lt;br /&gt;Quality-of-Service (QoS) Requirements  QoS requirements, such as security, maintainability, and interoperability, may impact your performance. You should have an agreement across software and infrastructure teams about QoS restrictions and requirements. &lt;br /&gt;Workload Requirements Total number of users, concurrent users, data volumes, and information about the expected use of the application. &lt;br /&gt;&lt;strong&gt;&lt;br /&gt;Inputs&lt;/strong&gt;&lt;br /&gt;A number of inputs are required for the performance modeling process. These include initial (maybe even tentative) information about the following: &lt;br /&gt;&lt;br /&gt;Scenarios and design documentation about critical and significant use cases. &lt;br /&gt;Application design and target infrastructure and any constraints imposed by the infrastructure. &lt;br /&gt;QoS requirements and infrastructure constraints, including service level agreements (SLAs). &lt;br /&gt;Workload requirements derived from marketing data on prospective customers. &lt;br /&gt;Outputs&lt;br /&gt;&lt;br /&gt;The output from performance modeling is the following: &lt;br /&gt;A performance model document. &lt;br /&gt;Test cases with goals. &lt;br /&gt;Performance Model Document&lt;br /&gt;The performance model document may contain the following: &lt;br /&gt;&lt;br /&gt;Performance objectives. &lt;br /&gt;Budgets. &lt;br /&gt;Workloads. &lt;br /&gt;Itemized scenarios with goals. &lt;br /&gt;Test cases with goals. &lt;br /&gt;An itemized scenario is a scenario that you have broken down into processing steps. For example, an order scenario might include authentication, order input validation, business rules validation, and orders being committed to the database. The itemized scenarios include assigned budgets and performance objectives for each step in the scenario.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Test Cases with Goals&lt;/strong&gt;&lt;br /&gt;You use test cases to generate performance metrics. They validate your application against performance objectives. Test cases help you determine whether you are trending toward or away from your performance objectives.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Eight step performance model&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The performance modeling process involves the following steps:&lt;/strong&gt; &lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Identify key scenarios&lt;/strong&gt;. Identify scenarios where performance is important and scenarios that pose the most risk to your performance objectives. &lt;br /&gt;&lt;strong&gt;Identify workload.&lt;/strong&gt; Identify how many users and concurrent users your system needs to support. &lt;br /&gt;&lt;strong&gt;Identify performance objectives&lt;/strong&gt;. Define performance objectives for each of your key scenarios. Performance objectives reflect business requirements. &lt;br /&gt;&lt;strong&gt;Identify budget.&lt;/strong&gt; Identity your budget or constraints. This includes the maximum execution time in which an operation must be completed and resource utilization constraints, such as CPU, memory, disk I/O, and network I/O. &lt;br /&gt;&lt;strong&gt;Identify processing steps.&lt;/strong&gt; Break down your key scenarios into component processing steps. &lt;br /&gt;&lt;strong&gt;Allocate budget.&lt;/strong&gt; Spread your budget (determined in Step 4) across your processing steps (determined in Step 5) to meet your performance objectives (defined in Step 3). &lt;br /&gt;&lt;strong&gt;Evaluate. &lt;/strong&gt;Evaluate your design against objectives and budget. You may need to modify your design or spread your response time and resource utilization budget differently to meet your performance objectives. &lt;br /&gt;Validate. Validate your model and estimates. This is an ongoing activity and includes prototyping, assessing, and measuring. &lt;br /&gt;The next sections describe each of the preceding steps.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Step 1 – Identify Key Scenarios&lt;/strong&gt;&lt;br /&gt;Identify your application scenarios that are important from a performance perspective. If you have documented use cases or user stories, use them to help you define your scenarios. Key scenarios include the following: &lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Critical scenarios. &lt;/strong&gt;&lt;br /&gt;Significant scenarios. &lt;br /&gt;Critical Scenarios&lt;br /&gt;These are the scenarios that have specific performance expectations or requirements. Examples include scenarios covered by SLAs or those that have specific performance objectives.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Significant Scenarios&lt;/strong&gt;&lt;br /&gt;Significant scenarios do not have specific performance objectives such as a response time goal, but they may impact other critical scenarios.&lt;br /&gt;&lt;br /&gt;To help identify significant scenarios, identify scenarios with the following characteristics: &lt;br /&gt;&lt;br /&gt;Scenarios that run in parallel to a performance-critical scenario. &lt;br /&gt;Scenarios that are frequently executed. &lt;br /&gt;Scenarios that account for a high percentage of system use. &lt;br /&gt;Scenarios that consume significant system resources. &lt;br /&gt;Do not ignore your significant scenarios. Your significant scenarios can influence whether your critical scenarios meet their performance objectives. Also, do not forget to consider how your system will behave if different significant or critical scenarios are being run concurrently by different users. This &quot;parallel integration&quot; often drives key decisions about your application&#39;s units of work. For example, to keep search response brisk, you might need to commit orders one line item at a time.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Step 2 – Identify Workload&lt;/strong&gt;&lt;br /&gt;Workload is usually derived from marketing data. It includes the following: &lt;br /&gt;Total users. &lt;br /&gt;Concurrently active users. &lt;br /&gt;Data volumes. &lt;br /&gt;Transaction volumes and transaction mix. &lt;br /&gt;For performance modeling, you need to identify how this workload applies to an individual scenario. The following are example requirements: &lt;br /&gt;You might need to support 100 concurrent users browsing. &lt;br /&gt;You might need to support 10 concurrent users placing orders. &lt;br /&gt;Note   Concurrent users are those users that hit a Web site at exactly the same moment. Simultaneous users are those users who have active connections to the same site.&lt;br /&gt;&lt;strong&gt;&lt;br /&gt;Step 3 – Identify Performance Objectives&lt;/strong&gt;&lt;br /&gt;For each scenario identified in Step 1, write down the performance objectives. The performance objectives are determined by your business requirements.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Performance objectives usually include the following: &lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Response time. For example, the product catalog must be displayed in less than 3 seconds. &lt;br /&gt;Throughput. For example, the system must support 100 transactions per second. &lt;br /&gt;Resource utilization. A frequently overlooked aspect is how much resource your application is consuming, in terms of CPU, memory, disk I/O, and network I/O. &lt;br /&gt;Consider the following when establishing your performance objectives: &lt;br /&gt;&lt;br /&gt;Workload requirements. &lt;br /&gt;Service level agreements. &lt;br /&gt;Response times. &lt;br /&gt;Projected growth. &lt;br /&gt;Lifetime of your application. &lt;br /&gt;For projected growth, you need to consider whether your design will meet your needs in six months time, or one year from now. If the application has a lifetime of only six months, are you prepared to trade some extensibility for performance? If your application is likely to have a long lifetime, what performance are you willing to trade for maintainability?&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Step 4 – Identify Budget&lt;/strong&gt;&lt;br /&gt;Budgets are your constraints. For example, what is the longest acceptable amount of time that an operation should take to complete, beyond which your application fails to meet its performance objectives.&lt;br /&gt;&lt;br /&gt;Your budget is usually specified in terms of the following: &lt;br /&gt;&lt;br /&gt;Execution time. &lt;br /&gt;Resource utilization. &lt;br /&gt;Execution Time&lt;br /&gt;Your execution time constraints determine the maximum amount of time that particular operations can take.&lt;br /&gt;&lt;br /&gt;Resource Utilization&lt;br /&gt;Resource utilization requirements define the threshold utilization levels for available resources. For example, you might have a peak processor utilization limit of 75 percent and your memory consumption must not exceed 50 MB.&lt;br /&gt;&lt;br /&gt;Common resources to consider include the following: &lt;br /&gt;&lt;br /&gt;CPU. &lt;br /&gt;Memory. &lt;br /&gt;Network I/O. &lt;br /&gt;Disk I/O. &lt;br /&gt;More Information&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Additional Considerations&lt;/strong&gt;&lt;br /&gt;Execution time and resource utilization are helpful in the context of your performance objectives. However, budget has several other dimensions you may be subject to. Other considerations for budget might include the following: &lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Network.&lt;/strong&gt; Network considerations include bandwidth. &lt;br /&gt;&lt;strong&gt;Hardware.&lt;/strong&gt; Hardware considerations include items, such as servers, memory, and CPUs. &lt;br /&gt;&lt;strong&gt;Resource dependencies.&lt;/strong&gt; Resource dependency considerations include items, such as the number of available database connections and Web service connections. &lt;br /&gt;&lt;strong&gt;Shared resources. &lt;/strong&gt;Shared resource considerations include items, such as the amount of bandwidth you have, the amount of CPU you get if you share a server with other applications, and the amount of memory you get. &lt;br /&gt;&lt;strong&gt;Project resources.&lt;/strong&gt; From a project perspective, budget is also a constraint, such as time and cost. &lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Step 5 – Identify Processing Steps&lt;/strong&gt;&lt;br /&gt;Itemize your scenarios and divide them into separate processing steps, such as those shown in Table 2.3. If you are familiar with UML, use cases and sequence diagrams can be used as input. Similarly, Extreme Programming user stories can provide useful input to this step.&lt;br /&gt;&lt;strong&gt;&lt;br /&gt; Processing Steps&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Processing Steps &lt;br /&gt;1. An order is submitted by client. &lt;br /&gt;2. The client authentication token is validated. &lt;br /&gt;3. Order input is validated. &lt;br /&gt;4. Business rules validate the order. &lt;br /&gt;5. The order is sent to a database server. &lt;br /&gt;6. The order is processed. &lt;br /&gt;7. A response is sent to the client. &lt;br /&gt;&lt;br /&gt;An added benefit of identifying processing steps is that they help you identify those points within your application where you should consider adding custom instrumentation. Instrumentation helps you to provide actual costs and timings when you begin testing your application.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Step 6 – Allocate Budget&lt;/strong&gt;&lt;br /&gt;Spread your budget (determined in Step 4, &quot;Identify Budget&quot;) across your processing steps (determined in Step 5, &quot;Identify Processing Steps&quot;) to meet your performance objectives. You need to consider execution time and resource utilization. Some of the budget may apply to only one processing step. Some of the budget may apply to the scenario and some of it may apply across scenarios.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Assigning Execution Time to Steps&lt;/strong&gt;&lt;br /&gt;When assigning time to processing steps, if you do not know how much time to assign, simply divide the total time equally between the steps. At this point, it is not important for the values to be precise because the budget will be reassessed after measuring actual time, but it is important to have an idea of the values. Do not insist on perfection, but aim for a reasonable degree of confidence that you are on track.&lt;br /&gt;&lt;br /&gt;You do not want to get stuck, but, at the same time, you do not want to wait until your application is built and instrumented to get real numbers. Where you do not know execution times, you need to try spreading the time evenly, see where there might be problems or where there is tension.&lt;br /&gt;&lt;br /&gt;If dividing the budget shows that each step has ample time, there is no need to examine these further. However, for the ones that look risky, conduct some experiments (for example, with prototypes) to verify that what you will need to do is possible, and then proceed.&lt;br /&gt;&lt;br /&gt;Note that one or more of your steps may have a fixed time. For example, you may make a database call that you know will not complete in less than 3 seconds. Other times are variable. The fixed and variable costs must be less than or equal to the allocated budget for the scenario.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Assigning Resource Utilization Requirements&lt;/strong&gt;&lt;br /&gt;When assigning resources to processing steps, consider the following: &lt;br /&gt;&lt;br /&gt;Know the cost of your materials. For example, what does technology x cost in comparison to technology y. &lt;br /&gt;Know the budget allocated for hardware. This defines the total resources available at your disposal. &lt;br /&gt;Know the hardware systems already in place. &lt;br /&gt;Know your application functionality. For example, heavy XML document processing may require more CPU, chatty database access or Web service communication may require more network bandwidth, or large file uploads may require more disk I/O. &lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Step 7 – Evaluate&lt;/strong&gt;&lt;br /&gt;Evaluate the feasibility and effectiveness of the budget before time and effort is spent on prototyping and testing. Review the performance objectives and consider the following questions: &lt;br /&gt;&lt;br /&gt;Does the budget meet the objectives? &lt;br /&gt;Is the budget realistic? It is during the first evaluation that you identify new experiments you should do to get more accurate budget numbers. &lt;br /&gt;Does the model identify a resource hot spot? &lt;br /&gt;Are there more efficient alternatives? &lt;br /&gt;Can the design or features be reduced or modified to meet the objectives? &lt;br /&gt;Can you improve efficiency in terms of resource consumption or time? &lt;br /&gt;Would an alternative pattern, design, or deployment topology provide a better solution? &lt;br /&gt;What are you trading off? Are you trading productivity, scalability, maintainability, or security for performance? &lt;br /&gt;Consider the following actions: &lt;br /&gt;&lt;br /&gt;Modify your design. &lt;br /&gt;Reevaluate requirements. &lt;br /&gt;Change the way you allocate budget. &lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Step 8 – Validate&lt;/strong&gt;&lt;br /&gt;Validate your model and estimates. Continue to create prototypes and measure the performance of the use cases by capturing metrics. This is an ongoing activity that includes prototyping and measuring. Continue to perform validation checks until your performance goals are met.&lt;br /&gt;&lt;br /&gt;The further you are in your project&#39;s life cycle, the greater the accuracy of the validation. Early on, validation is based on available benchmarks and prototype code, or just proof-of-concept code. Later, you can measure the actual code as your application develops.</content><link rel='replies' type='application/atom+xml' href='http://vishalsharmaind.blogspot.com/feeds/1680674347833240233/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/30591913/1680674347833240233' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/1680674347833240233'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/30591913/posts/default/1680674347833240233'/><link rel='alternate' type='text/html' href='http://vishalsharmaind.blogspot.com/2007/07/performance-modeling.html' title='Performance Modeling'/><author><name>Vishal Sharma</name><uri>http://www.blogger.com/profile/10593137667015526776</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>