How to access Session in javascript

Introduction

In this article we learn about how we can access ASP.NET server side session variable or data in client side JavaScript.
I have requirement for current user session variable in client side to perform some action based on user and its role.

Here are method or way to interact session variable in client side or in JavaScript.

1. Directly access session variable with mix code(Asp.net Server side)
as per the below code.
     //First way to access session 
     console.log("UserId:" + '<%=Session["UserId"] %>');
     console.log("UserRole:" + '<%=Session["UserRole"] %>');
2. Fetch session value from HiddenField
To fetch session value from hidden field first we have to set session data in server side and then we can access stored hidden value data in client side javascript.
//Set session value to hidden field for access this value in jquery 
     protected void setSessionToHiddenValue()
     {
         Session.Add("UserId", "Arvind");
         Session.Add("UserRole", "Admin");
         hdnUserId.Value = Convert.ToString(Session["UserId"]);
         hdnUserRole.Value = Convert.ToString(Session["UserRole"]);
     }
     //We can access hidden session data as below 
     console.log("UserId:" + '<%= hdnUserId.Value %>');
     console.log("UserRole:" + '<%= hdnUserRole.Value %>');

Conclusion

In this article we have learn about accessing server side session variable in client side for take action based on current session. 


Asp.Net Utility Functions

Introduction

This article contains most useful utility function for Asp.Net WebForm as well as Asp.Net MVC project. All this method is collected from Internet sources like stackoverflow so it will be useful to many developer to find all useful method at one place.

See listed below most useful functions


1. Replace all special character in input string with '-' character

This method replace special characters using Regex function
  public static string ReplaceSpecialChar(string input)
      {
        Regex rgx = new Regex("[^a-zA-Z0-9]");
        input = rgx.Replace(input, "-");
        return input;
      }

2. Remove all special characters from string

This method remove all special characters and prepare new string which contains alpha numeric character along with underscore and space.
     public static string RemoveSpecialCharacters(string str)
     {
      StringBuilder sb = new StringBuilder(); 
      for (int i = 0; i < str.Length; i++)
      {
          if ((str[i] >= '0' && str[i]<='9')||(str[i]>='A'&&str[i]<='z'
|| (str[i] == '_' || str[i] == ' ')))
               sb.Append(str[i]);
       }
      return sb.ToString();
     }

3. Convert Unix long timestamp to C# DateTime object

Most of system contains unix timestamp for storing date value,which is most REST API response datet as unix timestamp. So,Below method is very useful to convert timestamp to DateTime object.
public static DateTime ConvertUNIXTimeStampTODateTime(long date)
     {
        DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0,System.DateTimeKind.Utc);
        dtDateTime = dtDateTime.AddSeconds(date).ToLocalTime();
        return dtDateTime;
     }

4. Get short description from long length string value

In real world project many times this situation arise that we need to display on first 50 or 100 charcter from long string. This method trim long string value with ellipse format to display some short description.

public static string GetShortDescription(string Description)
        {
            string strDesc = string.Empty;
            try
            {
                if (Convert.ToString(Description) != string.Empty)
                {
                    if (Description.Trim().Length > 100)
                    {
                        strDesc = Description.Trim().Substring(0, 100) + "...";
                    }
                    else
                    {
                        strDesc = Description.Trim();
                    }
                }
            }
            catch (Exception)
            {
            }
            return strDesc;
        }

5. Convert C# DateTime to Unix long timestamp


As we require converting unix timestamp to C# DateTime,we also required to convert C# DateTime to Unix timestamp.
     public static long ConvertToUnixTimestamp(this DateTime target)
     {
            var date = new DateTime(1970, 1, 1, 0, 0, 0, target.Kind);
            var unixTimestamp = System.Convert.ToInt64((target - date).TotalSeconds);
            return unixTimestamp;
     }

Reference

    http://stackoverflow.com

Note

Fill free to contribute your own some useful functions in github repository which I have publish at Asp.Net-Utility-Functions

Conclusion

In this article we have seen most useful common utility function for Asp.Net, I will also updating this article in coming days, so we can get all common utility functions at one place.

Dynamic Query in LINQ using Predicate Builder

Introduction This tutorial explains how to create a dynamic query using LINQ, Using Predicate Builder  LINQ to SQL dynamic query an...

Learn More