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

Thursday, August 27, 2009

Image loading and saving in database in WPF using VB :-

WPF image uploading :-

In many forms we need to upload an image..In WPF we have imagebox in which we can upload an image..For that code is :-

<Button Height="23" HorizontalAlignment="Right" Margin="0,100,35,0" Name="btnBrowse" VerticalAlignment="Top" Width="75">Browse</Button>

Above is the code for button which will be used for browsing file path of that image.

Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnBrowse.Click
Dim ofd As New OpenFileDialog
If ofd.ShowDialog() Then
Dim fs As New FileStream(ofd.FileName, FileMode.Open)
Dim imgs As New ImageSourceConverter
Dim dat(fs.Length) As Byte
fs.Read(dat, 0, fs.Length)
fs.Close()
imgcompImage.SetValue(Image.SourceProperty, imgs.ConvertFromString(ofd.FileName.ToString()))
End If
End Sub

This code is the code which uploads image and saves it in database..For using few functions like ShowDialog() etc we need to import few namespaces as given below :-

Imports System.Windows.Media.Animation
Imports System.Windows.Navigation
Imports Microsoft.Win32
Imports System.Windows.Controls.Image
Imports System.Windows.Media.Imaging
Imports System.IO.MemoryStream

OpenFileDialog is to open a file while ShowDialog shows us the file path..SetValue function shows us the image on our page..To store image in database we read image in bytes as shown above in code and then store it in database..So now you can use image uploader in ur page..

Tuesday, August 25, 2009

WPF Toolkit Datagrid

DataGrid is part of User Interface.It is used for displaying data in tabular format.It provides sorting and editing functions. For using DataGrid in WPF

toolkit you have to first install WPF Toolkit. This Toolkit is open source. Datagrid is used for providing functions like create,update,delete,read on any data

source.Now lets start building our own WPF Application in which we will use a Datagrid....

For installing toolkit basic requirement is .Net Framework 3.5 SP1..If you have this installed on your machine you can install WPF Toolkit..For that you will

have to download WPF Toolkit (source or Binaries). You will get this here http://wpf.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=29117
When downloading is done run WPFToolkit.msi to install the WPFToolkit.dll and WPF Toolkit design time binaries to your Program Files folder.

When you start coding basic things which you have to do are :

1) Reference WPFToolkit.dll in your project
2) Import "Microsoft.Windows.Controls" in ur vb code.
3) In your XAML file you will have to add a new xmlns "http://schemas.microsoft.com/wpf/2008/toolkit" at the top of XAML file. Example showing this will be given

below..

Lets take a simple example of Categories table which include columns catId (Category Id), catName (Category Name), catDesc (Category Description), parcatId

(Parent Category Id) in database..From this catId is integer,catName and catDesc is string while parcatId is also integer in database but while displaying for user we

want to display it in dropdown (combobox for datagrid here) which shows catName in list but gets saved as integer in database..So lets start coding...


<Page x:Class="pgCategory"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="509" Height="409"

<Grid>
</Grid>
</Page>

This is the basic part generated when you open an XAML page..

xmlns:dd="http://schemas.microsoft.com/wpf/2008/toolkit"
xmlns:dg="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"

These are two important things of adding references like that of toolkit without which you cant include Datagrid in your form..

Now lets see datagrid part..

<Grid.Resources>
<ObjectDataProvider x:Key="categoryDataProvider" ObjectType="{x:Type local:Categories}" MethodName="GetCategories"/>
</Grid.Resources>

Here ObjectDataProvider defines an instance of the above class as our data source which includes objecttype and methodname through which it gives data..

<dg:DataGrid AlternatingRowBackground="AliceBlue"
AutoGenerateColumns="False"
CanUserAddRows="True"
CanUserDeleteRows="True"
Height="151"
IsReadOnly="False"
ItemsSource="{Binding Path=.}"
MaxColumnWidth="500"
MinColumnWidth="50"
Name="pgCategoryDG"
RowBackground="White"
RowDetailsVisibilityMode="VisibleWhenSelected"
RowHeaderWidth="25"
SelectionUnit="FullRow"
VerticalAlignment="Bottom"
Loaded="pgCategoryDG_Loaded" MouseDoubleClick="pgCategoryDG_MouseDoubleClick">

<dg:DataGrid.Columns>
<dg:DataGridTextColumn x:Name="dgcatName" Header="Category Name" Width="100" Binding="{Binding catName}" IsReadOnly="False"/>
<dg:DataGridTextColumn x:Name="dgcatDesc" Header="Category Description" Width="125" Binding="{Binding catDesc}" IsReadOnly="false"/>
<dg:DataGridComboBoxColumn SelectedValueBinding="{Binding parcatId}" SelectedValuePath="parcatId" DisplayMemberPath="catName" ItemsSource="{Binding

Source={StaticResource categoryDataProvider}}"/>
</dg:DataGrid.Columns>
</dg:DataGrid>
<Button HorizontalAlignment="Left" Margin="165,148,0,0" Name="btnSave" Width="75" Height="23" VerticalAlignment="Top">Save</Button>

Here combobox is used for dropdown list in which parcatId is gonna be considered and catName wil be displayed..Many other properties of datagrid are mentioned

here above..Also there is a Save button which when clicked things will be saved in databse..Based on this XAML file is our vb code which is as follows :-

Imports System.Windows.Controls
Imports System.Windows.Data

Partial Public Class pgCategory

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSave.Click
Dim dtCategories As System.Data.DataTable = pgCategoryDG.DataContext
Dim dtDeleted As System.Data.DataTable
For Each r As System.Data.DataRow In dtCategories.Rows
If r.RowState = DataRowState.Modified Then
modGlobal.objInventoryService.UpdateCategories(r.Item(0), r.Item(1), r.Item(2), r.Item(3))
ElseIf r.RowState = DataRowState.Added Then
If IsDBNull(r.Item(1)) Then
MsgBox("Enter CatName!!!")
Else
If IsDBNull(r.Item(3)) Then
If IsDBNull(r.Item(2)) Then
modGlobal.objInventoryService.InsertCategory(r.Item(1), "")
Else
modGlobal.objInventoryService.InsertCategory(r.Item(1), r.Item(2))
End If
Else
If IsDBNull(r.Item(2)) Then
modGlobal.objInventoryService.InsertCategories(r.Item(1), "", r.Item(3))
Else
modGlobal.objInventoryService.InsertCategories(r.Item(1), r.Item(2), r.Item(3))
End If
End If
End If
End If
Next
dtDeleted = dtCategories.GetChanges(DataRowState.Deleted)
If Not dtDeleted Is Nothing Then
dtDeleted.RejectChanges()
For i As Integer = 0 To dtDeleted.Rows.Count - 1
modGlobal.objInventoryService.DeleteCategories(dtDeleted.Rows(i)(0))
Next
End If
dtCategories.AcceptChanges()
End Sub


Private Sub pgCategoryDG_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
Dim a As System.Data.DataSet
a = modGlobal.objInventoryService.RetriveCategories()
pgCategoryDG.DataContext = a.Tables.Item(0)
End Sub


Public Class Categories
Public Function GetCategories() As System.Data.DataView
Dim a As System.Data.DataSet
a = modGlobal.objInventoryService.RetriveCategories()
Return a.Tables.Item(0).DefaultView
End Function
End Class

Here we have created another class called Categories which we have used for ObjectDataProvider. When form loads to display all data from database in Datagrid

we have written function Loaded. In code of Save button we have written code for inserting,deleting and updating. In that we have checked each row whether its Modified

(Update), Added (Insert), Deleted (Delete)..Based on that rowstate we can call our functions.

So this is the whole code for creating a datagrid project..I hope it will help you all to create your own Datagrid projects..I will post more blogs on Datagrid soon..

Sunday, August 16, 2009

DEVCON Event :-

Biggest event in Pune DEVCON was held on 8-9th August in Pune..This event was held in COEP,Pune..Inspite of the destruction named Swine Flu event was successfull..2 days event had a very nice grip in lectures given by speakers like Amol Vaidya,Abhishek Kant,Dhaval Faria,Dr. Nitin Paranjpe, Mayur Tendulkar, Raj Chaudhary,Sanjay Vyas,Sarang Datye, Vikram Pendse, Vic Parmar and many more..Many topics like Silverlight3,JQuery,Azure etc were covered in this event..I was managing registration desk and goodies..All enjoyed sessions also were keen for all topics..All got lot of knowledge from all sessions..Despite of swine flu thing speaker came from across India like Mumbai, Hyderabad, Bengaluru, Pune.. and lot of thanks to audience as well..thats the true spirit of community!!! Special thanks to Mahesh Mitkari and all volunteers..

Thursday, July 23, 2009

DEVCON Event :-

The biggest event DEVCON is here once again in Pune..Its going to be held on 8-9 August 09..Industry experts speakers going to give sessions on interesting topics like .Net 4.0,Silverlight,Windows Azure,Visual Studio 2010 etc..Do not miss it :-) For FREE registration and other details visit site http://www.puneusergroup.org/events/devcon2009/

Tuesday, July 7, 2009

ADO.NET output parameter in VB

This is used to give a direction to output parameter. When we write a stored procedure and when we declare output parameter in it in which we have to store output. This output parameter we have to declare in code also. While adding this parameter in code we have to use ParameterDirection.Output.

Example : -

Stored Procedure : -

CREATE PROCEDURE [dbo].[USP_AuthenticateUsers]

@username nvarchar(255),
@password varbinary(MAX),
@userId int output,

AS
BEGIN

SET @userId=0

SELECT @userId=userId , @roleId=roleId FROM Users WHERE username=@username and [password]=@password
END


Code : -

Public Function AuthenticateUser(ByVal username As String, ByVal password As Byte(), ByVal userIPAddr As String) As structUserSession

Dim objCom As New System.Data.SqlClient.SqlCommand
objCom.CommandType = CommandType.StoredProcedure
objCom.CommandText = "USP_AuthenticateUsers"
objCom.Parameters.Add("userName", SqlDbType.NVarChar, 255).Value = username
objCom.Parameters.Add("password", SqlDbType.VarBinary, password.Length).Value = password
objCom.Parameters.Add("userId", SqlDbType.Int).Direction = ParameterDirection.Output

DB.ExecuteNonQuery(objCom)

Dim objStructUserSession As New structUserSession
objStructUserSession.userId = objCom.Parameters.Item("userId").Value

Return objStructUserSession

End Function

If Condition in SQL

If...Else statement is used to test a condition. If we have more than 1 condition we can use If...Else statement. We can also have nested If...Else statements also. We have nested If...Else statements when we have to include 1 or more If...Else statements in 1 If...Else statement. If...Else Statement in SQL is used in execution os Stored Procedures.

Syntax for simple If...Else statement is,

IF ( Condition )
BEGIN
Sql Statements
END
ELSE
BEGIN
Sql Statements
END

Syntax for nested If...Else statements is,

IF ( Condition )
BEGIN
Sql Statements
IF ( Condition )
BEGIN
Sql Statements
END
ELSE
BEGIN
Sql Statements
END
END

ELSE
BEGIN
Sql Statements
END


Example for simple If...Else statement is,

CREATE PROCEDURE [dbo].[USP_InsertUserSession]
@userId int,
@userSession nvarchar(255),
@userDate datetime,

AS
BEGIN
declare @tmpuserId int
SELECT @tmpuserId=userId from UsersSessions WHERE userId=@userId

if @tmpuserId > 0
begin
UPDATE UsersSessions SET userSession=@userSession, userDate=@userDate WHERE userId=@tmpuserId
end

else
begin
INSERT INTO UsersSessions(userId,userSession,userDate) VALUES (@userId,@userSession,@userDate)
end