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