Monday, August 31, 2009

Que:- What is the sequence in which ASP.NET events are processed ?
Ans:- Following is the sequence in which the events occur :-
* Page_Init.
* Page_Load.
* Control events.
* Page_Unload event.
Page_init event only occurs when first time the page is started, but Page_Load occurs in subsequent request of the page.

Que:- In which event are the controls fully loaded ?
Ans:- Page_load event guarantees that all controls are fully loaded. Controls are also accessed in Page_Init events but you will see that viewstate is not fully loaded during this event.

Que:- How can we identify that the Page is PostBack ?
Ans:- Page object has a “IsPostBack” property which can be checked to know that is the page posted back.

Que:-What is event bubbling ?
Ans:- Server controls like Datagrid, DataList, Repeater can have other child controls inside them. Example DataGrid can have combo box inside datagrid. These child control do not raise there events by themselves, rather they pass the event to the container parent (which can be a datagrid, datalist, repeater), which passed to the page as “ItemCommand” event. As the child control send there events to parent this is termed as event bubbling.

Que:- If we want to make sure that no one has tampered with ViewState, how do we ensure it?
Ans:- Using the @Page directive EnableViewStateMac to True.

Que:- What is AppSetting Section in “Web.Config” file?
Ans:- Web.config file defines configuration for a webproject. Using “AppSetting” section we can define user defined values. Example below defined is ConnectionString” section which will be used through out the project for database connection.

Que:- Where is ViewState information stored ?
Ans:- In HTML Hidden Fields.

Que:- How can we create custom controls in ASP.NET ?
Ans:- User controls are created using .ASCX in ASP.NET. After .ASCX file is created you need to two things in order that the ASCX can be used in project:

* Register the ASCX control in page using the <%@ Register directive>.

<%@ Register tagprefix="Accounting" Tagname="footer" Src="Footer.ascx" %>
* Now to use the above accounting footer in page you can use the below directive.

Que:- How many types of validation controls are provided by ASP.NET ?
Ans:- There are six main types of validation controls :-
1). RequiredFieldValidator :-

It checks whether the control have any value. It's used when you want the control should not be empty.

2). RangeValidator :-

It checks if the value in validated control is in that specific range. Example
TxtCustomerCode should not be more than eight length.

3). CompareValidator:-

It checks that the value in controls should match the value in other control. Example
Textbox TxtPie should be equal to 3.14.

4). RegularExpressionValidator:-

When we want the control value should match with a specific regular expression.

5). CustomValidator:-

It is used to define UserDefined validation.

6). ValidationSummary:-

It displays summary of all current validation errors.

Que:- Can you explain what is “AutoPostBack” feature in ASP.NET ?
Ans:- If we want the control to automatically postback in case of any event, we will need to check this attribute as true. Example on a ComboBox change we need to send the event immediately to the server side then set the “AutoPostBack” attribute to true.

Que:- How can you enable automatic paging in DataGrid ?
Ans:- Following are the points to be done in order to enable paging in Datagrid :-
* Set the “AllowPaging” to true.
* In PageIndexChanged event set the current pageindex clicked.

Que:-What is the difference between “Web.config” and “Machine.Config” ?
Ans:- “Web.config” files apply settings to each web application, while Machine.config” file apply settings to all ASP.NET applications.

Que:- What is the difference between Server.Transfer and response.Redirect ?
Ans:- Following are the major differences between them:-
* Response.Redirect sends message to the browser saying it to move to some
different page, while server.transfer does not send any message to the browser
but rather redirects the user directly from the server itself. So in server.transfer
there is no round trip while response.redirect has a round trip and hence puts
a load on server.

* Using Server.Transfer you can not redirect to a different from the server itself.
Example if your server is you can use server.transfer to move
to but yes you can move to, i.e.
within websites. This cross server redirect is possible only using

* With server.transfer you can preserve your information. It has a parameter
called as “preserveForm”. So the existing query string etc. will be able in the
calling page. In response.redirect you can maintain the state, but has
lot of drawbacks.

Que:- What is the difference between Authentication and authorization?
Ans:- This can be a tricky question. These two concepts seem altogether similar but there is wide range of difference. Authentication is verifying the identity of a user and authorization is process where we check does this identity have access rights to the system. In short we can say the following authentication is the process of obtaining some sort of credentials from the users and using those credentials to verify the user’s identity. Authorization is the process of allowing an authenticated user access to resources. Authentication always proceed to Authorization; even if your application lets anonymous users connect and use
the application, it still authenticates them as being anonymous.

Que:- What are the various ways of authentication techniques in ASP.NET?
Ans:- Selecting an authentication provider is as simple as making an entry in the web.config file for the application. You can use one of these entries to select the corresponding built in authentication provider:

* authentication mode=”windows”
* authentication mode=”passport”
* authentication mode=”forms”
* Custom authentication where you might install an ISAPI filter in IIS that
compares incoming requests to list of source IP addresses, and considers
requests to be authenticated if they come from an acceptable address. In that
case, you would set the authentication mode to none to prevent any of the
.net authentication providers from being triggered.

Que:- How does authorization work in ASP.NET?
Ans:- ASP.NET impersonation is controlled by entries in the applications web.config file. The default setting is “no impersonation”. You can explicitly specify that ASP.NET shouldn’t use impersonation by including the following code in the file

It means that ASP.NET will not perform any authentication and runs with its own
privileges. By default ASP.NET runs as an unprivileged account named ASPNET. You
can change this by making a setting in the processModel section of the machine.config
file. When you make this setting, it automatically applies to every site on the server. To user a high-privileged system account instead of a low-privileged set the userNameattribute of the processModel element to SYSTEM. Using this setting is a definite security risk, as it elevates the privileges of the ASP.NET process to a point where it can do bad things to the operating system.

Que:- What’s difference between Datagrid, Datalist and repeater ?
Ans:- A Datagrid, Datalist and Repeater are all ASP.NET data Web controls.
They have many things in common like DataSource Property, DataBind Method
ItemDataBound and ItemCreated.
When you assign the DataSource Property of a Datagrid to a DataSet then each DataRow
present in the DataRow Collection of DataTable is assigned to a corresponding
DataGridItem and this is same for the rest of the two controls also. But The HTML code generated for a Datagrid has an HTML TABLE element created for the particular DataRow and its a Table form representation with Columns and Rows.
For a Datalist its an Array of Rows and based on the Template Selected and the
RepeatColumn Property value We can specify how many DataSource records should
appear per HTML table row. In short in datagrid we have one record per row, but in
datalist we can have five or six rows per row.
For a Repeater Control, the Datarecords to be displayed depends upon the Templates
specified and the only HTML generated is the due to the Templates.
In addition to these, Datagrid has a in-built support for Sort, Filter and paging the Data,which is not possible when using a DataList and for a Repeater Control we would require to write an explicit code to do paging.

Que:- From performance point of view how do they rate ?
Ans:- Repeater is fastest followed by Datalist and finally datagrid.

Que:- What is the method to customize columns in DataGrid?
Ans:- Use the template column.

Que:- How can we format data inside DataGrid?
Ans:- Use the DataFormatString property.

Que:- How to decide on the design consideration to take a Datagrid, datalist or repeater ?
Ans:- Many make a blind choice of choosing datagrid directly, but that's not the right way.
Datagrid provides ability to allow the end-user to sort, page, and edit its data. But it comes at a cost of speed. Second the display format is simple that is in row and columns.
Real life scenarios can be more demanding that With its templates, the DataList provides more control over the look and feel of the displayed data than the DataGrid. It offers better performance than datagrid Repeater control allows for complete and total control. With the Repeater, the only HTML emitted are the values of the databinding statements in the templates along with the HTML markup specified in the templates—no "extra" HTML is emitted, as with the DataGrid and DataList. By requiring the developer to specify the complete generated HTML markup, the Repeater often requires the longest development time. But repeater does not provide editing features like datagrid so everything has to be coded by programmer. However, the Repeater does boast the best performance of the three data Web controls.
Repeater is fastest followed by Datalist and finally datagrid.

Que:- Difference between ASP and ASP.NET?
Ans:- ASP.NET new feature supports are as follows :-

Better Language Support

* New ADO.NET Concepts have been implemented.
ASP.NET supports full language (C#, VB.NET, C++) and not simple scripting

Better controls than ASP

* ASP.NET covers large set’s of HTML controls..
* Better Display grid like Datagrid, Repeater and datalist.Many of the display
grids have paging support.

Controls have events support

* All ASP.NET controls support events.
* Load, Click and Change events handled by code makes coding much simpler and much better organized.

Compiled Code

The first request for an ASP.NET page on the server will compile the ASP.NET code and
keep a cached copy in memory. The result of this is greatly increased performance.
Better Authentication Support
ASP.NET supports forms-based user authentication, including cookie management and
automatic redirecting of unauthorized logins. (You can still do your custom login page and custom user checking).

User Accounts and Roles

ASP.NET allows for user accounts and roles, to give each user (with a given role) access to different server code and executables.

High Scalability

* Much has been done with ASP.NET to provide greater scalability.
* Server to server communication has been greatly enhanced, making it possible
to scale an application over several servers. One example of this is the ability
to run XML parsers, XSL transformations and even resource hungry session objects on other servers.

Easy Configuration

Configuration of ASP.NET is done with plain text files.
* Configuration files can be uploaded or changed while the application is running.
No need to restart the server. No more metabase or registry puzzle.

Easy Deployment

No more server restart to deploy or replace compiled code. ASP.NET simply redirects all new requests to the new code.

Que:- What are major events in GLOBAL.ASAX file ?
Ans:- The Global.asax file, which is derived from the HttpApplication class, maintains a pool
of HttpApplication objects, and assigns them to applications as needed. The Global.asax
file contains the following events:

Application_Init: Fired when an application initializes or is first called. It is invoked for
all HttpApplication object instances.

Application_Disposed: Fired just before an application is destroyed. This is the ideal
location for cleaning up previously used resources.

Application_Error: Fired when an unhandled exception is encountered within the

Application_Start: Fired when the first instance of the HttpApplication class is created.
It allows you to create objects that are accessible by all HttpApplication instances.
Application_End: Fired when the last instance of an HttpApplication class is destroyed.
It is fired only once during an application's lifetime.

Application_BeginRequest: Fired when an application request is received. It is the first
event fired for a request, which is often a page request (URL) that a user enters.

Application_EndRequest: The last event fired for an application request.

Application_PreRequestHandlerExecute: Fired before the ASP.NET page framework
begins executing an event handler like a page or Web service.

Application_PostRequestHandlerExecute: Fired when the ASP.NET page framework has finished executing an event handler

Applcation_PreSendRequestHeaders: Fired before the ASP.NET page framework sends
HTTP headers to a requesting client (browser).

Application_UpdateRequestCache: Fired when the ASP.NET page framework completes
handler execution to allow caching modules to store responses to be used to handle
subsequent requests.

Application_AuthenticateRequest: Fired when the security module has established the
current user's identity as valid. At this point, the user's credentials have been validated.
Application_AuthorizeRequest: Fired when the security module has verified that a user
can access resources.

Session_Start: Fired when a new user visits the application Web site.

Session_End: Fired when a user's session times out, ends, or they leave the application
Web site.

Que:- What order they are triggered ?
Ans:- They're triggered in the following order:

* Application_BeginRequest
* Application_AuthenticateRequest
* Application_AuthorizeRequest
* Application_ResolveRequestCache
* Application_AcquireRequestState
* Application_PreRequestHandlerExecute
* Application_PreSendRequestHeaders
* Application_PreSendRequestContent
* Application_PostRequestHandlerExecute
* Application_ReleaseRequestState
* Application_UpdateRequestCache
* Application_EndRequest.

Que:- How can we force all the validation control to run ?
Ans:- Page.Validate

Que:- How can we check if all the validation control are valid and proper ?
Ans:- Using the Page.IsValid() property you can check whether all the validation are done.

Que:- Which JavaScript file is referenced for validating the validators at the client side ?
Ans:- WebUIValidation.js javascript file installed at “aspnet_client” root IIS directory is used
to validate the validation controls at the client side

Que:- What is Tracing in ASP.NET ?
Ans:- Tracing allows us to view how the code was executed in detail.

Que:- How do we enable tracing ?
Ans:- <%@ Page Trace="true" %>

Que:- How can we kill a user session ?
Ans:- Session.abandon

Que:- How do I send email message from ASP.NET ?
ANs:- ASP.NET provides two namespaces System.WEB.mailmessage classand
System.Web.Mail.Smtpmail class. Just a small homework create a Asp.NET project and
send a email at "Email Adress". Do not Spam.

Que:- Explain the differences between Server-side and Client-side code?
Ans:- Server side code is executed at the server side on IIS in ASP.NET framework, while
client side code is executed on the browser.

Silverlight Baskit Ball

Saturday, August 29, 2009

Download Source Code

What’s new in ASP.NET 4.0

Sunday, August 16, 2009

With Visual Studio 2010 Beta 1 and .NET Framework Beta 1 out for some time, this post is due from me for a long time. ASP.NET 4.0 has many improvements for different set of scenarios such as Webforms, Dynamic Data & AJAX based web development. There are also a lot of enhancements to the core runtime that powers ASP.NET such as Caching, Session & Request/Response objects.

For this post, we will examine some of the web form enhancements. There are sure a lot of them and we will examine some of them in the future posts.

Controlling View State using the ViewStateMode Property – Performance Enhancement

One of the most complained thing in ASP.NET Webform is the growing viewstate which becomes a concern for performance. While earlier you can set the EnableViewState property to true or false, post that, all the controls, by default inherit and even if you set it to enabled at control level, the behaviour was inconsistent.

With ASP.NET 4.0, the ViewStateMode property helps to determine for every control, whether the ViewState should be enabled, disabled or inherited accordingly. Ex.-

When you run the above page, you can find that the intial value for both the labels is set to “Value set in code behind” whereas after clicking on the button (postback), the value of label1 changes to “Value set in markup” whereas the value of label2 remains unchanged. As you can see, the Panel which holds both these lables has ViewStateMode set to Disabled and label1 is inherting the mode (this is the default if not specified) and label2 has it enabled. That is the reason label2 maintains viewstate while label1 loses it.

While it is arguably possible using the simple EnableViewState property earlier, it was never consistent. Considering the fact that in most of our performance sessions, we talk about disabling viewstate and then enabling it at control level while it doesnt work, this ViewStateMode is a welcome architectural change to improve performance.

Page Meta Keyword & Description – Search Engine Optimization feature

Upto Visual Studio 2008, one can set the Title of the page declaratively or through program using Page.Title. However, as more and more web traffic is happening through search engines, Page’s Title, Keyword and description become more important. Although the Keyword feature was exploited and hence many search engines today ignore it, Page Description is something still major search engines such as Google, Bing use for identifying and indexing pages based on content.

The new feature in ASP.NET 4.0 allows users to programmatically set the Page Description and Keywords as follows:-

The above code appends the following markup

And the way it works is that, if the meta tags are already present in the HTML markup, whatever is set in the code behind will fill up the “content” part alone if the “name” tag is matching.

Although this looks simple, it is very useful in cases where you want to set these dynamically based on a condition / criteria. So far, these were set statically in the HTML. Now with Page Class level access, these can be set dynamically.

There are many more enhancements to Webforms such as Routing improvements, setting ClientID etc., which we will examine in the future posts.

Cheers !!!


Friday, August 14, 2009

An application runs in the cloud, uses services provided by the cloud, or both, some kind of application platform is required. Viewed broadly, an application platform can be thought of as anything that provides developer-accessible services for creating applications. In the local, on-premises Windows world, for example, this includes technologies such as the .NET Framework, SQL Server, and more. To let applications exploit the cloud, cloud application platforms must also exist. And because there are a variety of ways for applications to use cloud services, different kinds of cloud platforms are useful in different situations.
Microsoft’s Azure Services Platform is a group of cloud technologies, each providing a specific set of services to application developers. As Figure 1 shows, the Azure Services Platform can be used both by applications running in the cloud and by applications running on local systems.

Figure 1: The Azure Services Platform supports applications running in the cloud and on local systems.
The components of the Azure Services Platform can be used by local applications running on a variety of systems, including various flavors of Windows, mobile devices, and others. Those components include:
• Windows Azure: Provides a Windows-based environment for running applications and storing data on servers in Microsoft data centers.
• Microsoft .NET Services: Offers distributed infrastructure services to cloud-based and local applications.
• Microsoft SQL Services: Provides data services in the cloud based on SQL Server.
• Live Services: Through the Live Framework, provides access to data from Microsoft’s Live applications and others. The Live Framework also allows synchronizing this data across desktops and devices, finding and downloading applications, and more.
Each component of the Azure Services Platform has its own role to play. This overview describes all four, first at a high level, then in a bit more detail. While none of them are yet final—details and more might change before their initial release—it’s not too early to start understanding this new set of platform technologies.
At a high level, Windows Azure is simple to understand: It’s a platform for running Windows applications and storing their data in the cloud. Figure 2 shows its main components.

Figure 2: Windows Azure provides Windows-based compute and storage services for cloud applications.
As the figure suggests, Windows Azure runs on a large number of machines, all located in Microsoft data centers and accessible via the Internet. A common Windows Azure fabric knits this plethora of processing power into a unified whole. Windows Azure compute and storage services are built on top of this fabric.
The Windows Azure compute service is based, of course, on Windows. For the initial availability of this service, a Community Technology Preview (CTP) made public in the fall of 2008, Microsoft allowed Windows Azure to run only applications built on the .NET Framework. The company has announced plans to support unmanaged code as well, i.e., applications that aren’t built on the .NET Framework, on Windows Azure in 2009.
In the CTP version of Windows Azure, developers can create .NET-based software such as ASP.NET applications and Windows Communication Foundation (WCF) services. To do this, they can use C# and other .NET languages, along with traditional development tools such as Visual Studio 2008. And while many developers are likely to use this initial version of Windows Azure to create Web applications, the platform also supports background processes that run independently—it’s not solely a Web platform.
Both Windows Azure applications and on-premises applications can access the Windows Azure storage service, and both do it in the same way: using a RESTful approach. The underlying data store is not Microsoft SQL Server, however. In fact, Windows Azure storage isn’t a relational system, and its query language isn’t SQL. Because it’s primarily designed to support applications built on Windows Azure, it provides simpler, more scalable kinds of storage. Accordingly, it allows storing binary large objects (blobs), provides queues for communication between components of Windows Azure applications, and even offers a form of tables with a straightforward query language.
.NET Services
Microsoft .NET Services are a set of Microsoft-hosted, highly scalable, developer-oriented services that provide key building blocks required by many cloud-based and cloud-aware applications. Much like the .NET Framework provides higher-level class libraries that make developers more productive, Microsoft .NET Services enables developers to focus on their application logic rather than building and deploying their own cloud-based infrastructure services.
Windows Azure
Windows Azure is the cloud services operating system that serves as the development, service hosting, and service management environment for the Windows Azure Platform. Windows Azure provides developers with on-demand compute and storage to host, scale, and manage Internet or cloud applications. and services on the Internet in Microsoft data centers.
Windows Azure supports a consistent development experience through its integration with Visual Studio. In the early stages of CTP, .NET managed applications built using Visual Studio will be supported. Windows Azure is an open platform that will support both Microsoft and non-Microsoft languages and environments. Windows Azure welcomes third-party tools and languages such as Eclipse, Ruby, PHP, and Python.
Microsoft Cloud Computing Tools
Windows Azure Tools for Microsoft Visual Studio extend Visual Studio 2008 and Visual Studio 2010 Beta 1 to enable the creation, building, debugging, running, and packaging of scalable Web applications and services on Windows Azure.
SQL Azure
Microsoft SQL Azure extends the capabilities of Microsoft SQL Server into the cloud as a Web-based, distributed relational database. It provides Web services that enable relational queries, search, and data synchronization with mobile users, remote offices and business partners. It can store and retrieve structured, semi-structured, and unstructured data.
Web Developers
The Windows Azure Platform is built to help you create, deploy, and distribute Web services and applications on the Internet. Web developers can create applications that run in a browser or build and publish your own set of services by harnessing the flexibility of SOAP, REST, and XML; use your current skill set on a range of Microsoft and non-Microsoft tools on a standards-based platform; create and share results quickly; and extend solutions to a millions of Windows Liv customers.
Corporate Developers
With the Windows Azure Platform, you can augment your company’s software solutions and connect with your partners’ systems more quickly and easily than ever before. You can create, test, and deploy software by using the skills, tools, and frameworks that you already know best –— without additional training or costly capital investments.
independent Software Vendors ISVs
Azure is a comprehensive services platform that ISVs can use to take full advantage of the reach and scalability of the Internet without sacrificing their investments in existing applications. Because it is an extension of the Microsoft platform, developers are able to use Azure to create .NET-based applications that run in Microsoft data centers and use cloud-based services that extend the value of on-premises software.
System Integrators and Value-Added Partners
As the hub of the Microsoft software-plus-services initiative, the Windows Azure Platform affords system integrators and value-added partners an opportunity to both streamline their own infrastructure investments and help their clients to do the same.
The Windows Azure Platform provides cloud-based computing and services designed to make Internet-scale computing easier for developers in corporate and enterprise settings. These services decrease the capital and operational costs of maintaining existing applications or planning for new initiatives by using Microsoft’s infrastructure in a pay-as-you-use pricing model.
Creating the Project
Open Visual Studio 2008 and create a Web Cloud Service project.

Updating Service Definition

The first step to do is to update the service definition and service configuration files to include the storage account. Edit your service definition file found in the Guestbook project and enter these settings

This specifies your Windows Azure account name
The shared key used to authenticate requests made against your Windows Azure account
The base URI of the table storage service
Updating Service Configuration
After setting the properties in our service definition, we need to set the values of those properties in our service configuration file found in the Guestbook project

All the values reflect your local development storage and nothing in the cloud. The development storage supports only the above fixed account and is same for everyone.
We should be able to test our azure application locally in the local development storage before deploying it to the cloud. Testing your application locally will also help you to debug your applications.
Creating the Table Schema
Defining the table schema is as easy as creating classes. The idea here is to create a class, where the class name corresponds to the table name and the properties correspond to the table properties. The local development storage environment uses ADO.NET to create tables in the local environment, whereas this is not needed when we host our application in the cloud.
Creating these classes are made simple by using the StorageClient library provided in the Windows Azure SDK

You can add the StorageClient project to our Guestbook solution or just reference the library.

Below is our class which represents the Guestbook table:

As you can see in the above screenshot, our class GuestDataModel inherits TableStorageEntity. This TableStorageEntity class is available in the StorageClient library and defines some of the properties such as partition key and row key that is required for each entity in the table.

The GuestDataModel consists of three properties:

1) Message
2) Name
3) Url

And our simple constructor where we initialize the partition key and row key:

As the local storage uses ADO.NET we are going to create class GuestDataServiceContext which inherits from TableStorageDataServiceContext from the StorageClient library. The TableStorageDataServiceContext represents the runtime context of our ADO.NET service.

Now having the data model and the data context in place, its very easy to query our storage and perform the usual insert, delete operations

We create a GuestDataSource which is going to help interact with the data context and insert, delete and get all the GuestDataModel entities

As you can see, it's pretty straight forward. Below are insert and delete methods:

Creating our Tables
We saw how to insert, delete and get all our entities from the table using a simple data source, but where are we actually creating the table?

We are going to create the table on the first request to the website which can be done by adding the appropriate code into the global application class.
Executing this guestbook sample
Executing this guestbook sample is just as same as executing a normal application! Hit F5 and Visual Studio 2008 will take care of everything - from starting the local development storage, creating the tables and debugging the application.

Download Code

Usama Wahab Khan & Atif Shahzad

Zune HD

Monday, August 10, 2009

About Microsoft
Founded in 1975, Microsoft is the worldwide leader in software, services and solutions that help people and businesses realize their full potential.

Supported 720p HD video files play on the device, downscaled to fit the screen at 480 x 272 - not HD resolution. Zune HD and AV Dock, and an HDTV (all sold separately) are required to view video at HD resolution. 
Introducing Zune HD
Microsoft's Zune HD's overexposed -- both in quantity of pics and in quality of photography -- camera shoot with the FCC has been made public, showing off quite a bit of the device, its internals, and its dock. We've got two model numbers listed here, 1395 and 1402 representing the 16GB and 32GB models, respectively, and in case you're wondering, that's Windows CE you're seeing above, the OS on which Zune HD's UI is built. Hit up the read link to browse yourself, or check out the gallery below for the highlights, including a NVIDIA Tegra chip sighting and an amusing "For our princess" tattoo on the inside of the back cover. Now if we could only get a MSRP or narrower release window...

Microsoft Announces the Expansion of the Zune Entertainment Service to New Platform and Markets; Confirms New Zune HD Portable Media Player
Microsoft Corp. today announced the evolution of Zune, the company's end-to-end music and entertainment service, to a new platform and new markets. Zune will extend its video service to Xbox LIVE internationally this fall. This marks an important development in the Zune strategy and brings the Zune brand to more than 17 million international Xbox LIVE subscribers. In addition, Microsoft confirmed the next generation of the Zune portable media player, Zune HD. Available in the U.S. this fall, Zune HD is the first portable media player that combines a built-in HD Radio receiver, high-definition (HD) video output capabilities, organic light-emitting diode (OLED) touch screen, Wi-Fi and an Internet browser.

"The Zune music player is an integral part of the overall Zune experience, and we're proud to be growing and extending our offering beyond the device," said Enrique Rodriguez, corporate vice president of the Microsoft TV, Video and Music Business Group. "Delivering on Microsoft's connected entertainment vision, this news marks a turning point for Zune as it brings cross-platform experiences and premium video content to living rooms around the world."
Zune Service Expands to New Platform
Zune will be a premium partner in the Xbox LIVE Video Marketplace, bringing an exciting catalog of TV and film to the platform. Zune will occupy the first slot within the Xbox user interface in the Xbox LIVE Video Marketplace, exposing the Zune brand experience to millions of new consumers for the first time. At the Electronic Entertainment Expo (E3) next week, attendees will see firsthand how Zune integrates into Xbox LIVE to create a game-changing entertainment experience.

Zune HD is the next iteration of the Zune device family and brings a new level of listening and viewing experiences to the portable media player category.
•Zune HD comes with a built-in HD Radio receiver so users can listen to higher-quality sound than traditional radio on the go. Users also will have access to the additional song and artist data broadcast by HD Radio stations as well as additional channels from their favorite stations multicasting in HD. If you don't like the song playing on your station's HD channel, switch to its HD2 or HD3 channels for additional programming.
•The bright OLED touch screen interface allows users to flip through music, movies and other content with ease, and the 16:9 widescreen format display (480x272 resolution) offers a premium viewing experience on the go.
•The HD-compatible output lets Zune HD customers playback supported HD video files from the device through a premium high-definition multimedia interface (HDMI) audiovisual docking station (sold separately) direct to an HD TV in 720p.*
•Zune HD will include a full-screen Internet browser optimized for multitouch functionality.
•Zune HD is Wi-Fi enabled, allowing for instant streaming to the device from the more than 5 million-track Zune music store.
More information on Zune and related images is available at

About Zune
Zune is Microsoft's music and entertainment brand that provides an integrated digital entertainment experience. The Zune platform includes a line of portable digital media players, elegant software, the Zune Marketplace online store, Zune Pass music subscription service, and the Zune Social online music community, created to help people discover more music. Zune is part of Microsoft's Entertainment and Devices Division and supports the company's software-based services vision to help drive innovation in the digital entertainment space. More information can be found online at
About Xbox LIVE
Xbox LIVE connects more than 17 million members across 26 countries to each other and the entertainment they love. Home of more content from one remote than can be found from any device connected to the television, Xbox LIVE is also a unified online social network bringing friends together, no matter where they are - in the living room or across the world.
Zune HD on-screen keyboard and browser caught on camera

Yahoo! Tech managed to get a hands-on with the device, snapping some pictures of the browser and, more importantly, the on-screen keyboard. It's only a minor glimpse, but it definitely looks sleek. Shot of the browser after the break, and hit up the read link for full gallery. Microsoft, add a 3G chipset and dialer app, and you can go ahead and draft those "million seller" press releases already.

By Usama Wahab Khan and Atif Shahzad

Show Large Images with Deep Zoom Composer - Video Tour

Wednesday, August 5, 2009

Deep Zoom Composer is a free software from Microsoft that lets you place high resolution photographs and other large images in a web page without resizing them.
Your viewers can then navigate through the images using standard zoom and pan controls similar to what we have in Google Maps. The only thing they would need is Silverlight.
It take three steps to create a composition (or collage) in Deep Zoom Composer.
Step 1: Import your pictures into Deep Zoom Composer

Step 2: If you have just one picture to showcase, you are ready to go. Else your may arrange and resize the pictures in any manner you like. There’re are helpful on-screen guides to help you with the alignments and resizing.

Step 3: The last step is to export your composition. You can either export them onto your local drive or let Deep Zoom Composer upload it to Microsoft’s PhotoZoom website from where anyone can view your pictures.

You may also watch this screencast video on how to quickly create a composition with Deep Zoom Composer.
With Deep Zoom Composer, you can not only put high-res images on the web but the software can also be used for stitching panoramas on the fly. Just select the images that are part of the panorama, right click and select "Create Panoramic Photo."

Download Source Code
Usama Wahab Khan and Atif Shahzad


Microsoft Office SharePoint Server is an integrated suite of server capabilities that can help improve organizational effectiveness by providing comprehensive content management and enterprise search, accelerating shared business processes, and facilitating information-sharing across boundaries for better business insight. Additionally, this collaboration and content management server provides IT professionals and developers with the platform and tools they need for server administration, application extensibility, and interoperability.
Microsoft Office SharePoint Server is an integrated suite of server capabilities that can help improve organizational effectiveness by providing comprehensive content management and enterprise search, accelerating shared business processes, and facilitating information-sharing across boundaries for better business insight. Additionally, this collaboration and content management server provides IT professionals and developers with the platform and tools they need for server administration, application extensibility, and interoperability.

Site- or web-scoped Features can also be referenced within a site definition, so that as new sites get created your features will get activated.

Ultimately, though, not every behavior or kind of change you’d want to implement can be expressed in XML. For this reason, you can also define a feature receiver which contains callbacks which will get fired when the Feature is installed or activated.

Features are designed to be a way for developers to express building blocks for SharePoint, and for site admins to pick and choose new functionality they can add to their site. Out of the box, Microsoft Office SharePoint Server and WSS have about 128 features defined, combined. That’s a lot of building blocks :)

First, one goal was to make it possible for people to choose a site template, but over time add (or remove) capabilities as people needed them -- the philosophy is that choice of site template shouldn’t be a binding choice to force particular functionality for a site forever. To implement this, we needed to express to site admins which set of capabilities they can turn on. Calling these capabilities "Features" seemed to be more intuitive than calling them something a bit geekier, like "modules" or "components". Because the UI term for these was "Features", it made sense to call the development capability called "Features" too.

Second, the design of features was in part influenced by the way things are defined in Windows Installer. Windows Installer has the concept of "features" and "components". Features are those things you see in some setups where you can pick and choose, in a tree view, which various bits of software to install. For a brief moment the idea for SharePoint was to have features and components too, but to simplify things a little bit we just put features in (not components.)
What are master pages
Master pages are a feature of ASP.NET 2.0; they work the same way in Windows SharePoint Services 3.0 and Office SharePoint Server 2007 as they do in ASP.NET 2.0. Using master pages, you can create a single page template and then use that template as the basis for multiple pages, instead of having to build each new page from scratch.
Microsoft has made available a package of four sample master page sets that were built using new CSS and Master Page editing tools within Office SharePoint Designer 2007. These sample master pages:
Enable you to apply a pre-designed style and layout to SharePoint sites
Work with the forty new Application Templates for Windows SharePoint Services 3.0
Provide a starting point for deeper SharePoint site look and feel customizations
Windows SharePoint Services 3.0
Windows SharePoint Services 3.0 is the platform on which all SharePoint Products and Technologies are built. WSS 3.0 is for is suitable for small teams, projects and organizations.
WSS’s project collaboration, document workspace, meeting sub-site, and discussion board features allow individuals and small teams to collaborate and share information online. Past versions of Windows SharePoint Services included Windows SharePoint Services 2.0 and SharePoint Team Services. New features in WSS 3.0 include integrated workflows, RSS feeds, blogs, wikis and ASP-style Web parts.
SharePoint Designer 2007
Microsoft Office SharePoint Designer 2007 is the next generation of Microsoft FrontPage that enables both the design and customization of SharePoint 2007 sites. SharePoint Designer 2007 allows organizations to automate common business processes through simple or complex custom workflows. Corporations can apply their corporate branding to their SharePoint portal providing a unified look and feel to all their end users. Companies can also create customized SharePoint sites based upon the unique needs of your company's end users, teams, or departments without having to turn to outside consultants.
No-code interactive solutions
With Office SharePoint Designer 2007, you can build sophisticated no-code solutions such as Data Views, reports, and workflow tracking quickly and easily by using menus, task panes, and templates.
Incorporate data from a wide variety of sources into interactive Web pages
With Office SharePoint Designer 2007, you can create custom Data Views and data forms that leverage Microsoft ASP.NET technology, allowing you to integrate external data into your Web site, including views that display data from multiple sources.
For example, suppose that your enterprise has a product database and a customer database, and you want to display product information on your SharePoint site — you can do this quickly and easily by creating a view on that data. Suppose that you also want a Web page that displays which customers have ordered which products. You can do this by linking your data sources — in this case, your two databases — so that you can view this information in a single joined Data View. What's more, you can use this Data View as a form, so you can write data back to your data sources.

Access a wide variety of data sources from the Data Source Library
You can create Data Views from a wide variety of data sources, including:
RSS feeds Add RSS feeds to the Data Source Library, and create Data Views by using the RSS feeds as a data source.
XML files Add XML files to the Data Source Library, and create Data Views that display XML data.
Office XML Create Data Views from 2007 Microsoft Office system documents. For example, create a view on data in Microsoft Office Word 2007 documents by using their new XML-based file format as a data source.
Create high-impact reports
Tools such as calculated fields, conditional formatting, and sorting, grouping, and filtering capabilities help you create high-impact reports in the form of Data Views. For example, you can apply conditional formatting to a Data View so that items in your inventory are highlighted when they drop below a specific number and need to be reordered.
Collaborate more efficiently with the built-in Workflow Designer
You can associate conditions and actions with tasks, lists, and document libraries to automate communications that are specific to your needs. For example, you can create a workflow to automatically route documents that are posted to the site for approval. With the Workflow Designer, you can refine the approval routing to actions that are based on the document being approved or rejected, or in case recipients are out of the office and have delegated their responsibilities to a colleague.
Apply SharePoint Application Templates
You can use built-in application Web sites such as Expense and Reimbursement Tracking and Absence and Vacation Management to share information more effectively. Each template is fully customizable and extensible by using Office SharePoint Designer 2007. (You can find links to more examples of application Web sites in the See Also section. These applications are for Microsoft Windows SharePoint Services 2.0. Applications for Microsoft Windows SharePoint Services 3.0 will be available in the future.)
Build interactive ASP.NET pages
You can create ASP.NET pages and insert custom ASP.NET controls by using the same powerful on-control activity menus and control property grid found in development tools such as Microsoft Visual Studio 2005.
Professional design tools
Office SharePoint Designer 2007 provides the professional design tools that you need to create compelling SharePoint sites that are customized to your needs.
Enjoy an intuitive design experience
You can view and change SharePoint pages with advanced what-you-see-is-what-you-get (WYSIWYG) capabilities.
Format SharePoint pages quickly and easily with powerful cascading style sheets (CSS) tools
New CSS tools such as the Apply Styles and Manage Styles task panes make applying and managing style sheets faster, easier, and more efficient.

New CSS task panes make it easy to edit and update the SharePoint style sheet.
Use ASP.NET master pages to maintain a consistent look and feel throughout your site
Office SharePoint Designer 2007 supports ASP.NET master pages, which you can use to control the layout of your entire Web site by creating and editing a single template.
Microsoft Office SharePoint Server 2007 integration
Office SharePoint Designer 2007 includes ground-breaking new functionality that Office SharePoint Server 2007 users and portal site managers can take advantage of, enabling you to design and extend portal sites or portal pages with more flexibility and power than ever before.
Easily customize your portal site pages
Office SharePoint Server 2007 portal sites are fully customizable with Office SharePoint Designer 2007. You can edit the SharePoint style sheet with state-of-the-art CSS editing tools.
Extend business document workflows
With the Workflow Designer in Office SharePoint Designer 2007, you can extend the built-in business document workflows that are available in Office SharePoint Server 2007 and create custom workflows from scratch.
Create custom views of enterprise data
With the Office SharePoint Server 2007 Business Data Catalog and Office SharePoint Designer 2007 Data Views, you can:
Create custom views of vital business data, and even create Data Views that integrate information from multiple data sources into a single Data View.
Use conditional formatting to call attention to important information.
Use Extensible Stylesheet Language Transformation (XSLT) data forms to quickly and easily create, update, and display data.
Enhanced management capabilities.
Office SharePoint Designer 2007 can be used by site administrators and IT managers to control the levels of access to ensure a consistent user experience across the site.
Use Contributor mode
By determining the levels of control for team members according to their roles, you can control which Office SharePoint Designer 2007 commands the users can access and what kinds of modifications the users can make to your SharePoint site. With Contributor mode, you can:
Create user groups and assign them specific permissions.
Create user groups that have access only to specified editable regions and content types.
Limit who can create and edit master pages, change cascading style sheets, and edit or delete the home page.
Control which master pages and style sheets can be used to create pages, and in which folders the site contributors can save their files.
Manage your site more efficiently
You can access tools and reports for a wide variety of site maintenance tasks, including hyperlink checking, CSS usage, and more.
Track customized pages
You can easily track customized pages by using the Site Template Pages report. With the Site Template Pages report, you can see a list of pages that have been customized, including the file name and file type, as well as the folder in which the file is located.
Roll back changes
You can use the Revert to Template Page command and the Site Template Pages report to restore previous versions of the page. Making changes to the live site is no longer a problem. If unwanted changes have been saved, you can now restore previous versions of the same page with the click of a button.
Office Diagnostics
Microsoft Office Diagnostics is a series of diagnostic tests that can help you to discover why your computer is crashing. The diagnostic tests can solve some problems directly and may identify ways that you can solve other problems. Microsoft Office Diagnostics replaces the following Microsoft Office 2003 features: Detect and Repair and Microsoft Office Application Recovery.
Proofing Tools
The following are some new features of the spelling checker:
The spelling checker has been made more consistent across the 2007 Microsoft Office system programs. Examples of this change include:
Several spelling checker options are now global. If you change one of these options in one Office program, that option is also changed for all the other Office programs. For more information, see Change the way spelling and grammar checking work.
In addition to sharing the same custom dictionaries, all programs can manage them using the same dialog box. For more information, see Use custom dictionaries to add words to the spelling checker.
The 2007 Microsoft Office system spelling checker includes the post-reform French dictionary. In Microsoft Office 2003, this was an add-in that had to be separately installed. For more information, see Change the way spelling and grammar checking work.
An exclusion dictionary is automatically created for a language the first time that language is used. Exclusion dictionaries let you force the spelling checker flag words you want to avoid using. They are handy for avoiding words that are obscene or that don't match your style guide. For more information, see Use exclusion dictionaries to specify a preferred spelling for a word.
Available Application Templates
Microsoft has developed forty application templates for Windows SharePoint Services 3.0 that can be downloaded at no extra charge. Each application template addresses a business scenario and provides a base of functionality that can be either used directly out of the box, or customized for company specific needs.

Home page view of the Integrated Marketing Campaign Tracking application template.

Home page view of the Integrated Marketing Campaign Tracking application template

Customizing SharePoint Sites and Templates
Office SharePoint Designer 2007 is a Web site development and management program that provides powerful tools to build, customize and contribute to Windows SharePoint Services sites. Using the latest Web design technologies and established standards, technical users are able to create and deploy interactive solutions without having to write or deploy complex code.
Office SharePoint Designer 2007 helps automate business process workflow such as document approval, custom event notification and other collaboration tasks with the workflow designer. It allows report creation data tracking applications using views and forms to gather and aggregate information from within the site and from locations on the Web. Advanced users can extend the power of Windows SharePoint Services with interactive Microsoft ASP.NET pages using the same powerful activity menus and control property grids previously found in the Microsoft Visual Studio® development system.
Application Templates for Windows SharePoint Services 3.0 are separated into two groups, site admin templates and server admin templates, providing the right combination of integration with the platform and ease-of-deployment within an organization.
Site admin templates are custom templates (*.stp files) that are easy for any SharePoint site administrator to install into the template gallery without requiring server administration access.
Server admin templates are site definitions (*.wsp files), enabling tighter integration and enhanced functionality within the Windows SharePoint Services platform. They require a server administrator to install.
Usama Wahab Khan and Atif Shahzad

use QueryString in

Sunday, August 2, 2009

User query string in asp,.net
Download Source code

ADO . Net

ADO.NET provides consistent access to data sources such as Microsoft SQL Server, as well as data sources exposed through OLE DB and XML. Data-sharing consumer applications can use ADO.NET to connect to these data sources and retrieve, manipulate, and update data.
ADO.NET cleanly factors data access from data manipulation into discrete components that can be used separately or in tandem. ADO.NET includes .NET Framework data providers for connecting to a database, executing commands, and retrieving results. Those results are either processed directly, or placed in an ADO.NET DataSet object in order to be exposed to the user in an ad-hoc manner, combined with data from multiple sources, or remoted between tiers. The ADO.NET DataSet object can also be used independently of a .NET Framework data provider to manage data local to the application or sourced from XML.
The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes found in System.Xml.dll. When compiling code that uses the System.Data namespace, reference both System.Data.dll and System.Xml.dll.

// Add Namespace of sqlClient

using System.Data.SqlClient;

private static string strConnection ="user id=sa;password=openthegate;database=northwind;server=DevServer";

public OrderGrid()
Page.Init += new System.EventHandler(Page_Init);

// Connect to the Database

private SqlConnection GetConnection()
SqlConnection objConnection = new SqlConnection(strConnection);
return objConnection;
// this method will populate the DataGrid OrdGrid

private void PopulateGrid()
// Connect to the Database
SqlConnection objConnection=GetConnection();
DataSet objDataSet = new DataSet("OD-Prod");
SqlDataAdapter objDataAdapter = new SqlDataAdapter();
// copy the table Order Details in to the DataSet
string strCmd="SELECT OD.ProductID,OD.Quantity,P.ProductName FROM [Order Details] OD, ";
strCmd+=" Products P WHERE OD.ProductID=P.ProductID AND ";
strCmd+="OD.OrderID = "+ OrderID.Text;
SqlCommand selCommand = new SqlCommand(strCmd,objConnection);
objDataAdapter.SelectCommand=selCommand ;
OrdGrid.DataSource =objDataSet.Tables["JoinTable"];

private void InitializeComponent()
this.OrdGrid.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.CancelGrid);
this.OrdGrid.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.EditGrid);
this.OrdGrid.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.UpdateGrid);


protected void SerchClicK(object sender, System.EventArgs e)

System.Web.UI.WebControls.DataGridCommandEventArgs e)
OrdGrid.EditItemIndex= e.Item.ItemIndex;
// prevent the TextBox from changeing the OrderID


// Eventhandler for the event Cancel the Edit(DataGrid)
private void CancelGrid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
// able the TextBox to change the OrderID


private int DirectCommand(string strCmdText)
SqlConnection objConnection = GetConnection();
SqlCommand objCommand = new SqlCommand(strCmdText,objConnection);
int nAffected = objCommand.ExecuteNonQuery();

return nAffected;


// Eventhandler for the event Updating the DataGrid
private void UpdateGrid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
string strQuantity= ((TextBox)e.Item.Cells[3].Controls[0]).Text;
string strProductID = e.Item.Cells[1].Text;
string strUpdate ="UPDATE [Order Details] SET Quantity = "+strQuantity;
strUpdate+=" WHERE OrderID = "+ OrderID.Text;
strUpdate += " AND ProductID = "+strProductID;
// Update the table "Order Details"
int nCheck = DirectCommand(strUpdate);

// able the TextBox to change the OrderID
One more option to delete the row
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Data" %>
<%@ Language=C# Debug="True" %>
<script runat="server">
public void Page_Load()
OleDbConnection conStudent;
OleDbCommand cmdAuthDel;
string myConnString;
string strDelete;

myConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=c:\\inetpub\\wwwroot\\dataaccess\\Northwind.mdb;";
conStudent = new OleDbConnection( myConnString );

strDelete = "DELETE * FROM Student WHERE au_fname=’Usama’";
cmdAuthDel = new OleDbCommand( strDelete, conStudent );


<meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">

Records deleted!

Usama Wahab Khan and Atif Shahzad

Caching in ASP.NET Using by C#

What is Caching
Caching is a technique of persisting the data in memory for immediate access to requesting program calls. Many in the developer community consider caching as one of the features available to improve performance of Web applications.
Why Caching
Consider a page that has list of Employee name, contact numbers and mail-Ids of existing employees of a company on an intranet accessible by all employees. This is very useful information that is available throughout the company and could also be one of the most accessed pages. The functionality of adding, updating or deleting is usually less intensive compared to more transaction-based systems like Purchase ordering, Voucher creation etc. Now in a normal scenario the
process of querying database for each request is not cost-effective in terms of server resources, hence is lot better to cache or persist the data to avoid this costly loss of resources.
Web caching technology in ASP.NET and C# is helpful for popular website reducing its server workload and improving access times. This tutorial will show you how to use web caching save data to RAM, and improve data access times therefore.
First, import the namespace of System.Web.Caching

using System.Web.Caching

Declare the variables

static bool itemRemoved = false;
static CacheItemRemovedReason reason;
CacheItemRemovedCallback onRemove = null;

Define the method of AddItemToCache, it will use Cache.Add to add items to cache

public void AddItemToCache(Object sender, EventArgs e)
itemRemoved = false;
onRemove = new CacheItemRemovedCallback(this.RemovedCallback);
if (Cache["Key1"] == null)
Cache.Add("Key1", "Caching", null, DateTime.Now.AddSeconds(60), TimeSpan.Zero, CacheItemPriority.High, onRemove);
Define the method of RemoveItemFromCache, it will use Cache.Remove to remove items from cache
public void RemoveItemFromCache(Object sender, EventArgs e)
if (Cache["Key1"] != null)
When using the method of Cache.Remove , it will be leaded to invoke RemovedCallback method

public void RemovedCallback(String k, Object v, CacheItemRemovedReason r)
itemRemoved = true;
reason = r;
protected void Page_Load(object sender, EventArgs e)
if (itemRemoved)
Response.Write("RemovedCallback event raised.");
Response.Write("Reason: " + reason.ToString() + "");
Response.Write("Value of cache key: " + Server.HtmlEncode(Cache["Key1"] as string) + "");
The HTML of the web page

The .NET Advantage
ASP.NET provides the flexibility in terms of caching at different levels.
Page Level Output Caching
This is at the page level and one of the easiest means for caching pages. This requires one to specify Duration of cache and Attribute of caching.

The above syntax specifies that the page be cached for duration of 60 seconds and the value "none" for VaryByParam* attribute makes sure that there is a single cached page available for this duration specified.
VaryByParam can take various "key" parameter names in query string. Also there are other attributes like VaryByHeader, VaryByCustom etc. Please refer to MSDN for more on this.
Fragment Caching
Even though this definition refers to caching portion/s of page, it is actually caching a user control that can be used in a base web form page. In theory, if you have used include files in the traditional ASP model then this caching model is like caching these include files separately. In ASP.NET more often this is done through User Controls. Initially even though one feels a bit misleading, this is a significant technique that can be used especially when implementing "n" instances of the controls in various *.aspx pages. We can use the same syntax that we declared for the page level caching as shown above, but the power of fragment caching comes from the attribute "VaryByControl". Using this attribute one can cache a user control based on the properties exposed.

The above syntax when declared within an *.ascx file ensures that the control is cached for 60 seconds and the number of representations of cached control is dependant on the property "DepartmentId" declared in the control.

Add the following into an *.ascx file. Please note the use of tag "Control" and the cache declaration.

Add the following to an *.aspx file. Please note the way "Register" tag is used; the declaration of control using syntax <[TagPrefix]:[TagName]>; Usage of property " DepartMentId". Open the page in two browsers and closely watch the Base form timing and the User control timing. Also note that the following page results in two copies or representation of user control in the cache.

Application Level Caching
With Page level Output caching one cannot cache objects between pages within an application. Fragment caching is great in that sense but has limitations by using user controls as means to do. We can use the Cache object programmatically to take advantage of caching objects and share the same between pages. Further the availability of different overloaded methods gives a greater flexibility for our Cache policy like Timespan, Absolute expiration etc. But one of the biggest takes is the CacheDependancy. This means that one can create a cache and associate with it a dependency that is either another cache key or a file.

In almost all Web applications there could be numerous master tables that act as lookups to application specific tables. For e.g. if you take up adding a Employee, usually one has master tables like "tblQualification" to get list of qualifications, "tblLocations" to get list of locations etc. These tables* are usually set during the initial application configuration phase and could be modified once a month or even less than that. Hence it makes sense for us to use them in our Cache rather than making calls to database on each request. But then what Cache Policy do we adopt?

We cannot hold these objects in Cache for entire application instance, because if anybody changes data in these tables one has to also refresh the cache. It is here that CacheDependancy can be used.

Even though these tables are less frequently used for updates, they are extensively used in our select statements through out the applications.

Find below the snippet that uses CacheDependancy. Here what I have done is to provide a list view of existing employees. You need to create a Database in Sql Server, setup some data before you can continue.
Add database connection value in Web.Config and change the value as per your setup.

First I get the dataset into which I fill the user list. But before this I check for the cache initially if it exists I directly cast it to a dataset, if not create a cache again.


I create the cache with "Users" as key using Cache.Insert* and link this with a file "Master.xml". This "Master.xml" is a XML file that contains Master data of "tblQualifications" and "tbllocations". I have used "Server.MapPath" to get the physical path of the file on the server. The CacheDependancy instance will make sure that any change in this dependency file means that you need to recreate your cache key definition. This is a great feature to use since I can recreate my cache only when required instead of caching the data at the page level.

For other overloaded parameters refer MSDN.

Also note how we could use trace within to add my own statements.

We created the page that initiates and uses the Cache. For testing purpose we need another page that will overwrite this "Master.xml" on click of a button for which the code snippet is as follows. This ideally should be our master maintenance page that adds/updates Master records in database and overwrites the XML. But to make it easy I have just written an overwriting sample.

Source Code
The following C# code snippet is a technique to get the best of both worlds. I personally use this all the time in my development.
public ArrayList GetUsers(bool AllowCache)
// this directive will force the variable AllowCache to
// false while in 'debug mode' in Visual Studios .NET
AllowCache = false;
string strCacheKey = "Users-GetUsers";
// cached?
if( AllowCache && ( null != HttpContext.Current.Cache[strCacheKey]) )
return (ArrayList)HttpContext.Current.Cache[strCacheKey];
// code to fetch users from database
ArrayList alUsers = null;
alUsers = Users.GetUsers();
// cache it if 'allowed'
if ((AllowCache) && (HttpContext.Current.Cache[strCacheKey] == null))
HttpContext.Current.Cache.Insert(strCacheKey, alUsers, null, DateTime.Now.AddMinutes(5), TimeSpan.Zero);
return alUsers;
So as you can see, the method has a parameter of type bool (true/false) that gets passed in while you’re calling the method. If you want to get live data, you pass in FALSE, for cached data you pass in TRUE. As an added bonus, you can add the #if DEBUG directive to your code to allow for non-cached data to be viewed while your coding your application in debug mode. If you switch to ‘release’ in VS.NET you will get cached data (assuming you passed in TRUE).

Now once you have created the above pages i.e. one that implements caching and other that overwrites the dependency file, create two instance of browser and open the cache implementation page and note for trace, label text; open the other instance of browser with the page which overwrites the XML. Note the former, the first time it fetches data from the database and the subsequent request will be from cache till your expiration time of 45 seconds is reached or anyone overwrites or changes the "Master.xml" file. Also give a look on Timespan parameter since you have a concept of Sliding expiration that can also be implemented. Keep refreshing the first page and you will see that trace indicates the cached page retrieval. Click the overwrite XML button on the latter page that would overwrite the XML and again refresh the former page to note that the data is retrieved from database. Though in this example I have not shown any direct relation between the cached data and the dependency file (like get values from dependency file and merge with cached object etc) in terms of integrated usage, this could very easily be designed and implemented. Dependency caching is a powerful technique that .NET supports and should be utilized wherever applicable.
Usama Wahab Khan and Atif Shahzad