Sunday, January 24, 2016

Tuesday, January 19, 2016

How to store string in a cookie and retrieve it

Writing a cookie

HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;
 
// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddYears(50); // For a cookie to effectively never expire
 
// Add the cookie.
Response.Cookies.Add(myCookie);

Reading a cookie

HttpCookie myCookie = Request.Cookies["MyTestCookie"];
 
// Read the cookie information and display it.
if (myCookie != null)
    Response.Write("<p>" + myCookie.Name + "<p>" + myCookie.Value);
else
    Response.Write("not found");

why cookies are always null after postback

private static string GetCookie(string name)
{
    return HttpContext.Current.Request != null ? HttpContext.Current.Request.Cookies[name].Value : string.Empty;
}
 
private static void SetCookie(string name, string value)
{
    HttpContext.Current.Request.Cookies[name].Value = value;
    HttpContext.Current.Request.Cookies[name].Expires = DateTime.Now.AddDays(100);
}

Monday, January 11, 2016

How to check if column exists in SQL Server table

IF EXISTS(SELECT * FROM sys.columns 
WHERE Name = N'columnName' AND Object_ID = Object_ID(qualified.table.name')) 
BEGIN 
    PRINT 'Column Exists'
END
--OR
IF COL_LENGTH('qualified.table.name','column_name') IS NULL
BEGIN
    PRINT 'Column does not exist or caller does not have permission to view the object'
END