Search content within the blog

Wednesday, April 29, 2009

Difference between application and Session object

Place the following code in your project and run the application under two different browsers but with the same instance of the IIS.The application object is common for entire application irrespective of the user but the session object is for a particular user only.

click both the buttons on different browers and the difference will be clear.

The code is self explanatory....

ASPX Page Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Stateobjects.aspx.cs" Inherits="Statemanagement_Stateobjects" Title="State Objects" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="frmStateObjects" runat="server">
<div>
Differenc between application, session
<br />
<br />
click the session button once and application button once by placing the paga on
different browsers<br />
<br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Application" />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Session" /></div>
</form>
</body>
</html>


ASPX.cs Code

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Statemanagement_Stateobjects : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button2_Click(object sender, EventArgs e)
{
int cnt=0;
try
{
cnt = Convert.ToInt32(Session["HitCounter"].ToString());
}
catch
{
//Session["HitCounter"] = "0";
}
finally
{
Session["HitCounter"] = cnt + 1;
}
Response.Write("Session counter: " + Session["HitCounter"].ToString()+"<br>");
if (Application["HitCounter"]!=null)
Response.Write("Application counter: " + Application["HitCounter"].ToString());
}
protected void Button1_Click(object sender, EventArgs e)
{
int cnt=0;
try
{
cnt = Convert.ToInt32(Application["HitCounter"].ToString());
}
catch
{
//Application["HitCounter"] = "0";
}
finally
{
Application["HitCounter"] = cnt + 1;
}
Response.Write("Application counter: " + Application["HitCounter"].ToString());
if (Session["HitCounter"] != null)
Response.Write("Session counter: " + Session["HitCounter"].ToString());
}
}

Difference between int.parse and convert.ToInt in asp.net

Int.Parse cannot convert null values to some default value like zero as Convert.ToInt does. so it is always safe to use Convert.ToInt instead of Int.Parse.

The code is self explanatory....

protected void Page_Load(object sender, EventArgs e)
{
string s = null;
Response.Write("Output: "+Convert.ToInt32(s).ToString()+"<br>");
try
{
Response.Write(Int32.Parse(s).ToString());
}
catch
{
Response.Write("Output : Int32.Parse is in try catch block as it cannot convert null to zero as Convert.ToInt32 does.");
}
}

Session in ASP.NET -- Part II

Q: Session state works on some browsers, but not on others. Why?
A: Assume you aren't using cookieless, you should make sure your browsers support cookie. Also see this KB: See http://support.microsoft.com/default.aspx?scid=kb;EN-US;q316112

Q: In Proc mode, why do I lose all my session occasionally?
A: Please see the "Robustness" section in the "Understanding session state modes" section of of this article.

Q: Session states works on some web servers but not on others.
A: Maybe machine name problem.
See http://support.microsoft.com/default.aspx?scid=kb;EN-US;q316112

Q: Why isn't session state available?

A:
- First, check your web.config, machine.config and your page directive to make sure you have enabled session state.
Reference:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconsessionstate.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconpage.asp

- Also, please note that session state isn't available just everywhere, anytime. It is available only after the HttpApplication.AcquireRequestState event is called. For example, it is NOT available in the Application_OnAuthenticateRequest handler inside global.asax.
For details, see: http://msdn.microsoft.com/library/default.asp?url=/library/enus/cpguide/html/cpconhandlingpublicevents.asp

- Lastly, make sure System.Web.SessionState.SessionStateModule is included the in your config files. A common case is that SharePoint application will remove this module from their web.config files (for performance reason), and thus session state isn't available.

Q: Why isn't Session_End fired?
A: This is one of the most frequently asked question.
1. Remember Session_End event is supported only in InProc mode.
2. Session_End won't be fired if you close your browser. HTTP is a stateless protocol, and the server has no way to know if your browser has closed or not.
3. Session_End will be fired only (i) after n minutes of inactivity (n = timeout value), or (ii) if someone calls Session.Abandon().
4. For case (i) (pt. 3), Session_End will be run by a background thread, which implies:

a. Your code in Session_End is running using the worker process account. You may have permission problem if you're accessing resource such as database.
b. If an error happens in Session_End, it will fail silently.
5. For case (ii), please note that in order for Session_End to be fired, your session state has to exist first. That means you have to store some data in the session state and has completed at least one request.
6. Again for case (ii), Session_End will be called only if the abandoned session is actually found. As a result, if you create and abandon a session inside the same request, because the session hasn't been saved and thus can't be found, Session_End won't be called. This is a bug in v1 and upcoming v1.1.

Q: Why are my Session variables lost frequently when using InProc mode?
A: Probably because of application recycle.
See http://support.microsoft.com/default.aspx?scid=kb;en-us;Q316148
In v1, there is also a bug that will cause worker process to restart. It's fixed in SP2 and v1.1. See http://support.microsoft.com/default.aspx?scid=kb;EN-US;321792

For more details about app recycling, see my other FAQ:
http://www.asp.net/Forums/ShowPost.aspx?tabindex=1&PostID=232621

Q: Why does the SessionID remain the same after the Session times out or abandoned?
A:Even though the session state expires after the indicated timeout period, the session ID lasts as long as the browser session. What this implies is that the same session ID can represent multiple sessions over time where the instance of the browser remain the same.

Q: Why does the SessionID changes in every request?
A: This may happen if your application has never stored anything in the session state. In this case, a new session state (with a new ID) is created in every request, but is never saved because it contains nothing.

However, there are two exceptions to this same session ID behavior:
- If the user has used the same browser instance to request another page that uses the session state, you will get the same session ID every time. For details, see "Why does the SessionID remain the same after the Session times out?"
- If the Session_OnStart event is used, ASP.NET will save the session state even when it is empty.

Q: What is the difference between Session.Abandon() and Session.Clear()?
A:The major practical difference is that if you call Session.Abandon(), Session_End will be fired (for InProc mode), and in the next request, Session_Start will be fired. Session.Clear( ) just clears the session data without killing it.

Q: Is the session Timeout attribute a sliding timeout value?
A: The session Timeout is a sliding expiration time, meaning whever your page access session state, the expiration time will be moved forward. Please note that as long as a page has NOT disabled session state, it will access the session automatically when requested.

Q: Can I share session state between ASP.NET and ASP pages?
A: No. But there is an MSDN article on how to work around it: http://www.msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/ConvertToASPNET.asp

There are also some 3rd party solutions:
(Disclaimer: the 3rd party solutions listed below is only for the convenience of customers, and does NOT imply any endorsement from Microsoft) http://www.consonica.com/solutions/dotnet/statestitch/index.html http://www.sessionbridge.com

Q: Can I share session state between web applications (i.e. "virtual directories" or "applications" in IIS)?
A: No. Sorry.

Q: What kinds of object can I store in session state?
A: It depends on which mode you are using:
- If you are using InProc mode, objects stored in session state are actually live objects, and so you can store whatever object you have created.
- If you are using State Server or SQL Server mode, objects in the session state will be serialized and deserialized when a request is processed. So make sure your objects are serializable and their classes must be marked as so. If not, the session state will not be

saved successfully. In v1, there is a bug which makes the problem happen unnoticed in SQLServer mode and will make your request hang. The hanging problem is fixed in v1.1. The QFE fix for KB 324479 also contains the fix for this problem. The problem will be fixed in v1 SP3 too.

See this KB for more info:
http://support.microsoft.com/directory/article.asp?ID=KB;EN-US;q312112

Q: Why did my request hang after I switch to SQLServer mode?
A: Please read the answer for the question: "What kinds of object can I store in session state?"

Q: How come Response.Redirect and Server.Transfer is not working in Session_End?
A: Session_End is fired internally by the server, based on an internal timer. And thus there is no HttpRequest associted when that happens. That is why Response.Redirect or Server.Transferdoes not make sense and will not work.

Q: In Session_End, do I have a valid HttpSessionState object and HttpContext object?
A: You will have the HttpSessionState object available. Just use 'Session' to access it. For HttpContext, it is not available because this event is not associated with any request.

Q: Will my session state be saved when my page hit an error?
A: If you're using StateServer or SQLServer mode, for data integrity reason session state module will not save any changes to session state if there is an error. To work around this, you can call Server.ClearError in your exception handler.
For InProc mode, changes are made directly to the in-memory objects and so whatever changes you've made so far will stay in the memory. However, if it's a new session, ASP.NET will not insert your session state into the internal table, and thus your session state will NOT be saved, unless you call Server.ClearError in your exception handler.

Q: How do I use session state with web services?
A: The extra trick needed is on the caller side. You have to save and store the cookies used by the web service. See the MSDN documentation on HttpWebClientProtocol.CookieContainer property.

However, please note if you're using proxy object to call a web service from your page, the web service and your page cannot share the same session state due to architecture limitation.

This can be done if you call your web service through redirect.

Q: I am writing my own HttpHandler. Why is session state not working?
A: Your HttpHandler has to implement the "marker" interface IRequiresSessionState or IReadOnlySessionState in order to use session state.

Q: I am using a webfarm, and I lost session state when directed to some web servers. A: For session state to be maintained across different web servers in the web farm, the Application Path of the website (For example \LM\W3SVC\2) in the IIS Metabase should be identical (case sensitive) in all the web servers in the web farm. See KB 325056 for details.

Q: If using "cookieless", how can I redirect from a HTTP page to an HTTPS page? A: Try this:


String originalUrl = "/fxtest3/sub/foo2.aspx";
String modifiedUrl = "https://localhost" + Response.ApplyAppPathModifier(originalUrl);
Response.Redirect(modifiedUrl);

Q: Does session state have a locking mechanism that serialize the access to state?
A: Session state implements a reader/writer locking mechanism:
- A page (or frame) that has session state write access (e.g. <%@ Page EnableSessionState="True" %>) will hold a writer lock on the session until the request finishes.
- A page (or frame) that has session state read access (e.g. <%@ Page EnableSessionState="ReadOnly" %>) will hold a reader lock on the session until the request finishes.
- Reader lock will block a writer lock; Reader lock will NOT block reader lock; Writer lock will block all reader and writer lock.
- That's why if two frames both have session state write access, one frame has to wait for the other to finish first.

Q: How do I detect a session has expired and redirect it to anther page?
A: It's a much requested feature, and unfortunately there is no easy way to do it right now. We will look into in the next major version. In the meantime, if you are using cookie, you can store a marker in your cookie so you can tell the difference between "fresh browser + new session" and "old browser + expired session". Below is a sample code that will redirect the page to an expired page if the session has expired.


void Session_OnStart(Object sender, EventArgs e) {
HttpContext context = HttpContext.Current;
HttpCookieCollection cookies = context.Request.Cookies;

if (cookies["starttime"] == null) {
HttpCookie cookie = new HttpCookie("starttime", DateTime.Now.ToString());
cookie.Path = "/";
context.Response.Cookies.Add(cookie);
}
else {
context.Response.Redirect("expired.aspx");
}
}


Q: In Session_End, I tried to do some cleanup job using SQL but it failed. Why?
A: First, Session_End is supported only in InProc mode.
Second, Session_End is run using the account which runs the worker process (aspnet_wp.exe), which can be specified in machine.config. Therefore, in your Session_End, if you connect to SQL using integrated security, it will use that worker process account credential to connect, and may fail depending on your SQL security settings.

Q: I am using SQLServer mode. Why aren't my sessions expiring?
A: In SQLServer mode, session expiration is carried out by the SQL Agent using a registered job. Make sure your SQL Agent is running.

Q: I have a frameset page which has an HTM extension, and I found out each frame it contains display a different session id on the first request. Why?
A:The reason is that your frameset page is an HTM file instead of an ASPX file.

In normal case, if the frameset is an aspx file, when you request the page, it will first send the request to the web server, receive an asp.net session cookie (which holds the session id), and then the browser will send individual requests for the frames, and each request will carry the same session id.

However, since your frameset page is an htm file, the first request comes back without any session cookie because the page was serviced by ASP and not ASP.NET. Then again your browser sends out individual requests for each frame. But this time each individual request will NOT carry any session id, and so each individual frame will create its own new session. That's why you will see different session ids in each frame. The last request that comes back will win by overwriting the cookie written by the previous two requests. If you do a refresh, you will see them having the same session id.

This behaviour is by-design, and the simple solution is to change your frameset page to .aspx.

Q: I set EnableSessionState to "ReadOnly", but in InProc mode I can still modify the session. Why is that?
A: Even those enableSessionState is marked as ReadOnly, but in InProc state, the user can still modify the session. The only difference is that the session will not be locked during the request. This limitation is by-design. And I sorry that it’s not documented in MSDN.

Q: I set "cookieless" to true, and now my session variables are lost after a Redirect. Why?
A: If you're using cookieless, you must use relative path (e.g. ..\hello.aspx) instead of absolute path (e.g. \foo\bar\hello.aspx). If you use absolute path, ASP.NET cannot preserve your session ID in the URL.

Q: What are the disadvantages of setting cookieless to true?
A: Setting Cookieless=true implies some restrictions, mainly:
1. You cannot use absolute link in your pages.
2. You have to do extra thing to switch between http and https pages in your application.
3. If your customer send a link to a friend, the URL will contain the session ID and both
users could be using the same session ID at the same time.

Q: In InProc mode, I change the timeout value of a session programmatically, and
that causes my Session_End to be called. Why?
A:It is a a bug of InProc mode. If you change a session's timeout to a different value,
Session_End will be called (but not Session_Start). We will looking into that in v2 and
see if we can fix it.

Q: In SqlServer mode, can I store my session state in a database other than tempdb?
A:Yes. See KB311209.

Q: How can I avoid putting plain password for my sql connection?
A: See sql trusted connection, or put the connection string as encrypted data in the
registry. For details, KB 329250 and 329290.

Q: What SQL permissions do I need when using SqlServer mode?
A:The caller needs EXEC permission on the following stored procedures in ASPState:

dbo.TempGetAppID
dbo.TempGetStateItem
dbo.TempGetStateItemExclusive
dbo.TempReleaseStateItemExclusive
dbo.TempInsertStateItemLong
dbo.TempInsertStateItemShort
dbo.TempUpdateStateItemLong
dbo.TempUpdateStateItemShort
dbo.TempUpdateStateItemShortNullLong
dbo.TempUpdateStateItemLongNullShort
dbo.TempRemoveStateItem
dbo.TempResetTimeout

For version 1.1, you also need EXEC permission on the following stored procs in
ASPState:

dbo.TempGetStateItem2
dbo.TempGetStateItemExclusive2

Please note that the owner of the sprocs must have SELECT/INSERT/UPDATE/DELETE permissions on the session state tables (dbo.ASPStateTempSessions and dbo.ASPStateTempApplications). The owner is the account which ran the installsqlstate.sql (or the persistent version (see KB311209)) to install the tables/sprocs/databases needed for sql session state.
Also note that if your session state table lives in tempdb (by default), any permission settings on that table will be lost if you recycle SQL server.

Q: Can I write my own custom session state module?
A: In v1 and v1.1, there are very limited support for writing your own custom session state module. I can suggest two approaches:
Approach #1 - replace SessionStateModule
In this approach, you write your own custom module and replace the original one in . This way, you simply roll out your own implementation.
Drawbacks:
i. Since the constructor of HttpSessionState isn't public, you can't create your own
instance of it and stick it to HttpContext like the way ASP.NET SessionStateModule does. Instead, you have to expose your session through some custom class, and the user can't access it through Page.Session nor HttpContext.Session.
ii. You have to implement all the code to handle session and session id creation/maintenance/expiry, etc. That can be quite tedious.


Approach #2 - complement SessionStateModule
In this approach, you still rely on original ASP.NET SessionStateModule for session and
session id creation/maintenance/expiry, etc. But at the same time, you write your own
custom module, and have it subscribed to at least the following HttpApplication events:
(a) PreRequestHandlerExecute - When this event happens, AcquireRequestState has been
fired already, and thus HttpContext.Session is available. In your even handler, you read
your data from your own store and copy them to HttpContext.Session.
(b) PostRequestHandlerExecute - This event is fired before ReleaseRequestState. Your
event handler will save all the data in HttpContext.Session to your own store, and call
HttpContext.Session.Clear() to remove all items so they won't be saved by ASP.NET
session state.
(c) EndRequest - If an error occurs during the execution of the page,
PostRequestHandlerExecute might be skipped and EndRequest will be fired directly.
Your module might need to do some maintenance work here.
Please note that you shouldn't subscribe to AcquireRequestState and ReleaseRequestState like ASP.NET session state module does because if 2 modules subscribe to an event, there is no guarantee which module will get called first.
Drawbacks:
i. Your custom session data won't be available before PreRequestHandlerExecute and after PostRequestHandlerExecute.
ii. You need to figure out how to cleanup during session expiry or abandonment (in InProc, may piggyback Session_End; hard to resolve in StateServer or SQLServer mode), etc.

In the next major release ASP.NET will increase the support for customizing session state module. Stay tuned.

Q: How does (de)serialization work in SqlServer and State Server mode?
A: SqlServer and State Server modes use serialization to store objects in a remote store. Understanding how it works will help you write your application correctly.

Assume your page foo.aspx has this piece of code:

line 1 MyClass class = (MyClass)Session["abc"];
line 2 if (class == null) {
line 3 class = new MyClass();
line 4 Session["abc"] = class;
line 5 }
line 6
line 7 class.LastAccess = DateTime.Now; // This change will reflect in Session["abc"]
line 8
line 9 int total;
line 10 if (Session["def"] == null) {
line 11 total = 0;
line 12 }
line 13
line 14 total = total + 1;
line 15 Session["def"] = total;
line 16 total = total + 100; // This change will NOT reflect in Session["def"]

First, let me explain one area which confuses many people.

Assume the page hits line 1 and it gets null. Then the page will create the object (line 3), and put it in session (line 4). Please note that what Session has is just a reference to your object (and actually the local var 'class' is also just a reference to your object). So when you modify the object in line 7, you are actually modifying the same object pointed to by Session["abc"]. Bottom line is that 'Session["abc"]' and 'class' are just two references that point to the same object.

However, the situation in line 9-15 is different. Line 16 has no effect on Session["def"]. It's because 'total' is a value type, and so 'Session["def"]' and 'total' are two integers which are independent of each other.

Please note that the above difference has nothing to do with session state, but with the fundamental difference between a value type (e.g. int), and an object type (e.g. MyClass). You will have the same behavior if you replace 'Session' by, for example, a hashtable object.

Now, back to the actual question. When do deserialization and serialization happen?

Assume you hit the above page with a brand new empty session. After the HttpHandler is done executing your page, ASP.NET will later fire the HttpApplication.ReleaseRequestState event. At that point, the session state module will go thru all the items in session state, serialize them all into a single binary blob, and save it to a remote store.

Now, when you hit the page again, before HttpHandler execute your page, ASP.NET will fire the HttpApplication.AcquireRequestState event. At that point, the session state module will read the saved binary blob from the remote store, deserialize it into individual items, and stick them into Session. But once again, what it puts into Session["abc"] is just a reference to an object (of type MyClass) which was created during the deserialization.

Q: How can I secure my state server?
A: If the state server is running on the same machine as web server, run state server in local only mode by setting the DWORD registry value HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Param ters\AllowRemoteConnection to 0. This will prevent remote clients from connecting to the State Server. This feature is available in v1.1, and in the to-be-shipped v1 SP3.

The state server must be protected by a firewall from external connections to truly guarantee security. The default port is TCP 42424, although it can be changed by setting HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Param ters\Port. Block all external connections on this port except 127.0.0.1 if in local mode, or explicitly disallow all addresses other then the connecting web server if in remote mode.

Using IPSec is another way of protecting your state server.

Q: Can I subscribe to SessionStateModule.End event using a non-global.asax handler method?
A: The answer is NO. When SessionStateModule raises the End event, only the method
defined in global.asax will be called.

It's limited this way for a technical safety reason. Suppose asp.net allows a user to use any arbitrary handler to the handle the End event. In the case, users will usually use a page method as a handler. When you pass in that handler during event subscription, that handler (unless it's static) is associated with the HttpApplication instance your request is running on. Please note that HttpApplication instances are recycled to serve other requests. So later on, when the End event gets fired, asp.net will call the handler, and the HttpApplication instance it is associated with is now being used by another request. Such a situation will cause all sorts of problem. So to avoid this danger, in v1 a decision was made to call only the method defined in global.asax. Hope you all can bear with this limitation.

Q: Can different apps store their session state in different databases on the same SQL server?
A: The answer is yes. See this KB for more details. http://support.microsoft.com/default.aspx?scid=kb;EN-US;836680

Session in ASP.NET--Part I

Understanding Session State Modes

Storage location
InProc - session kept as live objects in web server (aspnet_wp.exe)

StateServer - session serialized and stored in memory in a separate process aspnet_state.exe). State Server can run on another machine

SQLServer - session serialized and stored in SQL server

Performance
InProc - Fastest, but the more session data, the more memory is consumed on the web server, and that can affect performance.

StateServer - When storing data of basic types (e.g. string, integer, etc), in one test environment it's 15% slower than InProc. However, the cost of serialization/deserialization can affect performance if you're storing lots of objects. You have to do performance testing for your own scenario.

SQLServer - When storing data of basic types (e.g. string, integer, etc), in one test environment it's 25% slower than InProc. Same warning about serialization as in StateServer.

Performance tips for Out-of-Proc (OOP) modes
If you're using OOP modes (State Server or SQL Server), one of your major cost is the serialization/deserialization of objects in your session state. ASP.NET performs the serialization/deserialization of certain "basic" types using an optimized internal method. ("Basic" types include numeric types of all sizes (e.g. Int, Byte, Decimal, String, DateTime, TimeSpan, Guid, IntPtr and UIntPtr, etc)

If you have a session variable (e.g. an ArrayList object) that is not one of the "basic" types, ASP.NET will serialize/deserialize it using the BinaryFormatter, which is relatively slower.

So for performance sake it is better to store all session state data using one of the "basic" types listed above. For example, if you want to store two things, Name and Address, in session state, you can either (a) store them using two String session variables, or (b) create a class with two String members, and store that class object in a session variable. Performance wise, you should go with option (a).

To further understand this topic, please see the question in this FAQ: "How does (de)serialization work in SqlServer and State Server mode?"

Robustness
InProc - Session state will be lost if the worker process (aspnet_wp.exe) recycles, or if the appdomain restarts. It's because session state is stored in the memory space of an appdomain. The restart can be caused by the modification of certain config files such as web.config and machine.config, or any change in the \bin directory (such as new DLL after you've recompiled the application using VS) For details, see KB324772. In v1, there is also a bug that will cause worker process to restart. It's fixed in SP2 and in v1.1. See KB321792.

If you're using IIS 6.0, you may want to go to IIS Manager, go to Application Pools/DefaultAppPool, and see if any of the parameters on the Recycling and Performance tabs are causing the IIS worker process (w3svc.exe) to shutdown.

For more details about app recycling, see my other FAQ: http://www.asp.net/Forums/ShowPost.aspx?tabindex=1&PostID=232621

StateServer - Solve the session state loss problem in InProc mode. Allows a webfarm to store session on a central server. Single point of failure at the State Server.

SQLServer - Similar to StateServer. Moreover, session state data can survive a SQL server restart, and you can also take advantage of SQL server failover cluster, after you've followed instructions in KB 311209.

Friday, April 24, 2009

Using XML, XSLT in Asp.net

XSLT is the W3C specification for formatting XML documents and displaying the contents in the required format.

XML File --books.xml

<?xml version="1.0" encoding="utf-8" ?>
<books>
<book>
<bookid> B001 </bookid>
<title> Understanding XML </title>
<Price> $30 </Price>
<Author>
<FirstName> Lily </FirstName>
<LastName> Hicks </LastName>
</Author>
</book>
<book>
<bookid> B002 </bookid>
<title> .NET Framework </title>
<Price> $45 </Price>
<Author>
<FirstName> Jasmine </FirstName>
<LastName> Williams </LastName>
</Author>
</book>
<book>
<bookid>B003</bookid>
<title>ASP.NET</title>
<Price>$35</Price>
</book>
</books>

XSLT file--- style_sheet.xslt

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="Author">
<xsl:value-of select="FirstName"/>
<xsl:text>,</xsl:text>
<xsl:value-of select="LastName"/>
<xsl:if test="position()!=last()">,</xsl:if>
</xsl:template>
<xsl:template match="/">
<HTML>
<HEAD>
<TITLE>BOOKS AT WEBSHOPPE</TITLE>
</HEAD>
<BODY>
<H1>BOOKS AT WEBSHOPPE</H1>
<TABLE BORDER="3" CELLSPACING="2" CELLPADDING="6">
<THEAD ALIGN="CENTER" BGCOLOR="LightBlue">
<TH> BOOK ID </TH>
<TH> TITLE </TH>
<TH> PRICE </TH>
<TH> AUTHOR(S) </TH>
</THEAD>
<TBODY>
<xsl:for-each select="books/book">
<TR>
<TD>
<font color="green">
<xsl:value-of select="bookid"/>
</font>
</TD>
<TD>
<i>
<xsl:value-of select="title"/>
</i>
</TD>
<TD>
<u>
<xsl:value-of select="Price"/>
</u>
</TD>
<TD>
<b>
<xsl:apply-templates select="Author"/>
</b>
</TD>
</TR>
</xsl:for-each>
</TBODY>
</TABLE>
</BODY>
</HTML>
</xsl:template>
</xsl:stylesheet>


ASPX Page Contents

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="WithXML.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:Xml id="Xml1" runat="server" DocumentSource="books.xml" TransformSource="style_sheet.xslt"></asp:Xml>
</form>
</body>
</HTML>

Output :

Threads and Thread Synchronization in C#

Introduction

Although C# contains many innovative features, one of the most exciting is its built in support for multithreaded programming.

A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking.

Multithreaded applications provide the illusion that numerous activities are happening at more or less the same time. But the reality is the CPU uses something known as “Time Slice” to switch between different threads.

The principal advantage of multithreading is that it enables you to write very efficient programs because it lets you utilize the idle time that is present in most programs. But using too many threads in our programs can actually “degrade” performance, as the CPU must switch between the active threads in the process which takes time. When a thread’s time slice is up, the existing thread is suspended to allow other thread to perform its business. For a thread to remember what was happening before it was kicked out of the way, it writes information to its local storage and it is also provided with a separate call stack, which again put extra load on the CPU.

- from Herbert Schildt's book "C# 2.0 The complete Reference". chepter 22
Multithreading Fundamentals

There are two distinct types of multitasking: process-based and thread-based.

The differences between process-based and thread-based multitasking can be summarized like this:

Process-based multitasking handles the concurrent execution of programs, while Thread-based multitasking deals with the concurrent execution of pieces of the same program.

Process-based: Example — running word processor at the same time you are browsing the net.
Thread-based: Example — A text editor can be formatting text at the same time that it is printing.

Simply we can define a thread as a line of execution within a process and it can exist in any of these several states.

It can be running. It can be ready to run as soon as it gets CPU time. A running thread can be suspended, which is a temporary halt to its execution. It can later be resumed, A thread can be blocked when waiting for a resource. A thread can be terminated, in which case its execution ends and cannot be resumed.

The .NET Framework defines two types of threads: foreground and background.

By default when you create a thread, it is a foreground thread, but you can change it to a background thread. The only difference between a foreground and background thread is that a background thread will be automatically terminated when all foreground threads in its process have stopped.

The “Foreground” threads have the ability to prevent the current application from terminating. The CLR will not shutdown an application until all foreground threads have ended. The “Background” threads are viewed by the CLR as expandable paths of execution that can be ignored at any point of time even if they are laboring over some unit of work. Thus, if all foreground threads have terminated, any background threads operating are automatically killed when the application terminates.

All processes have at least one thread of execution, which is usually called the main thread because it is the one that is executed when your program begins. From the main thread you can create other threads.

The classes that support multithreaded programming are defined in the System.Threading namespace.

Thus, you will usually include this statement at the start of any multithreaded program:
Collapse

using System.Threading;

Creating a Thread

To create a thread, you instantiate an object of type Thread. Thread defines the following constructor:
Collapse

public Thread( ThreadStart entrypoint)

Here, entrypoint is the name of the method that will be called to begin execution of the thread. ThreadStart is a delegate defined by the .NET Framework as shown here:
Collapse

public delegate void ThreadStart()

Thus, your entrypoint method must have a void return type and take no arguments.

Once created, the new thread will not start running until you call its Start() method, which is defined by Thread. The Start() method is shown here:
Collapse

public void Start()

Once started, the thread will run until the method specified by entryPoint returns. Thus, when entryPoint returns, the thread automatically stops. If you try to call Start() on a thread that has already been started, a ThreadStateException will be thrown.
Example
Collapse

using System;
using System.Threading;
namespace CSharpThreadExample
{
class Program
{
public static void run()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("In thread " + Thread.CurrentThread.Name + i);
Thread.Sleep(1000);
}
}
static void Main(string[] args)
{
Console.WriteLine("Main Thread Starting");
Thread.CurrentThread.Name = "Main ";

Thread t1 = new Thread(new ThreadStart(run));
t1.Name = "Child";
t1.Start();

for (int i = 0; i < 5; i++)
{
Console.WriteLine("In thread " + Thread.CurrentThread.Name + i);
Thread.Sleep(1000);
}
Console.WriteLine("Main Thread Terminates");
Console.Read();
}
}
}

Notice the call to Sleep(), which is a static method defined by Thread.
The Sleep() method causes the thread from which it is called to suspend execution for the specified period of milliseconds. The form used by the program is shown here:
Collapse

public static void Sleep(int milliseconds)

The number of milliseconds to suspend is specified in milliseconds. If milliseconds is zero, the calling thread is suspended only to allow a waiting thread to execute.

Here’s the output:



Each thread maintains a private set of structures that the O/S uses to save information(the thread context) when the thread is not running including the value of CPU registers. It also maintains the priority levels. We can assign higher priority to a thread of more important task than to a thread which works in background. In all cases time slice allocated to each thread is relatively short, so that the end user has the perception that all the threads (and all the applications) are running concurrently.

O/S has thread scheduler which schedules existing threads and preempts the running thread when its time slice expires. We make the most use of multithreading when we allocate distinct threads to tasks that have different priorities or that take a lot of time to complete.

The main problem with threads is that they compete for shared resource, a resource can be a variable, a database connection, a H/W device. We must synchronize the access to such resources — otherwise we will result in deadlock situations. A thread terminates when the task provided to it terminates or when the thread is programmatically killed by calling Abort(). An application as a whole terminates only when all its threads terminate.
Methods

* Suspend() -> Suspends the execution of a thread till Resume() is called on that.
* Resume() -> Resumes a suspended thread. Can throw exceptions for bad state of the thread.
* Sleep() -> A thread can suspend itself by calling Sleep(). Takes parameter in form of milliseconds. We can use a special timeout 0 to terminate the current time slice and give other thread a chance to use CPU time
* Join()-> Called on a thread makes other threads wait for it till it finishes its task.

States of a Thread

States of a thread can be checked using ThreadState enumerated property of the Thread object which contains a different value for different states.

* Aborted -> Aborted already.
* AbortRequested -> Responding to an Abort() request.
* Background -> Running in background. Same as IsBackground property.
* Running -> Running after another thread has called the start()
* Stopped -> After finishing run() or Abort() stopped it.
* Suspended -> Suspended after Suspend() is called.
* Unstarted -> Created but start() has not been called.
* WaitSleepJoin -> Sleep()/Wait() on itself and join() on another thread. If a thread Thread1 calls sleep() on itself and calls join() on the thread Thread2 then it enters WaitSleepJoin state. The thread exists in this state till the timeout expires or another thread invokes Interrupt() on it.

It is wise to check the state of a thread before calling methods on it to avoid ThreadStateException.




This picture describes in detail about the states of the thread [ Collected from “Thinking in C#” by Bruce Eckel ]
Properties of a Thread

* Thread.CurrentThread -> Static method gives the reference of the thread object which is executing the current code.
* Name -> Read/Write Property used to get and set the name of a thread
* ThreadState -> Property used to check the state of a thread.
* Priority -> Property used to check for the priority level of a thread.
* IsAlive -> Returns a Boolean value stating whether the thread is alive or not.
* IsBackground -> Returns a Boolean value stating the running in background or foreground.

PriorityLevels of Thread

Priority levels of thread is set or checked by using an enumeration i.e. ThreadPriority. The valid values are for this enumeration are;

* Highest
* AboveNormal
* Normal
* BelowNormal
* Lowest

Synchronization in Threads

When we have multiple threads that share data, we need to provide synchronized access to the data. We have to deal with synchronization issues related to concurrent access to variables and objects accessible by multiple threads at the same time. This is controlled by giving one thread a chance to acquire a lock on the shared resource at a time. We can think it like a box where the object is available and only one thread can enter into and the other thread is waiting outside the box until the previous one comes out.
Collapse

using System;
using System.Threading;
namespace CSharpThreadExample

{
class Program
{
static void Main(string[] arg)
{
Console.WriteLine("*****Multiple Threads*****");
Printer p=new Printer();
Thread[] Threads=new Thread[3];
for(int i=0;i<3;i++)
{
Threads[i]=new Thread(new ThreadStart(p.PrintNumbers));
Threads[i].Name="Child "+i;
}
foreach(Thread t in Threads)
t.Start();

Console.ReadLine();
}
}
class Printer
{
public void PrintNumbers()
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(100);
Console.Write(i + ",");
}
Console.WriteLine();
}
}
}

In the above example, we have created three threads in the main method and all the threads are trying to use the PrintNumbers() method of the same Printer object to print to the console. Here we get this type of output:




Now we can see, as the thread scheduler is swapping threads in the background each thread is telling the Printer to print the numerical data. We are getting inconsistent output as the access of these threads to the Printer object is synchronized. There are various synchronization options which we can use in our programs to enable synchronization of the shared resource among multiple threads.
Using the Lock Keyword

In C# we use lock(object) to synchronize the shared object.

Syntax:
Collapse

lock (objecttobelocked) {

objecttobelocked.somemethod();
}

Here objecttobelocked is the object reference which is used by more than one thread to call the method on that object. The lock keyword requires us to specify a token (an object reference) that must be acquired by a thread to enter within the lock scope. When we are attempting to lock down an instance level method, we can simply pass the reference to that instance. (We can use this keyword to lock the current object) Once the thread enters into a lock scope, the lock token (object reference) is inaccessible by other threads until the lock is released or the lock scope has exited.

If we want to lock down the code in a static method, we need to provide the System.Type of the respective class.
Converting the Code to Enable Synchronization using the Lock Keyword
Collapse

public void PrintNumbers()
{
lock (this)
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(100);
Console.Write(i + ",");
}
Console.WriteLine();
}
}

OUTPUT



Using the Monitor Type

The C# lock keyword is just a notation for using System.Threading.Monitor class type. The lock scope actually resolves to the Monitor class after being processed by the C# compiler.
Converting the Code to Enable Synchronization using the Monitor Class
Collapse

public void PrintNumbers()
{
Monitor.Enter(this);
try
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(100);
Console.Write(i + ",");
}
Console.WriteLine();
}
finally
{
Monitor.Exit(this);
}
}

Monitor.Enter() method is the ultimate recipient of the thread token. We need to write all code of the lock scope inside a try block. The finally clause ensures that the thread token is released(using the Monitor.Exit() method), regardless of any runtime exception.
OUTPUT

How to: Use a Thread Pool (C# Programming Guide)

A thread pool is a collection of threads that can be used to perform a number of tasks in the background. (See Using Threading for background information.) This leaves the primary thread free to perform other tasks asynchronously.

Thread pools are often employed in server applications. Each incoming request is assigned to a thread from the thread pool, so the request can be processed asynchronously, without tying up the primary thread or delaying the processing of subsequent requests.

Once a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task.

Thread pools typically have a maximum number of threads. If all the threads are busy, additional tasks are placed in queue until they can be serviced as threads become available.

You can implement your own thread pool, but it is easier to use the thread pool provided by the .NET Framework through the ThreadPool class.

The following example uses the .NET Framework thread pool to calculate the Fibonacci result for ten numbers between 20 and 40. Each Fibonacci result is represented by the Fibonacci class, which provides a method called ThreadPoolCallback that performs the calculation. An object representing each Fibonacci value is created, and the ThreadPoolCallback method is passed to QueueUserWorkItem, which assigns an available thread in the pool to execute the method.

Because each Fibonacci object is given a semi-random value to compute, and because each of the ten threads will be competing for processor time, there is no way to know in advance how long it will take for all ten results to be calculated. That's why each Fibonacci object is passed an instance of the ManualResetEvent class during construction. Each object signals the provided event object when its calculation is complete, which allows the primary thread to block execution with WaitAll until all ten Fibonacci objects have calculated a result. The Main method then displays each Fibonacci result.

using System;
using System.Threading;

public class Fibonacci
{
public Fibonacci(int n, ManualResetEvent doneEvent)
{
_n = n;
_doneEvent = doneEvent;
}

// Wrapper method for use with thread pool.
public void ThreadPoolCallback(Object threadContext)
{
int threadIndex = (int)threadContext;
Console.WriteLine("thread {0} started...", threadIndex);
_fibOfN = Calculate(_n);
Console.WriteLine("thread {0} result calculated...", threadIndex);
_doneEvent.Set();
}

// Recursive method that calculates the Nth Fibonacci number.
public int Calculate(int n)
{
if (n <= 1)
{
return n;
}

return Calculate(n - 1) + Calculate(n - 2);
}

public int N { get { return _n; } }
private int _n;

public int FibOfN { get { return _fibOfN; } }
private int _fibOfN;

private ManualResetEvent _doneEvent;
}

public class ThreadPoolExample
{
static void Main()
{
const int FibonacciCalculations = 10;

// One event is used for each Fibonacci object
ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations];
Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations];
Random r = new Random();

// Configure and launch threads using ThreadPool:
Console.WriteLine("launching {0} tasks...", FibonacciCalculations);
for (int i = 0; i < FibonacciCalculations; i++)
{
doneEvents[i] = new ManualResetEvent(false);
Fibonacci f = new Fibonacci(r.Next(20,40), doneEvents[i]);
fibArray[i] = f;
ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
}

// Wait for all threads in pool to calculation...
WaitHandle.WaitAll(doneEvents);
Console.WriteLine("All calculations are complete.");

// Display the results...
for (int i= 0; i<FibonacciCalculations; i++)
{
Fibonacci f = fibArray[i];
Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN);
}
}
}
Sample Output

launching 10 tasks...
result calculated...
result calculated...
result calculated...
result calculated...
result calculated...
result calculated...
result calculated...
result calculated...
result calculated...
result calculated...
all calculations complete
Fibonacci(22) = 17711
Fibonacci(25) = 75025
Fibonacci(32) = 2178309
Fibonacci(36) = 14930352
Fibonacci(32) = 2178309
Fibonacci(26) = 121393
Fibonacci(35) = 9227465
Fibonacci(23) = 28657
Fibonacci(39) = 63245986
Fibonacci(22) = 17711

How to: Create and Terminate Threads (C# Programming Guide)

This example demonstrates how an auxiliary or worker thread can be created and used to perform processing in parallel with the primary thread. Making one thread wait for another and gracefully terminating a thread are also demonstrated.

The example creates a class named Worker that contains the method that the worker thread will execute called DoWork. This is essentially the Main function for the worker thread. The worker thread will begin execution by calling this method, and terminate automatically when this method returns.


The Worker class contains an additional method that is used to indicate to DoWork that it should return. This method is called RequestStop.

The RequestStop method merely assigns the _shouldStop data member to true. Because this data member is checked by the DoWork method, this has the indirect effect of causing DoWork to return, thereby terminating the worker thread. However, it is important to note that DoWork and RequestStop will be executed by different threads. DoWork is executed by the worker thread, and RequestStop is executed by the primary thread, so the _shouldStop data member is declared volatile

he volatile keyword alerts the compiler that multiple threads will access the _shouldStop data member, and therefore it should not make any optimization assumptions about the state of this member.


using System;
using System.Threading;

public class Worker
{
// This method will be called when the thread is started.
public void DoWork()
{
while (!_shouldStop)
{
Console.WriteLine("worker thread: working...");
}
Console.WriteLine("worker thread: terminating gracefully.");
}
public void RequestStop()
{
_shouldStop = true;
}
// Volatile is used as hint to the compiler that this data
// member will be accessed by multiple threads.
private volatile bool _shouldStop;
}

public class WorkerThreadExample
{
static void Main()
{
// Create the thread object. This does not start the thread.
Worker workerObject = new Worker();
Thread workerThread = new Thread(workerObject.DoWork);

// Start the worker thread.
workerThread.Start();
Console.WriteLine("main thread: Starting worker thread...");

// Loop until worker thread activates.
while (!workerThread.IsAlive);

// Put the main thread to sleep for 1 millisecond to
// allow the worker thread to do some work:
Thread.Sleep(1);

// Request that the worker thread stop itself:
workerObject.RequestStop();

// Use the Join method to block the current thread
// until the object's thread terminates.
workerThread.Join();
Console.WriteLine("main thread: Worker thread has terminated.");
}
}


Sample Output

main thread: starting worker thread...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: terminating gracefully...
main thread: worker thread has terminated

Thursday, April 23, 2009

Threads in .net - Part 2

The System.Threading Namespace



The System.Threading namespace provides classes and interfaces that enables multithreaded programming. This namespace includes a ThreadPool class that manages groups of threads, a Timer class that enables a delegate to be called after a specified amount of time, and a Mutex Class for synchronizing mutually-exclusive threads. System.Threading also provides classes for thread scheduling, wait notification, and deadlock resolution.



Some of the important classes in System.Threading namespace is discussed below.



Thread - Represents threads that execute within the runtime, to create and control threads.



ThreadPool - Posts work items to the thread pool. Queue work items for execution on the first available thread from the thread pool. One OS thread pool per process. Efficient use of thread resources.



Timeout - Contains timeout values for the system



Times - Specifies a delegate to be called at a specified time. The wait operation is performed by a thread in the thread pool.



Monitor - Provides the synchronization of threading objects using locks and wait/signals.



Mutex - A synchronization primitive that can also be used for interprocess synchronization. Wait can be used to request ownership of the mutex. The state of the mutex is signaled if no thread owns it.



The thread that owns a mutex can specify the same mutex in repeated wait function calls without blocking its executions. It must release the mutex as many times ti release ownership. If a thread terminates normally while owning a mutex, the state of the mutex is set to signaled and the next waiting thread gets ownership.



Life Cycle Methods



Starting a Thread

The thread class of System.Threading Namespace represents a thread object. By using class object, we can create new threads, delete, pause and resume threads. The thread class creates a new thread and Thread.Start method starts a thread.



thread = new Thread(new TreadStart( writeData ));
thread.start();



where writeData is a function which will be executed by the program.



Killing a Thread

Thread class's Abort method is called to kill a thread permanently. Make sure IsAlive is called before Abort.



if( thread.IsAlive )

{

thread.Abort();

}



Pausing a Thread

Thread.Sleep method can be used to pause a thread for a fixed period of time.



thread.Sleep();



Suspending a Thread

The Suspend method of the thread class suspends a thread. The thread is suspended until Resume method is called.



if( thread.ThreadState == ThreadState.Running)
{
thread.Suspend();
}



Resume a suspended Thread

The Resume method is called to resume a suspended thread. If the thread is not suspended, there will be no effect of Resume method.



if(thread.ThreadState == ThreadState.Suspended)
{
thread.Resume();
}

Threads in asp.net - Part 1

What are threads?

Each application that is executed has its own 'process space' in the operating system. A Process is an isolated area of memory specifically set aside for that application to be executed in. A Thread on the other hand is a single unit that executes within a process and more specifically by which the operating system allocates processor time. A process will always have at least one thread running in it but it is possible for a process to contain multiple threads that execute simultaneously.

Let me illustrate the difference between a single threaded and a multi threaded application:

Say, for example that you have written a single threaded email client application. This application has only one thread running in its process. When you perform a lengthly operation, such as a 'Send and Receive', because the thread is managing the user interface as well as all the other code, the user has to wait for that operation to complete before they are given back the focus to the user interface.
If it were written as a multi threaded application, the 'Send and Receive' operation could be fired off an a new thread. This would mean that the first thread, that is running the user interface, would still have the focus for the user to interact with as both threads will be running at the same time.

A real life example of this is in Microsoft Outlook. When you click 'Send and Receive' a new thread is started to perform this operation. This allows you to continue to do other things such as compose a new email or view your calendar.

Using threads in this way is an extremely powerful technique. It allows the application to make the best use of the processor's time by running threads in the background in between the application's events.

Example :

using System;
using System.Threading;

public class my3Methods {

public void myMethod1() {
Console.WriteLine("...myThread1 created!");
Thread.Sleep(5000);
Console.WriteLine("...myThread1 has finished!");
}

public void myMethod2() {
Console.WriteLine("...myThread2 created!");
Thread.Sleep(3000);
Console.WriteLine("...myThread2 has finished!");
}

public void myMethod3() {
Console.WriteLine("...myThread3 created!");
Thread.Sleep(1000);
Console.WriteLine("...myThread3 has finished!");
}
}

public class ThreadTest {

public static int Main(String[] args) {

my3Methods testClass = new my3Methods();

Thread myThread1 = new Thread(new ThreadStart(testClass.myMethod1));
myThread1.Start();

Thread myThread2 = new Thread(new ThreadStart(testClass.myMethod2));
myThread2.Start();

Thread myThread3 = new Thread(new ThreadStart(testClass.myMethod3));
myThread3.Start();

return 0;
}
}

Wednesday, April 22, 2009

Built in functions in sqlserver

CAST
DECLARE @StrSalary Varchar(10),
@StrHours Varchar(6),
@WeeklySalary Decimal(6,2)
SET @StrSalary = '22.18';
SET @StrHours = '38.50';

SET @WeeklySalary = CAST(@StrSalary As Decimal(6,2)) *
CAST(@StrHours As Decimal(6,2));
SELECT @WeeklySalary;
GO

Convert
DECLARE @Side As Decimal(10,3),
@Perimeter As Decimal(10,3),
@Area As Decimal(10,3);
SET @Side = 48.126;
SET @Perimeter = @Side * 4;
SET @Area = @Side * @Side;
PRINT 'Square Characteristics';
PRINT '-----------------------';
PRINT 'Side = ' + CONVERT(varchar(10), @Side, 10);
PRINT 'Perimeter = ' + CONVERT(varchar(10), @Perimeter, 10);
PRINT 'Area = ' + CONVERT(varchar(10), @Area, 10);
GO

Len
DECLARE @FIFA varchar(120)
SET @FIFA = 'Fédération Internationale de Football Association'
SELECT @FIFA AS FIFA
SELECT LEN(@FIFA) AS [Number of Characters]

ASCII
DECLARE @ES varchar(100)
SET @ES = 'El Salvador'
SELECT @ES AS ES
SELECT ASCII(@ES) AS [In ASCII Format]

Char
select char(65) As 'charA'


Lower
DECLARE @FIFA varchar(120)
SET @FIFA = 'Fédération Internationale de Football Association'
SELECT @FIFA AS FIFA
SELECT LOWER(@FIFA) AS Converted


Upper
DECLARE @FIFA varchar(120)
SET @FIFA = 'this is a great color to choose'
SELECT @FIFA AS FIFA
SELECT UPPER(@FIFA) AS Converted

Left
CREATE FUNCTION GetUsername
(@FirstName varchar(40),
@LastName varchar(40))
RETURNS varchar(50)
AS
BEGIN
DECLARE @Username AS varchar(50);
SELECT @Username = LOWER(LEFT(@FirstName, 1)) +
LEFT(LOWER(@LastName), 4)
RETURN @Username;
END
GO

SELECT Exercise1.dbo.GetUsername('Francine', 'Moukoko');
GO

Right
CREATE FUNCTION Last4DigitsOfSSN(@SSN varchar(12))
RETURNS char(4)
AS
BEGIN
RETURN RIGHT(@SSN, 4);
END
GO

SELECT Exercise1.dbo.Last4DigitsOfSSN('836483846');
GO

Please Click here to read further

Temporary tables and Table Variables in sqlserver

Temporary tables are a useful tool in SQL Server provided to allow for short term use of data. There are two types of temporary table in SQL Server, local and global.

Local temporary tables are only available to the current connection to the database for the current user and are dropped when the connection is closed. Global temporary tables are available to any connection once created, and are dropped when the last connection using it is closed.

Both types of temporary tables are created in the system database tempdb.

Creating Temporary Tables

Temporary tables can be created like any table in SQL Server with a CREATE TABLE or SELECT..INTO statement. To make the table a local temporary table, you simply prefix the name with a (#). To make the table a global temporary table, prefix it with (##).

-- Create a local temporary table using CREATE TABLE
CREATE TABLE #myTempTable
(
DummyField1 INT,
DummyField2 VARCHAR(20)
)

-- Create a local temporary table using SELECT..INTO
SELECT
age AS DummyField1,
lastname AS DummyField2
INTO #myTempTable
FROM DummyTable


Both of these samples create a local temporary table named #myTempTable with two fields DummyField1 and DummyField2.

To make these into global temporary tables, just replace (#) with (##)

CREATE TABLE ##myTempTable
(
DummyField1 INT,
DummyField2 VARCHAR(20)
)

SELECT
age AS DummyField1,
lastname AS DummyField2
INTO ##myTempTable
FROM DummyTable


Similarly, you can SELECT, INSERT, and UPDATE like any other table, but remember the prefix is part of the table name.

Deciding between Local and Global

When deciding which type of table to use ask yourself two questions. First, "Do I need this data to persist when I am done using it?" If so, I need a standard table, not a temporary table. Second, Do I need the data to be accessed outside of my single process?" This question can sometimes be a little tougher to figure out, so I have a simple suggestion. Make it a local temporary table for now, and if you find out you need a larger scope, change it later. In today's world there are plenty of tools to find and replace, so there's no reason to start with a global temporary table unless you know you will need it.


Table Variables

If you are using SQL Server 2000 or higher, you can take advantage of the new TABLE variable type. These are similar to temporary tables except with more flexibility and they always stay in memory. The code above using a table variable might look like this:

DECLARE @TibetanYaks TABLE (
YakID int,
YakName char(30) )

INSERT INTO @TibetanYaks (YakID, YakName)
SELECT YakID, YakName
FROM dbo.Yaks
WHERE YakType = 'Tibetan'

-- Do some stuff with the table

Table variables don't need to be dropped when you are done with them.
Which to Use

* If you have less than 100 rows generally use a table variable. Otherwise use a temporary table. This is because SQL Server won't create statistics on table variables.
* If you need to create indexes on it then you must use a temporary table.
* When using temporary tables always create them and create any indexes and then use them. This will help reduce recompilations. The impact of this is reduced starting in SQL Server 2005 but it's still a good idea.

Cursors in SqlServer - Part II

Create a table by name Ashwin and perform some inserts into it
here is the code to create the table

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Ashwin](
[Name] [varchar](32) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF

here is the query to insert values into it
insert into ashwin
select 'value1' union
select 'value2' union
select 'value3'

now we create a cursor which runs through each row and displays the name contained in eachrow
Declare @name varchar(32)
declare cursorname cursor read_only for
select name from Ashwin

open cursorname
fetch NEXT from cursorname into @name
while(@@Fetch_status=0)
begin
print @name
fetch next from cursorname into @name
end
close cursorname
deallocate cursorname


Now we declare a cursor which updates the values present in each row

Declare @nameUpdate varchar(32)
Declare cursorupdate cursor for
select name from Ashwin
for update of name

open cursorupdate
fetch next from cursorupdate into @nameUpdate
while (@@Fetch_status=0)
begin
update ashwin set name='new'+@nameUpdate
where current of cursorupdate

fetch next from cursorupdate into @nameUpdate
end

close cursorupdate
deallocate cursorupdate

select * from Ashwin

Cursors in Sqlserver -Part I

Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, instead of the typical SQL commands that operate on all the rows in the set at one time. For example, you can use cursor to include a list of all user databases and make multiple operations against each database by passing each database name as a variable.

The server side cursors were first added in SQL Server 6.0 release and now supported in all editions of SQL Server 7.0 and SQL Server 2000.

Before using cursor, you first must declare the cursor. Once a cursor has been declared, you can open it and fetch from it. You can fetch row by row and make multiple operations on the currently active row in the cursor. When you have finished working with a cursor, you should close cursor and deallocate it to release SQL Server resources.


Advantages of Using Cursors with the Query Processor :

Some advantages of using cursors in conjunction with the query processor are:

* Efficiency. The query optimizer automatically selects the appropriate query plan, so the developer does not need to design a complex algorithm to access the required data.

* Adaptability. As data changes or indexes are added or dropped, the query optimizer automatically adapts its behavior by using alternative plans.

* Fewer errors. Instead of the developer handling data and algorithms in the application, the SQL Server Compact 3.5 Database Engine natively supports the required operations.




Advantage:

you can do row vise validation from a table

Disadvantage:

of example you are retrieving 100 row...
every single row you retrieve will hit the server as a
single select query so performance will be low.

consumes lot of resources.

Disadvantages of user defined functions over stored procedures

1)UDF Accepts Lesser Numbers of Input Parameters.
UDF can have upto 1023 input parameters, Stored Procedure can have upto 21000 input parameters.

2)UDF can not Call Stored Procedure
Only access to Extended Stored Procedure.

3)UDF can not Execute Dynamic SQL, temporary tables.

4)UDF can not Return XML.

5)UDF does not Support Error Handling
RAISEERROR or @@ERROR are not allowed in UDFs.

Difference between varchar and nvarchar in sqlserver

VarChar is a variable length string of ASCII characters.
NVarChar is a variable length string of UNICODE characters.

ASCII characters each take one Byte of space.
UNICODE characters each take Two Bytes of space.

NVarChar is truncate the whitespce but not in VarChar.

For the most part the two datatypes are identical in how you would work with them within SQL Server or from an application. The difference is that nvarchar is used to store unicode data, which is used to store multilingual data in your database tables. Other languages have an extended set of character codes that need to be saved and this datatype allows for this extension. If your database will not be storing multilingual data you should use the varchar datatype instead. The reason for this is that nvarchar takes twice as much space as varchar, this is because of the need to store the extended character codes for other languages.

In principle they are the same and are handled the same by your application. The only difference is that NVARCHAR can handle unicode characters allowing you to use multiple languages in the database. NVARCHAR takes twice as much space to store to allow for the extended character set required by some other languages. So if you are not using other languages then definitley use VARCHAR for character data.

Indexes in SqlServer

Relational databases like SQL Server use indexes to find data quickly when a query is processed.The SQL Server engine uses an index in much the same way a reader uses a book index.

Microsoft SQL Server supports two types of indexes:
Clustered indexes define the physical sorting of a database table’s rows in the storage media. For this reason, each database table may have only one clustered index. If a PRIMARY KEY constraint is created for a database table and no clustered index currently exists for that table, SQL Server automatically creates a clustered index on the primary key.

Non-clustered indexes are created outside of the database table and contain a sorted list of references to the table itself. SQL Server 2000 supports a maximum of 249 non-clustered indexes per table. However, it’s important to keep in mind that non-clustered indexes slow down the data modification and insertion process, so indexes should be kept to a minimum

You should consider creating non-clustered indexes on any columns that are frequently referenced in the WHERE clauses of SQL statements. Other good candidates are columns referenced by JOIN and GROUP BY operations.

You may wish to also consider creating non-clustered indexes that cover all of the columns used by certain frequently issued queries. These queries are referred to as “covered queries” and experience excellent performance gains.

1 clustered index per table (usually primary key)
249 non- clustered indexes per table are possible.

Also refer the following links :Link1

Link2

Storing and retreiving connection string from web.config

<configuration>
<connectionStrings>
<add name="pubs" connectionString="Data Source=yourservername; Initial Catalog=pubs;User ID=yourusername;Password=yourpassword;" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>

Note if windows authentication use following format
<add name="Pubs" connectionString="Server=(local)\SQLExpress;Integrated Security=True;Database=pubs;Persist Security Info=True"
providerName="System.Data.SqlClient" />



/// <summary>

/// method to retrieve connection stringed in the web.config file

/// </summary>

/// <param name="str">Name of the connection</param>

/// <remarks>Need a reference to the System.Configuration Namespace</remarks>

/// <returns></returns>

public string GetConnectionString(string str)

{

//variable to hold our return value

string conn = string.Empty;

//check if a value was provided

if (!string.IsNullOrEmpty(str))

{

//name provided so search for that connection

conn = ConfigurationManager.ConnectionStrings[str].ConnectionString;

}

else

//name not provided, get the 'default' connection

{

conn = ConfigurationManager.ConnectionStrings["YourConnName"].ConnectionString;

}

//return the value

return conn;

}

Enabling session in web services using EnableSession.

To enable session in web services we use the EnableSession attribute to be set to true.
once you have created your web service and added the refrence to it in your project refresh your aspx page to know how the session works.The code is self explanatory.

Webservice code
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;

namespace SampleService
{
///
/// Summary description for EnableSession
///

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class EnableSession : System.Web.Services.WebService
{

[WebMethod(Description="Describes how to use session in web services",EnableSession=true)]
public string HelloWorld()
{
// get the Count out of Session State
int? Count = (int?)Session["Count"];

if (Count == null)
Count = 0;

// increment and store the count
Count++;
Session["Count"] = Count;

return "Hello World - Call Number: " + Count.ToString();

}
}
}

ASPX.CS code
localhost.EnableSession objEnbSession;
// try to get the proxy from Session state
objEnbSession = Session["MyService"] as localhost.EnableSession;
if (objEnbSession == null)
{
// create the proxy
objEnbSession = new localhost.EnableSession();

// create a container for the SessionID cookie
objEnbSession.CookieContainer = new CookieContainer();

// store it in Session for next usage
Session["MyService"] = objEnbSession;
}

// call the Web Service function
Response.Write(objEnbSession.HelloWorld() + "<br />");

Enabling caching in Web services using cacheduration and using application object in web services.

Copy paste the code in your respective web services and aspx pages . Because the caching is enabled in the web services for duration of 5 seconds even if multiple refreshes are made within 5 seconds the webservice data which is cahed at the server is presented to the user and fresh data is presented and cached at the end of 5 every seconds.

Webservice code
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;

namespace SampleService
{
///
/// Summary description for CacheDuration
///

[WebService(Namespace = "http://tempuri.org/",Description="An example to descript cache")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class CacheDuration : System.Web.Services.WebService
{

[WebMethod(Description="An example to descript cache",CacheDuration=10)]
public string HelloWorld()
{

if (Application["cachecount"] == null)
Application["cachecount"] = 1;
else
Application["cachecount"] = int.Parse(Application["cachecount"].ToString()) + 1;

return Application["cachecount"].ToString();

}
}
}


ASPX.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using localhost;

public partial class WebServices_EmployeeService : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CacheDuration objDuration = new CacheDuration();
//objDuration.CookieContainer = objCookieConnt;
Response.Write("Duration:"+objDuration.HelloWorld()+"<br>");
}
}

Web services Authentication and authorization using Soap headers

In the following code an attempt is made to access the web service without providing any credentials which is rejected and then with wrong credentials and finally with proper credentials the web service is accessed ans the user is authenticated.The code is self explanatory.
Web service code

using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

namespace AuthForWebServices
{
///
/// Summary description for WebService.
///

public class WebService : System.Web.Services.WebService
{
public AuthHeader Authentication;

public WebService()
{
//CODEGEN: This call is required by the ASP.NET Web Services Designer
InitializeComponent();
}

#region Component Designer generated code

//Required by the Web Services Designer
private IContainer components = null;

///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///

private void InitializeComponent()
{
}

///
/// Clean up any resources being used.
///

protected override void Dispose( bool disposing )
{
if(disposing && components != null)
{
components.Dispose();
}
base.Dispose(disposing);
}

#endregion

[SoapHeader ("Authentication", Required=true)]
[WebMethod (Description="Returns some sample data")]
public string SensitiveData()
{

//Do our authentication
//this can be via a database or whatever
string data = null;
if(Authentication.Username.ToLower().Trim() == "ashwin" && Authentication.Password.ToLower().Trim() == "payal")
{
data= "Authenticated user
";
}
else
{
data= "Invalid credentials
";
}

return data;
}

}

public class AuthHeader : SoapHeader
{
public string Username;
public string Password;
}
}

ASPX page code
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace AuthForWebServices
{
///
/// Summary description for WebForm1.
///

public class WebForm1 : System.Web.UI.Page
{

private void Page_Load(object sender, System.EventArgs e)
{
//simple client
AuthWebService.WebService webService = new AuthWebService.WebService();
AuthWebService.AuthHeader authentication = new AuthWebService.AuthHeader();

//without username password
try
{
Response.Write(webService.SensitiveData());
}
catch
{
Response.Write("Attempt 1 : no crendentials supplied.
");
}

authentication.Username = "Mr.x";
authentication.Password = "payal";
webService.AuthHeaderValue = authentication;

//Invalid username password
try
{
Response.Write(webService.SensitiveData());
}
catch
{
Response.Write("Attempt 1 : no crendentials supplied.");
}
//valid uname, password
authentication.Username = "ashwin";
authentication.Password = "payal";
webService.AuthHeaderValue = authentication;
Response.Write(webService.SensitiveData());

}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///

private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion
}
}

//output is as follows
Attempt 1 : no crendentials supplied.
Invalid credentials
Authenticated user

Tuesday, April 21, 2009

Delegates and Events in c# - Part IV

Events

Note : read the previous parts to understand this one thoroughly

Events are the messages sent by an object to indicate the occurrence of an event. Event can also be defined as a member that enables an object to provide notification. Events provide a very powerful means of inter-process communication. The most familiar example of events are graphical user interface, events are fired when any control is clicked on the GUI.
We can associate an event to a delegate.

Example...
Add a page called Events and Delegates.aspx in your code
Replicate your code- behind with the following

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Events_and_Delegates_EandD : System.Web.UI.Page
{
public delegate void PrintString(string msg);
public event PrintString eventprint;

protected void Page_Load(object sender, EventArgs e)
{
eventprint+=new PrintString(printmsg);
if (eventprint != null)
{
eventprint("Message using event and delgate"+"<br>");
}
}
}

public void printmsg(string msg)
{
Response.Write("Message:" + msg);
}

//output will be as follows
Message:Message using event and delgate

Delegates and Events in c#- part III

You can refer previous to parts on the same topic for the basics

Multicast Delegates

MultiCast Delegates are nothing but a single delegate that can invoke multiple methods of matching signature. MultiCast Delegate derives from System.MulticastDelegate class which is a subclass of System.Delegate.

In Multi-Casting basically we create a single delegate that in turn invokes multiple encapsulated methods. We can use MultiCast Delegates when multiple calls to different methods are required. For example if we are required to call two methods on a single button click event or mouse over event then using MultiCast Delegates we can easily call the methods.

The System.MulticastDelegate class provides required methods to play with delegates. There are two methods, Combine and Remove, which are used to play with delegates.

The Combine method is a static method of System.MulticastDelegate class which is used to combine the delegates and the Remove method is used to remove the delegate from the list.

The example of combine and remove is presented in the previous part.click here to view previous part

Multicast Example
Add a page called Events and Delegates.aspx in your code
Replicate your code- behind with the following

using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Events_and_Delegates_EandD : System.Web.UI.Page
{
//declare the following delegate
public delegate void PrintEmpnameDelegate(string empname);

protected void Page_Load(object sender, EventArgs e)
{
PrintEmpnameDelegate objPeintDel = null;
objPeintDel += new PrintEmpnameDelegate(PrintEmpName);
//or even the followinf is correct
// PrintEmpnameDelegate objPeintDel = new PrintEmpnameDelegate(PrintEmpName);
PassEmpNameToPrint(objPeintDel);
objPeintDel = null;
objPeintDel += new PrintEmpnameDelegate(PrintEmpNameSmall);
PassEmpNameToPrint(objPeintDel);
}

}

//Add the following methods

public void PrintEmpName(string empname)
{
Response.Write("Name:"+empname+"<br>");
}

public void PassEmpNameToPrint(PrintEmpnameDelegate objPrntDel)
{
if(objPrntDel!= null)
{
objPrntDel("Ashwin" + "<br>");
}
}

public void PrintEmpNameSmall(string empname)
{
Response.Write(empname.ToLower());
}

//Output will be as follows
Name:Ashwin
ashwin

Delegates and events in C# - Part II

Types of Delegate

Delegates are of two types:
Single cast delegate

A delegate is called single cast delegate if it invokes a single method. In other words we can say that SingleCast Delegates refer to a single method with matching signature. SingleCast Delegates derive from the System.Delegate class

SingleCast Delegates can be defined using the following syntax:

public delegate int mydelegatename(int param1, int param2);

Note : parameters are optional

Add a page called Events and Delegates.aspx in your code
Replicate your code- behind with the following

using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Events_and_Delegates_EandD : System.Web.UI.Page
{
delegate int AddDelgate(int num1, int num2); //declaring the delegate
protected void Page_Load(object sender, EventArgs e)
{
AddDelgate objAddDel = new AddDelgate(Add); //instansiate it
Response.Write("Result:" + objAddDel(2, 3).ToString() + "<br>");
}
}

public int Add(int num1, int num2)
{
return (num1 + num2);
}

Output would be as follows:
Result:5

Next add one more method called max which returns maximum of two numbers as follows

public int Max(int num1, int num2)
{
if (num1 > num2)
{
return num1;
}
else
{
return num2;
}
}

continue to add these lines in page load
AddDelgate objmaxNumber = new AddDelgate(Max);
Response.Write("MaxNumber between 2 and 3:" + objmaxNumber(2, 3).ToString() + "<br>");

Now the result will be
Result:5
MaxNumber between 2 and 3:3

Use of cobine and remove
continue to add these lines in page load
Response.Write("combined delegate example <br>");
AddDelgate objSumdelegate = null;
objSumdelegate = (AddDelgate)System.Delegate.Combine(objAddDel, objmaxNumber);
Response.Write(objSumdelegate(2, 3).ToString()+"<br>");
Response.Write("remove delegate example :<br>");
objSumdelegate = (AddDelgate)System.Delegate.Remove(objSumdelegate, objmaxNumber);
Response.Write("After removing the result of addition is :<br>");
Response.Write(objSumdelegate(2, 3).ToString() + "<br>");


Now the reult will be
Result:5
MaxNumber between 2 and 3:3
combined delegate example
3
remove delegate example :
After removing the result of addition is :
5