Hope will help other people to deal with unique identifier to validate in ASP.NET on server side. Here is my solution
/// <summary>
/// Page Load event handler
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Check if session object has not been assigned - page is being loading first time or session has been expired
if (Session["ValidateId"] == null)
Session["ValidateId"] = Session.SessionID;
}
else
{
//Check if ViewState has not been previously assigned
if (ViewState["UniqueId"] == null)
{
//Always store ticks when page is being requested through post back
Int64 numberOfTicks = 0;
numberOfTicks = DateTime.Now.Ticks;
//keep this unique id to current page between post backs
ViewState["UniqueId"] = Session.SessionID + "_" + numberOfTicks.ToString();
}
}
}
/// <summary>
/// button click event handler
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnCalculate_Click(object sender, EventArgs e)
{
if (Session["ValidateId"] == null)
{
SetAlertMessage("Current Session is Expired. Please reload the page to continue.");
this.lblValidate.Text = "Current Session is Expired. Please reload the page to continue.";
return;
}
else
{
//Assign Unique Id from View State - id is unique across browser windows and belong only to current page
Session["UniqueId"] = ViewState["UniqueId"];
//Instantiate object to run some calculation and manipulate records in database
this._transformerloadParser = new TransformerLoadDataParser(ViewState["UniqueId"].ToString());
}
}
/// <summary>
/// User alert message through ClientScriptManager
/// </summary>
/// <param name="message"></param>
protected void SetAlertMessage(String message)
{
StringBuilder sb = null;
String scName = "AlertScript";
ClientScriptManager csm = Page.ClientScript;
Type scType = Page.GetType();
sb = new StringBuilder();
sb.Append("alert('");
sb.Append(message);
sb.Append("')");
ScriptManager.RegisterStartupScript(this, scType, scName, sb.ToString(), true);
}
//class logic
public class TransformerLoadDataParser
{
//Constructor
public TransformerLoadDataParser(String uniqueId)
{
Init(uniqueId);
}
/// <summary>
/// All required variable initialization
/// </summary>
protected void Init(String uniqueId)
{
try
{
this._userIdentityName = HttpContext.Current.User.Identity.Name;
if (HttpContext.Current.Session["UniqueId"] == null || !String.Equals(HttpContext.Current.Session["UniqueId"],uniqueId))
throw new Exception("UniqueId as Session Key has not been set, expired or not properly set.");
this._sessionId = uniqueId;
}
else
{
throw new Exception("Application settings are not defined in web config file.");
}
}
catch (Exception)
{
throw;
}
}
//some other logic
}