Posted by: savagerider | October 14, 2007

security in ASP.NET

Focusing on the authentication and authorization in ASP.NET. There are several authentication methods, namely, Windows, forms and passport. Comparing these three authentication methods, windows is the most straightforward approach. And passport is the most expensive approach. Let’s focus the discussion on forms. With this authentication, we need to create a login page for authentication. Instead of putting checking on every content page if the user is authenticated. We make sure of the authentication and authorization in web.config.

we need to add the following codes in web.config.

<authentication mode=”Forms”>

<forms name=”.ASPXAUTH” loginUrl=”login.aspx”>

<credentials passwordFormat=”Clear”>

<user name =”test” password=”test”></user>

<user name =”Kelvin” password=”test”></user>

</credentials>

</forms>

</authentication>

loginUrl indicates the login page location. Credentials child element shows the authenticatic user id and password.

 Please note that if <authorization> is set to all users (*). Whatever inside <authentication> will not function.

For login.aspx

We can make use of the asp.net API to check the user credential and redirect him/her back to the original accessing page. We can add the following when user hit enter.

if (FormsAuthentication.Authenticate(TextBox1.Text,TextBox2.Text)){

FormsAuthentication.RedirectFromLoginPage(TextBox1.Text,false);}

We can also make sure of User.Identity.Name, to show the user name.

Posted by: savagerider | September 23, 2007

Navigating in ASP.NET pages

There are 3 ways for us to navigate in ASP.NET pages.

 1. Response.redirect(“yourWebPage.aspx”);

This is way of navigating to new page is not new to us. We could redirect the page from any webserver. There several limitations on this method:

a) Unable to pass VIEWSTATE / Session / Application session parameters to redirected page.

2. Server.Transfer(“yourWebPage.aspx”, isPreserveForm);

We could pass the parameters from originating page to destinated page if isPreserveForm is set to true. The viewstate field of the originating page will be added to the destinated page, this causes the response stream is different with only destinated page alone. In this case, we need to turn off the consistency checking (ViewStateMac) on viewstate.We will have limitation on using this method to redirect page from the same web server, this will limit the scalability of the application.

3. Server.Execute(“yourWebPage.aspx”,TextWriter);

Page B will return back to Page A (originating page) after execution. This inherited the limitation from Server.Transfer, where the page must be from the same web server. The result of Page B is stored in TextWriter if it is set in 2nd parameter.

StringWriter sw = new StringWriter();Server.Execute(“WebForm2.aspx”,sw);

TextBox2.Text = sw.ToString();

Posted by: savagerider | September 9, 2007

Managing State

HTTP protocol is a stateless protocol. Information is not maintained from one page to another page. In this case it is not possible to keep continuity of user information on website.

Server-state Management 

Store state information on server side which has higher security. 

1. Application State

State information is available to all users of the web application. It makes use of  HttpApplicationState class for application state. Generally, data that is common to all users and does not change often will stay on Application State.

Since more than one user is able to access and modify the Application data at the same time, it is necessary for us to have a mechanism to handle concurrent issues. We could use

Application.Lock(); // to lock the application data, prevent it from updating

Application["TestValue"] = 123 ;

Application.Unlock();// unlock it, allow other to update it.

2. Session State

Maintain the state information for each user of a specific session. It makes use of HttpSessionState class for each active Web Application session. Generally, sensitive data and short-lived variables are stored in session state. This is useful when session state is used in web farm / web garden configuration.

An unique sessionID (120 bits) is assigned to session for identification purpose. Default session timeout is 20 mins, it is configurable in web.config, <sessionState timeout=”10″ />

Session is used to access related property or method from Session state value. There are two ways to add new session data.

i. Session["variable1"] = value;

ii. Session.Add(“variable1″,value);

We can create an instance of HttpSessionState and assign the current  session to it.

HttpSessionState currentState ;

currentState = Session; // or Page.Session;

Cookieless Session

SessionID from active session is stored in cookie, If cookie is disable on client browser, sessionID is lost on every request since HTTP is a stateless protocol.

With <sessionState cookieless = “false”/> is set in web.config. We will keep the sessionID in the QueryString. You will expect the following url appearing in the browser.

http://localhost/sessionState/(o2ikbu45ih4b0e2mftef3myl)/WebForm1.aspx 

In this case, it is not possible to use absolute URL to link the page.  

 3. Database Server/ State Server

Maintain state information on database or state server which has fault tolerance but there is a performance trade-off.

These ways allow us to avoid get into in-process situation, where we could allow multiple server to access the state information instead of only one server storing and accessing the information.

We could either use stateServer or sqlServer database to store the state session data. With the following syntax in web.config.

< sessionState mode=”SQLServer” sqlConnectionString=”data source=SQLServerName Integrated security=true”/>

The above syntax is using SQL Server to store session data in database. After inidicating SQLServer is used in web.config, we need to install the ASPState database into SQL Server. We can achieve that by executing the following line under the directory of C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322InstallSqlState.sql is the script to create ASPState and tempdb.

Ensure that ASPNET account has the access to the StoredProcedure in database ASPState.

C:\> OSQL SQLServerName -E <InstallSqlState.sql

You will expect ASPState and tempdb database are created in the sql server.

Client-state Management

Store state information on client side which has lower security but much faster if compare to server state management. 

1. Cookies

There are 2 ways to store data into cookies.

1. using HttpCookieCollection

HttpCookie objCookie = new HttpCookie(“testWeb”);objCookie.Values.Add(“Name”,”John”);

objCookie.Expires = DateTime.Now.AddDays(1);

Response.Cookies.Add(objCookie);

2. using Response directly 

Response.Cookies["testweb"]["Name"] = “Peter”;

Regardless of which method you use, the result is the same. To retrieve the cookies value simply use the following syntax:

HttpCookie obj = Request.Cookies["testWeb"];

Label1.Text = obj.Values["Name"];

Temporary cookies (Default). This kind of cookies is removed when browser is shut down. 

Permanent cookies. This kind of cookies is stored on hard dish with the file name of username@domainname.txt. The max size is 4 KB only.

2. ViewState

This state information is stored on hidden field on rendered html page. For good performance it is better to turn it off if it is not necessary.

3. QueryString

Keep state information on the QueryString in URL.

Global.asax

This file is stored in virtual root of the web application, there is only one global.asax located in a web application.

There are three types of events in global.asax.

1. Request Event

Events are fired when a page is requested.

[Application_BeginRequest, Application_AuthenticateRequest, ..... ]

2. Response Event

Events are fired when response is sent to the server

[Application_PostRequestHandlerExecute, Application_ReleaseRequestState, Application_UpdateRequestCache, Application_EndRequest]

3. Conditional Event

Events may or may not be raised during the processing of a request.

[Application_Start, Application_End, Session_Start, Session_End, Application_Error]

Posted by: savagerider | September 2, 2007

Collection

Default collection in .net platform include:

1. ArrayList

When we do not know the number of item in an array, it is good if we can use ArrayList which allows us to add item freely. With Add(), it will increase the array size according. ToArray() to copy item on the ArrayList to Array.

2. Queue

FIFO implementation, there are a list of methods for different purposes. E.g.

Enqueue : add object into the Queue

Dequeue : return and remove object from the Queue

Peek : Return the 1st object from the Queue

and many more.

3. Stack

FILO implementation, this is similar to Queue with a list of methods for different purposes. E.g.

Push : Add an object to top of the stack

Pop : Return and remove an object from the top of the stack

These three collections implement IEnumerable and IEnumerator. Meaning, we could use foreach loop for these three collections

Posted by: savagerider | September 2, 2007

indexer

We can make use of indexer to group a collection of class or type together just like an array. First, we could make use of param keyword in the signature to cater for multiple input values. Then, we use indexer to access array like property item.


  static void Main(string[] args)
  {
  testIndexer test = new testIndexer("test", "test1", "test2", "test3", "test4");
  for (int i=0; i < test.getCollectionSize() ; i++)
  {
  Console.WriteLine("Value is {0}", test[i]);
  }
  Console.ReadKey();
  }
  }
public class testIndexer : testInter
  {
  string []testString = new string[255];
  int ctr = 0;
public testIndexer(params Object[] values)
  {
  foreach (string s in values)
  {
  testString[ctr++] = s;
  }
  }

public string this[int index]
  {
  set
  {
  testString[index] = value;
  }
  get
  {
  return testString[index];
  }
  }

public int getCollectionSize()
  {
  return ctr;
  }
  }

interface testInter
  {
  int getCollectionSize();

}

public string this[int index] make the stored array can be accessed like property item. With the param keyword in the constructor we could cater for multiple inputs. The format is like:

 param Type[] variableName

Collection without implementing IEnumerable and IEnumerator cannot be used in foreach case. We use IEnumerable to implement GetEnumerator which returns the instance of Enumeration.

Posted by: savagerider | September 2, 2007

Reference type VS Value type

The type values in c# is catogoried into reference type and value type. Value type is straight forward, it is just like normal variable value that we stored in the stack memory. However, compiler store reference type in the heap memory. When we create an instance of class, we have the following code:
Form f1;                        // Allocate the reference
f1 = new Form();                // Allocate the object 
f2 = f1; 

f1 and f2 are pointing to the same object which is Form. In this case, if we pass f1 into a method, a local of copy of f1 is created. The changes made on the local copy will affect f1, but it is not true for null case. It is because if we set null to the local copy, only the local copy is destroyed but not f1.

As mentioned, value type is stored in stack, the stack is popped when the variable is not in use anymore. Reference type is like a room that filled with objects, which reference to an object is provided. This reference can be located in stack or it could be another heap-object. In the above example, f1 is stored in stack while Form object is stored in heap. For the below case, the reference is another heap-object.


Font f = new Font("Arial",10);
f1.font = f;

f is another reference in heap,which is pointing to Font class object.

For value type variable, it is not possible to modify them in the method. Let’s consider the following code:

public void test(int x)
{
  x = 5 ;
  return;
}

It is not possible for us to modify variable x in the method.  However, with keyword ref, we are able to make the changes on variable x. It is because we pass the variable by reference.
public void test(ref int x)
{
  x = 5 ;
  return;
}

It is possible to use keyword out instead of ref. The main difference between them is that ref must be initialized before it is passed into the method.

Static Variable is shared across all objects in the same class.

Static Constructor will only be executed once, it takes no parameter and no access modifier (private/public). It will executed once and first before other constructor take place. e.g.

static ClassName()
{
//doSomething

}

Readonly: one time initialization, the value can only be initialized in constructor.

const : constant value that cannot be modified, implicitly static variable

sealed : class that cannot be inherited.

abstract : As the name implies, it only provide the overall view on the class. Meaning, there is no implementation for the method. It only defines the methodName and signature. This type of class cannot be instantiated. The abstract method must belong to abstract class.

The derived class that inherited this abstract class must override the abstract method and provide the implementation for it.

virtual  : This is similar to abstract which provide the derived class flexibility to modify the implementation for the virtual method. The only difference between virtual and abstract is that, for virtual case, the base class has implementation for the method whereas in abstract case, there is no implementation for the method provided. This is essential to implement polymorphism in C#, where we could have the different implementation for the same method name.

base : This refers to the base class in derived class. Since C# does not support multiple inheritance, it is not necessary to specify the name for the base class.

this : This keyword refers to the current object

new : This create a new method in derived class when the method name in both base class and derived class are the same. The method with new is not polymorphised.

interface : This provides the overall view on the method name and signature but no the detailed implementation for method. The syntax for interface does not contain access modifier (public / private), it is implicitly declared as public. The class that implement this interface do not need to add keyword override to the method that defined in interface.


interface Itest {
void test1();
void test2(int x);
}

The class that implement interface must provide implementation for all methods defined in the interface. It is possible to support more than one interface.

Interface cannot be instantiated. If A implements interface B, we could say A is B. Therefore, we could assign objA to objB. As a result, there are referring to the same reference type (A).

//interface B { ... }
//public class A : B
A objA = new A();
B objB = (B) objA;
//both objA and objB refer to reference type A.

If a class implements more than one interface and the method name is repeated in these interfaces. It is necessary to specify the interface name explicitly.

interface Istorage
  {
  void read();
  void write();
  }
interface Isave
  {
  void read();
  void write();
  }

public class Document : Istorage , Isave
  {
  public void read()
  {
  Console.WriteLine("Read method from istorage Document");
  }

void Isave.read()
  {
  Console.WriteLine("Read method from isave Document");
  }
  }

We need to specify the interface name without access modifier (public/ private) to define the implementation for read(). The first read method in this class refers to Istorage because istorage has the preceding position. Class is allowed to have multiple interface but this is not true for inheritance.

Posted by: savagerider | August 26, 2007

Creating User Control

To promote reusability of code and UI, we could create our own custom user control (.ascx).

User control can never request independently as asp.net page. It must use together with web form.

User control does not contain <html>, <body>, <form>. As these tags are needed for web form.

User control is neither custom server control nor web custom control.

Just like normal web form, which contains the code-behind page. In this case, user control makes use of “<@ control > ” tag to indicate the properties of it. This is similar to @ page in web form. Control tag does not support TRACE and ASPCompat !!!

<%@ Control Language=”c#” AutoEventWireup=”false” Codebehind=”WebUserControl1.ascx.cs” Inherits=”WebApplication1.WebUserControl1″> 

User control normally used as headers, navigation bars and repeating blocks of code.

User control uses its own namespace, this ensures no conflict on the variables and methods. It has its own postBack and control component.

User control can be written in different language from the hosting page.

To use user control in hosting page. Firstly, we need the following code on the top of .aspx

<%@ Register TagPrefix=”uc1″ TagName=”WebUserControl1″ Src=”WebUserControl1.ascx” %>

TagPrefix is the unique namespace

TagName is the unique name for the user control

Src is the file name of the user control

We add the user control with the following code:

<uc1:webusercontrol1 id=”WebUserControl11″ runat=”server”> 

 uc1 is the tagPrefix, webusercontrol1 is the tagName, id is used for behind-code.

To interact with the user control in behind-code, user control should expose control property on the user control page to hosting page. With this, the hosting page can access to the user control. Adding the following code to create a user control object [tagName].

protected WebUserControl1 WebUserControl11;

WebUserControl11.XXXX can access to the user control elements.

Two ways to create User Controls :

1. Create New User controls using visual studio .NET

2. Convert asp.net page to user controls (.ascx)

Posted by: savagerider | August 26, 2007

Debug Web Form

There are two ways to debug web form on asp.net page.

1. Debug object

2. Trace object

For debug object, it requires to compile the code in debug mode with namespace System.Diagnostics. Debug object will not function if it is not compiled in debug mode.

For Trace object, you are able to disable it by configuring web.config file. This can avoid the efforts to remove all trace objects on production server.

Trace object can be enabled in two levels:

1. Page level

2. Application level

For Page level, we could do it on Page attribute in .aspx with Trace=”true” ,the trace message can display on the page.

For Application level,  we could do it on web.config file. This will enable the trace on every page in the application. The trace message can be displayed on the page or memory. You will see the following code on web.config file.

<configuration><system.web>
    <trace enabled =”true” pageOutput=”true” localOnly=”true”/>
</system.web></configuration>

attribute pageOutput indicates if there is any output shown on the page. If it is false, the trace is kept in the memory, it is required to use http://servername / projName / trace.axd to view the trace information in the memory.This will create a security risks as the trace information is very sensitive to an application. It is possible to turn off the trace in memory with the following code in machine.config in WIN \ Microsoft.NET\Framework\version No.\Config

 <httpHandlers> <add verb=”*” path = ” ” type = ” …….. > </httpHandlers>

The default value for path is trace.axd.

attribute localOnly indicates if the trace is shown on the local computer instead of the all the client desktop.

For both cases, we can use Trace.Write and Trace.Warn to display trace information. Warn method will display message in red. These 2 methods have the following format:

Trace.Write(“Category”,”Msg”);

Trace result is shown at the bottom of the page, which consists of the following information:

1. Request Details
2. Trace Information
3. Control Tree
4. Cookies Collection
5. Headers Collection
6. Form Collection
7. Server Variables

The priority of enabling trace information is from page (high) to Application (low). If page-level trace is enabled, regarding of whether application-level trace is enabled, the trace information is shown.

Trace into a Component

It is possible to disable the trace on page level, but enable it on a desired component. With the following steps:

1. Use System.Web namespace

2. Turn on the trace on a component. HttpContext.Current.Trace.IsEnabled = true,

3. Write something, HttpContext.Current.Trace.Write(“Category”,”msg”);

When trace is enabled on a component, trace is shown on any page that access to the components, even if trace is disabled for that page.

 If trace on a component is ON,trace on page is OFF.

–> Trace message on component is shown but on page is not shown

If trace on a component is OFF, trace on page is ON

–> Trace message on component is NOT shown.

If trace on a component is not set, trace on page is ON

–> Trace message on component and page is shown

trace listener and trace switches??

Posted by: savagerider | August 26, 2007

Adding code to Web Form on ASP.NET

There are three ways to add codes to web form:

1. Mixed code

This is the least preferred method as the code is very messy and did not seperate business logic from interface.

2. Inline code

This method include a “script” section on html content. Business logic does not mix with html interface

3. Code-behind

This is the default method with Visual Studio .net. The .cs normally will have the same name as the .aspx. Code-behind page need to be compiled before sending information to the client browser. It can be pre-compiled in visual studio .net if you foresee that there isn’t much changes on the code, or it is also possible to compile it during first time that user access the page. In this way, user can use the latest copy of code-behind page.

Page attribute:

Codebehind: indicate the associating file [this attribute is no longer in use on asp.net 2.0]

Src : indicate the code-behind page if the page is not pre-compiled. It is more for JIT compilation.

Inherits: .aspx inherit the class from the specificed code-behind page.

Event Procedures

This is the procedure to handle user interaction such as submit event, mouse click event.

Server-side event VS client-side event

Client side event can only be processed with HTML controls. Normally, when the event is triggered, it makes use of javascript to process the actions. It has no interaction with the server, in this case it is not possible to access server resources like database. This is normally used as the validation on user input to save the network traffic.

Server-side event is triggered with the component that has runat=”server”. It can handle event generated by server controls and html server controls.

It is very important to know that there is only one <form> tag with runat=”server” allowed, and the component with this attribute must keep inside <form> tag.

Page Event

Page event life cycle consists of a few events:

1. Page_init

this happens when the page is initially created.

2. Page_load

this happens when the page is requested

3. other control component event

4. Page_unload

this happens when the page is closed.

PostBack

This process post information back to  asp.net server for processing. It can be user clicking the submit button or with the AutoPostBack property set to true.

Page.IsPostBack is to check if the request is a postback request. It will return false if the page is first created.

Older Posts »

Categories

Follow

Get every new post delivered to your Inbox.