Sunday, 4 October 2020

CRUD operations using Azure Function

 


using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;

namespace FunctionApp1
{
    public static class Function1
    {
        public static readonly List<EMP> lst = new List<EMP>();
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function,"post", Route = "Save")] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("Receive new employee request.");
            IActionResult returnValue = null;
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            EMP emp = JsonConvert.DeserializeObject<EMP>(requestBody);
            try
            {
               if(emp!=null)
                {
                    lst.Add(new EMP { EID = emp.EID, NAME = emp.NAME });
                    returnValue = new OkObjectResult("Data Saved.");
                }
               else
                {
                    returnValue = new StatusCodeResult(StatusCodes.Status400BadRequest);
                }

            }
            catch (Exception ex)
            {
                log.LogError($"Exception thrown: {ex.Message}");
                returnValue = new StatusCodeResult(StatusCodes.Status500InternalServerError);
            }
            return returnValue;
        }
        [FunctionName("Function2")]
        public static async Task<IActionResult> Run2(
           [HttpTrigger(AuthorizationLevel.Function, "get", Route = "Gets")] HttpRequest req,
           ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            //string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            ////dynamic data = JsonConvert.DeserializeObject(requestBody);
            ////name = name ?? data?.name;

            ////string responseMessage = string.IsNullOrEmpty(name)
            ////    ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            ////    : $"Hello, {name}. This HTTP triggered function executed successfully.";
            //EMP emp = JsonConvert.DeserializeObject<EMP>(requestBody);
            //lst.Add(new EMP { EID = emp.EID, NAME = emp.NAME });
            return new OkObjectResult(lst);
        }
        [FunctionName("Function3")]
        public static async Task<IActionResult> Run3(
           [HttpTrigger(AuthorizationLevel.Function, "get", Route = "Get/{id:int}")] HttpRequest req,
           ILogger log,int id)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            //string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            ////dynamic data = JsonConvert.DeserializeObject(requestBody);
            ////name = name ?? data?.name;

            ////string responseMessage = string.IsNullOrEmpty(name)
            ////    ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            ////    : $"Hello, {name}. This HTTP triggered function executed successfully.";
            //EMP emp = JsonConvert.DeserializeObject<EMP>(requestBody);
            //lst.Add(new EMP { EID = emp.EID, NAME = emp.NAME });
            EMP emp = lst.FirstOrDefault(m => m.EID == id);
            return new OkObjectResult(emp);
        }
        [FunctionName("Function4")]
        public static async Task<IActionResult> Run4(
           [HttpTrigger(AuthorizationLevel.Function, "put", Route = "Update/{id:int}")] HttpRequest req,
           ILogger log,int id)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            //string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            //dynamic data = JsonConvert.DeserializeObject(requestBody);
            //name = name ?? data?.name;

            //string responseMessage = string.IsNullOrEmpty(name)
            //    ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            //    : $"Hello, {name}. This HTTP triggered function executed successfully.";
            EMP emp = JsonConvert.DeserializeObject<EMP>(requestBody);
            lst.Remove(lst.FirstOrDefault(m=>m.EID==id));
            lst.Add(new EMP { EID = emp.EID, NAME = emp.NAME });
            return new OkObjectResult("Data updated.");
        }
        [FunctionName("Function5")]
        public static async Task<IActionResult> Run5(
           [HttpTrigger(AuthorizationLevel.Function, "delete", Route = "delete/{id:int}")] HttpRequest req,
           ILogger log, int id)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            //string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            ////dynamic data = JsonConvert.DeserializeObject(requestBody);
            ////name = name ?? data?.name;

            ////string responseMessage = string.IsNullOrEmpty(name)
            ////    ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            ////    : $"Hello, {name}. This HTTP triggered function executed successfully.";
            //EMP emp = JsonConvert.DeserializeObject<EMP>(requestBody);
            //lst.Add(new EMP { EID = emp.EID, NAME = emp.NAME });
             lst.Remove(lst.FirstOrDefault(m=>m.EID==id));
            return new OkObjectResult("Data Deleted.");
        }
    }
}




how to add css for mobile

.text-panel{
 margin-top:-150px ;
 @include respond-below(medium) {
  margin-top:-10px;
}
}

Tuesday, 22 September 2020

CRUD operations using CORE(3.1) MVC,AutoMapper,Generic Repository & Dependency Injection, core EF code first approach ,Bootstrap modal popup,datepicker & multiselect drop down.


                                             


 using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using System.ComponentModel.DataAnnotations;


namespace WebApplication6.DAL

{

    public class Country

    {

        [Key]

        public int CID { get; set; }

        [MaxLength(50)]

        public string CNAME { get; set; }

    }

}

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

namespace WebApplication6.DAL
{
    public class State
    {
        [Key]
        public int SID { get; set; }
        [MaxLength(50)]
        public string SNAME { get; set; }
        public int CID { get; set; }
        [ForeignKey("CID")]
        public virtual Country Country { get; set; }
    }
}
-
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication6.DAL
{
    public class Hobby
    {
        [Key]
        public int HID { get; set; }
        [MaxLength(50)]
        public string HNAME { get; set; }
    }
}
-
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication6.DAL
{
    public class Hobbymap
    {
        [Key]
        public int ID { get; set; }
        public int EID { get; set; }
        [ForeignKey("EID")]
        public virtual EMP EMP { get; set; }
        public int HID { get; set; }
        [ForeignKey("HID")]
        public virtual Hobby Hobby { get; set; }
    }
}
-
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication6.DAL
{
    public class AppDbContext:DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {

        }
        public DbSet<Country> Countries { get; set; }
        public DbSet<State> States { get; set; }
        public DbSet<Hobby> Hobbies { get; set; }

        public DbSet<Hobbymap> Hobbymaps { get; set; }
        public DbSet<EMP> EMPs { get; set; }
        public DbSet<DEPT> Depts { get; set; }
        public DbSet<Test> Tests { get; set; }
        public DbSet<Newemp> Newemps { get; set; }
        public DbSet<Hobbym> Hobbyms { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Country>().HasData(new Country { CID = 1, CNAME = "X" }, new Country { CID = 2, CNAME = "Y" }, new Country { CID = 3, CNAME = "Z" });
            modelBuilder.Entity<Hobby>().HasData(new Hobby { HID = 1, HNAME = "Cricket" }, new Hobby { HID = 2, HNAME = "Football" }, new Hobby { HID = 3, HNAME = "Baseball" }, new Hobby { HID = 4, HNAME = "Hockey" });
            modelBuilder.Entity<State>().HasData(new State { SID = 1, SNAME = "A", CID = 1 }, new State { SID = 2, SNAME = "B", CID = 1 }, new State { SID = 3, SNAME = "C", CID = 2 }, new State { SID = 4, SNAME = "D", CID = 2 }, new State { SID = 5, SNAME = "E", CID = 3 }, new State { SID = 6, SNAME = "F", CID = 3 });
        }
    }
}
-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication6.DAL
{
   public interface IRepository<T> where T: class
    {
        Task<IEnumerable<T>> Gets();
        Task<T> Get(int ID);
        Task<T> Save(T t);
        Task<string> Update(T t);
        Task<string> Delete(int ID);
        Task<string> SaveAll(List<T> lst);
        Task<string> DeleteAll(List<T> lst);
    }
}
-
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication6.DAL
{
    public class Repository<T> : IRepository<T>  where T : class
    {
        #region
        private readonly AppDbContext Context;
        #endregion
        public Repository(AppDbContext context)
        {
            this.Context = context;
        }
        public async Task<string> Delete(int ID)
        {
            Context.Set<T>().Remove(await Context.Set<T>().FindAsync(ID));
            await Context.SaveChangesAsync();
            return "Data Deleted.";
        }

        public async Task<string> DeleteAll(List<T> lst)
        {
            Context.Set<T>().RemoveRange(lst);
            await Context.SaveChangesAsync();
            return "All Data Deleted.";
        }

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

        public async Task<IEnumerable<T>> Gets()
        {
            return await Context.Set<T>().ToListAsync();
        }

        public async Task<T> Save(T t)
        {
            Context.Set<T>().Add(t);
            await Context.SaveChangesAsync();
            return t;
        }

        public async Task<string> SaveAll(List<T> lst)
        {
            Context.Set<T>().AddRange(lst);
            await Context.SaveChangesAsync();
            return "All Data Saved.";
        }

        public async Task<string> Update(T t)
        {
            Context.Set<T>().Update(t);
            await Context.SaveChangesAsync();
            return "Data Updated.";
        }
    }
}
-
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication6.DAL;

namespace WebApplication6.Models
{
    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            CreateMap<EMP, EMPVM>();
            CreateMap<EMPVM, EMP>();
            CreateMap<Newemp, NEWEMPVM>();
            CreateMap<NEWEMPVM, Newemp>();
        }
    }
}
-
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication6.Models
{
    public class NEWEMPVM
    {

        public NEWEMPVM()
        {
            HOBBY = new List<string>();
            Lhobby = new List<SelectListItem>();
            LCID = new List<SelectListItem>();
            LSID = new List<SelectListItem>();
        }
        public int EID { get; set; }
        [Required]
        public string NAME { get; set; }
        [Required]
        [DataType(DataType.MultilineText)]
        public string ADDRESS { get; set; }
        [Required]
        public string GENDER { get; set; }
        [Required]
        [EmailAddress]
        public string EMAIL { get; set; }
        [Required]
        public Decimal? SALARY { get; set; }
        [Required]
        public DateTime? DOJ { get; set; }
        [Required]
        public List<string> HOBBY { get; set; }
        public List<SelectListItem> Lhobby { get; set; }
        [Required]
        [Display(Name = "COUNTRY")]
        public int CID { get; set; }
        public List<SelectListItem> LCID { get; set; }
        [Required]
        [Display(Name = "STATE")]
        public int SID { get; set; }
        public List<SelectListItem> LSID { get; set; }
        [Required(ErrorMessage ="Please select a photo.")]
        public IFormFile PHOTO { get; set; }
        public string PATH { get; set; }

        [Required]

        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]

        [DataType(DataType.Password)]

        [Display(Name = "Password")]

        [RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{6,100}$", ErrorMessage = "Password contains at least one number,one uppercase,one lowercase & one special charecter .")]

        public string Password { get; set; }

        [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Invalid mobile number.")]

        public string Mobile { get; set; }

[RegularExpression(@"^(\d{6,9})$", ErrorMessage = "Zip code will only accept numeric digits with length 6 digit")]
        [RegularExpression(@"\d{5}", ErrorMessage = "Zip code will only accept numeric digits with length 5 digit")]

[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Please enter letters only")]

        public void fillddl(List<SelectListItem> cl, List<SelectListItem> hl, List<SelectListItem> sl = null)
        {
            LCID = cl;
            Lhobby = hl;
            LSID = sl;
        }
    }
}
-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using WebApplication6.DAL;
using WebApplication6.Models;

namespace WebApplication6
{
    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.AddAutoMapper(typeof(MappingProfile));
            services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(@"Data Source=(localdb)\MSSQLLocalDB;DataBase=Testdb0;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"));
            services.AddScoped<IRepository<Country>, Repository<Country>>();
            services.AddScoped<IRepository<State>, Repository<State>>();
            services.AddScoped<IRepository<Hobby>, Repository<Hobby>>();
            services.AddScoped<IRepository<Hobbymap>, Repository<Hobbymap>>();
            services.AddScoped<IRepository<EMP>, Repository<EMP>>();
            services.AddScoped<IRepository<Newemp>, Repository<Newemp>>();
            services.AddScoped<IRepository<Hobbym>, Repository<Hobbym>>();
            services.AddControllersWithViews()
          .AddJsonOptions(options =>
          {
              options.JsonSerializerOptions.PropertyNamingPolicy = null;
              //options.JsonSerializerOptions.Converters.Add(new WebApplication1.Models.LongToStringConverter());
          });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment 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.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
-
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using WebApplication6.DAL;
using WebApplication6.Models;


namespace WebApplication6.Controllers
{
    public class NewEmpController : Controller
    {
        #region
        private readonly IRepository<Country> ic;
        private readonly IRepository<State> ist;
        private readonly IRepository<Hobby> ih;
        private readonly IRepository<Hobbym> ihm;
        private readonly IRepository<Newemp> ie;
        private readonly IMapper mapper;
        private readonly IHostingEnvironment hostingEnvironment;
        #endregion
        public NewEmpController(IRepository<Country> ic, IRepository<State> ist,
            IRepository<Hobby> ih, IRepository<Hobbym> ihm, IRepository<Newemp> ie, IMapper mapper, IHostingEnvironment hostingEnvironment)
        {
            this.ic = ic;
            this.ist = ist;
            this.ih = ih;
            this.ihm = ihm;
            this.ie = ie;
            this.mapper = mapper;
            this.hostingEnvironment = hostingEnvironment;
        }
        [HttpGet]
        public async Task<IActionResult> Index()
        {
            var lst = await ie.Gets();
            return View(lst.ToList());
        }
        [HttpGet]
        public async Task<IActionResult> Create()
        {
            NEWEMPVM nEWEMPVM = new NEWEMPVM();
            var data = await ic.Gets();
            nEWEMPVM.fillddl(data.Select(x => new SelectListItem { Value = x.CID.ToString(), Text = x.CNAME }).ToList(), ih.Gets().Result.Select(n => new SelectListItem { Value = n.HID.ToString(), Text = n.HNAME }).ToList(), new List<SelectListItem>());
            return View(nEWEMPVM);
        }
        [HttpGet]
        public async Task<IActionResult> Fillddl(int CID)
        {
            var data = await ist.Gets();
            return Json(data.Where(m => m.CID == CID).ToList());
        }
        [HttpGet]
        public async Task<IActionResult> Edit(int id)
        {
            Newemp newemp = await ie.Get(id);
            NEWEMPVM nEWEMPVM = new NEWEMPVM();
            mapper.Map(newemp, nEWEMPVM);
            var data = await ic.Gets();
            nEWEMPVM.fillddl(data.Select(x => new SelectListItem { Value = x.CID.ToString(), Text = x.CNAME }).ToList(), ih.Gets().Result.Select(n => new SelectListItem { Value = n.HID.ToString(), Text = n.HNAME }).ToList(), ist.Gets().Result.Where(m => m.CID == nEWEMPVM.CID).Select(p => new SelectListItem { Value = p.SID.ToString(), Text = p.SNAME }).ToList());
            var data1= await ihm.Gets();
            nEWEMPVM.HOBBY = data1.Where(m => m.EID == id).Select(p => p.HID.ToString()).ToList();
            return View("Create", nEWEMPVM);
        }
        [HttpPost]
        public async Task<IActionResult> Create(NEWEMPVM nEWEMPVM)
        {
            Newemp emp = new Newemp();
            mapper.Map(nEWEMPVM, emp);
            if (nEWEMPVM.EID > 0)
                ModelState.Remove("PHOTO");
            if (ModelState.IsValid)
            {

                if (nEWEMPVM.PHOTO != null)
                {
                    string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "Image");
                    string uniqueFileName = Guid.NewGuid().ToString() + "_" + nEWEMPVM.PHOTO.FileName.Substring(3);
                    string filePath = Path.Combine(uploadsFolder, nEWEMPVM.PHOTO.FileName);
                    nEWEMPVM.PHOTO.CopyTo(new FileStream(filePath, FileMode.Create));
                    emp.PATH = nEWEMPVM.PHOTO.FileName;
                }
                if (nEWEMPVM.EID < 1)
                {
                    emp = await ie.Save(emp);
                }
                else
                {
                    string t = await ie.Update(emp);
                    t = await ihm.DeleteAll(ihm.Gets().Result.Where(m => m.EID == nEWEMPVM.EID).ToList());
                }
                string s = await ihm.SaveAll(nEWEMPVM.HOBBY.Select(x => new Hobbym { EID = emp.EID, HID = Convert.ToInt32(x) }).ToList());
                return RedirectToAction("Index");
            }
            else
            {
                var data = await ic.Gets();
                nEWEMPVM.fillddl(data.Select(x => new SelectListItem { Value = x.CID.ToString(), Text = x.CNAME }).ToList(), ih.Gets().Result.Select(n => new SelectListItem { Value = n.HID.ToString(), Text = n.HNAME }).ToList(), ist.Gets().Result.Where(m => m.CID == nEWEMPVM.CID).Select(p => new SelectListItem { Value = p.SID.ToString(), Text = p.SNAME }).ToList());
                return View(nEWEMPVM);
            }

        }
        [HttpGet]
        public async Task<IActionResult> Delete(int id)
        {
            await ie.Delete(id);
         string   t = await ihm.DeleteAll(ihm.Gets().Result.Where(m => m.EID == id).ToList());
            return RedirectToAction("Index");
        }
    }
}
-
@model IEnumerable<WebApplication6.DAL.Newemp>

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


<p>
    <a asp-action="Create" class="btn btn-primary">Add New</a>
</p>
<table class="table table-bordered table-hover" id="tb">
    <thead class="bg-primary">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.NAME)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ADDRESS)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.GENDER)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EMAIL)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.SALARY)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.DOJ)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.PATH)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
               
                <td>
                    @Html.DisplayFor(modelItem => item.NAME)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.ADDRESS)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.GENDER)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.EMAIL)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.SALARY)
                </td>
                <td>
                    @{ 
                        string s = string.Format("{0:dd-MM-yyyy}", item.DOJ);
                    }
                   @s
                </td>
                <td>
                    <img height="50" width="50" src="@("Image/"+item.PATH)"/>
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new {  id=item.EID }) |
                    @Html.ActionLink("Delete", "Delete", new {  id=item.EID })
                </td>
            </tr>
        }
    </tbody>
</table>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        var table = $("#tb").DataTable({
            "order": [[0, "asc"]],
            "lengthMenu": [[2, 10, 25, 50, -1], [2, 10, 25, 50, "All"]],
            "scroller": true,
            "orderClasses": false,
        });
    });

</script>
-
@model WebApplication6.Models.NEWEMPVM

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


<div class="row">
    <div class="col-md-4">
        <form asp-action="Create" enctype="multipart/form-data">
            <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" />
                <input asp-for="EID" type="hidden" />
                <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 asp-for="GENDER" type="radio" value="Male" />Male
                <input asp-for="GENDER" type="radio" value="Female" />Female
                <span asp-validation-for="GENDER" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="EMAIL" class="control-label"></label>
                <input asp-for="EMAIL" class="form-control" />
                <span asp-validation-for="EMAIL" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="SALARY" class="control-label"></label>
                <input asp-for="SALARY" class="form-control" />
                <span asp-validation-for="SALARY" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="DOJ" class="control-label"></label>
                <input asp-for="DOJ" class="form-control" />
                <span asp-validation-for="DOJ" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="HOBBY" class="control-label"></label>
                <select asp-for="HOBBY" asp-items="Model.Lhobby" class="form-control" multiple></select>
                <span asp-validation-for="HOBBY" 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">
                <label asp-for="PHOTO" class="control-label"></label>
                <input asp-for="PHOTO" type="file" class="form-control" />
                <input type="hidden" asp-for="PATH" />
                <span asp-validation-for="PHOTO" 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>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $('#DOJ').prop("type", "text");
        $('#HOBBY').chosen();
      
      
        $('#DOJ').datetimepicker({
            format:'DD-MM-YYYY'
        });
        var id =@Html.Raw(Json.Serialize(Model.EID));
        if (id == 0) {
            $('#DOJ').val('');
            //$("#PHOTO").rules("remove", "required");
            //$("#PHOTO").rules("add", "required");
        }  
        else {
             $("#PHOTO").removeAttr('data-val-required');
            var dt = new Date(@Html.Raw(Json.Serialize(Model.DOJ)));
              $('#DOJ').val((dt.getDate() < 10 ? ("0" + dt.getDate()) : dt.getDate()) + "-" + (parseInt(dt.getMonth() + 1) < 10 ? ("0" + parseInt(dt.getMonth() + 1)) : parseInt(dt.getMonth() + 1)) + "-" + dt.getFullYear());
        }
        $('#CID').change(function () {
            $('#SID').empty().append("<option>Select</option>");
            $.ajax({
                url: '@Url.Action("Fillddl","NewEmp")',
                data: { CID: $(this).val() },
                success: function (data) {
                    $.each(data, function (i, v) {
                         $('#SID').append("<option value="+v.SID+">"+v.SNAME+"</option>");
                    });
                }
            });
        });
    });
</script>

Monday, 15 June 2020

CRUD operations using Angular9 & CORE WEBAPI(3.1) ,AutoMapper,Repository, Dependency Injection, EF core code first approach & implementing store procedure in EF core.



Dot net core webapi code :

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

namespace Automapper007.Models
{
    public class EMP
    {
        [Key]
        public int EID { get; set; }
        [MaxLength(50)]
        public string NAME { get; set; }
        [MaxLength(50)]
        public string GENDER { get; set; }
    }
}


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

namespace Automapper007.Models
{
    public class AppDbContext:DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options):base(options)
        {

        }
        public DbSet<EMP> Emps { get; set; }

    }
}

--
Add-migraion 4th;

Write below code :

using Microsoft.EntityFrameworkCore.Migrations;

namespace Automapper007.Migrations
{
    public partial class _4th : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            var sp = @"CREATE procedure dbo.SP_DML2
                        (
                        @EID int=null,
                        @NAME nvarchar(50)=null,
                        @GENDER nvarchar(50)=null,
                        @MARK int,
                        @message nvarchar(Max)='' output
                        )
                        as
                        begin
                         begin Try
                           if @MARK=1
                           begin
                           insert into Emps(NAME,GENDER) values(@NAME,@GENDER)
                           set @message='Data Saved Successfully.'
                           end
                           else if @MARK=2
                           begin
                           update Emps set NAME=@NAME,GENDER=@GENDER where EID=@EID
                           set @message='Data Updated Successfully.'
                           end
                           else if @MARK=3
                           begin
                           delete from  Emps  where EID=@EID
                           set @message='Data Deleted Successfully.'
                           end
                         end Try
                         begin catch
                         SELECT   @message='Error on Procedure :'+ERROR_PROCEDURE()+'Error on line :'+ ERROR_LINE()+'Error message :'+ERROR_MESSAGE() 
                         end catch
                            end";
            migrationBuilder.Sql(sp);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {

        }
    }
}

update-database
--
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Automapper007.Models;

namespace Automapper007.Services
{
  public interface IRepository
    {
        public Task<IEnumerable<EMP>> Gets();
        public Task<EMP> Get(int EID);
        public Task<string> Save(EMP emp);
        public Task<string> Update(EMP emp);
        public Task<string> Delete(int EID);


    }
}
--
using Automapper007.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Automapper007.Models;
using Automapper007.Services;
using Microsoft.EntityFrameworkCore;


namespace Automapper007.Services
{
    public class Repository : IRepository
    {
        private readonly AppDbContext context;
        string Message = "";
        public Repository(AppDbContext context)
        {
            this.context = context;
        }
        public async Task<string> Delete(int EID)
        {
             await context.Database.ExecuteSqlRawAsync($"EXEC dbo.SP_DML2 @EID={EID},@MARK={3},@message={Message} output");
            return Message;
        }

        public async Task<EMP> Get(int EID)
        {
            return await context.Emps.FromSqlRaw($"select * from Emps where EID={EID}").FirstAsync();
        }

        public async Task<IEnumerable<EMP>> Gets()
        {
            return await context.Emps.FromSqlRaw("select * from Emps").ToListAsync();
        }

        public async Task<string> Save(EMP emp)
        {
           
                await context.Database.ExecuteSqlRawAsync($"EXEC dbo.SP_DML2 @EID={emp.EID},@NAME={emp.NAME},@GENDER={emp.GENDER},@MARK={1},@message={Message} output");
                return Message;
           
            
        }

        public async Task<string> Update(EMP emp)
        {
            await context.Database.ExecuteSqlRawAsync($"EXEC dbo.SP_DML2 @EID={emp.EID},@NAME={emp.NAME},@GENDER={emp.GENDER},@MARK={2},@message={Message} output");
            return Message;
        }
    }
}
--
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Automapper007.Models;
using Automapper007.Services;

namespace Automapper007.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmpController : ControllerBase
    {
        private readonly IRepository repository;
      
        public EmpController(IRepository repository)
        {
            this.repository = repository;
        }
        [HttpGet]
        public async Task<ActionResult<IEnumerable<EMP>>> Gets()
        {
            try
            {
                return Ok(await repository.Gets());
            }
            catch (Exception ex)
            {

                return StatusCode(StatusCodes.Status500InternalServerError, ex);
            }
        }
        [HttpGet("{EID:int}")]
        public async Task<ActionResult<EMP>> Get(int EID)
        {
            try
            {
                return Ok(await repository.Get(EID));
            }
            catch (Exception ex)
            {

                return StatusCode(StatusCodes.Status500InternalServerError, ex);
            }
        }
        [HttpPost]
        public async Task<ActionResult> Save(EMP emp)
        {
            try
            {
                return CreatedAtAction(nameof(Get), new { EID = emp.EID }, await repository.Save(emp));
            }
            catch (Exception ex)
            {

                return StatusCode(StatusCodes.Status500InternalServerError, ex);
            }
        }
        [HttpPut]
        public async Task<ActionResult> Update(EMP emp)
        {
            try
            {
                return Ok(await repository.Update(emp));
            }
            catch (Exception ex)
            {

                return StatusCode(StatusCodes.Status500InternalServerError, ex);
            }
        }
        [HttpDelete("{EID:int}")]
        public async Task<ActionResult<EMP>> Delete(int EID)
        {
            try
            {
                return Ok(await repository.Delete(EID));
            }
            catch (Exception ex)
            {

                return StatusCode(StatusCodes.Status500InternalServerError, ex);
            }
        }
    }
}
--
Angular9 Code :

Model :

export class IEMP {
    EID: number;
    NAME: string;
    GENDER: string;
}

Service :
import { Injectable } from '@angular/core';
import { IEMP } from './emp.model';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/observable/throw';

@Injectable()
export class EmpServices {
    baseUrl = 'https://localhost:44393/api/Emp';
    constructor(private http: HttpClient) { }
    Gets() {
        return this.http.get(`${this.baseUrl}`)
            .catch((err) => {
                return Observable.throw(err);
            });
    }
    Get(eid: number) {
        return this.http.get(`${this.baseUrl}/${eid}`)
            .catch((err) => {
                return Observable.throw(err);
            });
    }
    Save(emp: IEMP) {
        return this.http.post(`${this.baseUrl}`
        , JSON.stringify(emp)
        , {headers: new HttpHeaders({'Content-Type' : 'application/json'})} )
        .catch( (err) => {
            return Observable.throw(err);
        });
    }
    Update(emp: IEMP) {
        return this.http.put(`${this.baseUrl}`
        , JSON.stringify(emp)
        , {headers: new HttpHeaders({'Content-Type' : 'application/json'})}
        )
            .catch((err) => {
                return Observable.throw(err);
            });
    }
    Delete(eid: number) {
        return this.http.delete(`${this.baseUrl}/${eid}`
        , {headers: new HttpHeaders({'Content-Type' : 'application/json'})}
        )
            .catch((err) => {
                return Observable.throw(err);
            });
    }
}

Pipe :

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


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

Create View :

<form class="form-horizontal" [formGroup]="frmEmp">
    <div class="form-group">
        <label class="control-label col-lg-4"></label>
        <div class="col-lg-4 alert-danger" *ngIf='errorMessage !== undefined'>
          {{errorMessage}}
        </div>
</div>
  <div class="form-group" [ngClass]="{'has-error':frmEmp.get('EID').errors && (frmEmp.get('EID').touched || frmEmp.get('EID').dirty)}">
      <label class="control-label col-lg-4">EID</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" formControlName="EID" />
      </div>
      <span class="help-block has-error" *ngIf="frmEmp.get('EID').errors && (frmEmp.get('EID').touched || frmEmp.get('EID').dirty)">Eid should not be blank.</span>
  </div>
  <div class="form-group" [ngClass]="{'has-error':frmEmp.get('NAME').errors && (frmEmp.get('NAME').touched || frmEmp.get('NAME').dirty)}">
      <label class="control-label col-lg-4">NAME</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" formControlName="NAME" />
      </div>
      <span class="help-block has-error" *ngIf="frmEmp.get('NAME').errors && (frmEmp.get('NAME').touched || frmEmp.get('NAME').dirty)">Name should not be blank.</span>
  </div>
  <div class="form-group" [ngClass]="{'has-error':frmEmp.get('GENDER').errors && (frmEmp.get('GENDER').touched || frmEmp.get('GENDER').dirty)}">
      <label class="control-label col-lg-4">GENDER</label>
      <div class="col-lg-4">
          <input type="radio" value="Male" formControlName="GENDER" />Male
          <input type="radio" value="Female" formControlName="GENDER" />Female
      </div>
      <span class="help-block has-error" *ngIf="frmEmp.get('GENDER').errors && (frmEmp.get('GENDER').touched || frmEmp.get('GENDER').dirty)">Please select a gender.</span>
  </div>
  <div class="form-group" >
      <label class="control-label col-lg-4"></label>
      <div class="col-lg-4">
          <input type="button" value="Submit" (click)="save(frmEmp.invalid)" class="btn btn-primary" style="width:80px" />
          <input type="button" value="Reset" (click)="reset(frmEmp)" class="btn btn-primary" style="width:80px" />
          <a [routerLink]="['/list']">Back To List</a>
      </div>
  </div>
</form>

Create Component :

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { EmpServices } from '../emp/emp.service';
import { IEMP } from './test.model';
import { NgForm } from '@angular/forms';


@Component({
  selector: 'app-createtest',
  templateUrl: './createtest.component.html',
  styleUrls: ['./createtest.component.css']
})
export class CreatetestComponent implements OnInit {
  EMP: IEMP;
  frmEmp: FormGroup;
  errorMessage: string;
  eid: number;
  constructor(private ro: Router, private ar: ActivatedRoute, private es: EmpServices, private fb: FormBuilder) { }

  ngOnInit() {
    this.CLR();
    this.frmEmp = this.fb.group({
      EID: [null, Validators.required],
      NAME: [null, Validators.required],
      GENDER: [null, Validators.required]
    });
    this.eid = this.ar.snapshot.params['id'];
    if (this.eid !== undefined) {
      this.es.Get(this.eid).subscribe((data) => {
        this.frmEmp.setValue({
          EID: data.EID,
          NAME: data.NAME,
          GENDER: data.GENDER
        });
      }, (err) => {
        this.errorMessage = err.message;
      });
    }
  }
  CLR(): void {
    this.EMP = {
      EID: null,
      NAME: null,
      GENDER: null
    };
  }
  reset(nf: NgForm): void {
    nf.reset();
  }
  save(isValid: boolean): void {
    if (!isValid) {
      this.EMP.EID = Number(this.frmEmp.value.EID);
      this.EMP.NAME = this.frmEmp.value.NAME;
      this.EMP.GENDER = this.frmEmp.value.GENDER;
      if (this.eid !== undefined) {
        this.es.Update(this.EMP).subscribe((data) => {
          this.ro.navigate(['/list']);
        }, (err) => {
          this.errorMessage = err.message;
        });
      } else {
        this.es.Save(this.EMP).subscribe((data) => {
          this.ro.navigate(['/list']);
        }, (err) => {
          this.errorMessage = err.message;
        });
      }
    }
  }
}

List View :

<div class="row">
  <input type="button" value="Add New" [routerLink]="['/create']"  class="btn btn-primary" style="width:80px" />
</div><br>
<div class="row alert-danger" *ngIf='errorMessage !== undefined'>
          {{errorMessage}}
</div>
<div class="row">
  <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|TestPipe: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>

List Component :

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { EmpServices } from '../emp/emp.service';
import { IEMP } from './test.model';

@Component({
  selector: 'app-listtest',
  templateUrl: './listtest.component.html',
  styleUrls: ['./listtest.component.css']
})
export class ListtestComponent implements OnInit {
  errorMessage: string;
  list: IEMP[];
  constructor(private es: EmpServices) { }

  ngOnInit() {
    this.fill();
  }
  fill(): void {
    this.es.Gets().subscribe((data) => {
      this.list = data;
    }, (err) => {
      this.errorMessage = err.message;
    });
  }
  del(eid: number): void {
    if (confirm('Do you want to delete it ?')) {
      this.es.Delete(eid).subscribe((data) => {
        this.fill();
      }, (err) => {
        this.errorMessage = err.message;
      });
    }
  }
}

App View :

<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>
App Model :

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { RouterModule, Routes } from '@angular/router';
import {EmpServices} from './emp/emp.service';
import { HttpClientModule } from '@angular/common/http';
import { CreatetestComponent } from './test/createtest.component';
import { ListtestComponent } from './test/listtest.component';
import { TcustomPipe } from './test/test.pipe';

const appRoutes: Routes = [
  { path: 'list', component: ListtestComponent },
  { path: 'create/:id', component: CreatetestComponent  },
  { path: 'delete/:id', component: CreatetestComponent  },
  { path: 'create', component: CreatetestComponent  },
  { path: '', redirectTo: '/list', pathMatch: 'full' },
  { path: '**', component: ListtestComponent  }
];

@NgModule({
  declarations: [
    AppComponent,
    ListEmployeesComponent,
    CreateEmployeeComponent,
    CreateDepartmentComponent,
    CreateStapComponent,
    CreateFacultyComponent,
    CreateDoctorComponent,
    CreatePatientComponent,
    EmplistComponent,
    EmpcreateComponent,
    CreatetestComponent,
    ListtestComponent,
    TcustomPipe
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    HttpModule,
    HttpClientModule,
    BsDatepickerModule.forRoot(),
    RouterModule.forRoot(appRoutes),
    ToastrModule.forRoot(),
    
  ],
  providers: [EmployeeService, DepartmentServices, StapServices, FacultyServices, DoctorServie, PatienServices, EmpServices],
  bootstrap: [AppComponent]
})
export class AppModule { }