Friday, May 25, 2018

Web API Demo

--------------------------------------------
PendotaAPI - Controller - CustomerController.cs
--------------------------------------------

using PendotaAPI_Repository.DTO;
using PendotaAPI_Repository.Service;
using PendotaAPI_Repository.ServiceContract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace PendotaAPI.Controllers
{
    public class CustomerController : ApiController
    {
        private ICustomer_Repository _ICustomer_Repository;

        public CustomerController()
        {
            this._ICustomer_Repository = new Customer_Repository();
        }

        [HttpGet]
        [Route("api/Customer")]
        //GET: api/Customer
        public  HttpResponseMessage Get()
        {
            try
            {
                List<Customer> curList = new List<Customer>();
                curList = _ICustomer_Repository.Get();
                HttpResponseMessage rea = Request.CreateResponse(HttpStatusCode.OK, curList.ToList());
                return rea;
                //   return Ok(curList.AsEnumerable());
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        [Route("api/Customer/{id}")]
        // GET: api/Customer/5
        [HttpGet]
        public Customer Get(int id)
        {
            return _ICustomer_Repository.GetCustomerById(id);
        }

        // POST: api/Customer
        [HttpPost]
        [Route("api/Customer")]
        public void Post([FromBody]Customer objCustomer)
        {
            try
            {
                _ICustomer_Repository.Save(objCustomer);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        // PUT: api/Customer/5
        [HttpPut]
        [Route("api/Customer/{id}")]
        public void Put(int id, [FromBody]Customer objCustomer)
        {
            try
            {
                objCustomer.CustomerID = id;
                _ICustomer_Repository.Save(objCustomer);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        // DELETE: api/Customer/5
        [HttpDelete]
        [Route("api/Customer/{id}")]
        public void Delete(int id)
        {
            try
            {
                _ICustomer_Repository.Delete(id);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }
}

--------------------------------------------
PendotaAPI - Web.config
--------------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=301879
  -->
<configuration>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.6" />
    <httpRuntime targetFramework="4.6" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  <connectionStrings>
    <add name="Dalc_Conn" connectionString="Data Source=DESKTOP-QANVEDT\SQLEXPRESS;Initial Catalog=PendotaDB;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />
      </customHeaders>
    </httpProtocol>
   
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
  <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers></system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.6.0" newVersion="5.2.6.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.6.0" newVersion="5.2.6.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>

--------------------------------------------
PendotaAPI_Repository - DTO - Customer.cs
--------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PendotaAPI_Repository.DTO
{
    public class Customer
    {
        [Key]
        public int CustomerID { get; set; }

        [Required(ErrorMessage = "Customer Name Required.")]
        public string CustomerName { get; set; }

        [Required(ErrorMessage = "Customer Phone Required.")]
        public string CustomerPhone { get; set; }

        [Required(ErrorMessage = "Customer Email Required.")]
        public string CustomerEmail { get; set; }

        [Required(ErrorMessage = "Country Required.")]
        public int Country { get; set; }

        public string Address { get; set; }

        public string Zipcode { get; set; }

        public bool Status { get; set; }

        public string CityName { get; set; }
    }
}
--------------------------------------------
PendotaAPI_Repository - Service- Customer_Repository.cs
--------------------------------------------

using PendotaAPI_Repository.DataServices;
using PendotaAPI_Repository.ServiceContract;
using PendotaAPI_Repository.DTO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace PendotaAPI_Repository.Service
{
    public class Customer_Repository : ICustomer_Repository
    {

        // Get Customer List
        public List<Customer> Get()
        {
            try
            {
                SqlParameter[] para = new SqlParameter[0];
                return new dalc().FetchListBySP<Customer>("Usp_FetchCustomerList", para);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        // Get Customer
        public Customer GetCustomerById(int id)
        {
            try
            {
                SqlParameter[] para = new SqlParameter[1];
                para[0] = new SqlParameter().CreateParameter("@CustomerID", id);
                return new dalc().FetchListBySP<Customer>("Usp_FetchCustomer", para).FirstOrDefault();
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        // Get Customer Save
        public void Save(Customer objCustomer)
        {
            try
            {
                SqlParameter[] para = new SqlParameter[7];
                para[0] = new SqlParameter().CreateParameter("@CustomerID", objCustomer.CustomerID);
                para[1] = new SqlParameter().CreateParameter("@CustomerName", objCustomer.CustomerName);
                para[2] = new SqlParameter().CreateParameter("@CustomerPhone", objCustomer.CustomerPhone);
                para[3] = new SqlParameter().CreateParameter("@CustomerEmail", objCustomer.CustomerEmail);
                para[4] = new SqlParameter().CreateParameter("@Country", objCustomer.Country);
                para[5] = new SqlParameter().CreateParameter("@Address", objCustomer.Address);
                para[6] = new SqlParameter().CreateParameter("@Zipcode", objCustomer.Zipcode);
                new dalc().IUDbySP("Usp_SaveCustomer", para);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        // Get Customer Delete
        public void Delete(int id)
        {
            try
            {
                SqlParameter[] para = new SqlParameter[1];
                para[0] = new SqlParameter().CreateParameter("@CustomerID", id);
                new dalc().IUDbySP("Usp_DeleteCustomer", para);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}

--------------------------------------------
PendotaAPI_Repository - ServiceContract - ICustomer_Repository.cs
--------------------------------------------

using PendotaAPI_Repository.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PendotaAPI_Repository.ServiceContract
{
    public interface ICustomer_Repository
    {
        List<Customer> Get();
        Customer GetCustomerById(int id);
        void Save(Customer objBank);
        void Delete(int id);
    }
}

--------------------------------------------
PendotaAPI_Repository - DataServices - dalc.cs
--------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Configuration;

namespace PendotaAPI_Repository.DataServices
{

    public class dalc
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Dalc_Conn"].ConnectionString);

        public dalc()
        {
        }

        // CRUD Opration By String Query
        public void IUDByQuery(string str)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 0;
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = str;
            //cmd.Parameters.AddRange(para);
            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();

            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
                cmd.Dispose();
            }
        }

        // Fetch DataTable By String Query
        public DataTable FetchDataTableByQuery(string str)
        {
            DataTable dt = new DataTable();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 0;
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = str.ToString();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            try
            {
                conn.Open();
                da.Fill(dt);
                return dt;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
                cmd.Parameters.Clear();
                cmd.Dispose();
                // conn.Dispose();
            }
        }

        // Fetch DataSet By String Query
        public DataSet FetchDataSetByQuery(string str)
        {
            DataSet ds = new DataSet();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 0;
            cmd.Connection = conn;
            cmd.CommandText = str.ToString();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            try
            {
                conn.Open();
                da.Fill(ds);
                return ds;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
                cmd.Parameters.Clear();
                cmd.Dispose();
                conn.Dispose();
            }
        }

        // Fetch List By String Query
        public List<T> FetchListByQuery<T>(string str)
        {
            DataTable dt = new DataTable();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 0;
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = str.ToString();
            SqlDataReader dr;
            try
            {
                conn.Open();
                dr = cmd.ExecuteReader();
                List<T> lst = new List<T>();
                while (dr.Read())
                {
                    T item = CommonFunctions.GetItem<T>(dr);
                    lst.Add(item);
                }
                return lst;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
                cmd.Parameters.Clear();
                cmd.Dispose();
                // conn.Dispose();
            }
        }


        // CRUD Opration By String Store Procedure
        public void IUDbySP(string SPName, SqlParameter[] para)
        {
            SqlCommand cmd = GetCommand();
            cmd.CommandText = SPName.ToString();
            cmd.Parameters.AddRange(para);
            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
                cmd.Parameters.Clear();
                cmd.Dispose();
                conn.Dispose();
            }
        }

        // Fetch DataTable By Store Procedure
        public DataTable FetchDataTableBySP(string Spname, SqlParameter[] para)
        {
            DataTable dt = new DataTable();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 0;
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddRange(para);
            cmd.CommandText = Spname.ToString();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            try
            {
                conn.Open();
                da.Fill(dt);
                return dt;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
                cmd.Parameters.Clear();
                cmd.Dispose();
                conn.Dispose();
            }
        }

        // Fetch DataSet By Store Procedure
        public DataSet FetchDataSetBySP(string Spname, SqlParameter[] para)
        {
            DataSet ds = new DataSet();
            SqlCommand cmd = GetCommand();
            cmd.Parameters.AddRange(para);
            cmd.CommandText = Spname.ToString();
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            try
            {
                conn.Open();
                da.Fill(ds);
                return ds;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
                cmd.Parameters.Clear();
                cmd.Dispose();
                conn.Dispose();
            }
        }

        // Fetch List By Store Procedure
        public List<T> FetchListBySP<T>(string Spname, SqlParameter[] para)
        {
            DataTable dt = new DataTable();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 0;
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddRange(para);
            cmd.CommandText = Spname.ToString();
            SqlDataReader dr;
            try
            {
                conn.Open();
                dr = cmd.ExecuteReader();
                List<T> lst = new List<T>();
                while (dr.Read())
                {
                    T item = CommonFunctions.GetItem<T>(dr);
                    lst.Add(item);
                }
                return lst;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
                cmd.Parameters.Clear();
                cmd.Dispose();
                // conn.Dispose();
            }
        }


        // Call By Store Procedure
        public SqlCommand GetCommand()
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 0;
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;
            return cmd;
        }

        // Fetch DataTable By String Query With Parameter
        public DataTable FetchDataTableByText(string Query, SqlParameter[] para)
        {
            DataTable dt = new DataTable();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 0;
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddRange(para);
            cmd.CommandText = Query.ToString();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            try
            {
                conn.Open();
                da.Fill(dt);
                return dt;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
                cmd.Parameters.Clear();
                cmd.Dispose();
                // conn.Dispose();
            }
        }

        // Fetch List By String Query With Parameter
        public List<T> FetchListByText<T>(string Query, SqlParameter[] para)
        {
            DataTable dt = new DataTable();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 0;
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddRange(para);
            cmd.CommandText = Query.ToString();
            SqlDataReader dr;
            try
            {
                conn.Open();
                dr = cmd.ExecuteReader();
                List<T> lst = new List<T>();
                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        T item = CommonFunctions.GetItem<T>(dr);
                        lst.Add(item);
                    }
                }
                return lst;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
                cmd.Parameters.Clear();
                cmd.Dispose();
                // conn.Dispose();
            }
        }

    }
}

--------------------------------------------
PendotaAPI_Repository - DataServices - CreatePara.cs
--------------------------------------------

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PendotaAPI_Repository.DataServices
{
    public static class CreatePara
    {
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, string paraVal, int size = 50, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.Size = size;
            para.SqlDbType = System.Data.SqlDbType.NVarChar;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, int paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.Int;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, decimal paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.Decimal;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, float paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.Float;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, DateTime paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.IsNullable = true;
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.DateTime;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, System.Data.DataTable paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.Structured;
            para.Direction = dir;
            return para;
        }
    }
}



--------------------------------------------
PendotaAPI_Repository - DataServices - CommonFunctions.cs
--------------------------------------------

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Drawing;
using System.IO;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System.Web.UI;
using System.Reflection;
using System.Net.Mail;
using System.Configuration;
using System.Net;
using System.Data.SqlClient;
using System.Web.Script.Serialization;

namespace PendotaAPI_Repository.DataServices
{
    public static class CommonFunctions
    {
        // Convert To List
        public static List<T> ConvertToList<T>(this DataTable dt)
        {
            List<T> data = new List<T>();
            foreach (DataRow row in dt.Rows)
            {
                //T item = GetItem<T>(row);
                //data.Add(item);
            }
            return data;
        }
        // Convert To Class
        public static T GetItem<T>(SqlDataReader dr)
        {
            Type temp = typeof(T);
            T obj = Activator.CreateInstance<T>();

            for (int i = 0; i < dr.FieldCount; i++)
            {
                foreach (PropertyInfo pro in temp.GetProperties())
                {
                    if (pro.Name.ToLower() == "barcode")
                    {
                        var abc = "";
                    }
                    if (pro.Name.ToLower() == dr.GetName(i).ToLower())
                    {
                        if (!string.IsNullOrEmpty(Convert.ToString(dr[i])))
                        {
                            if (pro.PropertyType.Name == "String")
                                pro.SetValue(obj, Convert.ToString(dr[i]));
                            else if (pro.PropertyType.Name == "Byte[]" && string.IsNullOrEmpty(Convert.ToString(dr[i])))
                                pro.SetValue(obj, new byte[0]);
                            else
                                pro.SetValue(obj, dr[i]);
                        }
                        break;
                    }
                }
            }
            return obj;
        }
        // Random String
        public static string RandomString(int Size)
        {
            Random random = new Random();
            string input = "abcdefghijklmnopqrstuvwxyz0123456789";
            var chars = Enumerable.Range(0, Size).Select(x => input[random.Next(0, input.Length)]);
            return new string(chars.ToArray());
        }
        // Encode Function
        public static string Base64Encode(string plainText)
        {
            try
            {
                var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
                return System.Convert.ToBase64String(plainTextBytes);
            }
            catch (Exception)
            {
                throw;
            }

        }
        // Decode Function
        public static string Base64Decode(string base64EncodedData)
        {
            try
            {
                var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
                return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
            }
            catch (Exception)
            {
                throw;
            }
        }
        // Convert DataTable to Json
        public static string ConvertToJSON(this DataTable table, Boolean IsSkipTotalRow = true)
        {
            var list = new List<Dictionary<string, object>>();

            foreach (DataRow row in table.Rows)
            {
                var dict = new Dictionary<string, object>();

                foreach (DataColumn col in table.Columns)
                {
                    if (IsSkipTotalRow && col.ColumnName.ToLower() != "totalrows")
                        dict[col.ColumnName] = row[col];
                }
                list.Add(dict);
            }
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.MaxJsonLength = Int32.MaxValue;
            return serializer.Serialize(list);
        }
        // Convert DataTable to Json
        public static string GetJsonForDataTableJS(this DataTable dt)
        {
            StringBuilder sb = new StringBuilder();
            string data = dt.ConvertToJSON();
            sb.AppendLine("{\"data\":" + data);
            sb.Append(",\"draw\":\"" + Convert.ToString(HttpContext.Current.Request.Form["draw"]) + "\"");
            sb.Append(",\"recordsFiltered\":\"" + (dt.Rows.Count == 0 ? "0" : dt.Rows[0]["TotalRows"].ToString()) + "\"");
            sb.Append(",\"recordsTotal\":\"" + (dt.Rows.Count == 0 ? "0" : dt.Rows[0]["TotalRows"].ToString()) + "\"}");
            return sb.ToString();
        }

    }
}

Monday, March 12, 2018

MVC Demo With Grid Paging,Sorting,Serching

===============================
Home Controller - Controller
===============================
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UniqDataMvc.DataService;
using UniqDataMvc.Models;

namespace UniqDataMvc.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetEmployees()
        {
            using (VensystemMvcEntities dc = new VensystemMvcEntities())
            {
                //dalc dc = new dalc();
                //var employees = dc.EmployeeMasters.OrderBy(a => a.Name).ToList();
                //return Json(new { data = employees }, JsonRequestBehavior.AllowGet);

                List<EmployeeMaster> emp = new dalc().selectbyquerydt("select E.*,D.DepName As DepartmentName from EmployeeMaster as E inner join departmentMaster as D on D.DepId=E.depId").ConvertToList<EmployeeMaster>().ToList();
                return Json(new { data = emp }, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpGet]
        public ActionResult Save(int id)
        {
            using (VensystemMvcEntities dc = new VensystemMvcEntities())
            {
                var v = dc.EmployeeMasters.Where(a => a.EmpId == id).FirstOrDefault();
                ViewBag.deptList = dc.departmentMasters.ToList();
                return View(v);
            }
        }

        public ActionResult Save(EmployeeMaster emp)
        {
            bool status = false;
            if (ModelState.IsValid)
            {
                using (VensystemMvcEntities dc = new VensystemMvcEntities())
                {
                    if (emp.EmpId > 0)
                    {
                        //Edit
                        var v = dc.EmployeeMasters.Where(a => a.EmpId == emp.EmpId).FirstOrDefault();
                        if (v != null)
                        {
                            v.Name = emp.Name;
                            v.Email = emp.Email;
                            v.MobileNo = emp.MobileNo;
                            v.depId = emp.depId;
                            v.Birthdate = emp.Birthdate;
                        }
                    }
                    else
                    {
                        //Save
                        dc.EmployeeMasters.Add(emp);
                    }
                    dc.SaveChanges();
                    status = true;
                }
            }
            return new JsonResult { Data = new { status = status } };
        }

        [HttpGet]
        public ActionResult Delete(int id)
        {
            using (VensystemMvcEntities dc = new VensystemMvcEntities())
            {
                EmployeeMaster v = dc.EmployeeMasters.Where(a => a.EmpId == id).FirstOrDefault();
                if (v != null)
                {
                    return View(v);
                }
                else
                {
                    return HttpNotFound();
                }
            }
        }

        [HttpPost]
        [ActionName("Delete")]
        public ActionResult DeleteEmployee(int id)
        {
            bool status = false;
            using (VensystemMvcEntities dc = new VensystemMvcEntities())
            {
                var v = dc.EmployeeMasters.Where(a => a.EmpId == id).FirstOrDefault();
                if (v != null)
                {
                    dc.EmployeeMasters.Remove(v);
                    dc.SaveChanges();
                    status = true;
                }
            }
            return new JsonResult { Data = new { status = status } };
        }
    }
}
===============================
Model Class -- CLass
===============================
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace UniqDataMvc.Models
{
    [MetadataType(typeof(EmployeeMetadata))]
    public partial class EmployeeMaster
    {
        public string DepartmentName { get; set; }
    }

    public class EmployeeMetadata
    {
        [Required(AllowEmptyStrings = false, ErrorMessage = "Please provide first name")]
        public string Name { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Please Select department")]
        public int depId { get; set; }

        [Required(ErrorMessage = "Email Required.")]
        [DataType(DataType.EmailAddress, ErrorMessage = "Email is not valid")]
        public string Email { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Please provide Mobile No")]
        public string MobileNo { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Please provide Birthdate")]
        public string Birthdate { get; set; }
    }
}
===============================
Index.cshtml - List -- View
===============================

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" />
    <link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />
    <style>
        span.field-validation-error {
            color: red;
        }
    </style>
</head>
<body>
    <div style="width:90%; margin:0 auto" class="tablecontainer">
        <a class="popup btn btn-primary" href="/home/save/0" style="margin-bottom:20px; margin-top:20px;">Add New Employee</a>
        <table id="myDatatable">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>dep Name</th>
                    <th>Email</th>
                    <th>MobileNo</th>
                    <th>Birthdate</th>
                    <th>Edit</th>
                    <th>Delete</th>
                </tr>
            </thead>
        </table>
    </div>

    <script src="~/Scripts/jquery-3.1.1.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>

    <script>
        $(document).ready(function () {
            var oTable = $('#myDatatable').DataTable({
                "ajax": {
                    "url" : '/home/GetEmployees',
                    "type" : "get",
                    "datatype" : "json"
                },
                "pageLength": 5,
                "columns": [
                    { "data": "Name", "autoWidth": true },
                    //{ "data": "depId", "autoWidth" : true},
                    { "data": "DepartmentName", "autoWidth": true},
                    { "data": "Email", "autoWidth": true },
                    { "data": "MobileNo", "autoWidth": true },
                    { "data": "Birthdate", "autoWidth": true },
                    {
                        "data": "EmpId", "width": "50px", "render": function (data) {
                            return '<a class="popup" href="/home/save/'+data+'">Edit</a>';
                        }
                    },
                    {
                        "data": "EmpId", "width": "50px", "render": function (data) {
                            return '<a class="popup" href="/home/delete/' + data + '">Delete</a>';
                        }
                    }
                ]
            })
            $('.tablecontainer').on('click', 'a.popup', function (e) {
                debugger
                e.preventDefault();
                OpenPopup($(this).attr('href'));
            })
            function OpenPopup(pageUrl) {
                debugger
                var $pageContent = $('<div/>');
                $pageContent.load(pageUrl, function () {
                    $('#popupForm', $pageContent).removeData('validator');
                    $('#popupForm', $pageContent).removeData('unobtrusiveValidation');
                   // $.validator.unobtrusive.parse('form');

                });

                $dialog = $('<div class="popupWindow" style="overflow:auto"></div>')
                          .html($pageContent)
                          .dialog({
                              draggable : false,
                              autoOpen : false,
                              resizable : false,
                              model : true,
                              title:'Popup Dialog',
                              height : 550,
                              width : 600,
                              close: function () {
                                  $dialog.dialog('destroy').remove();
                              }
                          })

                $('.popupWindow').on('submit', '#popupForm', function (e) {
                    debugger
                    var url = $('#popupForm')[0].action;
                    $.ajax({
                        type : "POST",
                        url : url,
                        data: $('#popupForm').serialize(),
                        success: function (data) {
                            if (data.status) {
                                $dialog.dialog('close');
                                oTable.ajax.reload();
                            }
                        }
                    })

                    e.preventDefault();
                })

                $dialog.dialog('open');
            }
        })
    </script>
</body>
</html>
===============================
Save.cshtml - IU Functionality -- View
===============================
@model UniqDataMvc.Models.EmployeeMaster

<h2>Save</h2>

@using (Html.BeginForm("save", "home", FormMethod.Post, new { id = "popupForm" }))
{
    if (Model != null && Model.EmpId > 0)
    {
        @Html.HiddenFor(a => a.EmpId)
    }

    <div class="form-group">
        <label>First Name</label>
        @Html.TextBoxFor(a => a.Name, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.Name)
    </div>
    <div class="form-group">
        <label>Department Name</label>
        @Html.DropDownListFor(x => x.depId, new SelectList(ViewBag.deptList, "DepId", "DepName"), "Select", htmlAttributes: new { @class = "select form-control" })
        @Html.ValidationMessageFor(a => a.depId)
    </div>
    <div class="form-group">
        <label>Email</label>
        @Html.TextBoxFor(a => a.Email, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.Email)
    </div>
    <div class="form-group">
        <label>MobileNo</label>
        @Html.TextBoxFor(a => a.MobileNo, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.MobileNo)
    </div>
    <div class="form-group">
        <label>Birthdate</label>
        @Html.TextBoxFor(a => a.Birthdate, new { @class = "form-control",type="date" })
        @Html.ValidationMessageFor(a => a.Birthdate)
    </div>
 

    <div>
        <input type="submit" value="Save" />
    </div>
}

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
===============================
CommonFunction - -- DataServices
===============================
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;

namespace UniqDataMvc.DataService
{
    public static class CommmanFunction
    {
        public static List<T> ConvertToList<T>(this DataTable dt)
        {
            List<T> data = new List<T>();
            foreach (DataRow row in dt.Rows)
            {
                T item = GetItem<T>(row);
                data.Add(item);
            }
            return data;
        }
        public static T GetItem<T>(DataRow dr)
        {
            Type temp = typeof(T);
            T obj = Activator.CreateInstance<T>();

            foreach (DataColumn column in dr.Table.Columns)
            {
                foreach (PropertyInfo pro in temp.GetProperties())
                {
                    if (pro.Name == column.ColumnName)
                    {
                        if (!string.IsNullOrEmpty(Convert.ToString(dr[column.ColumnName])))
                        {
                            if (pro.PropertyType.Name == "String")
                                pro.SetValue(obj, Convert.ToString(dr[column.ColumnName]));
                            else
                                pro.SetValue(obj, dr[column.ColumnName]);
                        }
                    }
                    else
                        continue;
                }
            }
            return obj;
        }
    }
}
===============================
CreatePara - -- DataServices
===============================
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace UniqDataMvc.DataService
{
    public static class CreatePara
    {
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, string paraVal, int size = 50, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.Size = size;
            para.SqlDbType = System.Data.SqlDbType.NVarChar;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, int paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.Int;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, decimal paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.Decimal;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, float paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.Float;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, DateTime paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.DateTime;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, System.Data.DataTable paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.Structured;
            para.Direction = dir;
            return para;
        }
    }
}
===============================
Dalc - -- DataServices
===============================
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Web;

namespace UniqDataMvc.DataService
{
    public class dalc
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Dalc_Conn"].ConnectionString);
        // SqlConnection conn;

        public dalc()
        {
            //conn.ConnectionString = ConfigurationSettings.AppSettings["myconn"];


            // conn.ConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

        }

        public DataSet selectbyquery(string str)
        {
            DataSet ds = new DataSet();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 0;
            cmd.Connection = conn;
            cmd.CommandText = str.ToString();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            try
            {
                conn.Open();
                da.Fill(ds);
                return ds;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
                cmd.Parameters.Clear();
                cmd.Dispose();
                conn.Dispose();
            }
        }

        public DataTable selectbyquerydt(string str)
        {
            DataTable dt = new DataTable();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 0;
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = str.ToString();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            try
            {
                conn.Open();
                da.Fill(dt);
                return dt;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
                cmd.Parameters.Clear();
                cmd.Dispose();
                conn.Dispose();
            }
        }

       
    }
}

Demo for Repository Pattern in ASP.Net

----------------------------------------------------------- ----------------------------------------------------------- Repository Projec...