Monday, March 15, 2010

BACKUP LOG [db name] WITH TRUNCATE_ONLY

BACKUP LOG [DB name] WITH TRUNCATE_ONLY in sql sever, when transaction log is full.

Friday, January 29, 2010

Singleton Design Pattern in Asp.net using C#

Singleton Design Pattern in Asp.net using C#


Introduction

When we want to make a only one instance of a class and also making sure that there is a global access point to that object then the design pattern we user is called Singleton. The pattern ensures that the class is instantiated only once and that all requests are directed to that one and only object.
Usage

In asp.net you can use singleton through sessions or application variables easily however i will show you how to implement singleton object to User class.
Problem

In Asp.net to get user information like first name, surname or username through Memebership object does not look neat because to get UserID first you need to know user User.Identity.Name then use Membership.GetUser in order to get more detail for user.
Solution

I have created a interface called IUser which you can use anywhere on the page.

public interface IUser

{

string Email { get; set; }

string Firstname { get; set; }

string Surname { get; set; }

string UserID { get; set; }

string Username { get; set; }

}

Here is our Singleton class implementing IUser.

public sealed class Singleton

{

private const string IUserSessionName = "User";

private static IUser objUser = new UserClass();

Singleton()

{



}

///

/// Loading user information

///


public static IUser IUserInstance

{

get

{

if (null == Session[IUserSessionName])

{

if (User.Identity.IsAuthenticated)

{

string userID = Membership.GetUser().ProviderUserKey.ToString();

// getting userinformation from database

objUser = new UserClass().GetUserInformation(userID);

Session[IUserSessionName] = objUser;

}

}

else

{

objUser = (IUser)Current.Session[IUserSessionName];

}



return objUser;

}

set

{

Session[IUserSessionName] = value;

}

}



public static void UserInstanceFlush()

{

Session[IUserSessionName] = null;

}



}

Because of IuserSessionName you are also making sure that you will keep this session name unique and at only one place.

IUser is a static property which can be used on any page from Singleton.IUserInstance.UserID.

UserInstanceFlush flushes the session if you want to remove the session value.