Friday, 16 August 2019

CRUD operations using CORE MVC(2.1) ,Repository Pattern & Dependency Injection,EF code first approach



Models :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace WebApplication1.Models
{
    public class EMP
    {
        [Key]
        public int EID { get; set; }
        [MaxLength(50)]
        public string NAME { get; set; }
        public string ADDRESS { get; set; }
        [MaxLength(50)]
        public string PASSWORD { get; set; }
        [MaxLength(50)]
        public string GENDER { get; set; }
        public int CID { get; set; }
        public int SID { get; set; }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace WebApplication1.Models
{
    public class COUNTRY
    {
        [Key]
        public int CID { get; set; }
        [MaxLength(50)]
        public string CNAME { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace WebApplication1.Models
{
    public class STATE
    {
        [Key]
        public int SID { get; set; }
        [MaxLength(50)]
        public string SNAME { get; set; }
        public int CID { get; set; }
    }
}


app

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace WebApplication1.Models
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options):base(options)
        { }
        public DbSet<EMP> EMPs { get; set; }
        public DbSet<COUNTRY> COUNTRIEs { get; set; }
        public DbSet<STATE> STATEs { get; set; }
    }
}


IRepository Interface :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;


namespace WebApplication1.Models
{
    public interface IRepository <T> where T : class
    {
        IQueryable<T> Gets();
        Task<T> Get(int t);
        Task Save(T t);
        Task Update(T t);
        Task Delete(int t);
    }
}

Repository Class where implement the IRepository interface :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace WebApplication1.Models
{
    public class Repository<T> : IRepository<T> where T : class
    {
        private readonly AppDbContext context;
        

        public Repository(AppDbContext Context)
        {
            this.context = Context;
        }

        public async Task Delete(int t)
        {
            var data = await Get(t);
            context.Set<T>().Remove(data);
            await context.SaveChangesAsync();
        }

        public async Task<T> Get(int t)
        {
            return await context.Set<T>().FindAsync(t);
        }

        public IQueryable<T> Gets()
        {
            return context.Set<T>().AsNoTracking();
        }

        public async Task Save(T t)
        {
            await context.Set<T>().AddAsync(t);
            await context.SaveChangesAsync();
        }

        public async Task Update(T t)
        {
            context.Set<T>().Update(t);
            await context.SaveChangesAsync();
        }

       
    }
}

Connection string in the appsettings.json file :

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DBConnection": "server=(localdb)\\MSSQLLocalDB;database=SIVDB;Trusted_Connection=true"
  }
}

Startup.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using WebApplication1.Models;

namespace WebApplication1
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DBConnection")));
            services.AddScoped<IRepository<EMP>, Repository<EMP>>();
            services.AddScoped<IRepository<COUNTRY>, Repository<COUNTRY>>();
            services.AddScoped<IRepository<STATE>, Repository<STATE>>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Test}/{action=Index}/{id?}");
            });
        }
    }
}

View Model :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Immutable;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace WebApplication1.Models
{
    public class EMPVM
    {
        public EMPVM()
        {
            LCID = new List<SelectListItem>();
            LSID = new List<SelectListItem>();
        }
        public int EID { get; set; }
        [Required(ErrorMessage ="Name should not be blank.")]
        [MaxLength(50, ErrorMessage = "Name length should max 50 charecter long.")]
        public string NAME { get; set; }
        [Required(ErrorMessage = "Address should not be blank.")]
        [DataType(DataType.MultilineText)]
        public string ADDRESS { get; set; }
        [Required(ErrorMessage = "Password should not be blank.")]
        [StringLength(8,MinimumLength =6,ErrorMessage ="Password length between 6 to 8 charecters long.")]
        [DataType(DataType.Password)]
        public string PASSWORD { get; set; }
        [Required(ErrorMessage = "Confirm password should not be blank.")]
        [Display(Name ="CONFIRM PASSWORD")]
        [DataType(DataType.Password)]
        [Compare("PASSWORD")]
        public string CPASSWORD { get; set; }
        [Required(ErrorMessage = "Please select a gender.")]
        public string GENDER { get; set; }
        [Required(ErrorMessage = "Please select a country.")]
        [Display(Name ="COUNTRY")]
        public int? CID { get; set; }
        public List<SelectListItem> LCID { get; set; }
        [Required(ErrorMessage = "Please select a state.")]
        [Display(Name = "STATE")]
        public int? SID { get; set; }
        public List<SelectListItem> LSID { get; set; }
    }
}

Controller :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace WebApplication1.Controllers
{
    public class TestController : Controller
    {
        private IRepository<EMP> iRepository;
        private IRepository<COUNTRY> cRepository;
        private IRepository<STATE> sRepository;
        public TestController(IRepository<EMP> Irepository, IRepository<COUNTRY> Crepository, IRepository<STATE> Srepository)
        {
            iRepository = Irepository;
            cRepository = Crepository;
            sRepository = Srepository;
        }
        [HttpGet]
        public  IActionResult Index()
        {
            return View(iRepository.Gets());
        }
        [HttpGet]
        public JsonResult Fillddl(int CID)
        {
             return Json(JsonConvert.SerializeObject(sRepository.Gets().Where(m => m.CID == CID).ToList()));
        }
        [HttpGet]
        public IActionResult Create()
        {

            EMPVM vm = new EMPVM();
            vm.LCID = cRepository.Gets().Select(m => new SelectListItem { Value=m.CID.ToString(), Text=m.CNAME }).ToList();
            return View(vm);
        }
        [HttpGet]
        public IActionResult Delete(int id)
        {
            iRepository.Delete(id);
            return RedirectToAction("Index");
        }

        [HttpGet]
        public IActionResult Edit(int id)
        {

            EMPVM vm = new EMPVM();
            EMP data = iRepository.Get(id).Result;
            vm.EID = data.EID;
            vm.NAME = data.NAME;
            vm.ADDRESS = data.ADDRESS;
            vm.PASSWORD = data.PASSWORD;
            vm.GENDER = data.GENDER;
            vm.LCID = cRepository.Gets().Select(m => new SelectListItem { Value = m.CID.ToString(), Text = m.CNAME }).ToList();
            vm.CID = data.CID;
            vm.LSID = sRepository.Gets().Select(m => new SelectListItem { Value = m.SID.ToString(), Text = m.SNAME }).ToList();
            vm.SID = data.SID;
            return View(vm);
        }
        [HttpPost]
        public IActionResult Create(EMPVM vm)
        {
            if (ModelState.IsValid)
            {
                EMP emp = new EMP();
                emp.NAME = vm.NAME;
                emp.ADDRESS = vm.ADDRESS;
                emp.PASSWORD = vm.PASSWORD;
                emp.GENDER = vm.GENDER;
                emp.CID = vm.CID??0;
                emp.SID = vm.SID ?? 0;
                iRepository.Save(emp);
                return RedirectToAction("Index");
            }
            return View(vm);
        }
        [HttpPost]
        public IActionResult Edit(EMPVM vm)
        {
            ModelState.Remove("PASSWORD");
            ModelState.Remove("CPASSWORD");
            if (ModelState.IsValid)
            {
                EMP emp = iRepository.Get(vm.EID).Result;
                emp.NAME = vm.NAME;
                emp.ADDRESS = vm.ADDRESS;
                emp.GENDER = vm.GENDER;
                emp.CID = vm.CID ?? 0;
                emp.SID = vm.SID ?? 0;
                iRepository.Update(emp);
                return RedirectToAction("Index");
            }
            return View(vm);
        }
    }

}

Create view:

@model WebApplication1.Models.EMPVM

@{
    ViewData["Title"] = "Create";
}




<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>

            <div class="form-group">
                <label asp-for="NAME" class="control-label"></label>
                <input asp-for="NAME" class="form-control" />
                <span asp-validation-for="NAME" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ADDRESS" class="control-label"></label>
                <textarea asp-for="ADDRESS" class="form-control"></textarea>
                <span asp-validation-for="ADDRESS" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="PASSWORD" class="control-label"></label>
                <input asp-for="PASSWORD" class="form-control" />
                <span asp-validation-for="PASSWORD" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="CPASSWORD" class="control-label"></label>
                <input asp-for="CPASSWORD" class="form-control" />
                <span asp-validation-for="CPASSWORD" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="GENDER" class="control-label"></label>
                <input type="radio" value="Male" asp-for="GENDER" />Male
                <input type="radio" value="Female" asp-for="GENDER" />Female
                <span asp-validation-for="GENDER" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="CID" class="control-label"></label>
                <select asp-for="CID" asp-items="Model.LCID" class="form-control">
                    <option value="">Select</option>

                </select>
                <span asp-validation-for="CID" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="SID" class="control-label"></label>
                <select asp-for="SID" asp-items="Model.LSID" class="form-control">
                    <option value="">Select</option>
                </select>
                <span asp-validation-for="SID" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>



@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script type="text/javascript">
        $(function () {

            $('#CID').change(function () {
                            $.ajax({

                url: '@Url.Action("Fillddl", "Test")',

              data: { CID: $(this).val() },

                type: 'GET',

                dataType: 'json',

                contentType: 'application/json; charset=utf-8',

                success: function (result) {

                    $('#SID').empty();

                    $('#SID').append("<option value=''>Select</option>");

                    $.each(JSON.parse(result), function (i, j) {

                        $('#SID').append("<option value='" + j.SID + "'>" + j.SNAME + "</option>");

                    });

                }

            });

            });
        });
    </script>
}

Edit View :

@model WebApplication1.Models.EMPVM

@{
    ViewData["Title"] = "Edit";
}

<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>

            <div class="form-group">
                <input type="hidden" asp-for="EID" />
                <label asp-for="NAME" class="control-label"></label>
                <input asp-for="NAME" class="form-control" />
                <span asp-validation-for="NAME" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ADDRESS" class="control-label"></label>
                <textarea asp-for="ADDRESS" class="form-control"></textarea>
                <span asp-validation-for="ADDRESS" class="text-danger"></span>
            </div>
            
            <div class="form-group">
                <label asp-for="GENDER" class="control-label"></label>
                <input type="radio" value="Male" asp-for="GENDER" />Male
                <input type="radio" value="Female" asp-for="GENDER" />Female
                <span asp-validation-for="GENDER" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="CID" class="control-label"></label>
                <select asp-for="CID" asp-items="Model.LCID" class="form-control">
                    <option value="">Select</option>

                </select>
                <span asp-validation-for="CID" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="SID" class="control-label"></label>
                <select asp-for="SID" asp-items="Model.LSID" class="form-control">
                    <option value="">Select</option>
                </select>
                <span asp-validation-for="SID" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>



@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script type="text/javascript">
        $(function () {

            $('#CID').change(function () {
                            $.ajax({

                url: '@Url.Action("Fillddl", "Test")',

              data: { CID: $(this).val() },

                type: 'GET',

                dataType: 'json',

                contentType: 'application/json; charset=utf-8',

                success: function (result) {

                    $('#SID').empty();

                    $('#SID').append("<option value=''>Select</option>");

                    $.each(JSON.parse(result), function (i, j) {

                        $('#SID').append("<option value='" + j.SID + "'>" + j.SNAME + "</option>");

                    });

                }

            });

            });
        });
    </script>
}

Index View :
@model IEnumerable<WebApplication1.Models.EMP>

@{
    ViewData["Title"] = "Index";
}


<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.EID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.NAME)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ADDRESS)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.PASSWORD)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.GENDER)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.SID)
            </th>
            <th>ACTION</th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.EID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.NAME)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ADDRESS)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.PASSWORD)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.GENDER)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.SID)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.EID }) |

                @Html.ActionLink("Delete", "Delete", new { id=item.EID })
            </td>
        </tr>
}
    </tbody>
</table>






Thursday, 15 August 2019

CRUD operations using CORE MVC(2.1) ,Repository Pattern & Dependency Injection

Model :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace WebApplication2.Models
{
    public class EMP
    {
        [Key]
        public int EID { get; set; }
        public string NAME { get; set; }
    }
}

View Model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace WebApplication2.Models
{
    public class EMPVM
    {
        [Required(ErrorMessage ="Eid should not be blank.")]
        public int EID { get; set; }
        [Required(ErrorMessage = "Name should not be blank.")]
        public string NAME { get; set; }
    }
}

Repository :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication2.Models
{
   public interface IRepository
    {
        IEnumerable<EMP> Gets();
        EMP Get(int EID);
        EMP Save(EMP emp);
        EMP Update(EMP emp);
        EMP Delete(int EID);
    }
}

Implement Repository :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication2.Models
{
    public class SQLRepository : IRepository
    {
        private readonly AppDbContext context;
        public SQLRepository(AppDbContext Context)
        {
            this.context = Context;
        }
        

        public EMP Get(int EID)
        {
            return context.EMPs.Find(EID);
        }

        public IEnumerable<EMP> Gets()
        {
            return context.EMPs;
        }

        public EMP Save(EMP emp)
        {
            context.EMPs.Add(emp);
            context.SaveChanges();
            return emp;
        }

        public EMP Update(EMP emp)
        {
            var Emp = context.EMPs.Attach(emp);
            Emp.State = Microsoft.EntityFrameworkCore.EntityState.Modified;
            context.SaveChanges();
            return emp;
        }
        public EMP Delete(int EID)
        {
            EMP emp = context.EMPs.Find(EID);
            if (emp != null)
            {
                context.EMPs.Remove(emp);
                context.SaveChanges();
            }
            return emp;
        }
    }
}
DbContext :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace WebApplication2.Models
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options):base(options)
        { }
        public DbSet<EMP> EMPs { get; set; }
    }
}
    
Add connection string in appsettings.json :

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DBConnection": "server=(localdb)\\MSSQLLocalDB;database=sivdb;Trusted_Connection=true"
  }
}

Register Dependency Injection in dependency  container Startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using WebApplication2.Models;
using Microsoft.EntityFrameworkCore;

namespace WebApplication2
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DBConnection")));
            services.AddScoped<IRepository, SQLRepository>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Test}/{action=Index}/{id?}");
            });
        }
    }
}
Use 2 commands for migration :
Add-Migration Intialmigraion
Update-Database

Controller :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication2.Models;

namespace WebApplication2.Controllers
{
    public class TestController : Controller
    {
        private IRepository _iRepository;
        public TestController(IRepository iRepository)
        {
            this._iRepository = iRepository;
        }
        [HttpGet]
        public IActionResult Index()
        {
            return View(_iRepository.Gets());
        }
        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Create(EMPVM vm)
        {
            if (ModelState.IsValid)
            {
                EMP emp = new EMP();
                emp.NAME = vm.NAME;
                EMP emp1=_iRepository.Save(emp);
                return RedirectToAction("Index");
            }
            return View(vm);
        }
        [HttpGet]
        public IActionResult Edit(int id)
        {
            EMP emp = _iRepository.Get(id);
            EMPVM vm = new EMPVM();
            vm.EID = emp.EID;
            vm.NAME = emp.NAME;
            return View(vm);
        }
        [HttpPost]
        public IActionResult Edit(EMPVM vm)
        {
            if (ModelState.IsValid)
            {
                EMP emp = new EMP();
                emp.EID = vm.EID;
                emp.NAME = vm.NAME;
                EMP empn = _iRepository.Update(emp);
                return RedirectToAction("Index");
            }
            return View(vm);
        }
        [HttpGet]
        public IActionResult Delete(int id)
        {
            EMP emp = _iRepository.Delete(id);
            return RedirectToAction("index");
        }
    }
}
Index view :

@model IEnumerable<EMP>

@{
    ViewData["Title"] = "Index";
}



<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table table-bordered table-hover table-responsive-lg table-striped">
    <thead class="bg bg-primary">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.EID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.NAME)
            </th>
            <th>ACTION</th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.EID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.NAME)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new {  id=item.EID}) |
                @Html.ActionLink("Delete", "Delete", new {  id=item.EID })
            </td>
        </tr>
}
    </tbody>
</table>

Create View :

@model WebApplication2.Models.EMPVM

@{
    ViewData["Title"] = "Create";
}


<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="EID" class="control-label"></label>
                <input asp-for="EID" class="form-control" />
                <span asp-validation-for="EID" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="NAME" class="control-label"></label>
                <input asp-for="NAME" class="form-control" />
                <span asp-validation-for="NAME" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Edit View :

@model WebApplication2.Models.EMPVM

@{
    ViewData["Title"] = "Edit";
}


<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="EID" class="control-label"></label>
                <input asp-for="EID" class="form-control" />
                <span asp-validation-for="EID" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="NAME" class="control-label"></label>
                <input asp-for="NAME" class="form-control" />
                <span asp-validation-for="NAME" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}


Thursday, 1 August 2019

Implementing Crud operation & Angular Route using Angular6 & Webapi2




View Model :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication8.Models
{
    public class EMPVM
    {
        public int EID { get; set; }
        public string NAME { get; set; }
        public string ADDRESS { get; set; }
        public string PASSWORD { get; set; }
        public string GENDER { get; set; }
        public int? CID { get; set; }
        public int? SID { get; set; }
        public List<int> LHOBBY { get; set; }
    }
}

Web api :

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication8.Models;

namespace WebApplication8.Controllers
{
    [RoutePrefix("api/Emp")]
    public class EmpController : ApiController
    {
        [HttpGet]
        [Route("Countries")]
        public HttpResponseMessage Countries()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.COUNTRies.ToList());
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,ex);
            }
        }
        [HttpGet]
        [Route("Hobbies")]
        public HttpResponseMessage Hobbies()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.HOBBies.ToList());
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpGet]
        [Route("Emps")]
        public HttpResponseMessage Emps()
        {
            try
            {

                using (Database1Entities obj = new Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.EMPs.ToList());
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpGet]
        [Route("Emp/{EID:int}",Name ="Get")]
        public HttpResponseMessage Emp(int EID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    EMPVM vm = obj.EMPs.Select(n => new EMPVM { EID = n.EID, NAME = n.NAME, ADDRESS = n.ADDRESS, PASSWORD = n.PASSWORD, GENDER = n.GENDER, CID = n.CID, SID = n.SID }).SingleOrDefault(m => m.EID == EID);
                    vm.LHOBBY = obj.HMAPs.Where(p => p.EID == EID).Select(q => q.HID.Value).ToList();
                    return Request.CreateResponse(HttpStatusCode.OK,vm);
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpGet]
        [Route("States/{CID:int}")]
        public HttpResponseMessage States(int CID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.STATEs.Where(m=>m.CID==CID).ToList());
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpPost]
        [Route("Save")]
        public HttpResponseMessage Save(EMPVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    EMP emp = new EMP();
                    emp.EID = vm.EID;
                    emp.NAME = vm.NAME;
                    emp.ADDRESS = vm.ADDRESS;
                    emp.PASSWORD = vm.PASSWORD;
                    emp.GENDER = vm.GENDER;
                    emp.CID = vm.CID;
                    emp.SID = vm.SID;
                    obj.Entry(emp).State = EntityState.Added;
                    obj.SaveChanges();
                    obj.HMAPs.AddRange(vm.LHOBBY.Select(p => new HMAP { EID = vm.EID, HID = p }).ToList());
                    obj.SaveChanges();
                    var req= Request.CreateResponse(HttpStatusCode.Created,"Data Saved.");
                    req.Headers.Location = new Uri(Url.Link("Get",new { EID=vm.EID }));
                    return req;
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpPut]
        [Route("Update")]
        public HttpResponseMessage Update(EMPVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    EMP emp = obj.EMPs.Find(vm.EID);
                    emp.NAME = vm.NAME;
                    emp.ADDRESS = vm.ADDRESS;
                    emp.PASSWORD = vm.PASSWORD;
                    emp.GENDER = vm.GENDER;
                    emp.CID = vm.CID;
                    emp.SID = vm.SID;
                    obj.Entry(emp).State = EntityState.Modified;
                    obj.SaveChanges();
                    obj.HMAPs.AddRange(vm.LHOBBY.Select(p => new HMAP { EID = vm.EID, HID = p }).ToList());
                    obj.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, "Data Updated.");
                 
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpDelete]
        [Route("Delete/{EID:int}")]
        public HttpResponseMessage Delete(int EID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(obj.EMPs.Find(EID)).State = EntityState.Deleted;
                    obj.SaveChanges();
                    obj.HMAPs.RemoveRange(obj.HMAPs.Where(p=>p.EID==EID));
                    obj.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, "Data Delted.");
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
    }

}

app.component.html :

<div style="padding:5px" class="container">
 
   <ul class="nav nav-tabs">

    <li routerLinkActive="Active">

      <a routerLink="list">Empioyee</a>

    </li>

    <li routerLinkActive="Active">

       <a routerLink="create">Department</a>

     </li>

   </ul>

 <br>

 <router-outlet></router-outlet>


 </div>

Angular Models :

export class COUNTRY {
    CID: number;
    CNAME: string;
}

export class STATE {
    SID: number;
    SNAME: string;
    CID: number;
}
export class HOBBY {
    HID: number;
    HNAME: string;
}
export class EMPVM {
    EID: number;
    NAME: string;
    ADDRESS: string;
    PASSWORD: string;
    GENDER: string;
    CID: number;
    SID: number;
    LHOBBY: number[];
}


Angular Service :

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { EMPVM, COUNTRY, STATE, HOBBY } from './chinai.model';
import 'rxjs/add/operator/toPromise';


@Injectable()
export class ChinaiService {
    baseUrl='http://localhost:65426/api/Emp';
    constructor(private http: HttpClient){
    }
    Getc(): Promise<COUNTRY[]> {
        return this.http.get<COUNTRY[]>(`${this.baseUrl}/${"Countries"}`)
        .toPromise();
    }
    Geth(): Promise<HOBBY[]> {
        return this.http.get<HOBBY[]>(`${this.baseUrl}/${"Hobbies"}`)
        .toPromise();
    }
    Gets(cid: number): Promise<STATE[]> {
        return this.http.get<STATE[]>(`${this.baseUrl}/${"States"}/${cid}`)
        .toPromise();
    }
    Get(eid: number): Promise<EMPVM> {
        return this.http.get<EMPVM>(`${this.baseUrl}/${"Emp"}/${eid}`)
        .toPromise();
    }
    Gete(): Promise<EMPVM[]> {
        return this.http.get<EMPVM[]>(`${this.baseUrl}/${"Emps"}`)
        .toPromise();
    }
    Save(emp: EMPVM): Promise<string> {
        return this.http.post<string>(`${this.baseUrl}/${"Save"}`
        ,JSON.stringify(emp)
        ,{headers: new HttpHeaders({'Content-Type': 'application/json'})}
        )
        .toPromise();
    }
    Update(emp: EMPVM): Promise<string> {
        return this.http.put<string>(`${this.baseUrl}/${"Update"}`
        ,JSON.stringify(emp)
        ,{headers: new HttpHeaders({'Content-Type': 'application/json'})}
        )
        .toPromise();
    }
    Delete(eid: number): Promise<string> {
        return this.http.delete<string>(`${this.baseUrl}/${"Delete"}/${eid}`
        ,{headers: new HttpHeaders({'Content-Type': 'application/json'})}
        )
        .toPromise();
    }

listchinai.component.html :

<div class="row">

    <div class="col-lg-4">
        <input type="button" class="btn btn-primary" value="Add New" (click)="add()" style="width:80px" />
    </div>
    <div class="col-lg-4">
    </div>
    <div class="col-lg-4">
    </div>
</div><br>
<div class="row">
    <div class="col-lg-12">
        <table class="table table-bordered table-condensed table-hover table-responsive table-striped">
            <thead class="bg bg-primary">
                <tr>
                    <th>Sl No.</th>
                    <th>NAME</th>
                    <th>GENDER</th>
                    <th>ACTION</th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let c of list;let i=index">
                    <td>{{i+1}}</td>
                    <td>{{c.NAME|CustomPipe1:c.GENDER}}</td>
                    <td>{{c.GENDER}}</td>
                    <td>
                        <a [routerLink]="['/create',c.EID]">Edit</a> |
                        <a (click)="del(c.EID)">Delete</a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

listchinai.component.ts :

import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
import { ChinaiService } from './chinai.service';
import { EMPVM } from './chinai.model';

@Component({
  selector: 'app-listchinai',
  templateUrl: './listchinai.component.html',
  styleUrls: ['./listchinai.component.css']
})
export class ListchinaiComponent implements OnInit {
list: EMPVM[];
  constructor(private ch: ChinaiService, private ru: Router) { }

  ngOnInit() {
   this.fill();
  }
  add(): void {
    this.ru.navigate(['/create']);
  }
  fill(): void {
    this.ch.Gete().then(data => this.list= data);
  }
  del(eid: number): void {
    if (confirm('Do you want to delete it.')) {
      this.ch.Delete(eid).then(data => {
        alert(data);
        this.fill();
      });
    }
  }
}

createchinai.component.html :

<form class="form-horizontal" #frmEmp="ngForm">
  <div class="form-group" [class.has-success]="EID.valid" [class.has-error]="EID.invalid && EID.touched">
      <label class="control-label col-lg-4">EID</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" required name="EID" [(ngModel)]="EMP.EID" #EID="ngModel" />
      </div>
      <span class="help-block" *ngIf="EID.invalid && EID.touched">Eid should not be blank.</span>
  </div>
  <div class="form-group" [class.has-success]="NAME.valid" [class.has-error]="NAME.invalid && NAME.touched">
      <label class="control-label col-lg-4">NAME</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" required name="NAME" [(ngModel)]="EMP.NAME" #NAME="ngModel" />
      </div>
      <span class="help-block" *ngIf="NAME.invalid && NAME.touched">Name should not be blank.</span>
  </div>
  <div class="form-group" [class.has-success]="ADDRESS.valid" [class.has-error]="ADDRESS.invalid && ADDRESS.touched">
      <label class="control-label col-lg-4">ADDRESS</label>
      <div class="col-lg-4">
          <textarea class="form-control" required name="ADDRESS" [(ngModel)]="EMP.ADDRESS" #ADDRESS="ngModel"></textarea>
      </div>
      <span class="help-block" *ngIf="ADDRESS.invalid && ADDRESS.touched">Address should not be blank.</span>
  </div>
  <div class="form-group" [class.has-success]="PASSWORD.valid" [class.has-error]="PASSWORD.invalid && PASSWORD.touched">
      <label class="control-label col-lg-4">PASSWORD</label>
      <div class="col-lg-4">
          <input type="password" class="form-control" required name="PASSWORD" [(ngModel)]="EMP.PASSWORD" #PASSWORD="ngModel" />
      </div>
      <span class="help-block" *ngIf="PASSWORD.invalid && PASSWORD.touched">Password should not be blank.</span>
  </div>
  <div class="form-group" [class.has-success]="GENDER.valid" [class.has-error]="GENDER.invalid && GENDER.touched">
      <label class="control-label col-lg-4">GENDER</label>
      <div class="col-lg-4">
          <input type="radio" required name="GENDER" [(ngModel)]="EMP.GENDER" #GENDER="ngModel" value="Male" />Male
          <input type="radio" required name="GENDER" [(ngModel)]="EMP.GENDER" #GENDER="ngModel" value="Female" />Female
      </div>
      <span class="help-block" *ngIf="GENDER.invalid && GENDER.touched">Please select a gender.</span>
  </div>
  <div class="form-group" [class.has-success]="LHOBBY.valid" [class.has-error]="LHOBBY.invalid && LHOBBY.touched">
      <label class="control-label col-lg-4">HOBBY</label>
      <div class="col-lg-4">
          <select class="form-control" multiple="multiple" required name="LHOBBY" [(ngModel)]="EMP.LHOBBY" #LHOBBY="ngModel">
              <option *ngFor="let c of listh" [value]="c.HID">{{c.HNAME}}</option>
          </select>
      </div>
      <span class="help-block" *ngIf="LHOBBY.invalid && LHOBBY.touched">Please select a hobby.</span>
  </div>
  <div class="form-group" [class.has-success]="CID.valid" [class.has-error]="CID.invalid && CID.touched">
      <label class="control-label col-lg-4">COUNTRY</label>
      <div class="col-lg-4">
          <select class="form-control" required name="CID" [(ngModel)]="EMP.CID" #CID="ngModel" (change)="fillddl()">
              <option [ngValue]=null >Select</option>
              <option *ngFor="let c of listc" [value]="c.CID">{{c.CNAME}}</option>
          </select>
      </div>
      <span class="help-block" *ngIf="CID.invalid && CID.touched">Please select a country.</span>
  </div>
  <div class="form-group" [class.has-success]="SID.valid" [class.has-error]="SID.invalid && SID.touched">
      <label class="control-label col-lg-4">STATE</label>
      <div class="col-lg-4">
          <select class="form-control" required name="SID" [(ngModel)]="EMP.SID" #SID="ngModel">
                <option [ngValue]=null >Select</option>
              <option *ngFor="let c of lists" [value]="c.SID">{{c.SNAME}}</option>
          </select>
      </div>
      <span class="help-block" *ngIf="SID.invalid && SID.touched">Please select a state.</span>
  </div>
  <div class="form-group">
      <label class="control-label col-lg-4"></label>
      <div class="col-lg-4">
          <input type="button" class="btn btn-primary" style="width:80px" value="Save" (click)="save(frmEmp.invalid)" />
          <input type="button" class="btn btn-primary" style="width:80px" value="Reset" (click)="reset(frmEmp)" /><br>
          <a [routerLink]="['/list']" >Back To List</a>
      </div>
  </div>
</form>

createchinai.component.ts :


import { Component, OnInit, ViewChild } from '@angular/core';
import { COUNTRY, STATE, EMPVM, HOBBY } from './chinai.model';
import { ChinaiService } from './chinai.service';
import {  ActivatedRoute, Router } from '@angular/router';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-createchinai',
  templateUrl: './createchinai.component.html',
  styleUrls: ['./createchinai.component.css']
})
export class CreatechinaiComponent implements OnInit {
EMP: EMPVM;
listc: COUNTRY[];
lists: STATE[];
listh: HOBBY[];
Eid: number;
@ViewChild('frmEmp') public empfrm: NgForm;
  constructor(private cs: ChinaiService, private ru: Router , private ac: ActivatedRoute) { }

  ngOnInit() {
   
    this.CLR();
    this.cs.Getc().then(data => this.listc = data);
    this.cs.Geth().then(data => this.listh = data);
    this.Eid = this.ac.snapshot.params['id'];
    if (this.Eid !== null) {
      this.cs.Get(this.Eid).then(data => {
        this.fx(data.CID);
        this.EMP = data;
      });
    }
  }
  fillddl(): void {
   this.fx(this.EMP.CID);
  }
  fx(cid: number): void {
    this.cs.Gets(cid).then(data => this.lists = data);
  }
  save(isValid: boolean): void {
    if (!isValid){
      if (this.Eid === undefined) {
        this.cs.Save(this.EMP).then(data => {
          alert(data);
          this.ru.navigate(['\list']);
        });
      } else {
        this.cs.Update(this.EMP).then(data => {
          alert(data);
          this.ru.navigate(['\list']);
        });
      }
      
    }
    this.empfrm.reset();
  }
  reset(frme: NgForm): void {
   frme.reset();
  }
CLR(): void {
  this.EMP = {
     EID: null,
     NAME: null,
     ADDRESS: null,
     PASSWORD: null,
     GENDER: null,
     LHOBBY:[],
     CID: null,
     SID: null
  };
}
}

Augular Pipe :

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
    name: 'CustomPipe1'
})
export class ChinaiPipe implements PipeTransform {
    transform(value: string, gender: string): string {
            if (gender.toLowerCase() === "male" ){
              return "Mr. " + value;   
            }else {
                return "Miss. " + value;
            }
    }
}

app.module.ts :

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';


import { HttpClientModule } from '@angular/common/http';


import { RouterModule, Routes } from '@angular/router';
import { CreatechinaiComponent } from './chinai/createchinai.component';
import { ListchinaiComponent } from './chinai/listchinai.component';
import { ChinaiService } from './chinai/chinai.service';
import { ChinaiPipe } from './chinai/chinai.pipe';



const appRoutes: Routes = [
  { path: 'list', component: ListchinaiComponent },
  { path: 'create/:id', component: CreatechinaiComponent  },
  { path: 'delete/:id', component: CreatechinaiComponent  },
  { path: 'create', component: CreatechinaiComponent  },
  { path: '', redirectTo: '/list', pathMatch: 'full' },
  { path: '**', component: ListchinaiComponent  }
];
@NgModule({
  declarations: [
    AppComponent,
    CreatechinaiComponent,
    ListchinaiComponent,
    ChinaiPipe
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
    HttpClientModule,
    FormsModule
  ],
  providers: [ChinaiService],
  bootstrap: [AppComponent]
})
export class AppModule { }