Saturday, 9 September 2023

Introduction of C#

 Introduction of C#

What is C#?

C# is pronounced "C-Sharp".

It is an object-oriented programming language created by Microsoft that runs on the .NET Framework.

C# has roots from the C family, and the language is close to other popular languages like C++ and Java.

The first version was released in year 2002. The latest version, C# 11, was released in November 2022.

C# is used for:

1.     Web API

2.     Mobile applications

3.     Desktop applications

4.     Web applications

5.     Web services

6.     Web sites

7.     Games

8.     VR

9.     Database applications

________________________________________

Why Use C#?

           It is one of the most popular programming language in the world

           It is easy to learn and simple to use

           It has a huge community support

           C# is an object oriented language which gives a clear structure to programs and allows code to be reused, lowering development costs

           As C# is close to C, C++ and Java, it makes it easy for programmers to switch to C# or vice versa

 

Tuesday, 15 August 2023

Tuesday, 26 May 2020

How to create 'Column chart' using HighCharts in MVC Application?

How to create 'Column chart' using HighCharts in MVC Application?

There are following step to create Column Chart.

Step 1.

Create MVC Application.

Step 2.

Add KeyValuePair Class.

example:
public class KeyValuePair
{
    public string Key { get; set; }
    public double Value { get; set; }
}

Step 3.

Add New controller with name 'HightChartsController'.

example:

using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace DotNetByPriyanshu.Controllers
{
    public class HightChartsController : Controller
    {
       //to do here
    }
}

Step 4.

Add Action method with name 'Charts'.

example:

[HttpGet]  
public ActionResult Charts()
        {
            return View();
        }

Step 5.

Add View for Charts.

example:


@{
    ViewBag.Title = "Charts";
}

<h2>Charts</h2><br />

Step 6.

Add 'Div' for Column chart.

<div id="containerColumnChart" style="height: 500px; width: 500"></div>

Step 7.

Add Highcharts & Jquery links.

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

Step 8.

Add 

example:

[HttpGet]
public ActionResult GetData()
        {
            try
            {
                List<KeyValuePair> objList = new List<KeyValuePair>();
                KeyValuePair obj = new KeyValuePair();
                obj.Key = "Delhi";
                obj.Value = 44.2;
                objList.Add(obj);
                KeyValuePair obj1 = new KeyValuePair();
                obj1.Key = "Bangalore";
                obj1.Value = 26.6;
                objList.Add(obj1);
                KeyValuePair obj2 = new KeyValuePair();
                obj2.Key = "Pune";
                obj2.Value = 20;
                objList.Add(obj2);
                KeyValuePair obj3 = new KeyValuePair();
                obj3.Key = "Patna";
                obj3.Value = 3.1;
                objList.Add(obj3);
                KeyValuePair obj4 = new KeyValuePair();
                obj4.Key = "Other";
                obj4.Value = 5.4;
                objList.Add(obj4);

                return Json(objList, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json("", JsonRequestBehavior.AllowGet);
            }
        }

Step 9.

Added Jquery for Column Char.

example:

 $(document).ready(function () {
        createColumnChart();
    });
    function createColumnChart() {
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: "/HightCharts/GetData",
            dataType: 'json',

            success: function (response) {
                var aData = response;
                var arr = []

                $.map(aData, function (item, index) {
                    var i = [item.Key, item.Value];
                    var obj = {};
                    obj.name = item.Key;
                    obj.y = item.Value;
                    arr.push(obj);
                });
                var jsonArray = JSON.parse(JSON.stringify(arr));
                drawColumnChart(jsonArray);
            },
            error: function (response) {
            }
        });
    }
    function drawColumnChart(seriesData) {

        Highcharts.chart('containerColumnChart', {
            chart: {
                type: 'column'
            },
            title: {
                text: 'Population percentage city wise'
            },

            xAxis: {
                categories: [
                    'Delhi',
                    'Bangalore',
                    'Pune',
                    'Patna',
                    'Others'
                ],
                crosshair: true
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Percentage'
                }
            },
            tooltip: {
                pointFormat: '{point.y:.1f} %'
            },
            plotOptions: {
                column: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        format: '{point.y:.1f} %',
                        style: {
                            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'green'
                        }
                    }
                }
            },
            series: [{
                name: "Brands",
                colorByPoint: true,
                data: seriesData
            }]
        });
    }

Step 10.

Add link in  Layout page.

example:

 <li>@Html.ActionLink("High Charts", "Charts", "HightCharts")</li>

                                 Consolidate Code:

C# Code with Controller:

using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace DotNetByPriyanshu.Controllers
{
    public class HightChartsController : Controller
    {
        [HttpGet]
        public ActionResult Charts()
        {
            return View();
        }
        [HttpGet]
        public ActionResult GetData()
        {
            try
            {
                List<KeyValuePair> objList = new List<KeyValuePair>();
                KeyValuePair obj = new KeyValuePair();
                obj.Key = "Delhi";
                obj.Value = 44.2;
                objList.Add(obj);
                KeyValuePair obj1 = new KeyValuePair();
                obj1.Key = "Bangalore";
                obj1.Value = 26.6;
                objList.Add(obj1);
                KeyValuePair obj2 = new KeyValuePair();
                obj2.Key = "Pune";
                obj2.Value = 20;
                objList.Add(obj2);
                KeyValuePair obj3 = new KeyValuePair();
                obj3.Key = "Patna";
                obj3.Value = 3.1;
                objList.Add(obj3);
                KeyValuePair obj4 = new KeyValuePair();
                obj4.Key = "Other";
                obj4.Value = 5.4;
                objList.Add(obj4);

                return Json(objList, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json("", JsonRequestBehavior.AllowGet);
            }
        }
    }
}

public class KeyValuePair
{
    public string Key { get; set; }
    public double Value { get; set; }
}

View:


@{
    ViewBag.Title = "Charts";
}

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

<h2>Charts</h2><br />

<div id="containerColumnChart" style="height: 500px; width: 500"></div>

JQuery:


    $(document).ready(function () {
        createColumnChart();
    });
    function createColumnChart() {
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: "/HightCharts/GetData",
            dataType: 'json',

            success: function (response) {
                var aData = response;
                var arr = []

                $.map(aData, function (item, index) {
                    var i = [item.Key, item.Value];
                    var obj = {};
                    obj.name = item.Key;
                    obj.y = item.Value;
                    arr.push(obj);
                });
                var jsonArray = JSON.parse(JSON.stringify(arr));
                drawColumnChart(jsonArray);
            },
            error: function (response) {
            }
        });


    }
    function drawColumnChart(seriesData) {
        Highcharts.chart('containerColumnChart', {
            chart: {
                type: 'column'
            },
            title: {
                text: 'Population percentage city wise'
            },

            xAxis: {
                categories: [
                    'Delhi',
                    'Bangalore',
                    'Pune',
                    'Patna',
                    'Others'
                ],
                crosshair: true
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Percentage'
                }
            },
            tooltip: {
                pointFormat: '{point.y:.1f} %'
            },
            plotOptions: {
                column: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        format: '{point.y:.1f} %',
                        style: {
                            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'green'
                        }
                    }
                }
            },
            series: [{
                name: "Brands",
                colorByPoint: true,
                data: seriesData
            }]
        });
    }


                                                     Output:


Monday, 25 May 2020

How to create 'Pie chart' using HighCharts in MVC Application?

How to create 'Pie chart' using HighCharts in MVC Application?

There are following step to create Pie Chart.

Step 1.

Create MVC Application.

Step 2.

Add KeyValuePair Class.

example:
public class KeyValuePair
{
    public string Key { get; set; }
    public double Value { get; set; }
}

Step 3.

Add New controller with name 'HightChartsController'.

example:

using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace DotNetByPriyanshu.Controllers
{
    public class HightChartsController : Controller
    {
       //to do here
    }
}

Step 4.

Add Action method with name 'Charts'.

example:

[HttpGet]  
public ActionResult Charts()
        {
            return View();
        }

Step 5.

Add View for Charts.

example:


@{
    ViewBag.Title = "Charts";
}

<h2>Charts</h2><br />

Step 6.

Add 'Div' for Pie chart.

<div id="containerPieChart" style="height: 500px; width: 500"></div>

Step 7.

Add Highcharts & Jquery links.

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

Step 8.

Add 

example:

[HttpGet]
public ActionResult GetData()
        {
            try
            {
                List<KeyValuePair> objList = new List<KeyValuePair>();
                KeyValuePair obj = new KeyValuePair();
                obj.Key = "Delhi";
                obj.Value = 44.2;
                objList.Add(obj);
                KeyValuePair obj1 = new KeyValuePair();
                obj1.Key = "Bangalore";
                obj1.Value = 26.6;
                objList.Add(obj1);
                KeyValuePair obj2 = new KeyValuePair();
                obj2.Key = "Pune";
                obj2.Value = 20;
                objList.Add(obj2);
                KeyValuePair obj3 = new KeyValuePair();
                obj3.Key = "Patna";
                obj3.Value = 3.1;
                objList.Add(obj3);
                KeyValuePair obj4 = new KeyValuePair();
                obj4.Key = "Other";
                obj4.Value = 5.4;
                objList.Add(obj4);

                return Json(objList, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json("", JsonRequestBehavior.AllowGet);
            }
        }

Step 9.

Added Jquery for Pie Char.

example:

 $(document).ready(function () {
        createPieChart();
    });
    function createPieChart() {
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: "/HightCharts/GetData",
            dataType: 'json',

            success: function (response) {
                var aData = response;
                var arr = []

                $.map(aData, function (item, index) {
                    var i = [item.Key, item.Value];
                    var obj = {};
                    obj.name = item.Key;
                    obj.y = item.Value;
                    arr.push(obj);
                });
                var jsonArray = JSON.parse(JSON.stringify(arr));
                drawPieChart(jsonArray);
            },
            error: function (response) {
            }
        });


    }
    function drawPieChart(seriesData) {
        Highcharts.chart('containerPieChart', {
            chart: {
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false,
                type: 'pie'
            },
            title: {
                text: 'Population percentage city wise'
            },
            tooltip: {
                pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                        style: {
                            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'green'
                        }
                    }
                }
            },
            series: [{
                name: "Brands",
                colorByPoint: true,
                data: seriesData
            }]
        });
    }

Step 10.

Add link in  Layout page.

example:

 <li>@Html.ActionLink("High Charts", "Charts", "HightCharts")</li>

                                 Consolidate Code:

C# Code with Controller:

using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace DotNetByPriyanshu.Controllers
{
    public class HightChartsController : Controller
    {
        [HttpGet]
        public ActionResult Charts()
        {
            return View();
        }
        [HttpGet]
        public ActionResult GetData()
        {
            try
            {
                List<KeyValuePair> objList = new List<KeyValuePair>();
                KeyValuePair obj = new KeyValuePair();
                obj.Key = "Delhi";
                obj.Value = 44.2;
                objList.Add(obj);
                KeyValuePair obj1 = new KeyValuePair();
                obj1.Key = "Bangalore";
                obj1.Value = 26.6;
                objList.Add(obj1);
                KeyValuePair obj2 = new KeyValuePair();
                obj2.Key = "Pune";
                obj2.Value = 20;
                objList.Add(obj2);
                KeyValuePair obj3 = new KeyValuePair();
                obj3.Key = "Patna";
                obj3.Value = 3.1;
                objList.Add(obj3);
                KeyValuePair obj4 = new KeyValuePair();
                obj4.Key = "Other";
                obj4.Value = 5.4;
                objList.Add(obj4);

                return Json(objList, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json("", JsonRequestBehavior.AllowGet);
            }
        }
    }
}

public class KeyValuePair
{
    public string Key { get; set; }
    public double Value { get; set; }
}

View:


@{
    ViewBag.Title = "Charts";
}

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

<h2>Charts</h2><br />

<div id="containerPieChart" style="height: 500px; width: 500"></div>

JQuery:


    $(document).ready(function () {
        createPieChart();
    });
    function createPieChart() {
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: "/HightCharts/GetData",
            dataType: 'json',

            success: function (response) {
                var aData = response;
                var arr = []

                $.map(aData, function (item, index) {
                    var i = [item.Key, item.Value];
                    var obj = {};
                    obj.name = item.Key;
                    obj.y = item.Value;
                    arr.push(obj);
                });
                var jsonArray = JSON.parse(JSON.stringify(arr));
                drawPieChart(jsonArray);
            },
            error: function (response) {
            }
        });


    }
    function drawPieChart(seriesData) {
        Highcharts.chart('containerPieChart', {
            chart: {
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false,
                type: 'pie'
            },
            title: {
                text: 'Population percentage city wise'
            },
            tooltip: {
                pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                        style: {
                            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'green'
                        }
                    }
                }
            },
            series: [{
                name: "Brands",
                colorByPoint: true,
                data: seriesData
            }]
        });
    }


                                                     Output:




Wednesday, 15 April 2020

Create dropdown with search text box using select2 library in MVC Application.

Create dropdown with search text box using select2 library in MVC Application.


Important Links for library:
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></scritp>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>

CSHTML Code:


                  <div class="form-group">
                         <label>Employee Code</label>
                        <div class="form-group">
                            <select id="ddlemployeeList" class="dropdownAuto form-control">
                            </select>
                            @Html.Hidden("lblemployeeId")
                        </div>
                    </div>


JQuery Code


$(document).ready(function () {
    $(".dropdownAuto").select2({
        placeholder: "EMPLOYEE NAME",
        allowClear: true
    });
    //-----------------------Get Employee List in dropdown list-----------------------------------------------
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: "/DotNetByPriyanshu/EmployeeList",
        dataType: 'json',
        success: function (Result) {
            $("#ddlemployeeList").append($("<option></option>").val('').html(''));
            $.each(Result, function (key, value) {
                $("#ddlemployeeList").append($("<option></option>").val(value.id).html(value.label));
            });
        },
        error: function (Result) {
            Swal.fire({
                icon: 'error',
                title: 'Oops...',
                text: 'Error on dropdown List ::' + Result
            })
        }
    });
});


Controller Code

 public class DotNetByPriyanshuController : Controller
{
        [HttpGet]
        public ActionResult EmployeeList()
        {
            KeyValuePair keyValuePair = new KeyValuePair();
            keyValuePair.id = 1;
            keyValuePair.label = "Priyanshu Kumar";

           List<KeyValuePair> EmpList= new List<KeyValuePair>();

           EmpList.Add(keyValuePair);

            return Json(EmpList, JsonRequestBehavior.AllowGet);
        }
}



OutPut:



Wednesday, 8 April 2020

Custom Method for Error Log.

Custom Method for Error Log.

Step 1. Create class with Name 'AppExceptionManager' in class library.


using System;
using System.Configuration;
using System.IO;
using System.Text;
using System.Web;

namespace DotNetByPriyanshu
{
    public class AppExceptionManager
    {

         /// <summary>
        /// Log Error Description to log file.
        /// </summary>
        /// <param name="errorDescription"></param>
        public static void LogError(System.Exception errorDescription)
        {
            string dateTime = string.Format("{0:MM-dd-yyyy}", DateTime.Now);
            string path = HttpContext.Current.Server.MapPath("~/ErrorLog/");
            string ExistingFilePath = path + "LogError" + dateTime + ".txt";
            if (File.Exists(ExistingFilePath.Trim()))
            {
                AppendExitingLogErrorFile(errorDescription, dateTime, ExistingFilePath.Trim());
            }
            else
            {
                WriteLogErrorFile(errorDescription, dateTime);
            }

        }

         /// <summary>
        /// It returns Error line number where at which line number exception raised .
        /// </summary>
        /// <param name="ex"></param>
        private static string GetErrorLine(System.Exception ex)
        {
            StringBuilder errorLineNumber = new StringBuilder();
            try
            {
                if (ex != null)
                {
                    if (ex.StackTrace.LastIndexOf(@"\") != -1)
                    {
                        string stackSubString = ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("line ") + 5);

                        if (stackSubString.IndexOf(' ') != -1)
                        {
                            errorLineNumber.Append(stackSubString.Remove(stackSubString.IndexOf(' ')));
                        }
                        else
                        {
                            errorLineNumber.Append(stackSubString);
                        }
                    }
                }
            }
            catch (System.Exception)
            {
            }
            return errorLineNumber.ToString();
        }



         /// <summary>
        /// Method for Append Exiting Log Error File
        /// </summary>
        /// <param name="errorDescription"></param>
        /// <param name="dateTime"></param>
        /// <param name="ExistingFilePath"></param>
        private static void AppendExitingLogErrorFile(System.Exception errorDescription, string  dateTime, string ExistingFilePath)
        {
            myStream = new FileStream(ExistingFilePath, FileMode.Append);
            StreamWriter myWriter = new StreamWriter(myStream);
            if (myWriter != null)
            {
                myWriter.WriteLine("---------------------------------------------------------");
                myWriter.WriteLine("--------------------------Start--------------------------");
                myWriter.WriteLine("Machine Name :" + Environment.MachineName);
                myWriter.WriteLine("Windows user :" + Environment.UserDomainName + "\\" + Environment.UserName);
                myWriter.WriteLine("Time stamp : " + System.DateTime.Now.ToString());
                myWriter.WriteLine("Inner Exception : " + errorDescription.InnerException);
                myWriter.WriteLine("Message : " + errorDescription.Message);
                myWriter.WriteLine("Exception Type : "+ errorDescription.GetType().ToString());
                myWriter.WriteLine("Error Line : " + GetErrorLine(errorDescription));
                myWriter.WriteLine("Stack trace : " + errorDescription.StackTrace);
                myWriter.WriteLine("OS Name : "+ Environment.OSVersion.ToString());
                myWriter.WriteLine("HelpLink : " + errorDescription.HelpLink);
                myWriter.WriteLine("-------------------------- End --------------------------");
                myWriter.Close();
                myStream.Close();
            }
        }

    }
}

  /// <summary>
        /// Method for Write Log Error File
        /// </summary>
        /// <param name="errorDescription"></param>
        /// <param name="dateTime"></param>
        private static void WriteLogErrorFile(System.Exception errorDescription, string dateTime)
        {
            string strFilePath = HttpContext.Current.Server.MapPath("~/ErrorLog/");
            using (StreamWriter myWriter = new StreamWriter(Path.Combine(strFilePath, "LogError" + dateTime + ".txt")))
            {
                if (myWriter != null)
                {

                    myWriter.WriteLine("---------------------------------------------------------");
                    myWriter.WriteLine("--------------------------Start--------------------------");
                    myWriter.WriteLine("Machine Name :" + Environment.MachineName);
                    myWriter.WriteLine("Windows user :" + Environment.UserDomainName + "\\" + Environment.UserName);
                    myWriter.WriteLine("Time stamp : "  + System.DateTime.Now.ToString());
                    myWriter.WriteLine("Inner Exception : " + errorDescription.InnerException);
                    myWriter.WriteLine("Message : "  + errorDescription.Message);
                    myWriter.WriteLine("Exception Type : " + errorDescription.GetType().ToString());
                    myWriter.WriteLine("Error Line : "  + GetErrorLine(errorDescription));
                    myWriter.WriteLine("Stack trace : " + errorDescription.StackTrace);
                    myWriter.WriteLine("OS Name : " + Environment.OSVersion.ToString());
                    myWriter.WriteLine("HelpLink : " + errorDescription.HelpLink);
                    myWriter.WriteLine("-------------------------- End --------------------------");
                    myWriter.Close();
                }
            }
        }

Step 2. Create ErrorLog folder in Application.


Session management in MVC.

Session management in MVC.

Step 1. Create Class with Name 'AppCacheManager'  in class library.

using System;
using System.Web;

namespace DotNetByPriyanshu
{
    public class AppCacheManager
    {
        #region Instance Property

        // This approach ensures that only one instance is created and only when the instance is needed. 
        // Also, the variable is declared to be volatile to ensure that assignment to the instance variable 
        // completes before the instance variable can be accessed. 
        // Lastly, this approach uses a syncRoot instance to lock on, rather than locking on the type itself, to avoid deadlocks. 
        //
        // This double-check locking approach solves the thread concurrency problems while avoiding an exclusive lock 
        // in every call to the Instance property method. 
        // It also allows you to delay instantiation until the object is first accessed.
        // In practice, an application rarely requires this type of implementation. 
        // In most cases, the static initialization approach is sufficient.
        private static volatile AppCacheManager _Instance = null;
        private static object syncRoot = new Object();

        /// <summary>
        /// Get/Set a Thread-Safe Instance of the AppCacheManager class
        /// </summary>
        public static AppCacheManager Instance
        {
            get
            {
                if (_Instance == null)
                {
                    lock (syncRoot)
                    {
                        if (_Instance == null)
                        {
                            _Instance = new AppCacheManager();
                        }
                    }
                }

                return _Instance;
            }
            set { _Instance = value; }
        }
        #endregion

        #region
        /// <summary>
        /// Get a specific value from the user (HttpContext.Current.Session) cache.
        /// If the key is not found, a null value is returned.
        /// </summary>
        /// <param name="key">The unique key of the cached value to retrieve</param>
        /// <returns>The cached value or null if the key/value is not found</returns>
        public T GetFromUserCache<T>(string key)
        {
            T ret;
            object value;

            value = HttpContext.Current.Session[key];
            if (value != null)
            {
                ret = (T)value;
            }
            else
            {
                ret = default(T);
            }

            return ret;
        }

        /// <summary>
        /// Call this method to add a key/value pair to cache that is specific for a user of the application.
        /// The SessionID is used to uniquely identify the user.
        /// </summary>
        /// <param name="key">A unique key to identify the cached value</param>
        /// <param name="value">The value to add to the cache</param>
        public void AddToUserCache(string key, object value)
        {
            HttpContext.Current.Session.Add(key, value);
        }

        #endregion
    }
}

Step 2 . Create class with Name 'AppUserSession' in class library.


using System;

namespace DotNetByPriyanshu
{
    /// <summary>
    /// Provides strongly-typed access to session variables.
    /// </summary>
    [Serializable]
    public class AppUserSession
    {
        // Add your own Properties in the following region
        #region Public Properties

        /// <summary>
        /// Get/Set the Last Employee Name used
        /// NOTE: This is a sample only, you can remove this.
        /// </summary>
        public string Name
        {
            get { return AppCacheManager.Instance.GetFromUserCache<string>("Name"); }
            set { AppCacheManager.Instance.AddToUserCache("Name", value); }
        }
       
        /// <summary>
        /// Get/Set the UserId used
        /// </summary>
        public int UserId
        {
            get { return AppCacheManager.Instance.GetFromUserCache<int>("UserId"); }
            set { AppCacheManager.Instance.AddToUserCache("UserId", value); }
        }


        #endregion
    }
}


Step 3. Create class with Name 'AppController' and inherit Controller in class library.

using System.Web.Mvc;

namespace DotNetByPriyanshu
{
    public class AppController : Controller
    {
        #region Protected Properties
        private AppUserSession _session;

        /// <summary>
        /// Get/Set the User Session information on a page
        /// </summary>
        protected AppUserSession UserSession
        {
            get
            {
                if (_session == null)
                {
                    _session = new AppUserSession();
                }
                return _session;
            }
            set { _session = value; }
        }
        #endregion

        #region Init Method
        /// <summary>
        /// Initialize any items needed by all controllers
        /// </summary>
        public void Init()
        {

        }
        #endregion

        /// <summary>
        /// Get Logged-In User Full-Name
        /// </summary>
        /// <returns></returns>
        public string GetLoggedInUserFullName()
        {
            string value = string.Empty;
            if (UserSession.Name != null)
                return value = UserSession.Name;
            else
                return value = "unknown";
        }

    }
}


Use of Session in MVC application:-

create controller and inherit AppController .

example:-

using DotNetByPriyanshu;
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Mvc;

namespace DotNetByPriyanshuWebApp.Controllers.Employee
{
        private readonly IUserInfo _userInfo;
      
        public EmployeeController(IUserInfo userInfo)
        {
            _userInfo = userInfo;
        }

    public class EmployeeController : AppController // change controller in to AppController 
    {
       
        [HttpGet]
        public ActionResult EmployeeList()
        {
            try
            {
                  var objList =_userInfo.getUserDetailsByUserId(UserSession.UserId);
                  // Here I am using Session

                return View(objList);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
      
    }
}