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;
            }
        }
      
    }
}

Monday, 6 April 2020

Create 'Validate Session Attribute' for validating session in MVC application.

Create 'Validate Session Attribute' for validating session  in MVC application.



using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace HRMS.UTILITIES
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class ValidateSessionAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (HttpContext.Current.Session["UserId"] == null ||  HttpContext.Current.Session["DivisionId"] == null)
            {
                filterContext.Result = new RedirectToRouteResult(new

                               RouteValueDictionary(new { controller = "Login", action = "Login", area = "" }));
                return;
            }
            base.OnActionExecuting(filterContext);
        }
    }
}


USE:- [ValidateSession]  over controller or methods

Saturday, 4 April 2020

Generic Collections

Generic Collections:-

List<T> :  It contains elements of specified type. It grows automatically as you add elements in it. 

Dictionary<TKey,TValue>: It contains key-value pairs.

SortedList<TKey,TValue>: SortedList stores key and value pairs. It automatically adds the elements in ascending order of key by default.

Hashset<T>: Hashset<T> contains non-duplicate elements. It eliminates duplicate elements.

Queue<T>: Queue<T> stores the values in FIFO style (First In First Out). It keeps the order in which the values were added. It provides an Enqueue() method to add values and a Dequeue() method to retrieve values from the collection.

Stack<T>: Stack<T> stores the values as LIFO (Last In First Out). It provides a Push() method to add a value and Pop() & Peek() methods to retrieve values.

Wednesday, 1 April 2020

Get Vs Post, Put Vs Patch, Put Vs Post,

difference between Get and Post method c#

                         Get                                                                   Post

1. GET requests can be cached                    1. POST requests are never cached

2. GET requests remain in the browser         2. POST requests do not remain in the 
     history                                                      browser history

3. GET requests can be bookmarked            3. POST requests cannot be bookmarked

4. GET requests have length restrictions       4. POST requests have no restrictions 
                                                                     on data length

5. GET requests are only used to request      5. POST requests are only used to 
    data (not modify).                                      request data modify.    



difference between Put and Post method c#

                        Put                                                                      Post

1. This method is idempotent.                      1. This method is not idempotent.

2. We use UPDATE query in PUT.              2. We use create query in POST.

3. Put works as specific                              3. Post work as abstract.

4. in Put method, the client decides           4. In Post method, the server decides 
    which URI resource should have.              which URI resource should have .

difference between Put and Patch method c#

                        Put                                                                 Patch 

1. Put is used to replace  an existing             1. Patch is used to replace  an existing
    resource entirely.                                        resource partially. 

2. Put is idempotent.                                   2. Patch can be idempotent, but not
                                                                     required 

                

Monday, 30 March 2020

Difference between interface and abstract class c#


Difference between interface and abstract class c#


               Interface                                               Abstract Class



1. Interface is by-default ‘Public’.                                       1. Abstract class is by-default ‘Private’.

2. Interface have declaration only,                              2. Abstract class can have declaration and
   it contains only methods declaration.                      and implementation part, it can have fields also.

3. Interface cannot be implementing partially.                3. Abstract class can be implementing partially.

4. An interface can inherit from another interface         4. An abstract class can inherit from another abstract 
    only and cannot inherit form an abstract class.              class or another interface.

5. Class can inherit multiple interfaces at the                 5. Class cannot inherit multiple classes at the same 
    same time.                                                                             time.

6. An interface cannot have Access Specifiers.               6. An abstract can have Access Specifiers.

Friday, 20 March 2020

How to find Missing Element in Series(1, 3, 5, 9, 11).

How to find Missing Element in Series(1, 3, 5, 9, 11).

Main Program

using System;
namespace DotNetByPriyanshu
{
    class Program
    {
        static void Main(string[] args)
        {

            int[] Series1 = { 1, 3, 5, 9, 11 }; // Output : 7
            int[] Series2 = { 2, 4, 6, 10, 12 }; // Output : 8

            // creating an object of missingElement  Class
            missingElement missingElement = new missingElement();

            int result1 = missingElement.Missing(Series1.Length, Series1);
            Console.WriteLine("Missing Element  for Series1= " + result1);

            int result2 = missingElement.Missing(Series2.Length, Series2);
            Console.WriteLine("Missing Element  for Series2= " + result2);

            Console.ReadLine();
        }
    }
}


Method:


namespace DotNetByPriyanshu
{
    public class missingElement
    {
        public int Missing(int size, int[] Array)
        {
            //Arithmetic Series sum of sequence.
            //sn=n/2[2a+(n-1)d]
            //sumOfSeries=1+3+5+9+11;
            //MissingNumber=sn-sumOfSeries.

            int MissingNumber = 0;
            int n = Array.Length + 1;
            int d = Array[1] - Array[0];
            int sn = n / 2 * (2 * Array[0] + (n - 1) * d);  // Formula

            // Sum of array.

            int sumOfArray = 0;
            for (int i = 0; i < Array.Length; i++)
            {
                sumOfArray = sumOfArray + Array[i];
            }

           // Calculate Missing Element.

            MissingNumber = sn - sumOfArray;
            return MissingNumber;
        }
    }
}


Output:

 Series1= { 1, 3, 5, 9, 11 }; // Output : 7
 Series2= { 2, 4, 6, 10, 12 }; // Output : 8