Monday, March 22, 2010

Animation in WPF

In WPF, we have 3 types of animations:
1) Color Animation – Used to change the color of the control.
2) Double Animation – Used to animate double values such as X/Y coordinate, Width and Height etc.
3) Key Frame Animation – This is a complex animation than color and double animation. In this animation we use key frames or a series of key frames.

Above we have seen just 1 line introduction of all types. We will learn more about them below along with their examples.

We all know that we have to write animation part in “Storyboard”. To begin storyboard we need to do “<BeginStoryBoard>”. It has two main properties – “TargetName” and “TargetProperty”. “TargetName” identifies the pbject and “TargetProperty” identifies the property of that oject. If we want to begin animation on some event like button click etc we can use “EventTrigger”. In animation there are two things – “To” and “From”. “To” specifies the start of animation and “From” specifies the end of animation. “TimeSpan” is 1 more keyword which specifies the time span for how much animation should run. These are few basic keywords which are necessary in our coding part for animation. We might come across few more keywords which I will explain them as they are used.
Now let’s start with examples of animations.

1) Color Animation:

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Rectangle Height="38" HorizontalAlignment="Left" Margin="133,156,0,0" x:Name="Rectchangecolor" Stroke="Black" Fill="Yellow" VerticalAlignment="Top" Width="200">
<Rectangle.Triggers>
<EventTrigger RoutedEvent="Rectangle.MouseLeftButtonDown">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetName="Rectchangecolor"
Storyboard.TargetProperty="Fill.Color"
From="Yellow"
To="DarkBlue"
Duration="0:0:1">
</ColorAnimation>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Rectangle.Triggers>
</Rectangle>
</Grid>
</Window>

Above is the code of color animation. In this example, we have a rectangle which is of yellow color which changes to blue color in time span of 1 second. In above code we have declared a rectangle which is already filled with yellow color. We have declared event on it as “MouseLeftButtonDown”. If we left single click on rectangle, animation will start. Now this animation we have declared below in StoryBoard in Color Animation. For this we have given TargetName the name of rectangle as that is our target for animation and TargetProperty we have declared as Fill.Color which fills the target with given color. Here we have also declared which color to fill which is blue. We have given duration as 0:0:1 which is 1 sec.

So after writing this code we will get the output as shown in below video.



2) Double Animation:

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Rectangle Height="38" HorizontalAlignment="Left" Margin="133,156,0,0" x:Name="Rectchangecolor" Stroke="Black" Fill="Red" VerticalAlignment="Top" Width="200">
<Rectangle.Triggers>
<EventTrigger RoutedEvent="Rectangle.MouseLeftButtonDown">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="Rectchangecolor"
Storyboard.TargetProperty="Height"
From="38"
To="100"
Duration="0:0:1.5">
</DoubleAnimation>
<DoubleAnimation Storyboard.TargetName="Rectchangecolor"
Storyboard.TargetProperty="Width"
From="200"
To="350"
Duration="0:0:3">
</DoubleAnimation>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Rectangle.Triggers>
</Rectangle>
</Grid>
</Window>

Above is the code of double animation. In this example, we have a rectangle which is of red color of height 38 and width 200 which changes to height 100 in time span of 1.5 second and width 350. We have declared event on it as “MouseLeftButtonDown”. If we left single click on rectangle, animation will start. Now this animation we have declared below in StoryBoard in Double Animation. For this we have given TargetName the name of rectangle as that is our target for animation and TargetProperty we have declared as Height for change in height and Width for change in width.
So after writing this code we will get the output as shown in below video.



Let’s see 1 more example of Double Animation in which we will write animation part in code.

In XAML you will have to write,
<Grid>
<Button Content="Animate" Height="33" HorizontalAlignment="Left" Margin="32,12,0,0" Name="btnRotate" VerticalAlignment="Top" Width="165" Click="btnRotate_Click" />
<Rectangle Height="200" HorizontalAlignment="Left" Margin="534,158,0,0" Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="50" Fill="#FF166C0F" />
<Rectangle Fill="#FF166C0F" Height="50" HorizontalAlignment="Left" Margin="457,235,0,0" Name="rectangle2" Stroke="Black" VerticalAlignment="Top" Width="200" />
</Grid>

In code we need to write,

namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void btnRotate_Click(object sender, RoutedEventArgs e)
{
DoubleAnimation da =new DoubleAnimation();
da.From = 0;
da.To = 90;
da.Duration = new Duration(TimeSpan.FromSeconds(3));
DoubleAnimation da1 = new DoubleAnimation();
da1.From = 0;
da1.To = -90;
da1.Duration = new Duration(TimeSpan.FromSeconds(3));
//da.RepeatBehavior = RepeatBehavior.Forever;
RotateTransform rt = new RotateTransform();
rectangle1.RenderTransform = rt;
rt.BeginAnimation(RotateTransform.AngleProperty, da);
RotateTransform rt1 = new RotateTransform();
rectangle2.RenderTransform = rt1;
rt1.BeginAnimation(RotateTransform.AngleProperty, da1);
}


}
}

Here we have taken two similar rectangles. We have given angle property to each of them. To 1 rectangle we have given angle 90 and to other we have given angle -90 due to which both rectangle animate in opposite direction. We have included animation in the code. For writing this in our code we need to include namespace using System.Windows.Media.Animation.

So after writing this code we will get the output as shown in below video.



We can also have a combination of Color and Double Animation.
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="433" Width="803">
<Grid>
<Button Content="Animate" Height="33" HorizontalAlignment="Left" Margin="32,12,0,0" Name="btnRotate"
VerticalAlignment="Top" Width="165"/>
<Rectangle Height="200" HorizontalAlignment="Left" Margin="534,158,0,0" Name="rectangle1"
Stroke="Black" VerticalAlignment="Top" Width="50" Fill="DarkGreen">
<Rectangle.RenderTransform>
<RotateTransform x:Name="TransRotate1"
CenterX="25" CenterY="25" Angle="0" />
</Rectangle.RenderTransform>
<Rectangle.Resources>
<Storyboard x:Key="spin1">
<DoubleAnimation Storyboard.TargetName="TransRotate1"
Storyboard.TargetProperty="Angle"
By="90"
Duration="0:0:10">
</DoubleAnimation>
<ColorAnimation Storyboard.TargetName="rectangle1"
Storyboard.TargetProperty="Fill.Color"
From="DarkGreen"
To="Red"
Duration="0:0:15">
</ColorAnimation>
</Storyboard>
</Rectangle.Resources>
</Rectangle>
<Rectangle Fill="DarkGreen" Height="50" HorizontalAlignment="Left" Margin="457,235,0,0" Name="rectangle2"
Stroke="Black" VerticalAlignment="Top" Width="200">
<Rectangle.RenderTransform>
<RotateTransform x:Name="TransRotate2"
CenterX="25" CenterY="25" Angle="0" />
</Rectangle.RenderTransform>
<Rectangle.Resources>
<Storyboard x:Key="spin2">
<DoubleAnimation Storyboard.TargetName="TransRotate2"
Storyboard.TargetProperty="Angle"
By="-90"
Duration="0:0:10">
</DoubleAnimation>
<ColorAnimation Storyboard.TargetName="rectangle2"
Storyboard.TargetProperty="Fill.Color"
From="DarkGreen"
To="DarkBlue"
Duration="0:0:15">
</ColorAnimation>
</Storyboard>
</Rectangle.Resources>
</Rectangle>
</Grid>
</Window>

Here we have taken the combination of color and double animation. We have considered the same above example for this. Here as time passes and angle changes the color of rectangle also changes.

So after writing this code we will get the output as shown in below video.



3) KeyFrame Animation:

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="433" Width="803">
<Grid>
<Rectangle Height="38" HorizontalAlignment="Left" Margin="133,156,0,0" x:Name="Rect" Stroke="Black" Fill="DarkGreen" VerticalAlignment="Top" Width="200">
<Rectangle.RenderTransform>
<TranslateTransform x:Name="RectTrans" X="0" Y="0" />
</Rectangle.RenderTransform>
<Rectangle.Triggers>
<EventTrigger RoutedEvent="Rectangle.MouseLeftButtonDown">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimationUsingKeyFrames Storyboard.TargetName="RectTrans"
Storyboard.TargetProperty="X"
Duration="0:0:15">
<LinearDoubleKeyFrame Value="350" KeyTime="0:0:7" />
<LinearDoubleKeyFrame Value="50" KeyTime="0:0:5" />
<LinearDoubleKeyFrame Value="200" KeyTime="0:0:3" />
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Rectangle.Triggers>
</Rectangle>

</Grid>
</Window>


Here we have taken a rectangle. It uses key frames to change the animation. Here we are using X value. We have changed it from 0 to 350 back to 50 and again to 200. We have used Linear key frame so it moves in Linear Fashion.

So after writing this code we will get the output as shown in below video.



Similarly we can do using spline double key frames as follows.

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="433" Width="803">
<Grid>
<Rectangle Height="38" HorizontalAlignment="Left" Margin="133,156,0,0" x:Name="Rect" Stroke="Black" Fill="DarkGreen" VerticalAlignment="Top" Width="200">
<Rectangle.RenderTransform>
<TranslateTransform x:Name="SplineTestTrans" X="0" Y="0" />
</Rectangle.RenderTransform>
<Rectangle.Triggers>
<EventTrigger RoutedEvent="Rectangle.MouseLeftButtonDown">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimationUsingKeyFrames Storyboard.TargetName="SplineTestTrans"
Storyboard.TargetProperty="X"
Duration="0:0:15">
<SplineDoubleKeyFrame Value="350" KeyTime="0:0:7" KeySpline="0.0,1.0, 1.0,0.0" />
<SplineDoubleKeyFrame Value="0" KeyTime="0:0:8" KeySpline="0.25,0.5, 0.5,0.75" />
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetName="SplineTestTrans"
Storyboard.TargetProperty="Y"
Duration="0:0:15">
<SplineDoubleKeyFrame Value="350" KeyTime="0:0:7" KeySpline="0.0,1.0, 1.0,0.0" />
<SplineDoubleKeyFrame Value="0" KeyTime="0:0:8" KeySpline="0.25,0.5, 0.5,0.75" />
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Rectangle.Triggers>
</Rectangle>

</Grid>
</Window>

Here we have used spline double key frames using which we can animate in any way.
So after writing this code we will get the output as shown in below video.

Monday, March 1, 2010

Report Writing in Windows Forms

Microsoft Report is based on report definition which is an XML file that gives us the data of a report. It may have different extensions. For eg. We can create a client-side report definition language (*.rdlc) file using Visual Studio. Reports also include tables, aggregated and multidimensional data, charts etc as per users requirements.

Let us see a example of creating a report. In this we will have a table in our report which will shoe us details of students like name,roll no etc.. Lets start is step by step..

Step 1:
We want to build a windows application so we will choose Windows Form Application. You can select any language you want according to your choice. May be it is VB or C#. Give it a name and move ahead by clicking ok. You can check it in screenshot given below. I have named it as SampleSQLReport.



Step 2:
After creating Windows Form Application we will get a form which will be completely blank. Now we will ask user to enter his name who wants to generate a report. For this we will need a label on which we will ask user to enter name, then a textbox in which user will enter their name, and last a button on clicking of which will generate a report. We can also increase form size by going into its properties and changing size of it. All these things are shown in screenshot below.



Step 3:
Now as we want to generate report we need to include a Microsoft ReportViewer. We can also use Crystal ReportViewer but here we will use Microsoft ReportViewer. We can get this from our toolbox which is on left side. In that we will get it from Reporting. So you can include Microsoft ReportViewer from there by dragging and dropping or by double clicking on it. You can see a report just below label, textbox etc. We can see all these things in screenshot below.



Step 4:
After this we have to add a file named .rdlc creating report. For adding this we need to add new item  Report. Name it. Here I have given its name as rptSample.rdlc. After adding it we get this in window as shown below.



Step 5:
Next thing we will do is that the textbox which we had asked on main application we will display that name on report too.. For that we need to put textbox on report too which will display name. For displaying name on this from main page textbox we need to add report parameters. We can do this by going into Report tab in above navigation bar. Report  Report Parameters. After you select this you will get a screen which is shown in below screenshot. In similar way you have to move ahead.



In above screenshot you can see we have added parameters. I have given its name as paraName. Similarly you can add your parameters.

In below screenshot we can see how to add parameters to textboxes so that its value gets displayed in textbox.



Step 6:
As we see above we have to select (Category) Parameters  (Item) All  (Parameter) parameter name which you have declared before in your code. Then after clicking ok you will get below screen.




Till what we have done, its code is given in below screenshot.



Till what we have done lets run it. So that we will get to know whether wat we did atleast till that point how its working. So after running you get this.



Step 7:
Now lets move ahead with database part as we want to display Student database in a tabular format in our report. So for that will add annother class in code which will include Student table format. We can see the code in below screenshot.



In above code DataTable Student is created with rows like rollno,name,div,marks and those columns are added in columns.

Step 8:
Now we have created DataTable but we need to add DataSource also to this. For that we have an option on left hand named data source. When you click on that we get an option Add New Data Source. After clicking on that we get screen as shown below and in that we have to choose object.





After selecting object click Next. After that you will get screen as shown below.



Step 9:
In aboce screenshot you can see options in which student option is included. It’s the same table name which we have created in our code. Select that and click Next. On left side you will see table and its columns which you had added in code. Now as we want to display this in tabular format we will dragand drop Table from toolbox on right side and we will get a table in our report page. Now we can see rows and columns in that table. We will select each column from left side and drag and drop it on particular column in the table. For eg. We will drag and drop rollno column and drag and drop it on 1st column of the table. Similarly we will do of remaining rows and this way we have added columns to our table. If you want to add more columns to the table you can right click on it and you will get option Insert column to right/left. So according to your needs you can add more columns to your table. Final output of this is shown in below screenshot.





Step 10:
Now we have to add some data in Student table. We will have to add this in code itself. For that we have to write code written in below screenshot marked in red.



Final Output:
After adding this data our work is finished. Now we will run our project and we will get output as shown in screenshot below.



So in this way you can create your reports.

Wednesday, February 3, 2010

JQuery in ASP.Net

Let’s see using JQuery in ASP.Net in this blog. We will see few examples for use of JQuery in ASP.Net.

1) Displaying an alert on Button click: -
Consider a button in our code.
<asp: Button ID =”Button” runat=”server” Text=”Show” />
Now once document is loaded we want to perform some action. We will tell browser to do that action using JQuery. For that we need to write a piece of code which is give below. Consider that we want to get an alert saying Welcome then we will write as following in code.
<script type=”text/javascript”>
$(document).ready(function() {
$(“#Button1”).click(function() {
alert(“Welcome!”); }) ;
});
</script>
Now let’s see details of the code in JQuery.
a) $ Sign - In JQuery, the most powerful symbol is the dollar sign. A $() function normally returns a set of objects followed by a chain of operations.
b) Document. Ready() – In JQuery, this is the most commonly used command. It gets executed only when page gets loaded. Usually code is placed inside this block.

2)Displaying datepicker: -
We can use datepicker in ASP.Net using JQuery. For that we have to write following code.

<script type=text/javascript>
$ (function () {
$ (“#datepicker”). datepicker ();
});
</script>
<div class=demo>
<p>Date: <input id=datepicker type=text></p>
</div>

In this code we have taken a textbox as an input in which we will get date. When we click on that textbox a calendar will be opened below attached to textbox. In that calendar we have to choose a date. If you don’t want to select date you can simply press Esc to escape. If date is selected then you will see that date in your textbox.

For including datepicker in your script, you need to download datepicker’s plugin for JQuery.

Monday, February 1, 2010

JQuery

JQuery is a lightweight open source JavaScript Library. It supports many browsers. It allows us to elegantly and efficiently traverse through HTML elements with minimum lines of code. In few days only JQuery has become very popular JavaScript Library. Few of its characteristics are: -
1) Light Weight
2) Cross browser compatibility
3) Simplicity

If any code is of 10 lines with traditional JavaScript, we can write in a single line using JQuery. Many people get confused between JavaScript and JQuery. Many think they are same. But it’s not! JavaScript is language whereas JQuery is a library which is written using JavaScript. Latest version of JQuery is 1.4.1. They provide two copies of JQuery –
1) Minified (23 kb zipped)
2) Uncompressed (157 kb)

Minified versions are used for production developments while uncompressed versions are used for debugging and reading. Out of these two, minified versions are best inspite of having large file size. You can download JQuery from here

There are many plugins available for JQuery which provide UI elements or special effects. Such plugins require very little JavaScript code but can do amazing things. Using JQuery is very simple, you should just simply add a like to the jQuery.js file in your html document.

We will see more on JQuery in next blogpost.

Friday, January 29, 2010

FILESTREAM in SQL Server 2008

In SQL Server many times our data type is not limited to only string and numbers. We need to store a large amount of data like documents, photos etc. in SQL Server table. SQL Server provides special data types for large volumes of data. They are known as Large object (LOB). Varbinary (MAX) is the data type that allows you to deal with large binary data. LOB type using this SQL Server Data Type is Binary Large Objects (BLOB).
FILESTREAM integrates the SQL Server Database Engine with an NTFS file system by storing BLOB data as files on the file system. Transact-SQL statements can insert, update, query, search, and back up FILESTREAM data. To improve the performance of Database engine, FILESTREAM caches file data using NT.

There are FILESTREAM filegroups which are used to store data. This filegroup contains file system directories instead of files. These directories are known as data containers. These data containers cannot be nested.

To save file in filestream we have to use FileUpload. It uploads the file and then saves it to Filestream file.

Byte [] buffer = new byte [ (int) FileUpload. FileContent. Length];
FileUpload .FileContent. Read (buffer, 0, buffer.Length);

GET_FILESTREAM_TRANSACTION_CONTEXT is also a newly added feature in SQL Server 2008 which returns current transaction context. To use files stored in Filestream field we have to use SqlFileStream. For that we need to include System. Data. SqlTypes.

SQL Server DELETE and TRUNCATE for ROW

I am currently working on a project, which requires to be synced with server database all the time, and there is lot of deletion which keeps happening, there are about 15,000+ records which gets deleted whenever synchronization is happening between server and client. I was performing DELETE statement to delete row from the table which was not required. Everything worked fine, the real problem started arrising when we were looking at the way database would act, we figured out that everytime we did deletion of 15,000+ rows, it will increase log file of database by 6.00MB. Which means within in a month database log file would increase upto 180MB, and 2190MB within in a year, and this is just regarding Deleting row.

I faced challange regarding how to make sure that the log file does not increase. While going through documentation, I found one keyword called TRUNCATE. When we used TRUNCATE keyword instead of DELETE, it worked perfectly fine, and log file was not increased, and we also found a good increase in performance.

Reason is that, when we use DELETE keyword it deletes row and also it keeps log of it in LOG file, but when we use TRUNCATE, it does not keep log of it, so nothing is recorded in LOG file, hence log file size does not increase. Which means that when we DELETE row(s) and we want to recover data back, we can use recover data back through log file, but when we use TRUNCATE keyword, we can not recover data back from log file.

But, here is the catch, if I use TRUNCATE keyword in TRANSACTION block, it allows us to recover data back, but there is no gurante of recovering data.

Sample Code:
BEGIN TRAN
SELECT * FROM MyTable
TRUNCATE TABLE MyTable
SELECT * FROM MyTable
ROLLBACK
SELECT * FROM MyTable

Thursday, January 28, 2010

Session Modes in ASP.Net

As I have mentioned in previous blog, there are 4 session modes: -
1) In-Proc Session Mode
2) State Server Mode
3) SQL Server Mode
4) Custom

We will see details of these states in this blog.

1) In-Proc Session Mode: -
This is default session mode in asp.net. In this mode session state is managed in process and if the process is recycled the state is lost. The main reason to use this mode inspite of state loss is ‘performance’. As the memory is read through process its performance increases. In web.config we have to mention Session mode and also we have to set the Timeout.

<system.Web>
<sessionState mode=”InProc” timeout=”30” />
</system.Web>

This Session TimeOut Setting keeps session alive for 30 minute. We can also adjust timeout in our code by writing

Session.TimeOut = 30

In-Proc mode is mainly useful for small websites and websites which have less number of users.

Advantages: -
1) It store Session data in memory object of current application domain. So accessing data is very fast and data is easily available.
2) Implementation is very easy.

DisAdvantages: -
1) If the process is run again, all data is lost.
2) Inspite of being fastest, more number of users affects performance.

2) StateServer Session Mode: -
This mode is also known as Out-proc session mode. It is independent to IIS and can also run on a separate server. It used as a Windows Service. It is managed by aspnet_state.exe. This server may run on the same system, but it can’t run inside main application domain. It has to run outside of that main application domain where your web application is running. Due to this feature even if process is restarted the session is alive.

By default”Startup Type" of ASP.NET state service is set to manual, we have to set it as "Automatic" startup type. By default this services listen TCP Port 42424, but we can change the port from registry editor. For State Server Setting we need have to specify the stateConnectionString. This will identify the system that is running state server. By default stateConnectionString used ip as 127.0.0.1 (localhost) and Port 42424.

<system.web>
<sessionState mode=”StateServer” stateConnectionString=”tcpip=127.0.0.1:42424” />
</system.web>

We can also set time to wait for the service to respond before cancelling the request. For doing that we need to add stateNetworkTimeout in above code. By default time is 10 seconds.

Advantages: -
1) Its keeps the data separate from IIS so, any Issue with IIS does not affect Session data.

Disadvantages: -
1) Process is slow.
2) State Server needs to be always running.

3) SQL Server Session Mode: -
This session mode provides us more secure and reliable Session management in asp.net. In this session mode, the Session data is serialized and stored in the SQL Server database. If we have to restart server very frequently, we can use SQL Server session mode. If we have to share sessions between two different applications, we can use SQL Server. In SQL server session mode we store data in SQL server so we need to specify database connection string in web.config. For doing this we can use sqlConnectionString attribute. The easiest way to configure SQL Server is using aspnet_regsql command.

To setup SQL Server we need to take help of two sql Script.
a) For Installing: InstallSqlState.sql
b) For Un-Installing: UninstallSQLState.sql

Advantages: -
1) Inspite of restarting IIS session data is not affected.
2) It is most reliable and secure mode.
3) It stores data centrally (i.e. in database).
4) It can be easily used from other application.

Disadvantages: -
1) Process is slow.
2) Here session data is handled in other server so SQL server should always be running.

4) Custom Session Mode: -
Custom session mode is the most interesting mode among all session modes. In
custom session mode we can we have full control on everything. We can even create session ID. For creating session ID we can even write our own algorithm. For creating session ID we need to implement ISessionIDManager. By using SessionStateStoreProviderBase class we can implement custom providers which store session data.

There are few methods which are called during implementation of Custom Session: -
a) Initialize: - We can set custom provider.
b) SetItemExpireCallback: - To set session time out.
c) Initialize request: - It is called on any request.
d) CreateNewStoreData: - Used to create new instance of SessionStateStoreData.

We need to configure our web.config like below,

<sessionState mode=”Custom” customProvider=”AccessProvider”>
<providers>
<add name=”AccessProvider” type=”CustomDataType” />
</providers>
</sessionState>

Advantages: -
1) We can use existing tables to store session data. When we have to use old databases this mode is more useful than SQL server mode.
2) It does not depend on IIS so even if we restart web server it does not affect session data.
3) We can create our own algorithm for generating session ID.

Disadvantages: -
1) Process is slow.
2) Being a low level task it needs to be handled carefully due to reason of security.

Monday, January 25, 2010

Session in ASP.Net

Consider a user visiting pages on an online shopping site. Now if that user has put 1 item in his cart and moved ahead 2 pay bill but suddenly he remembered that he wanted to order some other item too. So he goes back to previous page on which he has to add items to add that other item which he wanted to buy. But what he gets is the same page but the item he had selected is disappeared. Where did it go? It has got discarded. So he has to enter both items again. This is ok as he had added only 1 item but what if he would have already added 25 items? Just for adding 1 more item he had to type those previous 25 items again. Irritating? But a solution was given to this through a feature of ASP.Net. SESSION… Session is the thing in which we the previous requests are saved. So according to above example, the page on which 25 items were added will get saved in sessions so that even if he goes back his requests are retrieved. ASP.NET provides a solution for managing session information via the System.Web.SessionState namespace. This namespace describes a collection of classes used to enable storage of data specific to a single client within a Web application. Sessions can be used easily in ASP.NET with the Session object. For every client Session data store separately, means session data is stored as per client basis.
Basic Advantages: -
1) It helps to maintain user states and user data.
2) Implementation is easy.
3) Stores every client data separately.
4) It is secure.
Basic Disadvantages: -
1) It affects performance if number of users is large as session data is stored in server memory.
Let’s see how to store and retrieve values from sessions. In an ASP.NET page, the current session variables are exposed through the Session property of the Page object. We can interact with Session state with System.Web.SessionState.HttpSessionState class, because this provides built in Session Object with ASP.Net Pages.
Consider we have to store userId in session. Then we have to include following in our code: -
Session (“userId”) = txtuserId.Text
Similarly if we have to retrieve userId from session then we have to write: -
If Not Session (“userId”) Is Nothing Then
lbluserId.Text = “UserId is : “ & Session (“userId”)
End If

Each and every sessionId is identified by a unique Id which is known as SessionId. SessionId is created by Webserver when any page is requested by user. It is a 120 bit Id. The actual working between client, webserver and state provider is: -
1) Client requests for a page and wants to store information on it.
2) Webserver creates a secure SessionId and store data in state provider.
3) State provider stores client data separately.
4) When client wants to have same information again it again requests the same thing to webserver.
5) Server takes the SessionId and pass it to State Provider.
6) State provider sends data to Webserver based on SessionId.
In ASP.Net there are following session modes: -
1) InProc
2) StateServer
3) SQLServer
4) Custom
Details of these session modes will discuss in next blog.

In web.config, SessionState elements used for setting the configuration of session. Some of them are Mode, Timeout, StateConnectionString, Custom provider etc. Session Event is declared in global.asax. There are two types of Session Events: -
1) Session_Start
2) Session_End
When a new session initiate Session_Start event raised and Session_End event raised when a session is stopped.

Now as i mentioned in my previous blogs about cookies, in that i have mentioned that user's information is stored in cookies and in this blog I have written that user's information is stored in sessions.. Confused? Simple.. Cookies information is stored at client side in browser while Session information is stored at server side.. This is the difference between Cookies and Session.

Sunday, January 24, 2010

Writing and Reading Cookies in ASP.Net


In previous blog we learned about basics of cookies. Now let’s see how we can play with these cookies. We can write, use and retrieve these cookies. For working with cookies we need following 3 classes:-

1) HttpCookie: - It is used to create HTTP cookies.
2) HttpResponse: - This is a property which is used to create and save cookies on client machine.
3) HttpRequest: - This property is used to retrieve values of cookies.

Let’s see how to write and retrieve cookies: -

1) Write cookies: -
For writing cookies to visitor’s computer we need Response.Cookies command.
For example: -
If we want to write userId in cookie then we need to write in following way: -
Response.Cookies (“userId”).Value = 1
By above sentence we can save cookie with userId 1 to computer.
If we want to put expiry date then we need to write in following way: -
Response.Cookies (“userId”).Expires = DateTime.Now.AddDays (8)
By above sentence we can put expiry date after 8 days from now. So that after 8 days that particular cookie will be discarded i.e. its validity will get over in 8 days.

We can also write above code in following manner: -

Dim cookie As New HttpCookie (“userId”)
cookie.Value = 1
cookie.Expires = DateTime.Now.AddDays (8)
cookie. Domain = “abc.com”
Response.Cookies. Add (cookie)
From above code also we can save cookie.

2) Retrieve cookies: -
For retrieving cookies to visitor’s computer we need Request. Cookies command.
For example: -
Dim uId as Integer
uId = Request. Cookies (“userId”). Value

Now you must be thinking how exactly this cookie thing works. The process starts from web server. When you request for any page, web server sends few things like cookies, content etc. to browser. Then things like cookies get saved on your computer and the page gets displayed to you. So you can say cookies are a response from web server. So we use ‘Response’ for adding cookies. Similarly we use ‘Request’ for retrieving cookies as browser is requesting for cookies to web server.

Cookies in ASP.Net

Cookies are the things used to store users’ information. For example if we want to keep a track of userIds of the visitors who have visited any site so we can get it through cookies. We can store these all things in cookies from where we can retrieve it back. Let’s take a very simple example... When you login into your any account they ask you as “Remember password” etc… What is this? It’s nothing but cookies. They store your information in cookies of course in encrypted format so that no one can edit it. Using these cookies they can retrieve your password again and again based on your userId or username. Cookies are dependent on websites and not on any particular page. Cookies are exchanged between browser and server.

Most browsers support cookies of up to 4096 bytes. Browsers also impose limitations on how many cookies your site can store on the user's computer. Most browsers allow only 20 cookies per site; if you try to store more, the oldest cookies are discarded. Some browsers also put an absolute limit, usually 300, on the number of cookies they will accept from all sites combined.

Cookies are created by browsers and they store the cookies sent by websites. If user doesn’t want to store the cookie, user can disable cookies. Once user disables cookies, cookies won’t get stored even if website sends it to the browsers. Way to delete all the Cookies is: - Open Internet Explorer and select the menu "Tools > Internet Options", Press the button "Delete Cookies". This will delete all cookie files from your computer.

Later we will check how to write and read a cookie..