Handling Session Expiration in ASP.NET & MVC

hi again 🙂

In many projects that I have implemented in the past, Session was always  a very important part to exchange information between pages and different requests. However, the downside of using session is the Yellow Error Page 😦 that pops up to the user when the session expires and then the application crashes. I’ve been thinking a lot about this and I’ve came up with my own way to implement it, I’m using the exact same method in my current project and it works like a charm.

lets start coding, right!!! 

First we need to create a class that is going to handle the session :

public static class SessionManager
{

public const string UserInfoKey = “UserInfo”;
public static object _Session_UserInfo
{

get
{

if (HttpContext.Current.Session[UserInfoKey] == null)
{
HttpContext.Current.Response.Redirect(“/Account/Login?Expired=1”);
return null;
}

else
{
return HttpContext.Current.Session[LoginViewModel.UserInfoKey];
}
}

set
{
HttpContext.Current.Session[LoginViewModel.UserInfoKey] = value;

}

}

}

// and then you must start referencing the session in your code like this 

public ActionResult Index()

{

string fromsession =  SessionManager._Session_UserInfo;

return View(fromsession);

}

 

//and if the session expires the class will immediately redirect to your login page, this way you can rest assured that your application is not going to crash because of the session expiration thing!!!

 

thanks and enjoy your day!

 

Passing C# array to Stored Procedure

I’ve been searching through all the examples and answers of how to pass any array (say like List<int>, List<string> or even array[int or string],  to sql server,till i found this link, below is how I applied it to my project:

–The following code is going to get an Array as Parameter and insert the values of that –array into another table

Create Procedure Proc1

@INFO_ARRAY ARRAY nvarchar(max) //this is the array your going to pass from C# code

AS

declare @xml xml

set @xml = N'<root><r>’ + replace(@INFO_ARRAY,’,’,'</r><r>’) + ‘</r></root>’

Insert into Products
select
t.value(‘.’,’varchar(max)’)

from @xml.nodes(‘//root/r’) as a(t)
END

JQuery AutoComplete from a C# Dictionary in MVC4

hi,

Today I faced a problem where I want to map a key/value pair to a JQuery autocomplete so that I can have a user search that is going to provide a visible username to the user, and then give me the selected UserId so I can use it in other operations and database transactions, searched the web, but couldn’t find much!, so I decided to share it with you fellas in case nay of you run into this problem. (Note: you have to implement the below close event of the autocomplete so that you can ensure correct display of values in the text box):

in the View

———————-

you’ll need

1) textbox for the Jquery automcomplete (NewUser)

2) hiddent field to save the selected value (selectedNewUser)

3) hiddent field to set the selected Label (remember if you dont do this, you’ll end up having the value displayed in the autocomplete textbox instead of the Label) (selectedNewUserLabel)

<input type=”text” Id=”NewUser” value=”” />

<input type=”hidden” id=”selectedNewUser” value=”” />
<input type=”hidden” id=”selectedNewUserLabel” value=”” />

//then javascript

<script>

$(function () {

//form an array of Label and Value from the Dictionary
var _source = [];
@foreach (var item in Model.Dictionary1)
{
<text>
_source.push({

value:’@item.Key’,
label:’@item.Value’

});
</text>
}

$(“#Newuser”).autocomplete({
source: _source,
autoFill: true,

select: function (event, ui) {
var label = ui.item.label;
var value = ui.item.value;

//save the value in the hidden field
$(‘#selectedNewuser’).val(value);
//set the textfield again to the name

$(‘#selectedNewuserLabel’).val(label);

},

close: function (event, ui) {

$(“#Newuser”).val($(‘#selectedNewuserLabel’).val());

}

});

});

The Facade Design Pattern Example in C#

Facade design pattern is one of the most commonly used patterns. what this pattern provide is : a single interface (or facade) that encapsulates functionality from another interfaces (or classes).

I’ve written a very easy to understand example of this, and for you as a developer is very relate-able. the code below is a simple way of how to handle the Login (I bet you must ‘ve done login before !), so we will provide the application with one interface to call to get the user logged-in, and this interface (or again facade) will handle all operations that are involved in the login process from the different other classes. Enjoy!

//create a user class

public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }

}

//create the Ad authenticator class

public class Authenticator
{

public bool IsUserPartOfActiveDirectory(User _user)
{

//check User credentials against AD or whatever Auth provider
Console.WriteLine(“Authenticating User against Adctive Directory…”);

return true;

}

}

//create the roles checker class

public class UserRolesChecker
{

public bool DoesUserHaveAccessToApplication(User _user)
{
//check user against roles in Db or config file
Console.WriteLine(“Checking User Roles…”);
return true;

}

}

//the login db updater class

public class UserRecordUpdater
{
public void UpdateUserlastLoginTime(User _user)
{

Console.WriteLine(“Updating User Record in db..”);

}

}

//create the main facade class

//this class is going to be the Facade for all other participants in the Login Process
//So only one method for Login needs to be expposed from this calss , and this method
//should take care of calling all other necessary participant methods to login the user
public class LoginFacade
{
Authenticator _authenticator = new Authenticator();
UserRolesChecker _roleChecker = new UserRolesChecker();
UserRecordUpdater _dbUpdater = new UserRecordUpdater();

public bool LoginUser(User _user)
{
if (_authenticator.IsUserPartOfActiveDirectory(_user))
{

if (_roleChecker.DoesUserHaveAccessToApplication(_user))
{

_dbUpdater.UpdateUserlastLoginTime(_user);

return true;
}
else
return false;

}
else
{
return false;
}

}

}

//test the pattern in a console app

class Program
{
static void Main(string[] args)
{

Console.WriteLine(” ***********************Login Handler*******************\n\n\n”);
//initialize a user
User _user = new User();
_user.UserId = 1;
_user.UserName = “Allan”;
_user.Password = “123456”;

//so here you only call one facade to take care of all operations! isn’t that neat

LoginFacade _loginFacade = new LoginFacade();
if (_loginFacade.LoginUser(_user))
Console.WriteLine(“\n\nUser Logged-in successfully !”);
else
Console.WriteLine(“User doe not have the necessary rights/roles to access the system”);

Console.ReadLine();

}
}

//hope you enjoyed it, please note that I have included three steps in the user login process above ( Active Directory checker, Roles Checker and Db Updater), this is not mandatory, it all depends on your organization needs and whats on the ground!

Momento Design Pattern Example in C#

Hi,

(PLEASE NOTE: below is my simple understanding and explanation of the momento design pattern, just to give you a head-start with easy to understand explanation).

I thought of writing an example that simplifies the concept of using this design pattern. Momento is a design pattern that you use when you want to enable restoring previous states of objects (like enabling Undo functionality to the users) or you can use it also for logging old values of objects.

This pattern works by utilizing three main objects :

Original Object: which is your normal data class or any class that holds the information you need so that you program can use it. this class MUST PROVIDE two methods: save and restore. these methods will save and restore the state of the object.

Care Taker : is an interface to the momento class where you set the previous state of an object in, and restore it from this caretaker too. the original class should not deal with the Momento object directly.

Momento Object: is a class that has the same properties of the original class and a constructor that can set new values to all these properties when passed.

//Below is a sample easy to read code that I’ve written for this purpose:

//1) the original class

public class MainDataOrinigal
{
//this calss has to have two properties SaveMomento and Restore Momento beside its original Properties and methods

public string UserName { get; set; }
public string Passwword { get; set; }

public DataMomento SaveMomento()
{

return new DataMomento(this.UserName, this.Passwword);

}

public void RestorMomento(DataMomento _previousState)
{

this.UserName = _previousState.UserName;
this.Passwword = _previousState.Password;

}

}

//2) the caretaker class

public class DataMomentoCareTaker
{

public DataMomento KeepMomento { get; set; }

}

//3) the Momento Class

public class DataMomento
{

public string UserName { get; set; }
public string Password { get; set; }

public DataMomento(string _username, string _password)
{
this.UserName = _username;
this.Password = _password;
}
}

//lets write a simple Console app to test this:

///set orignial state

MainDataOrinigal orinigal = new MainDataOrinigal();
orinigal.UserName = “user111”;
orinigal.Passwword = “whateverpasswd”;

//save the state using Only CareTaker, no direct communications

DataMomentoCareTaker caretaker = new DataMomentoCareTaker();
caretaker.KeepMomento = orinigal.SaveMomento();

//change the orinigal state

orinigal.UserName = “AJ”;
orinigal.Passwword = “jjabrams”;

//done to here

//print out the current state

Console.WriteLine(“Current State ” + orinigal.UserName + ” ” + orinigal.Passwword);
Console.WriteLine(“calling caretaker to restore previous state momento “);
//Note Only CareTaker needs to be passed to the original RestoreMethod to restore
orinigal.RestorMomento(caretaker.KeepMomento);
Console.WriteLine(“Previous State ” + orinigal.UserName + ” ” + orinigal.Passwword);

Console.ReadLine();

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Hope this helps!