In this blog you will find ASP.NET 3.5 articles and some code samples. These code samples are created by me and should be working. Thanks for visiting my blog! Happy Dot Netting

Tuesday, November 11, 2008

Session Object - Maintaining State in ASP.NET 3.5

Unlike cookies, Session state has no size limitations. You can store any object in Session state

Adding a new item named session state that has value Hello
Session[“message”] = “Hello”;

When you use Session state, a session cookie named ASP.NET_SessionId is added to your browser automatically. This cookie contains a unique identifier. It is used to track you as
you move from page to page.

When you add items to the Session object, the items are stored on the web server and not
the web browser. The ASP.NET_SessionId cookie is used to associate the correct data with
the correct user.

By default, if cookies are disabled, Session state does not work. You don’t receive an error,
but items that you add to Session state aren’t available when you attempt to retrieve them

By default, the ASP.NET Framework assumes that a user has left the website when the user
has not requested a page for more than 20 minutes. At that point, any data stored in
Session state for the user is discarded.

The HttpSessionState class supports the following properties (this is not a complete list):

CookieMode—Enables you to specify whether cookieless sessions are enabled.
Count—Enables you to retrieve the number of items in Session state.
IsCookieless—Enables you to determine whether cookieless sessions are enabled.
IsNewSession—Enables you to determine whether a new user session was created with the current request.
IsReadOnly—Enables you to determine whether the Session state is read-only.
Keys—Enables you to retrieve a list of item names stored in Session state.
Mode—Enables you to determine the current Session state store provider. Possible values are Custom, InProc, Off, SqlServer, and StateServer.
SessionID—Enables you to retrieve the unique session identifier.
Timeout—Enables you to specify the amount of time in minutes before the web server assumes that the user has left and discards the session. The maximum value is 525,600 (1 year).

The HttpSessionState object also supports the following methods:
Abandon—Enables you to end a user session.
Clear—Enables you to clear all items from Session state.
Remove—Enables you to remove a particular item from Session state.

Handling Session Events

There are two events related to Session state that you can handle in the Global.asax file:
Session Start Event: is raised whenever a new user session begins
Session End Event:  is raised when a session ends. A session comes to an end
when it times out because of user inactivity or when it is explicitly ended with the
Session.Abandon() method.

In code below The Global.asax file is used to track the number of active sessions.
Whenever a new session begins, the Session Start event is raised and the SessionCount
variable is incremented by one. When a session ends, the Session End event is raised and
the SessionCount variable is decremented by one.

<%@ Application Language=”C#” %>
<script runat=”server”>
void Application_Start(object sender, EventArgs e)
{
Application[“SessionCount”] = 0;
}
void Session_Start(object sender, EventArgs e)
{
Application.Lock();
int count = (int)Application[“SessionCount”];
Application[“SessionCount”] = count + 1;
Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{
Application.Lock();
int count = (int)Application[“SessionCount”];
Application[“SessionCount”] = count - 1;
Application.UnLock();
}
</script>

The SessionCount variable is stored in the Application state, which contains items that are
shared among all users of a web application. Notice that the Application object is locked
before it is modified. You must lock and unlock the Application object because multiple
users could potentially access the same item in Application state at the same time.

Controlling When session State times out

You can specify the Session timeout in the web configuration file or you can set the
Session timeout programmatically

<system.web>
<sessionState timeout=”60” />
</system.web>

Using Cookieless Session State

You enable cookieless sessions by modifying the sessionState element in the web configuration file. The sessionState element includes a cookieless attribute that accepts the following values:

AutoDetect—The Session ID is stored in a cookie when a browser has cookies enabled. Otherwise, the cookie is added to the URL.
UseCookies—The Session ID is always stored in a cookie (the default value)
UseDeviceProfile—The Session ID is stored in a cookie when a browser supports cookies. Otherwise, the cookie is added to the URL.
UseUri—The Session ID is always added to the URL.


<system.web>
<sessionState cookieless=”AutoDetect” regenerateExpiredSessionId=”true” />
</system.web>


Note: When regenerateExpiredSessionId is enabled and a session times out, the Session ID in the URL is regenerated when a person requests the page.

Thursday, November 6, 2008

Cookie - Add, Delete, List

Following two images shows how to add / delete / retrieve from cookie in ASP.NET 3.5. 


Friday, October 24, 2008

XML Handling in ASP.NET 3.5


This is a code sample to get the elements from XML file. This XML file should be stored in website directory as it is mapped. 

      
 Dim reader As New XmlTextReader(Server.MapPath("SystemSettings.xml"))
        reader.Read()
        reader.ReadStartElement("Topelement")
        reader.ReadStartElement("Element1")
        EmailToAddress = reader.ReadString
        reader.ReadEndElement()
        reader.ReadStartElement("Element2")
        SwitchSystemBackInMintues = reader.ReadString
        reader.ReadEndElement()


SystemSettings.xml looks like this


Wednesday, October 22, 2008

Cookies - Maintaining State in ASP.NET 3.5


Developers who are new to programming for the web always have difficulty understanding the problem of maintaining state. The HTTP protocol, the fundamental protocol of the World Wide Web, is a stateless protocol. What this means is that from a web server’s perspective, every request is from a new user. The HTTP protocol does not provide you with any method of determining whether any two requests are made by the same person.
A cookie is nothing more than a little bit of text. You can store only string values when using a cookie. You actually can create two types of cookies: session cookies and persistent cookies. A Session cookie exists only in memory. If a user closes the web browser, the session cookie disappears forever.A persistent cookie, on the other hand, can last for months or even years.

Cookie Security Restrictions
All cookies are domain-relative. If the Amazon website sets a cookie, then the Barnes and Noble website cannot read the cookie. When a browser creates a cookie, the browser records the domain associated with the cookie and doesn’t send the cookie to another domain.
The other important restriction that browsers place on cookies is a restriction on size. A single domain cannot store more than 4096 bytes. This size restriction encompasses the size of both the cookie names and the cookie values.
Finally, most browsers restrict the number of cookies that can be set by a single domain to no more than 20 cookies (but not Internet Explorer). If you attempt to set more than 20 cookies, the oldest cookies are automatically deleted.

Creating Cookies
You create a new cookie by adding a cookie to the Response.Cookies collection.

Protected void Button_Click(object sender, EventArgs e)
{
Response.Cookies[“Message”].Value = txtCookieValue.Text;
}
Creates a new session cookie named Message

Response.Cookies[“counter”].Expires = DateTime.Now.AddYears(2);
When you set a particular expiration date for a cookie, the cookie is stored as a persistent cookie.

Reading Cookies
You use the Response.Cookies collection to create and modify cookies. You use the Request.Cookies collection to retrieve a cookie’s value.
lblCookieValue.Text = Request.Cookies[“message”].Value;

Setting Cookie Properties
Cookies are represented with the HttpCookie class. When you create or read a cookie, you can use any of the properties of this class:

. Domain—Enables you to specify the domain associated with the cookie. The default value is the current domain.
. Expires—Enables you to create a persistent cookie by specifying an expiration date.
. HasKeys—Enables you to determine whether a cookie is a multivalued cookie.
. HttpOnly—Enables you to prevent a cookie from being accessed by JavaScript.
. Name—Enables you to specify a name for a cookie.
. Path—Enables you to specify the path associated with a cookie. The default value is /.
. Secure—Enables you to require a cookie to be transmitted across a Secure Sockets Layer (SSL) connection.
. Value—Enables you to get or set a cookie value.
. Values—Enables you to get or set a particular value when working with a multivalued cookie

Deleting Cookies
The method for deleting cookies is not intuitive. To delete an existing cookie, you must set its expiration date to a date in the past.
Response.Cookies[txtCookieName.Text].Expires = DateTime.Now.AddDays(-1);

Working with Multivalued Cookies
According to the cookie specifications, browsers should not store more than 20 cookies from a single domain. You can work around this limitation by creating multivalued cookies.A multivalued cookie is a single cookie that contains subkeys. You can create as many subkeys as you need.
Response.Cookies[“preferences”][“firstName”] = txtFirstName.Text;
Response.Cookies[“preferences”][“lastName”] = txtLastName.Text;

You can use the HttpCookie.HasKeys property to detect whether a cookie is a normal
cookie or a multivalued cookie.

Tuesday, September 23, 2008

Data bound Controls

You use DataBound controls to generate your application’s user interface for working with data. The dataBound controls can be used to display and edit database data, XML data, or just about any other type of data you can imagine. There are three main types of DataBound controls: list controls, tabular DataBound controls, and hierarchical DataBound controls.

Working with List Controls
List controls are used to display simple option lists. The ASP.NET 3.5 Framework includes the following five List controls:

BulletedList— displays a bulleted list of items. Each item can be displayed as text, a link button, or a hyperlink.
CheckBoxList—displays a list of check boxes. Multiple check boxes in the list can be selected.
DropDownList—displays a drop-down list. Only one item in the drop-down list can be selected.
ListBox—displays a list box. You can configure this control so that only one item in the list can be selected or multiple items can be selected.
RadioButtonList—displays a list of radio buttons. Only one radio button can be selected.

Working with Tabular DataBound Controls
The tabular DataBound controls are the main set of controls that you use when working with database data. These controls enable you to display and, in some cases, modify data retrieved from a database or other type of data source.
There are six tabular DataBound controls. These controls can be divided into two types: Those that display multiple data items at a time and those that display a single data item at a time.
First, you can use any of the following controls to display a set of data items:
 
GridView—Displays a set of data items in an HTML table. For example, you can use the GridView control to display all the records contained in the Movies database table. This control enables you to display, sort, page, select, and edit data.
DataList—Displays a set of data items in an HTML table. Unlike the GridView control, more than one data item can be displayed in a single row.
Repeater—Displays a set of data items using a template. Unlike the GridView and DataList controls, a Repeater control does not automatically render an HTML table.
ListView—Displays a set of data items using a template. Unlike the Repeater control, the ListView control supports sorting, paging, and editing database data. You can use either of the following two controls to display a single data item at a time:
DetailsView—displays a single data item in an HTML table. For example, you can use the DetailsView control to display a single record from the Movies database table. This control enables you to display, page, edit, and add data.
FormView—Uses a template to display a single data item. Unlike the DetailsView, a FormView enables you to layout a form by using templates.

Working with Hierarchical DataBound Controls
A hierarchical DataBound control can be used to display nested data items. For example, you can use hierarchical DataBound controls to display the folder and page structure of your website, the contents of an XML file, or a set of master/detail database records. The ASP.NET 3.5 Framework includes two hierarchical DataBound controls:

Menu—Displays data items in a static or dynamic menu.
TreeView—Displays data items in a tree.

Using Data Source control
You bind a DataBound control to a DataSource control. A DataSource control is used to represent a particular type of data. The ASP.NET 3.5 Framework includes the following six DataSource controls:

SqlDataSource—Represents data retrieved from a SQL relational database, including Microsoft SQL  server, Oracle, or DB2.
LinqDataSource—Represents a LINQ to SQL query.
AccessDataSource—Represents data retrieved from a Microsoft Access database.
ObjectDataSource—Represents data retrieved from a business object.
XmlDataSource—Represents data retrieved from an XML document.
siteMapDataSource—Represents data retrieved from a Site Map Provider. A Site Map Provider represents the page and folder structure of a website.

The ASP.NET Framework contains two basic types of DataSource controls. The SqlDataSource, AccessDataSource, LinqDataSource, and ObjectDataSource controls all derive from the base DataSourceControl class. These controls can be used to represent tabular data. The XmlDataSource and SiteMapDataSource controls, on the other hand, derive from the base HierarchicalDataSourceControl control. These two controls can be used to represent both tabular and hierarchical data.

Programmatic data binding
Every DataBound control has a DataSource property and a DataBind() method. By using this property and method, you can programmatically associate a DataBound control with a data source.

Understanding Templates and DataBinding Expressions
Every DataBound control included in the ASP.NET 3.5 Framework supports templates with the sole exception of the TreeView control. You can use a template to format the layout and appearance of each of the data items that a DataBound control displays
A DataBinding expression is a special type of expression that is not evaluated until runtime. You mark a Databinding expression in a page by wrapping the expression in opening brackets.

< %# Eval(“Title”) %  >
< %# Eval(“Director”) % >

Thursday, September 11, 2008

SQLDataSource Control


1. The SqlDataSource control is built on top of ADO.NET. Under the covers, the SqlDataSource uses ADO.NET objectssuch as the DataSet, DataReader, and Command objects.

2. The SqlDataSource control is not an appropriate control to use when building more complicated multi-tier applications. The SqlDataSource control forces you to mix your data access layer with your user interface layer. If you want to build a more cleanly architected multi-tier application, then you should use the ObjectDataSource controlto represent your database data.

3. Accessing through connection String  
asp:SqlDataSource id="srcMovies" SelectCommand="SELECT * FROM Movies"  ConnectionString="" Runat="server" /
The expression is used to represent the connection string.

4. The SqlDataSource control can represent the data that it retrieves in two different ways. It can represent the data using either an ADO.NET DataSet or an ADO.NET DataReader.The advantage of using a DataReader is that it offers significantly better performance than the DataSet object.

5. Handling SQL Command Execution Errors

Whenever you build a software application you need to plan for failure. Databases go down, users enter unexpected values in form fields, and networks get clogged. It is miraculous that the Internet works at all. You can handle errors thrown by the SqlDataSource control by handling any or all of the following four events:

Deleted—Happens immediately after the SqlDataSource executes its delete command.
Inserted—Happens immediately after the SqlDataSource executes its insert command.
Selected—Happens immediately after the SqlDataSource executes its select command.
Updated—Happens immediately after the SqlDataSource executes its delete command.


protected void srcMovies_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
if (e.Exception != null)
{
lblError.Text = e.Exception.Message;
e.ExceptionHandled = true;
}
}

6. Canceling Command Execution

You can cancel SqlDataSource commands when some criterion is not met. For example, you might want to validate the parameters that you are using with the command before executing the command. You can cancel a command by handling any of the following events exposed by the SqlDataSource control:

Deleting—Happens immediately before the SqlDataSource executes its delete command.
Filtering—Happens immediately before the SqlDataSource filters its data.
Inserting—Happens immediately before the SqlDataSource executes its insert command.
Selecting—Happens immediately before the SqlDataSource executes its select command.
Updating—Happens immediately before the SqlDataSource executes its delete command.

Tuesday, July 22, 2008

RadioButtonList control - Array binding

Script that builds the list and binds the values in the list to the RadioButtonList control

Sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New ArrayList
  mycountries.Add("Norway")
  mycountries.Add("Sweden")
  mycountries.Add("France")
  mycountries.Add("Italy")
  mycountries.TrimToSize()
  mycountries.Sort()
  rb.DataSource=mycountries
  rb.DataBind()
end if
end sub


In ASPX page add a radio control and see if properties are as mentioned below
asp:RadioButtonList id="rb" runat="server" 

The Page.IsPostBack Property

The Page_Load subroutine runs EVERY time the page is loaded. If you want to execute the code in the Page_Load subroutine only the FIRST time the page is loaded, you can use the Page.IsPostBack property. If the Page.IsPostBack property is false, the page is loaded for the first time, if it is true, the page is posted back to the server (i.e. from a button click on a form):

Sub Page_Load
if Not Page.IsPostBack then
  lbl1.Text="The date and time is " & now()
end if
End Sub

Friday, July 18, 2008

Set SQL Password Policy OFF for set of users at once

 

Declare @MinUID as integer

-- Query ‘select * from sysusers’ and choose the minimum UID from where you would like to set password policy off

select @MinUID = 4

Declare @MaxUID as integer

-- Choose the maximum UID up to where you would like to set password policy off

select @MaxUID= 16384

declare @NextLoginName as varchar(30)

declare @strQuery as varchar(50)

 

DECLARE Login_name CURSOR FOR

select name from sysusers where   uid > @MinUID and uid < @MAxUID order by name

 

open login_name

 

fetch next from login_name into @NextLoginName

While @@fetch_status = 0

      Begin

            --print @NextLoginName

            set @strquery = 'alter login ' +  @NextLoginName + ' with check_policy = off'

            exec (@strquery )

      fetch next from login_name into @NextLoginName

      end

 

close login_name

deallocate login_name

Thursday, July 17, 2008

SQL SERVER 2005 - Fixed Server Roles

Fixed server role Server-level permission

1.       bulkadmin

Members of the bulkadmin fixed server role can run the BULK INSERT statement.

2.       dbcreator

Members of the dbcreator fixed server role can create databases, and can alter and restore their own databases.

3.       diskadmin

The diskadmin fixed server role is used for managing disk files.

4.       processadmin

Members of the processadmin fixed server role can terminate processes that are running in an instance of SQL Server.

5.       securityadmin

Members of the securityadmin fixed server role manage logins and their properties. They can GRANT, DENY, and REVOKE server-level permissions. They can also GRANT, DENY, and REVOKE database-level permissions. Additionally, they can reset passwords for SQL Server logins.

6.       serveradmin

Members of the serveradmin fixed server role can change server-wide configuration options and shut down the server.

7.       setupadmin

Members of the setupadmin fixed server role can add and remove linked servers, and also execute some system stored procedures.

8.       sysadmin

Members of the sysadmin fixed server role can perform any activity in the server. By default, all members of the Windows BUILTIN\Administrators group, the local administrator's group, are members of the sysadmin fixed server role.

Monday, July 14, 2008

Create SQL 2000 Database Login and User By a script

/****** Add Login [Newuserid]    ******/

EXEC master.dbo.sp_addlogin @loginame = N'Newuserid', @passwd = 'Newuserid', @defdb = N'master', @deflanguage = N'us_english'

 

USE [DBname]

GO

/****** Grant User [Newuserid]     ******/

 

EXEC dbo.sp_grantdbaccess @loginame = N'Newuserid', @name_in_db = N'Newuserid'

 

USE [DBname]

GO

/******Add DatabaseRole [db_NewuseridRole]    ******/

EXEC dbo.sp_addrole @rolename = N'db_NewuseridRole', @ownername = N'dbo'

Exec sp_addrolemember  @rolename =  'db_NewuseridRole' ,

     @membername = 'Newuserid'

 

/****** Grant Permissions [db_NewuseridRole]    ******/

GRANT EXECUTE ON [dbo].PurgeAPLExtract TO [db_NewuseridRole]

Add new DSN

You can add new DSN by utilizing the script I posted earlier. You need to save following entries from Registry settings [HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources] [HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\] [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo]

DSN update through a script

The code available below might help you tweak the DSN update through a script. Do the following steps

  1. Save the new updated DSN settings
  2. Create a BAT file. Example mentioned below
  3. Run the BAT file to update the registry settings

 

This comes in handy when you are looking to updates many user desktops.

 

Here is the example:

 

cls

echo off

cls

 

- Create directory for backup

if not exist c:\temp\DSN\nul md c:\temp\DSN

 

- Backup host file

if not exist c:\temp\DSN\hosts copy %windir%\system32\drivers\etc\hosts c:\temp\DSN\hosts

 

- Backup registry settings

if not exist c:\temp\DSN\DSN_restore.reg regedit /e c:\temp\DSN\DSN_restore.reg "HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI"

 

- Copy new Host file

Copy C:\NewRegFiles\hosts %windir%\system32\drivers\etc\hosts

 

- Add registry settings

regedit.exe /s C:\NewRegFiles\Newregistrysettings.reg

Process files on disk from ASP.NET code

This function would provide you an idea about how to process files on disk from ASP.NET code. It is a function which is quering some network location to get the number of files processed today.

Thanks

 

   Protected Function GetTotalTransactionsfromBackupLocation() As Integer

        Dim objShell = CreateObject("Shell.Application")

        Dim objFSO = CreateObject("Scripting.FileSystemObject")

        Dim objItem, objFile

        -- Set network location you would like to poll

        Dim objFolder = objShell.NameSpace("\\servername\location")

        Dim colItems = objFolder.Items

        Dim NumberOfFilesProcessed = 0

        For Each objItem In colItems

            objFile = objFSO.GetFile(objItem.Path)

            If Day(objItem.ModifyDate) = Day(Today()) Then

                NumberOfPDFProcessed = NumberOfPDFProcessed + 1

            End If

        Next

        Return NumberOfFilesProcessed

    End Function

How to get connection string from web.config file

Following function can get the connection string from web.config file. Please let me know your comments if it helped and saved your time. Thanks


    Public Shared Function GetConnectionString() As String

        Dim settings As ConnectionStringSettingsCollection = ConfigurationManager.ConnectionStrings

        ' Return No connection string found if there is nothing found

        Dim Constr = "No ConnectionString Found"

        If Not settings Is Nothing Then

            For Each cs As ConnectionStringSettings In settings

                If cs.Name = "XYZConnectionString" Then

                    Constr = cs.ConnectionString

                    Exit For

                End If

            Next

        End If

        Return Constr

    End Function

Thursday, July 3, 2008

How to execute SQL Query from ASP.NET page

Following example would show how to execute SQL Query from ASP.NET. You may create a function using code below and it anywhere in program.

Please let me know your comments on this. Thanks

Here is the example:  

Imports System

Imports System.Data

Imports System.Data.SqlClient

Imports System.Configuration

 -- Get connection string from web.config file. Please see my next post to see how to get connection string from web.config.

 Dim connectionString As String = GetConnectionString1()

 

        Dim queryString As String

         -- Set query here

        queryString = "Select * from application_users"

         -- Declare connection       

        Using connection As New SqlConnection(connectionString)

            Dim command As SqlCommand = connection.CreateCommand()

            command.CommandText = queryString

            Try

                connection.Open()

                 -- Declare data reader to read the result set    

                Dim dataReader As SqlDataReader = command.ExecuteReader()

                Do While dataReader.Read()

                    msgbox dataReader(0)

                    --msgbox dataReader(1)

                Loop

                dataReader.Close()

 

            Catch ex As Exception

                Console.WriteLine(ex.Message)

            End Try

        End Using