Monday, October 31, 2011

Embedding RavenDB into an ASP.NET MVC 3 Application

RavenDB Embedded and MVC
RavenDB can be run in three different modes:

1.As a Windows service
2.As an IIS application
3.Embedded in a .NET application
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:

Install-Package RavenDB-EmbeddedDetails of the package can be found on the NuGet gallery site at bit.ly/ns64W1.

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


Figure 1 App_Data Directory Structure

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.

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

Figure 2 Class for DocumentStore

public class DataDocumentStore
{
private static IDocumentStore instance;

public static IDocumentStore Instance
{
get
{
if(instance == null)
throw new InvalidOperationException(
"IDocumentStore has not been initialized.");
return instance;
}
}

public static IDocumentStore Initialize()
{
instance = new EmbeddableDocumentStore { ConnectionStringName = "RavenDB" };
instance.Conventions.IdentityPartsSeparator = "-";
instance.Initialize();
return instance;
}
}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:



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.

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.

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:

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);

DataDocumentStore.Initialize();
}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.

RavenDB Objects
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.

Figure 3 Bookmark Class

public class Bookmark
{
public string Id { get; set; }
public string Title { get; set; }
public string Url { get; set; }
public string Description { get; set; }
public List Tags { get; set; }
public DateTime DateCreated { get; set; }

public Bookmark()
{
this.Tags = new List();
}
}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.

The JSON serialization of a sample Bookmark document is represented in the following structure:

{
"Title": "The RavenDB site",
"Url": "http://www.ravendb.net",
"Description": "A test bookmark",
"Tags": ["mvc","ravendb"],
"DateCreated": "2011-08-04T00:50:40.3207693Z"
}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).

Figure 4 BookmarkModelBinder.cs

public class BookmarkModelBinder : DefaultModelBinder
{
protected override void OnModelUpdated(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
var form = controllerContext.HttpContext.Request.Form;
var tagsAsString = form["TagsAsString"];
var bookmark = bindingContext.Model as Bookmark;
bookmark.Tags = string.IsNullOrEmpty(tagsAsString)
? new List()
: tagsAsString.Split(',').Select(i => i.Trim()).ToList();
}
}Then I update the Globals.asax.cs file to add the BookmarkModelBinder to the model binders at application startup:

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);

ModelBinders.Binders.Add(typeof(Bookmark), new BookmarkModelBinder());
DataDocumentStore.Initialize();
}To handle populating an HTML text box with the current tags in the model, I’ll add an extension method to convert a List object to a comma-separated string:

public static string ToCommaSeparatedString(this List list)
{
return list == null ? string.Empty : string.Join(", ", list);
}Unit of Work
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:

using (var session = documentStore.OpenSession())
{
session.Store(bookmark);
session.SaveChanges();
}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.

Figure 5 BaseDocumentStoreController

public class BaseDocumentStoreController : Controller
{
public IDocumentSession DocumentSession { get; set; }

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.IsChildAction)
return;
this.DocumentSession = DataDocumentStore.Instance.OpenSession();
base.OnActionExecuting(filterContext);
}

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.IsChildAction)
return;
if (this.DocumentSession != null && filterContext.Exception == null)
this.DocumentSession.SaveChanges();
this.DocumentSession.Dispose();
base.OnActionExecuted(filterContext);
}
}MVC Controller and View Implementation
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.

Figure 6 BookmarksController Class

public class BookmarksController : BaseDocumentStoreController
{
public ViewResult Index()
{
var model = this.DocumentSession.Query()
.OrderByDescending(i => i.DateCreated)
.ToList();
return View(model);
}

public ViewResult Details(string id)
{
var model = this.DocumentSession.Load(id);
return View(model);
}

public ActionResult Create()
{
var model = new Bookmark();
return View(model);
}

[HttpPost]
public ActionResult Create(Bookmark bookmark)
{
bookmark.DateCreated = DateTime.UtcNow;
this.DocumentSession.Store(bookmark);
return RedirectToAction("Index");
}

public ActionResult Edit(string id)
{
var model = this.DocumentSession.Load(id);
return View(model);
}

[HttpPost]
public ActionResult Edit(Bookmark bookmark)
{
this.DocumentSession.Store(bookmark);
return RedirectToAction("Index");
}

public ActionResult Delete(string id)
{
var model = this.DocumentSession.Load(id);
return View(model);
}

[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(string id)
{
this.DocumentSession.Advanced.DatabaseCommands.Delete(id, null);
return RedirectToAction("Index");
}
}The IDocumentSession.Query 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.

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.

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:

@Html.TextBox("TagsAsString", 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.

Searching Objects
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:

var bookmarks = session.Query()
.Where( i=> i.DateCreated >= DateTime.UtcNow.AddDays(-5))
.OrderByDescending(i => i.DateCreated)
.ToList();Here’s one to page through the full list of bookmarks:

var bookmarks = session.Query()
.OrderByDescending(i => i.DateCreated)
.Skip(pageCount * (pageNumber – 1))
.Take(pageCount)
.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.

I can add the following action method to my BookmarksController class to handle getting bookmarks by tag:

public ViewResult Tag(string tag)
{
var model = new BookmarksByTagViewModel { Tag = tag };
model.Bookmarks = this.DocumentSession.Query()
.Where(i => i.Tags.Any(t => t == tag))
.OrderByDescending(i => i.DateCreated)
.ToList();
return View(model);
}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.

Tuesday, April 06, 2010

WCF Service For HTTP Get Request

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.

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.

So we will see a very small example how we can handle the Http get request.

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.

[OperationContract(Action="*", ReplyAction="*")]
void Process(Message msg);

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.

public void Process(Message request)
{
HttpRequestMessageProperty rp = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
if (rp.Method.Equals("Get", StringComparison.InvariantCultureIgnoreCase))
HttpContext.Current.Response.Write(Get(request));
}
so you can see In this code I am checking the request whether it's Get or POST and do my action on the basis of that.

In this case I don'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.

Tuesday, March 30, 2010

Property Handling in WCF

In this article I am talking about how you can define OperationContract for your properties of Service Contract.

As you know you can't put [OperationContract] attribute on your Properties it will give you an compile time error because this attribute is only valid for method declaration.

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.

int CustomerId
{

[OperationContract]
get;
[OperationContract]
set;
}
After doing this you will get set_CustomerId and get_CustomerId as normal method in your WCF proxy class.

Monday, March 29, 2010

Hooking Your class into WCF

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.

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.

void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
//ApplyDispatchBehavior

foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)
{
ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher;
if (channelDispatcher != null)
{
foreach (EndpointDispatcher endpoint in channelDispatcher.Endpoints)
{
//endpoint.DispatchRuntime.OperationSelector = this;
endpoint.DispatchRuntime.MessageInspectors.Add(new PrintMessageInterceptor());
}
}
}
}


In this method PrintMessageInterceptor is an instance of another class which is inherited from IDispatchMessageInspector which provide us two method AfterReceiveRequest and BeforeSendReply

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.

public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request,
IClientChannel channel, InstanceContext instanceContext)
{

XmlNodeReader reader;
XmlDocument document = new XmlDocument();
document.Load(request.GetReaderAtBodyContents());
//Get the body element operation
string bodyElement = document.DocumentElement.LocalName;
switch(bodyElement)
{
case "Add" :
strAction = Action.Add;
break;
}
return null;
}


public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply,
object correlationState)
{
MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);
reply = buffer.CreateMessage();
//Get the body element operation
XmlDocument document;
string bodyElement;

document = new XmlDocument();
document.Load(reply.GetReaderAtBodyContents());
//Get the body element operation
bodyElement = document.DocumentElement.LocalName;
switch (strAction.ToString())
{
case "Add":
Add(document);
reply = Message.CreateMessage(reply.Version, null, localReader);
break;
}
}

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.

private void Add(XmlDocument passedValue)
{

if (passedValue.DocumentElement.Name.Equals("Add"))
{
using (var passedReader = XmlReader.Create(new System.IO.MemoryStream(System.Text.Encoding.ASCII.GetBytes(passedValue.InnerXml))))
//using (var writer = XmlWriter.Create(new System.IO.MemoryStream(System.Text.Encoding.ASCII.GetBytes(reader.ReadInnerXml())), settings))
{
while (passedReader.Read())
{
switch (passedReader.NodeType)
{
case XmlNodeType.Element:
break;

case XmlNodeType.Text:
Sum += Convert.ToInt32(passedReader.Value);
break;
}
}
}
newNode = passedValue.CreateElement("AddResponse", "http://tempuri.org/");
childNode = passedValue.CreateElement("AddResult", "http://tempuri.org/");
childNode.InnerText = Sum.ToString();
newNode.AppendChild(childNode);
passedValue.RemoveChild(passedValue.DocumentElement);
passedValue.InnerXml = (newNode.OuterXml);

}

Let me know your feedback.

Thursday, March 11, 2010

How to Run the WCF Service on local system

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
Below is the code how you can define these bindings.

1.First you need to define the ServiceHost which will take type of your class which inherited the service contract.

using System.ServiceModel;
ServiceHost selfHost = new ServiceHost(typeof("Type of your class"), baseAddress);

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.

selfHost.AddServiceEndpoint(
typeof(IUploadInterface),
new WSHttpBinding(),
"UploadClass");
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.

ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.HttpGetUrl = new Uri("http://localhost:8000/UploadClass");
selfHost.Description.Behaviors.Add(smb);

4. You need to open the service host
selfHost.Open();

Monday, March 08, 2010

XML with Linq


System.Xml.Linq namespace provide good way of working with XML you don'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.

For e.g
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.

xlElement = new XElement("configuration",
new XElement("configSections",
new XElement("section", new XAttribute("name", "log4net"),
new XAttribute("type", "log4net.Config.Log4 NetConfigurationSectionHandler, log4net"))),
new XElement("log4net", new XAttribute("debug", "true")),
new XElement("appender", new XAttribute ("name", "AppTraceFileAppender"), new XAttribute("type", "log4net.Appender.FileAppender")),
new XElement("param", new XAttribute("name", "File"), new XAttribute
("value", "")));


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.

After defining this simply call xlElement.Save(filePath);

Thursday, March 04, 2010

Adding file as Link

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.

How to Add dll/file as link.

1. Right click on project choose add existing item
2. file add dialog box apprear.
3. Choose the file and click on combobox showing in Add button of file add dialog box.
4. Choose add as a link.

Wednesday, March 03, 2010

Using XPathDocument in place of DataSet

//Create object of XPathDocument
XPathDocument docNav = new XPathDocument(strPath);
//Create the XPathNavigator
XPathNavigator nav = docNav.CreateNavigator();
//Set the pointer at ShoppingRule node
expr = nav.Compile("/Rule/ShoppingRule");
//Get all the ShoppingRule node from the XML.
XPathNodeIterator parentIterator = nav.Select(expr);
//Treverse on all the shoppingRules node
while(parentIterator.MoveNext()
{
if (parentIterator.Current.HasChildren)
{
//Move to the first child node of the ShoppingRules
parentIterator.Current.MoveToChild(XPathNodeType.Element);
strTransactionCode = parentIterator.Current.Value;
}
//Get all the childs of ShoppingRules node
XPathNodeIterator children = childNode.SelectChildren(XPathNodeType.Element);
//Traverse on all the child node of the ShoppingRules nodes.
while (children.MoveNext())
{
}
}

Wednesday, December 17, 2008

The MRU List

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.

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.

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.

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.

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.

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.

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.

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.

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:


using System;
using System.Collections.Generic;
using System.Text;

namespace MostRecentlyUsedList
{
public delegate bool MruEqualityComparer(K key, T item);

public class MruList
{
private LinkedList items;
private int maxCapacity;
private MruEqualityComparer compareFunc;

public MruList(int maxCap, MruEqualityComparer compFunc)
{
maxCapacity = maxCap;
compareFunc = compFunc;
items = new LinkedList();
}

public T Find(K key)
{
LinkedListNode node = FindNode(key);
if (node != null)
{
items.Remove(node);
items.AddFirst(node);
return node.Value;
}
return default(T);
}

private LinkedListNode FindNode(K key)
{
LinkedListNode node = items.First;
while (node != null)
{
if (compareFunc(key, node.Value))
return node;
node = node.Next;
}
return null;
}

public void Add(T item)
{
// remove items until the list is no longer full.
while (items.Count >= maxCapacity)
{
items.RemoveLast();
}
items.AddFirst(item);
}


}
}


static class Program
{
static private MruList mru;
///
/// The main entry point for the application.
///

[STAThread]
static void Main()
{

mru = new MruList(1000, KeyCompare);

for (int count = 0; count < 1000; count++)
{
mru.Add(new SearchResult("Jim" + count, count));
}
FindItem("Jim999");

}

static private bool KeyCompare(string key, SearchResult item)
{
return key.Equals(item.Name);
}

static private void FindItem(string key)
{
SearchResult rslt = mru.Find(key);
if (rslt == null)
{
Console.WriteLine("’{0}’ not found", key);
}
else
{
Console.WriteLine("’{0}’ is {1}", rslt.Name, rslt.Age);
}

}


}


class SearchResult
{
private string _name;
private int _age;

public SearchResult(string n, int a)
{
_name = n;
_age = a;
}

public string Name
{
get { return _name; }
}

public int Age
{
get { return _age; }
}
}


The MRU List

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.

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.

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.

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.

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.

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.

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.

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.

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:


using System;
using System.Collections.Generic;
using System.Text;

namespace MostRecentlyUsedList
{
public delegate bool MruEqualityComparer(K key, T item);

public class MruList
{
private LinkedList items;
private int maxCapacity;
private MruEqualityComparer compareFunc;

public MruList(int maxCap, MruEqualityComparer compFunc)
{
maxCapacity = maxCap;
compareFunc = compFunc;
items = new LinkedList();
}

public T Find(K key)
{
LinkedListNode node = FindNode(key);
if (node != null)
{
items.Remove(node);
items.AddFirst(node);
return node.Value;
}
return default(T);
}

private LinkedListNode FindNode(K key)
{
LinkedListNode node = items.First;
while (node != null)
{
if (compareFunc(key, node.Value))
return node;
node = node.Next;
}
return null;
}

public void Add(T item)
{
// remove items until the list is no longer full.
while (items.Count >= maxCapacity)
{
items.RemoveLast();
}
items.AddFirst(item);
}


}
}


static class Program
{
static private MruList mru;
///
/// The main entry point for the application.
///

[STAThread]
static void Main()
{

mru = new MruList(1000, KeyCompare);

for (int count = 0; count < 1000; count++)
{
mru.Add(new SearchResult("Jim" + count, count));
}
FindItem("Jim999");

}

static private bool KeyCompare(string key, SearchResult item)
{
return key.Equals(item.Name);
}

static private void FindItem(string key)
{
SearchResult rslt = mru.Find(key);
if (rslt == null)
{
Console.WriteLine("’{0}’ not found", key);
}
else
{
Console.WriteLine("’{0}’ is {1}", rslt.Name, rslt.Age);
}

}


}


class SearchResult
{
private string _name;
private int _age;

public SearchResult(string n, int a)
{
_name = n;
_age = a;
}

public string Name
{
get { return _name; }
}

public int Age
{
get { return _age; }
}
}

Tuesday, December 16, 2008

Factory Method

Definition
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

using System;
using System.Collections;

namespace GangOfFour.Factory
{
///
/// MainApp startup class for Real-World
/// Factory Method Design Pattern.
///

class MainApp
{
///
/// Entry point into console application.
///

static void Main()
{
// Note: constructors call Factory Method
Document[] documents = new Document[2];
documents[0] = new Resume();
documents[1] = new Report();

// Display document pages
foreach (Document document in documents)
{
Console.WriteLine("\n" + document.GetType().Name+ "--");
foreach (Page page in document.Pages)
{
Console.WriteLine(" " + page.GetType().Name);
}
}

// Wait for user
Console.Read();
}
}

// "Product"

abstract class Page
{
}

// "ConcreteProduct"

class SkillsPage : Page
{
}

// "ConcreteProduct"

class EducationPage : Page
{
}

// "ConcreteProduct"

class ExperiencePage : Page
{
}

// "ConcreteProduct"

class IntroductionPage : Page
{
}

// "ConcreteProduct"

class ResultsPage : Page
{
}

// "ConcreteProduct"

class ConclusionPage : Page
{
}

// "ConcreteProduct"

class SummaryPage : Page
{
}

// "ConcreteProduct"

class BibliographyPage : Page
{
}

// "Creator"

abstract class Document
{
private ArrayList pages = new ArrayList();

// Constructor calls abstract Factory method
public Document()
{
this.CreatePages();
}

public ArrayList Pages
{
get{ return pages; }
}

// Factory Method
public abstract void CreatePages();
}

// "ConcreteCreator"

class Resume : Document
{
// Factory Method implementation
public override void CreatePages()
{
Pages.Add(new SkillsPage());
Pages.Add(new EducationPage());
Pages.Add(new ExperiencePage());
}
}

// "ConcreteCreator"

class Report : Document
{
// Factory Method implementation
public override void CreatePages()
{
Pages.Add(new IntroductionPage());
Pages.Add(new ResultsPage());
Pages.Add(new ConclusionPage());
Pages.Add(new SummaryPage());
Pages.Add(new BibliographyPage());
}
}
}

Factory Method:when and where use it:
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.
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).

Factory Method in .NET Framework
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
boolean with value true or false depending on the string value (“true” or “false”).
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.

Friday, December 12, 2008

Abstract Facotry

Definition
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
Frequency of use: high

using System;

namespace DoFactory.GangOfFour.Adapter
{

class MainApp
{
///
/// Entry point into console application.
///

static void Main()
{
// Non-adapted chemical compound
Compound unknown = new Compound(Chemical.Unknown);
unknown.Display();

// Adapted chemical compounds
Compound water = new RichCompound(Chemical.Water);
water.Display();

Compound benzene = new RichCompound(Chemical.Benzene);
benzene.Display();

Compound alcohol = new RichCompound(Chemical.Alcohol);
alcohol.Display();

// Wait for user
Console.Read();
}
}

// "Target"

class Compound
{
private Chemical name;
private float boilingPoint;
private float meltingPoint;
private double molecularWeight;
private string molecularFormula;

// Constructor
public Compound(Chemical name)
{
this.name = name;
}

public virtual void Display()
{
Console.WriteLine("\nCompound: {0} -- ", Name);
}

// Properties
public Chemical Name
{
get{ return name; }
}

public float BoilingPoint
{
get{ return boilingPoint; }
set{ boilingPoint = value; }
}

public float MeltingPoint
{
get{ return meltingPoint; }
set{ meltingPoint = value; }
}

public double MolecularWeight
{
get{ return molecularWeight; }
set{ molecularWeight = value; }
}

public string MolecularFormula
{
get{ return molecularFormula; }
set{ molecularFormula = value; }
}
}

// "Adapter"

class RichCompound : Compound
{
private ChemicalDatabank bank;

// Constructor
public RichCompound(Chemical name) : base(name)
{
}

public override void Display()
{
// Adaptee
bank = new ChemicalDatabank();

// Adaptee request methods
BoilingPoint = bank.GetCriticalPoint(Name, State.Boiling);
MeltingPoint = bank.GetCriticalPoint(Name, State.Melting);
MolecularWeight = bank.GetMolecularWeight(Name);
MolecularFormula = bank.GetMolecularStructure(Name);

base.Display();
Console.WriteLine(" Formula: {0}", MolecularFormula);
Console.WriteLine(" Weight : {0}", MolecularWeight);
Console.WriteLine(" Melting Pt: {0}", MeltingPoint);
Console.WriteLine(" Boiling Pt: {0}", BoilingPoint);
}
}

// "Adaptee"

class ChemicalDatabank
{
// The Databank 'legacy API'
public float GetCriticalPoint(Chemical compound, State point)
{
float temperature = 0.0F;

// Melting Point
if (point == State.Melting)
{
switch (compound)
{
case Chemical.Water : temperature = 0.0F; break;
case Chemical.Benzene : temperature = 5.5F; break;
case Chemical.Alcohol : temperature = -114.1F; break;
}
}
// Boiling Point
else if (point == State.Boiling)
{
switch (compound)
{
case Chemical.Water : temperature = 100.0F; break;
case Chemical.Benzene : temperature = 80.1F; break;
case Chemical.Alcohol : temperature = 78.3F; break;
}
}
return temperature;
}

public string GetMolecularStructure(Chemical compound)
{
string structure = "";

switch (compound)
{
case Chemical.Water : structure = "H20"; break;
case Chemical.Benzene : structure = "C6H6"; break;
case Chemical.Alcohol : structure = "C2H6O2"; break;
}
return structure;
}

public double GetMolecularWeight(Chemical compound)
{
double weight = 0.0;
switch (compound)
{
case Chemical.Water : weight = 18.015; break;
case Chemical.Benzene : weight = 78.1134; break;
case Chemical.Alcohol : weight = 46.0688; break;
}
return weight;
}
}

// Enumerations

public enum Chemical
{
Unknown,
Water,
Benzene,
Alcohol
}

public enum State
{
Boiling,
Melting
}
}


.NET optimized sample code

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.
Code in project: DoFactory.GangOfFour.Abstract.NetOptimized
Abstract Factory: when and where use it
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.
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.
Next are some reasons and benefits for creating objects using an Abstract Factory rather than calling constructors directly:
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.

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).
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:
Several overloaded constructors. Which one should you use?

// C#
public Vehicle (int passengers)
public Vehicle (int passengers, int horsePower)
public Vehicle (int wheels, bool trailer)
public Vehicle (string type)
' VB.NET
public Sub New (Byval passengers As Integer)
public Sub New (Byval passengers As Integer, _
Byval horsePower As Integer)
public Sub New (Byval wheels As Integer wheels, _
Byval trailer As Boolean)
public Sub New (Byval type As String)
The Factory pattern makes code more expressive and developers more productive
// C#
public Vehicle CreateCar (int passengers)
public Vehicle CreateSuv (int passengers, int horsePower)
public Vehicle CreateTruck (int wheels, bool trailer)
public Vehicle CreateBoat ()
public Vehicle CreateBike ()
' VB.NET
public Function CreateCar (Byval passengers As Integer) As Vehicle
public Function CreateSuv (Byval passengers As Integer, _
Byval horsePower As Integer) As Vehicle
public Function CreateTruck (Byval wheels As Integer, _
Byval trailer As Boolean) As Vehicle
public Function CreateBoat () As Vehicle
public Function CreateBike () As Vehicle

Abstract Factory in the .NET Framework
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.
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:
// C#
public abstract class StreamFactory
{
public abstract Stream CreateStream();
}
' VB.NET
Public MustInherit Class StreamFactory
Public MustOverride Function CreateStream() As Stream
End Class
In this scenario your factory type inherits from StreamFactory and is used to dynamically select the actual Stream type being created:
// C#
public class MemoryStreamFactory : StreamFactory
{
...
}
' VB.NET
Public Class MemoryStreamFactory
Inherits StreamFactory
...
End Class

The naming convention in .NET is to appends the word ‘Factory’ to the name of
that is being created. For example, a class that manufactures widget objects would
named WidgetFactory. A search through the libraries for the word ‘Factory’ reveals numerous classes that are implementations of the Factory design pattern.

Wednesday, June 18, 2008

Using SQL Management Objects to create.

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

Administrative Tasks - Retrieval of Database Server Settings, creating new databases Etc.
Application Oriented Task - Applying T-SQL Scripts
Scheduling Tasks - Creation of new Jobs, Running and maintenance of existing Jobs via SQL Server Agent.
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.

Scope of the Article
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).

Possible Applications
Such an approach to database creation can be made to effective use in scenarios such as:

Automated Database creation and Restoration:
If a need arises to create 'N' number of database and restore them from a common database backup (.bak).
Creation of a new database.
Overwriting an existing database.

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:

Reference SMO
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 ->Add Reference Tab and adding the following.

- Microsoft.SqlServer.ConnectionInfo
- Microsoft.SqlServer.Smo
- Microsoft.SqlServer.SmoEnum
- Microsoft.SqlServer.SqlEnum

Also include the following in the code editor of your Visual Studios 2005 project

Using Microsoft.SqlServer.Management.Smo;
The Configurable Values which are required are:
- Server Name -Name of the Server which you want to connect to and restore the
databases at.
- User Name and Password in case of SQL Authentication
- Name of the Database
- Data File Path of the Database - By default it will be stored under SQL Server Directory.
- Log File Path of the Database - By default it will be stored under SQL Server Directory.

Step1: Connecting to the Server
This can be done either by using SQL authentication or by using the built in NT authentication depending upon your usage and application.

a) SQL Authentication

ServerConnection conn = new ServerConnection();
//Windows Authentication is False conn.LoginSecure = false;
//Specify the UserName conn.Login = //Specify the Password conn.Password =
//Specify the Server Name to be connected conn.ServerInstance = ; Server svr = new Server(conn);
//Connect to the server using the configured Connection //String svr.ConnectionContext.Connect();

--------------------------------------------------------------------------------

b) Windows Authentication:

ServerConnection conn = new ServerConnection();
//Windows Authentication is True conn.LoginSecure = true;
//Specify the Server Name to be connected conn.ServerInstance = ; Server svr = new Server(conn); //Connect to the server using the configured Connection //String svr.ConnectionContext.Connect();

--------------------------------------------------------------------------------

Step2: Obtaining Information of the New Database to be Restored

a) Use Restore object to facilitate the restoration of the new Database. Specify the name of the New Database to be restored.

Restore res = new Restore(); res.Database = ;

--------------------------------------------------------------------------------

b) Specify the location of the Backup file from which the new database is to be restored.

//Restore from an already existing database backup
res.Action = RestoreActionType.Database; res.Devices.AddDevice(, DeviceType.File); res.ReplaceDatabase = true;
//Data Table to obtain the values of the Data Files of // the database. DataTable dt; dt = res.ReadFileList(svr);
//Obtaining the existing Logical Name and Log Name of //the database backup string TemplateDBName = dt.Rows[0]["LogicalName"].ToString(); string TemplateLogName = dt.Rows[1]["LogicalName"].ToString();

--------------------------------------------------------------------------------


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

// Now relocate the data and log files // RelocateFile reloData = new RelocateFile(TemplateDBName, @"D:\" + + "_data.mdf"); RelocateFile reloLog = new RelocateFile(TemplateLogName, @"D:\" + + "_log.ldf"); res.RelocateFiles.Add(reloData); res.RelocateFiles.Add(reloLog);

--------------------------------------------------------------------------------

d) Restore the Database. This will restore an exact replica of the database backup file which was specified.

//Restore the New Database File res.SqlRestore(svr); //Close connection svr.ConnectionContext.Disconnect();

--------------------------------------------------------------------------------

Conclusion
Such an implementation of SMO for automated database restore can be put to use by a Database administrator for ease of use and customization.

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.


Find out more information on http://www.sqlservercentral.com/

Wednesday, February 27, 2008

Smart Client Architecture

From thick clients to thin clients to Smart Clients

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.

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

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.

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.


Smart Clients -- combining the best of both worlds

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 "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." You can take a look at this guide here.

The following are the basic characteristics of Smart Client.

Use of local resources and processing
Support for both online and offline operations
Ease of deployment and configuration
Use of Web services for communication purposes
Support for hot updates

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.

Friday, August 17, 2007

Query Performance Tuning (SQL Server Compact Edition)

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.

Improve Indexes

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.

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.

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.

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.

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

The next few sections provide additional information about creating useful indexes.

Create Highly-Selective Indexes
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.

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.

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, "Customer ID" and "Ship Via", you can run the following stored procedures:

sp_show_statistics_steps 'orders', 'customer id';


RANGE_HI_KEY RANGE_ROWS EQ_ROWS DISTINCT_RANGE_ROWS

------------------------------------------------------------

ALFKI 0 7 0

ANATR 0 4 0

ANTON 0 13 0

AROUT 0 14 0

BERGS 0 23 0

BLAUS 0 8 0

BLONP 0 14 0

BOLID 0 7 0

BONAP 0 19 0

BOTTM 0 20 0

BSBEV 0 12 0

CACTU 0 6 0

CENTC 0 3 0

CHOPS 0 12 0

COMMI 0 5 0

CONSH 0 4 0

DRACD 0 9 0

DUMON 0 8 0

EASTC 0 13 0

ERNSH 0 33 0

(90 rows affected)

And

sp_show_statistics_steps 'orders', 'reference3';


RANGE_HI_KEY RANGE_ROWS EQ_ROWS DISTINCT_RANGE_ROWS

------------------------------------------------------------

1 0 320 0

2 0 425 0

3 0 333 0

(3 rows affected)


The results show that the "Customer ID" column has a much lower degree of duplication. This means an index on it will be more selective than an index on the "Ship Via" column.

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

Create Multiple-Column Indexes
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 ("Last Name" ASC, "First Name" ASC) helps evaluate the following queries:

... WHERE "Last Name" = 'Doe'

... WHERE "Last Name" = 'Doe' AND "First Name" = 'John'

... WHERE "First Name" = 'John' AND "Last Name" = 'Doe'

However, it is not useful for this query:

... WHERE "First Name" = 'John'

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.

Avoid Indexing Small Tables
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.

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.

* <# of rows>

<# of pages> = -----------------------------------------------------------------

4096

For example, suppose a table has the following schema:

Column Name Type (size)
Order ID
INTEGER (4 bytes)

Product ID
INTEGER (4 bytes)

Unit Price
MONEY (8 bytes)

Quantity
SMALLINT (2 bytes)

Discount
REAL (4 bytes)


The table has 2820 rows. According to the formula, it takes about 16 pages to store its data:

<# of pages> = ((4 + 4 + 8 + 2 + 4) * 2820) / 4096 = 15.15 pages

Choose What to Index

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.

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.

Use Indexes with Filter Clauses
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.

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:

Column operator

operator Column

SARG operators include =, >, <, >=, <=, IN, BETWEEN, and sometimes LIKE (in cases of prefix matching, such as LIKE 'John%'). A SARG can include multiple conditions joined with an AND. SARGs can be queries that match a specific value, such as:

"Customer ID" = 'ANTON'

'Doe' = "Last Name"

SARGs can also be queries that match a range of values, such as:

"Order Date" > '1/1/2002'

"Customer ID" > 'ABCDE' AND "Customer ID" < 'EDCBA'

"Customer ID" IN ('ANTON', 'AROUT')

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, <>, NOT EXISTS, NOT IN, NOT LIKE, and intrinsic functions.

Use the Query Optimizer

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.

Understand Response Time vs. Total Time

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.

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.

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.

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.

Index the ORDER-BY / GROUP-BY / DISTINCT Columns for Better Response Time
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.

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 ("Last Name" ASC, "First Name" ASC) can help optimize the following queries:

... ORDER BY / GROUP BY "Last Name" ...

... ORDER BY / GROUP BY "Last Name", "First Name" ...

It will not help optimize:

... ORDER BY / GROUP BY "First Name" ...

... ORDER BY / GROUP BY "First Name", "Last Name" ...

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:

... DISTINCT "Last Name", "First Name" ...

... DISTINCT "First Name", "Last Name" ...

It will not help optimize:

... DISTINCT "First Name" ...

... DISTINCT "Last Name" ...

Note:
If your query always returns unique rows on its own, avoid specifying the DISTINCT keyword, because it only adds overhead




Rewrite Subqueries to Use JOIN

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.

Note:
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.



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:

SELECT "Order ID" FROM Orders O

WHERE EXISTS (SELECT "Order ID"

FROM "Order Details" OD

WHERE O."Order ID" = OD."Order ID"

AND Discount >= 0.25)

You can also rewrite this by using JOIN:

SELECT DISTINCT O."Order ID" FROM Orders O INNER JOIN "Order Details"

OD ON O."Order ID" = OD."Order ID" WHERE Discount >= 0.25

Limit Using Outer JOINs
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.

For more information about a query that contains INNER JOIN, see Microsoft Knowledge Base.

Use Parameterized Queries

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:

SELECT "Customer ID" FROM Orders WHERE "Order ID" = ?

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.

Query Only When You Must

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.

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:

Open the Orders base table

Find the row, using the specific "Order ID"

Retrieve the "Customer ID"

Or you could issue the following query for each lookup:

SELECT "Customer ID" FROM Orders WHERE "Order ID" =


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.

Monday, August 06, 2007

Participating in Transactions in XML Web Services Created Using ASP.NET

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

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's context and enlists in the transaction through the Distributed Transaction Coordinator (DTC). The entire transaction occurs automatically.

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.

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.

<%@ WebService Language="C#" Class="Orders" %>
<%@ Assembly name="System.EnterpriseServices,Version=1.0.3300.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" %>

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using System.EnterpriseServices;

public class Orders : WebService
{
[ WebMethod(TransactionOption=TransactionOption.RequiresNew)]
public int DeleteAuthor(string lastName)
{
String deleteCmd = "DELETE FROM authors WHERE au_lname='" +
lastName + "'" ;
String exceptionCausingCmdSQL = "DELETE FROM NonExistingTable WHERE
au_lname='" + lastName + "'" ;

SqlConnection sqlConn = new SqlConnection(
"Persist Security Info=False;Integrated Security=SSPI;database=pubs;server=myserver");

SqlCommand deleteCmd = new SqlCommand(deleteCmdSQL,sqlConn);
SqlCommand exceptionCausingCmd = new
SqlCommand(exceptionCausingCmdSQL,sqlConn);

// This command should execute properly.
deleteCmd.Connection.Open();
deleteCmd.ExecuteNonQuery();

// This command results in an exception, so the first command is
// automatically rolled back. Since the XML Web service method is
// participating in a transaction, and an exception occurs, ASP.NET
// automatically aborts the transaction. The deleteCmd that
// executed properly is rolled back.

int cmdResult = exceptionCausingCmd.ExecuteNonQuery();

sqlConn.Close();

return cmdResult;
}
}

Managing State in XML Web Services Created Using ASP.NET

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.

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.


To access and store state specific to a particular client session

Declare an XML Web service method, setting the EnableSession property of the WebMethod attribute to true.

[ WebMethod(EnableSession=true) ]
public int PerSessionServiceUsage()

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.


<%@ WebService Language="C#" Class="ServerUsage" %>
using System.Web.Services;

public class ServerUsage : WebService {
[ WebMethod(Description="Number of times this service has been accessed.") ]
public int ServiceUsage() {
// If the XML Web service method hasn't been accessed,
// initialize it to 1.
if (Application["appMyServiceUsage"] == null)
{
Application["appMyServiceUsage"] = 1;
}
else
{
// Increment the usage count.
Application["appMyServiceUsage"] = ((int) Application["appMyServiceUsage"]) + 1;
}
return (int) Application["appMyServiceUsage"];
}

[ WebMethod(Description="Number of times a particualr client session has accessed this XML Web service method.",EnableSession=true) ]
public int PerSessionServiceUsage() {
// If the XML Web service method hasn't been accessed, initialize
// it to 1.
if (Session["MyServiceUsage"] == null)
{
Session["MyServiceUsage"] = 1;
}
else
{
// Increment the usage count.
Session["MyServiceUsage"] = ((int) Session["MyServiceUsage"]) + 1;
}
return (int) Session["MyServiceUsage"];
}
}

Wednesday, August 01, 2007

Post data to other Web pages with ASP.NET 2.0

ASP.NET 2.0's PostBackUrl attribute allows you to designate where a Web form and its data is sent when submitted.

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


The old approach

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.

< html >
< head >
< title > Sample HTML form</title></head>
<body>
<form name="frmSample" method="post" action="target_url">
<input type="text" name="fullname" id="fullname" />
<input type="button" name="Submit" value="submit" />

</form>
</body></html>The value entered in the text field (fullname) is submitted to the page or program specified in the form element's action attribute. For ASP.NET developers, standard HTML forms are seldom, if ever, used.

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.


ASP.NET 2.0 alternative

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.

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.

Listing A

<%@ Page language="vb" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<html><head>

<title>Cross Postback Example</title>

</head><body>

<form id="frmCrossPostback1" method="post" runat="server">

<asp:Label ID="lblName" runat="server" Text="Name:"></asp:Label>

<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />

<asp:Label ID="lblE-mailAddress" runat="server" Text="E-mail:"></asp:Label>

<asp:TextBox ID="txtE-mailAddress" runat="server"></asp:TextBox><br />

<asp:Button ID="btnSubmit" runat="server" Text="Submit" PostBackUrl="CrossPostback2.aspx" />

</form></body></html>
Working with previous pages

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.

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.

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.

Once you determine that a cross postback has occurred, you can access controls on the calling page via the PreviousPage object'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.

Listing B


<%@ Page language="vb" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<html><head>

<title>Cross Postback Example 2</title>

</head><body>

<script language="vb" runat="server">

Sub Page_Load()

If Not (Page.PreviousPage Is Nothing) Then

If Not (Page.IsCrossPagePostBack) Then
Response.Write("Name:" + CType(PreviousPage.FindControl("txtName"), TextBox).Text + "<BR>")
Response.Write("E-mail:" + CType(PreviousPage.FindControl("txtE-mailAddress"), TextBox).Text + "<BR>")

End If

End If

End Sub

</script></body></html>
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.


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.

Listing C


<%@ Page language="vb" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<html><head>

<title>Cross Postback Example</title>

<script language="vb" runat="server">

Public ReadOnly Property Name

Get

Return Me.txtName.Text

End Get

End Property

Public ReadOnly Property E-mailAddress

Get

Return Me.txtE-mailAddress.Text

End Get

End Property

</script></head><body>

<form id="frmCrossPostback1" method="post" runat="server">

<asp:Label ID="lblName" runat="server" Text="Name:"></asp:Label>

<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />

<asp:Label ID="lblE-mailAddress" runat="server" Text="E-mail:"></asp:Label>

<asp:TextBox ID="txtE-mailAddress" runat="server"></asp:TextBox><br />

<asp:Button ID="btnSubmit" runat="server" Text="Submit" PostBackUrl="CrossPostback2.aspx" />

</form></body></html>
Now that the properties have been established, you can easily access them. One caveat is that the Page class'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.

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.

Listing D


<%@ Page language="vb"
%>

<%@ Reference Page="~/CrossPostback1.aspx" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<html><head>

<title>Cross Postback Example 3</title>

</head><body>

<script language="vb" runat="server">

Sub Page_Load()

Dim cppPage As CrossPostback1_aspx

If Not (Page.PreviousPage Is Nothing) Then

If Not (Page.IsCrossPagePostBack) Then

If (Page.PreviousPage.IsValid) Then
cppPage = CType(PreviousPage, CrossPostBack1_aspx)
Response.Write("Name:" + cppPage.Name + "<br>")
Response.Write("E-mail:" + cppPage.E-mailAddress)

End If

End If

End If

End Sub

</script></body></html>

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.

Summary

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're working on your next ASP.NET 2.0 application.