Subscribe Us

LightBlog

Monday, 27 July 2020

July 27, 2020

CRUD Operations using MVC scaffolding with LINQ to SQL

In this article,I will show you CRUD operations using mvc scaffolding with linq to sql.

---Table Script---
create table Employee
(
   id int primary key identity(1,1),
   name varchar(50),
   salary decimal(18,2)
)

Here must add package in project solution :
   System.Data.Linq

---Model Class---
[Table]
public class Employee
{
    [Column(IsPrimaryKey = true, IsDbGenerated = true)]
    public int id { get; set; }
    [Column]
    public string name { get; set; }
    [Column]
    public decimal salary { get; set; }
}

---employee controller--
DataContext dc = new DataContext("Data Source=.;Initial Catalog=TESTDB;Integrated Security=True");

public ActionResult Index()
{
    IEnumerable<Employee> emp_data = dc.GetTable<Employee>();
    return View(emp_data);
}

public ActionResult Create()
{
    return View();
}

[HttpPost]
public ActionResult Create(Employee emp)
{
    dc.GetTable<Employee>().InsertOnSubmit(emp);
    dc.SubmitChanges();
    return RedirectToAction("Index");
}

[HttpGet]
public ActionResult Edit(int id)
{
    Employee emp = dc.GetTable<Employee>().Single(x => x.id == id);
    return View(emp);
}

[HttpPost]
public ActionResult Edit(Employee empobj)
{
    Employee emp = dc.GetTable<Employee>().Single(x => x.id == empobj.id);
    UpdateModel(emp);
    dc.SubmitChanges();
    return RedirectToAction("Index");
}

[HttpGet]
public ActionResult Delete(int id)
{
    Employee emp = dc.GetTable<Employee>().Single(x => x.id == id);
    return View(emp);
}

[HttpPost]
public ActionResult Delete(Employee empobj)
{
    Employee emp = dc.GetTable<Employee>().Single(x => x.id == empobj.id);
    dc.GetTable<Employee>().DeleteOnSubmit(emp);
    dc.SubmitChanges();
    return RedirectToAction("Index");
}

Note: Accoding to action method you can add scaffolding templet on view.

Thursday, 9 July 2020

July 09, 2020

How to Binding local data in Event Scheduler in Angular 7 ?

- app.component.html
<router-outlet></router-outlet>

- app.component.ts
import { Component } from '@angular/core';
import { EventSettingsModel, DayService, WeekService, WorkWeekService, MonthService, AgendaService } from '@syncfusion/ej2-angular-schedule';

@Component({
  selector: 'app-root',
  providers: [DayService, WeekService, WorkWeekService, MonthService, AgendaService],
  // specifies the template string for the Schedule component
  template: `<ejs-schedule width='100%' height='550px' 
  [selectedDate]='selectedDate' [eventSettings]='eventSettings'></ejs-schedule>`
})
export class AppComponent {
    public selectedDate: Date = new Date(2028, 1, 15);
    public eventSettings: EventSettingsModel = {
        dataSource: [
        {
            Id: 1,
            Subject: 'Explosion of Betelgeuse Star',
            StartTime: new Date(2018, 1, 15, 9, 30),
            EndTime: new Date(2018, 1, 15, 11, 0)
        }, {
            Id: 2,
            Subject: 'Thule Air Crash Report',
            StartTime: new Date(2018, 1, 12, 12, 0),
            EndTime: new Date(2018, 1, 12, 14, 0)
        }, {
            Id: 3,
            Subject: 'Blue Moon Eclipse',
            StartTime: new Date(2018, 1, 13, 9, 30),
            EndTime: new Date(2018, 1, 13, 11, 0)
        }]
    };
 }

- app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ScheduleModule } from '@syncfusion/ej2-angular-schedule';
import { ButtonModule } from '@syncfusion/ej2-angular-buttons';
import { DayService, WeekService, WorkWeekService, MonthService, AgendaService, MonthAgendaService} from '@syncfusion/ej2-angular-schedule';
import { AppComponent } from './app.component';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        ScheduleModule,
        ButtonModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [DayService, 
                WeekService, 
                WorkWeekService, 
                MonthService,
                AgendaService,
                MonthAgendaService]
})
export class AppModule { }

-app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';


const routes: Routes = [];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
Note:

Setup Angular Environment
You can use Angular CLI to setup your Angular applications. To install Angular CLI use the following command.
npm install -g @angular/cli

Create an Angular Application
Start a new Angular application using below Angular CLI command.

ng new my-app
cd my-app

Adding Syncfusion Schedule package
To install Schedule component, use the following command.
npm install @syncfusion/ej2-angular-schedule --save
                        

Wednesday, 1 July 2020

July 01, 2020

QRCode and Barcode generate in ASP.NET MVC

In this article, i will show you how to generate QRCode and Barcode in  ASP.NET MVC
  • Add this two packages QRCoder and GenCode128
         #region QR Code Generation 
        public ActionResult GetQRCodeImage(string qrcode)
        {
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(qrcode,
            QRCodeGenerator.ECCLevel.Q);
            QRCode qrCode = new QRCode(qrCodeData);
            Bitmap qrCodeImage = qrCode.GetGraphic(20);
            ImageConverter converter = new ImageConverter();
            byte[] img = (byte[])converter.ConvertTo(qrCodeImage, typeof(byte[]));
            return new FileStreamResult(new System.IO.MemoryStream(img), "image/jpeg");
        }
        #endregion

        #region Bar Code Generation
        public ActionResult GetBarcodeImage(string brcode)
        {
            Image myimg = Code128Rendering.MakeBarcodeImage(brcode, int.Parse("2"), true);
            ImageConverter converter = new ImageConverter();
            byte[] img = (byte[])converter.ConvertTo(myimg, typeof(byte[]));
            return new FileStreamResult(new System.IO.MemoryStream(img), "image/jpeg");
        }
        #endregion

QRCode
QRCode
Code128
GenCode128
 

Tuesday, 30 June 2020

June 30, 2020

Display Colorized Rows Of WebGrid In ASP.NET MVC

script type="text/javascript">
    $(document).ready(function()  
       {  
  
        $('#gridMapping > tbody > tr').each(function(index)  
            {  
  
            if ($(this).children('td:nth-child(5)').text() == "Done")  
            {  
                $(this).children('td').css("background-color", "#33CC99");  
            } else   
            {  
                $(this).children('td').css("background-color", "#FFCC99");  
            }  
  
        });  
    });  
</script>


Sunday, 28 June 2020

June 28, 2020

Asp.Net MVC CRUD Operations Using Datatable

Table Script

CREATE TABLE [dbo].[Employee](
[EmployeeID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Position] [varchar](50) NULL,
[Office] [varchar](50) NULL,
[Age] [int] NULL,
[Salary] [int] NULL,
)

Command to update MVC old versions to MVC 5.1 ➤ Install-Package Microsoft.AspNet.MVC -Version 5.1.0
implementing crud operation using ADO.NET Entity Model.

Employee Controller

-Create Empty controller.
public ActionResult Index() { return View(); } public ActionResult GetData() { using (MvcCRUDDBEntities db = new MvcCRUDDBEntities()) { List<Employee> empList = db.Employees.ToList<Employee>(); return Json(new { data = empList }, JsonRequestBehavior.AllowGet); } } [HttpGet] public ActionResult AddOrEdit(int id = 0) { if (id == 0) return View(new Employee()); else { using (MvcCRUDDBEntities db = new MvcCRUDDBEntities()) { return View(db.Employees.Where(x => x.EmployeeID==id).FirstOrDefault<Employee>()); } } } [HttpPost] public ActionResult AddOrEdit(Employee emp) { using (MvcCRUDDBEntities db = new MvcCRUDDBEntities()) { if (emp.EmployeeID == 0) { db.Employees.Add(emp); db.SaveChanges(); return Json(new { success = true, message = "Record Saved Successfully" }, JsonRequestBehavior.AllowGet); } else { db.Entry(emp).State = EntityState.Modified; db.SaveChanges(); return Json(new { success = true, message = "Record Updated Successfully" }, JsonRequestBehavior.AllowGet); } } } [HttpPost] public ActionResult Delete(int id) { using (MvcCRUDDBEntities db = new MvcCRUDDBEntities()) { Employee emp = db.Employees.Where(x => x.EmployeeID == id).FirstOrDefault<Employee>(); db.Employees.Remove(emp); db.SaveChanges(); return Json(new { success = true, message = "Record Deleted Successfully" }, JsonRequestBehavior.AllowGet); } } }

-Add view for method Index and AddOrEdit
-add Bootstrap and jQuery UI nuGet Package

Index.cshtml

@{
    ViewBag.Title = "Employee List";
}

<h2>Employee CRUD Operations</h2>

<a class="btn btn-success" style="margin-bottom:10px" onclick="PopupForm('@Url.Action("AddOrEdit","Employee")')"><i class="fa fa-plus"></i> Add New</a>
<table id="employeeTable" class="table table-striped table-bordered" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Salary</th>
            <th></th>
        </tr>
    </thead>
</table>

<link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

@section scripts{
    <script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>

    <script>
        var Popup, dataTable;
        $(document).ready(function () {
            dataTable =  $("#employeeTable").DataTable({
                "ajax": {
                    "url": "/Employee/GetData",
                    "type": "GET",
                    "datatype": "json"
                },
                "columns": [
                    { "data": "Name" },
                    { "data": "Position" },
                    { "data": "Office" },
                    { "data": "Age" },
                    { "data": "Salary" },
                    {"data":"EmployeeID" , "render" : function (data) {
                        return "<a class='btn btn-default btn-sm' onclick=PopupForm('@Url.Action("AddOrEdit","Employee")/" + data + "')><i class='fa fa-pencil'></i> Edit</a><a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete("+data+")><i class='fa fa-trash'></i> Delete</a>";
                    },
                        "orderable": false,
                        "searchable":false,
                        "width":"150px"
                    }

                ],
                "language": {

                    "emptyTable" : "No data found, Please click on <b>Add New</b> Button"
                }
            });
        });

        function PopupForm(url) {
            var formDiv = $('<div/>');
            $.get(url)
            .done(function (response) {
                formDiv.html(response);

                Popup = formDiv.dialog({
                    autoOpen: true,
                    resizable: false,
                    title: 'Fill Employee Details',
                    height: 500,
                    width: 700,
                    close: function () {
                        Popup.dialog('destroy').remove();
                    }

                });
            });
        }

        function SubmitForm(form) {
            $.validator.unobtrusive.parse(form);
            if($(form).valid()){
                $.ajax({
                    type : "POST",
                    url : form.action,
                    data : $(form).serialize(),
                    success : function (data) {
                        if(data.success)
                        {
                            Popup.dialog('close');
                            dataTable.ajax.reload();

                            $.notify(data.message,{
                                globalPosition :"top center",
                                className : "success"
                            })

                        }
                    }
                });
            }
            return false;
        }

        function Delete(id) {
            if(confirm('Are You Sure to Delete this Employee Record ?'))
            {
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("Delete","Employee")/' + id,
                    success: function (data) {
                        if (data.success)
                        {
                            dataTable.ajax.reload();

                            $.notify(data.message, {
                                globalPosition: "top center",
                                className: "success"
                            })

                        }
                    }

                });
            }
        }
    </script>
}

AddOrEdit.cshtml

@model Asp.NETMVCCRUD.Models.Employee @{ Layout = null; } @using (Html.BeginForm("AddOrEdit", "Employee", FormMethod.Post, new {onsubmit = "return SubmitForm(this)" })) { @Html.HiddenFor(model => model.EmployeeID) <div class="form-group"> @Html.LabelFor(model => model.Name, new { @class = "control-label" }) @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name) </div> <div class="form-group"> @Html.LabelFor(model => model.Position, new { @class = "control-label" }) @Html.EditorFor(model => model.Position, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Position) </div> <div class="form-group"> @Html.LabelFor(model => model.Office, new { @class = "control-label" }) @Html.EditorFor(model => model.Office, new { htmlAttributes = new { @class = "form-control" } }) </div> <div class="form-group"> @Html.LabelFor(model => model.Age, new { @class = "control-label" }) @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } }) </div> <div class="form-group"> @Html.LabelFor(model => model.Salary, new { @class = "control-label" }) <div class="input-group"> <span class="input-group-addon">$</span> @Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } }) </div> </div> <div class="form-group"> <input type="submit" value="Submit" class="btn btn-primary" /> <input type="reset" value="Reset" class="btn" /> </div> }

Monday, 8 June 2020

June 08, 2020

How to save data from Html controls in your local storage when page is load

Index.html

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <title></title>
   </head>
   <script type="text/javascript"></script>
   <body>
      <center>
         From Date:<br>
         <input type="date" id="datefrom" name="datefrom" class="auto-save">
         <br>
         To Date:<br>
         <input type="date" id="to" name="dateto" class="auto-save">
         <br>
      </center>
      <br><br><br><br>
      <button type="button" name="button" onclick="dstry()">Destroy all data</button>
   </body>
</html>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha384-vk5WoKIaW/vJyUAd9n/wmopsmNhiy+L2Z+SBxGYnUkunIxVxAv/UtMOhba/xskxh" crossorigin="anonymous"></script>
<script type="text/javascript" src="savy.js"></script>
<script type="text/javascript">
   $('.auto-save').savy('load',function(){
     console.log("All data from savy are loaded");
   });
   
   function dstry(){
     $('.auto-save').savy('destroy',function(){
       console.log("All data from savy are Destroyed");
       window.location.reload();
     });
   }
</script>

savy.js

(function($) {
  $.fn.savy = function(order,fn) {
    const sv = "savy-";
    if (order == "load") {
      $(this).each(function() {
        if ($(this).is(":radio")) {
          if(localStorage.getItem(sv+$(this).attr("name"))){
            if (localStorage.getItem(sv+$(this).attr("name")) == this.id) {
              this.checked = true;
            }else{
              this.checked = false
            }
          }
          $(this).change(function() {
            localStorage.setItem(sv+$(this).attr("name"), this.id);
          });
        }else if($(this).is(":checkbox")){
          if(localStorage.getItem(sv+this.id)){
            this.checked = (localStorage.getItem(sv+this.id) == "1" ? true : false);
          }
          $(this).change(function() {
            localStorage.setItem(sv+this.id, (this.checked ? "1" : "0"));
          });
        }else if($(this).is("input") || $(this).is("textarea")) {
          if(localStorage.getItem(sv+this.id)){
            this.value = localStorage.getItem(sv+this.id);
          }
          $(this).keyup(function() {
            localStorage.setItem(sv+this.id, this.value);
          });
        }else if($(this).is("select")) {
          if ($(this).is("[multiple]")) {
            if(localStorage.getItem(sv+this.id)){
              $(this).val(localStorage.getItem(sv+this.id).split(","));
            }else{
              localStorage.setItem(sv+this.id, $(this).val());
            }
            $(this).change(function() {
              localStorage.setItem(sv+this.id, $(this).val());
            });
          }else{
            if(localStorage.getItem(sv+this.id)){
              $(this).val(localStorage.getItem("savy-"+this.id));
            }else{
              localStorage.setItem(sv+this.id, $(this).val());
            }
            $(this).change(function() {
              localStorage.setItem(sv+this.id, $(this).val());
            });
          }

        }
      });
      if ($.isFunction(fn)){fn();}
    }else if (order == "destroy") {
      $(this).each(function() {
        if(localStorage.getItem(sv+this.id)){
          localStorage.removeItem(sv+this.id)
        }
      });
      if ($.isFunction(fn)){fn();}
    }else{
      console.error("savy action not defined please use $('.classname').savy('load') to trigger savy to save all inputs")
    }
  };
})(jQuery);


No image

Sunday, 31 May 2020

May 31, 2020

Generate c# class from SQLdatabase table


declare @TableName sysname = 'TableName'
declare @Result varchar(max) = 'public class ' + @TableName + '
{'
select @Result = @Result + '
    public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
'
from
(
    select
        replace(col.name, ' ', '_') ColumnName,
        column_id ColumnId,
        case typ.name
            when 'bigint' then 'long'
            when 'binary' then 'byte[]'
            when 'bit' then 'bool'
            when 'char' then 'string'
            when 'date' then 'DateTime'
            when 'datetime' then 'DateTime'
            when 'datetime2' then 'DateTime'
            when 'datetimeoffset' then 'DateTimeOffset'
            when 'decimal' then 'decimal'
            when 'float' then 'double'
            when 'image' then 'byte[]'
            when 'int' then 'int'
            when 'money' then 'decimal'
            when 'nchar' then 'string'
            when 'ntext' then 'string'
            when 'numeric' then 'decimal'
            when 'nvarchar' then 'string'
            when 'real' then 'float'
            when 'smalldatetime' then 'DateTime'
            when 'smallint' then 'short'
            when 'smallmoney' then 'decimal'
            when 'text' then 'string'
            when 'time' then 'TimeSpan'
            when 'timestamp' then 'long'
            when 'tinyint' then 'byte'
            when 'uniqueidentifier' then 'Guid'
            when 'varbinary' then 'byte[]'
            when 'varchar' then 'string'
            else 'UNKNOWN_' + typ.name
        end ColumnType,
        case
            when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier')
            then '?'
            else ''
        end NullableSign
    from sys.columns col
        join sys.types typ on
            col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
    where object_id = object_id(@TableName)
) t
order by ColumnId
set @Result = @Result  + '
}'
print @Result

Friday, 29 May 2020

May 29, 2020

How to get multiple checkbox value with all checkbox selection in jquery



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #count-checked-books {
            color:red;
        }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <form action="#" id="bookfromsample">
        <p><label><input type="checkbox" id="checkAll"/>Book Name</label></p>
             <div id="booksection">
                 <p><label><input type="checkbox" class="booknamecls" name="bookname"  
                 value="book1"/> Book 1</label></p>
                 <p><label><input type="checkbox" class="booknamecls" name="bookname"  
                  value="book2"/> Book 2</label></p>
                 <p><label><input type="checkbox" class="booknamecls" name="bookname"  
                  value="book3"/> Book 3</label></p>
                 <p><label><input type="checkbox" class="booknamecls" name="bookname"  
                  value="book4"/> Book 4</label></p>
            </div>
            <span id="count-checked-books">0</span> selected books <br><br>
            <button type="button">get book</button><br><br>
             <div id="display"></div>
            <div id="display2"></div>
    </form>
</body>
<script>
$(document).ready(function () {
    //prop all checkbox selected or unseleted
    $('#checkAll').click(function () {
    debugger;
        $('.booknamecls').prop('checked', this.checked);
    });

    $('.booknamecls').change(function () {
    debugger;
        var check = ($('.booknamecls').filter(":checked").length == $('.booknamecls').length);
        $('#checkAll').prop("checked", check);
    });

    //checkbox value count
    var checkboxes = $('#bookfromsample p input:checkbox');
    checkboxes.change(function(){
    debugger;
        var countcheckbox = checkboxes.filter('#booksection :checked').length;
        $('#count-checked-books').text(countcheckbox);
    });

    //get checkbox value name parameters
    $('#bookfromsample input:checkbox').change(function(){
      debugger;
  var booknameval=$('#booksection input:checkbox').map(function(n){
          if(this.checked){
                return  this.value;
              };
       }).get().join(',');
       $('#display').html("formate one: "+booknameval);
    })

    // or other formate

    <!-- $("button").click(function(){ -->
    <!-- debugger; -->
        <!-- var bookname = []; -->
        <!-- $.each($("input[name='bookname']:checked"), function(){ -->
            <!-- bookname.push($(this).val()); -->
        <!-- }); -->
        <!-- $('#display2').html("formate two: "+bookname.join(",")); -->
    <!-- }); -->
});
</script>
</html>






May 29, 2020

Easy CRUD for your Web API with Dapper




  • Create a new project in Visual Studio
  • File -> New Project -> Templates -> Visual C# -> Windows -> ASP.NET Web Application -> Save as proper name
  • We want to create a new ASP.Net Web API project. Select “Empty” then check the “Web API” box
  • Now, let’s create a MS-SQL database to connect to. Create a database, and make a note of the dbname, user and password for this.
          Let’s create a quick table on the database:

         CREATE TABLE [Customer](
                 [CustomerID] [int] IDENTITY(1,1) NOT NULL,
                 [CustomerFirstName] [varchar](50) NULL,
                 [CustomerLastName] [varchar](50) NULL,
                 [IsActive] [bit] NOT NULL,
         )
          Now let’s add a few records into the table.
  • Back in Visual Studio, open up your App.config file and add an SQL connection string:
              <connectionStrings>
                     <add name="DefaultConnection" providerName="System.Data.SqlClient"
                      connectionString="Server=server.com;Database=DapperDemo;
                      User Id=userid; Password=mypassword;" />
           </connectionStrings>
           We will be using this for our Web API connection.
  • Install Dapper from your Package Manager Console:
  • Install-Package Dapper
  • Next, right click on the “Models” folder and select “Add -> New Item”. We want to add a plain class (Visual C# -> Code -> Class. Name it “Customer.cs” and save it.
           public class Customer

          {
                 public int CustomerID { get; set; }

                 public string CustomerFirstName { get; set; }

                 public string CustomerLastName { get; set; }

                 public bool IsActive { get; set; }

           }

           This will be our model for this application.
  • Next, create a folder named “DAL” (Data Access Layer) and let’s create a repository.
  • Add an interface (add -> New Item -> Visual C# -> Code -> Interface) and call it “ICustomerRepository”.
In here we’ll add the methods for our interface:

using System.Collections.Generic;

using DapperDemoAPI.Models;
namespace DapperDemoAPI.DAL
{
    internal interface ICustomerRespository 
   {
               List<Customer> GetCustomers(int amount, string sort);
               Customer GetSingleCustomer(int customerId);
               bool InsertCustomer(Customer ourCustomer);
               bool DeleteCustomer(int customerId);
               bool UpdateCustomer(Customer ourCustomer);
    }
}
These will cover our CRUD (Create, Read, Update, Delete) operations, plus a list operation.
  • Now we’ll create a CustomerRepository class that implements this interface: (add -> New Item -> Visual C# -> Code -> Class) and call it CustomerRespository.cs.
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Dapper;
using DapperDemoAPI.Models;
namespace DapperDemoAPI.DAL
{
            public class CustomerRespository : ICustomerRespository
            {
                        private readonly IDbConnection _db;
                        public CustomerRespository()
                        {
                                      _db = new SqlConnection
                                              (ConfigurationManager.ConnectionStrings
                                              ["DefaultConnection"].ConnectionString);
                        }

                        public List<Customer> GetCustomers(int amount, string sort)
                        {
                                return this._db.Query<Customer>("SELECT TOP " + amount + 
                                          "[CustomerID], [CustomerFirstName], 
                                            [CustomerLastName],
                                            [IsActive] FROM [Customer] 
                                            ORDER BY CustomerID " + sort).ToList();
                        }

                        public Customer GetSingleCustomer(int customerId)
                        {
                                    return _db.Query<Customer>("SELECT[CustomerID],
                                              [CustomerFirstName],[CustomerLastName],
                                              [IsActive] FROM [Customer] WHERE
                                              CustomerID =@CustomerID", 
                                               new { CustomerID = customerId }).SingleOrDefault();
                        }

                        public bool InsertCustomer(Customer ourCustomer)
                        {
                                   int rowsAffected = this._db.Execute(
                                      @"INSERT Customer(
                                        [CustomerFirstName],
                                        [CustomerLastName], 
                                        [IsActive])  values (
                                       @CustomerFirstName,
                                       @CustomerLastName, 
                                       @IsActive)",   new 
                                       { CustomerFirstName =         
                                        ourCustomer.CustomerFirstName,
                                        CustomerLastName = ourCustomer.
                                        CustomerLastName, IsActive = true });
                                    if (rowsAffected > 0)
                                    {
                                                return true;
                                    }
                                    return false;
                        }
                        public bool DeleteCustomer(int customerId)
                        {
                                    int rowsAffected = this._db.Execute(@"DELETE FROM
                                                                   [Customer] 
                                                                   WHERE CustomerID = @CustomerID",
                                                                    new { CustomerID = customerId });
                                    if (rowsAffected > 0)
                                    {
                                                return true;
                                    }
                                    return false;
                        }
                        public bool UpdateCustomer(Customer ourCustomer)
                        {
                                    int rowsAffected = this._db.Execute(
                                                                   "UPDATE [Customer] SET 
                                                                   [CustomerFirstName]
                                                                   = @CustomerFirstName,
                                                                   [CustomerLastName] =
                                                                   @CustomerLastName, [IsActive] = 
                                                                   @IsActive 
                                                                   WHERE CustomerID = " +
                                                                   ourCustomer.CustomerID, ourCustomer);
                                    if (rowsAffected > 0)
                                    {
                                                return true;
                                    }
                                    return false;
                        }
            }
}
This class should implement the interface and it’s members, to start out let’s make it look like this:

CREATE Customer entries with InsertCustomer

In this method  we’ll insert a new customer:
public bool InsertCustomer(Customer ourCustomer)
{
          int rowsAffected = this._db.Execute(@"INSERT 
           Customer([CustomerFirstName],
           [CustomerLastName], [IsActive]) 
           values (@CustomerFirstName, 
           @CustomerLastName, @IsActive)",
           new { CustomerFirstName = 
           ourCustomer.CustomerFirstName, 
           CustomerLastName = 
           ourCustomer.CustomerLastName, 
           IsActive = true});
         if (rowsAffected > 0)
        {
                   return true;
        }
        return false;
}
If you look closely, we are using a parameterized query here. Then you pass in an object containing those parameters, taken from the object we passed in. This is pretty straightforward.

READ Customer entries with GetSingleCustomer

With this method we’ll retrieve a single customer by CustomerID:

public Customer GetSingleCustomer(int customerId)

{
`         return  _db.Query<Customer>("SELECT[CustomerID],

                     [CustomerFirstName], [CustomerLastName],[IsActive] 
                    FROM [Customer] WHERE CustomerID = @CustomerID",  
                    new { CustomerID = customerId }).SingleOrDefault();}

UPDATE Customer entries with UpdateCustomer

To update a customer we’ll need to pass in a Customer object, and we’ll update the record based on what’s in that object.
public bool UpdateCustomer(Customer ourCustomer)
{
               int rowsAffected = this._db.Execute("UPDATE [Customer] 
                                             SET [CustomerFirstName] = 
                                            @CustomerFirstName ,
                                             [CustomerLastName]
                                             = @CustomerLastName, 
                                             [IsActive] = @IsActive 
                                             WHERE CustomerID 
                                             = " + ourCustomer.CustomerID, 
                                             ourCustomer);
                if (rowsAffected > 0)
               {
                               return true;
               }
               return false;
}

DELETE Item with DeleteCustomer Method

In this method we’ll send a simple parameterized delete command based on the integer 
we pass in:
public bool DeleteCustomer(int customerId)
{
               int rowsAffected = this._db.Execute(@"DELETE FROM [jeremy].[Customer] 
                                              WHERE CustomerID = @CustomerID",
                                               new{ CustomerID = customerId });
               if (rowsAffected > 0)
               {
                               return true;
               }
               return false;
}
Like similar methods we pass a true/false based on the number of records affected, if it’s not zero
we’ll assume it was successful.

LIST Items with GetCustomers Method
In this method we are going to get a list of items. You can select how many items, and how you want to sort them.
public List<Customer> GetCustomers(int amount, string sort)
{               return this._db.Query<Customer>("SELECT TOP "+ amount +"
                          [CustomerID],[CustomerFirstName],
                           [CustomerLastName],[IsActive]
                           FROM [Customer]
                          ORDER BY CustomerID " + sort).ToList();}

Create a Web API Controller
Next, right click on the “Controlle” folder and select “Add ->Controller”. Name it “CustomerController” and save it.

CustomerController

using System.Collections.Generic;
using System.Web.Http;
using DapperDemoAPI.DAL;
using DapperDemoAPI.Models;

namespace DapperDemoAPI.Controllers
{
    public class CustomerController : ApiController
    {
                private CustomerRespository _ourCustomerRespository = new CustomerRespository();
              
                        // GET: /Customer
                        [Route("Customers")]
                        [HttpGet]
                        public List<Customer> Get()
                        {
                                    return _ourCustomerRespository.GetCustomers(10, "ASC");
                        }

                        // GET: /Customer/10/ASC
                        [Route("Customers/{amount}/{sort}")]
                        [HttpGet]
                        public List<Customer> Get(int amount, string sort)
                        {
                                    return _ourCustomerRespository.GetCustomers(amount, sort);
                        }

                        // GET: /Customer/5
                        [Route("Customers/{id}")]
                        [HttpGet]
                        public Customer Get(int id)
                        {
                                    return _ourCustomerRespository.GetSingleCustomer(id);
                        }

                        // POST: /Customer
                        [Route("Customers")]
                        [HttpPost]
                        public bool Post([FromBody]Customer ourCustomer)
                        {
                                    //return true;
                                    return _ourCustomerRespository.InsertCustomer(ourCustomer);
                        }

                        // PUT: api/Customer/5
                        [Route("Customers")]
                        [HttpPut]
                        public bool Put([FromBody]Customer ourCustomer)
                        {
                                    return _ourCustomerRespository.UpdateCustomer(ourCustomer);
                        }

                        // DELETE: api/Customer/5
                        [Route("Customers/{id}")]
                        [HttpDelete]
                        public bool Delete(int id)
                        {
                                    return _ourCustomerRespository.DeleteCustomer(id);
                        }
    }
}