Friday, November 29, 2019

Creating Asp.net Core web Api Entity framework Code First Appraoch | Testing Web Api Using Postman

Hello & As-salam u alikum ! In this Article we will learn to Implement Web Api and test the api through Postman.

Step# 1:  Create an Asp.net Web API Project as shown in the below Images.




Step# 2:  Create a model folder and add a new Entity Class named as "Product".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MircoServiceDocker.Model
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Price { get; set; }
        public DateTime ManufacturingDate { get; set; }
    }
}

Step# 3:  Install Microsoft.EntityFrameworkCore.SqlServer &  Microsoft.EntityFrameworkCore.Tools 
which I Had explained in my previous blog.

Step# 4:  Add a static class for seeding database , i.e. "ModelBuilderExtensions" & add the below code.

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

namespace MircoServiceDocker.Model
{
    public static class ModelBuilderExtensions
    {
        public static void Seed(this ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Product>().HasData(
              new Product
              {
                  Id = 1,
                  Name = "Soap",
                  Price = 23,
                  ManufacturingDate = DateTime.Now
              },
              new Product
              {
                  Id = 2,
                  Name = "Detergent",
                  Price = 200,
                  ManufacturingDate = DateTime.Now
              },
            new Product
           {
        Id = 3,
        Name = "Shampo",
        Price = 60,
        ManufacturingDate = DateTime.Now
          }

          );
        }
    }
}




Step# 5:  Add a class for data access layer , i.e. "ProductContext" & add the below code.

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

namespace MircoServiceDocker.Model
{
    public class ProductContext:DbContext
    {

        public ProductContext(DbContextOptions<ProductContext> options) : base(options)
        {

        }
        public DbSet<Product> Products { get; set; }



        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Seed();

        }

    }
}



Step# 6:  Add a product interface to use repository pattern with constructor Dependency injection.


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

namespace MircoServiceDocker.Model
{
   public interface Iproduct
    {
        Product GetProduct(int Id);

        IEnumerable<Product> GetAll();


        Product Add(Product Product);
        Product Update(int Id, Product Product);
        Product Delete(int Id);
    }
}


Step# 7:  Implement IPorduct repository in Product Repository class.


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

namespace MircoServiceDocker.Model
{
    public class ProductRepository : Iproduct
    {
        private readonly ProductContext db;
        public ProductRepository(ProductContext db)
        {
            this.db = db;
        }
        public Product Add(Product Product)
        {
            db.Products.Add(Product);
            db.SaveChanges();
            return Product;
        }

        public Product Delete(int Id)
        {

            Product product = db.Products.Where(x => x.Id == Id).SingleOrDefault();
            db.Products.Remove(product);
            db.SaveChanges();
            return product;
        }

        public IEnumerable<Product> GetAll()
        {
          return  db.Products.ToList();
        }

        public Product GetProduct(int Id)
        {
            return db.Products.SingleOrDefault(x => x.Id == Id);
        }

        public Product Update(int Id,Product Product)
        {
            Product product = db.Products.Where(x => x.Id == Id).SingleOrDefault();
            product.Name = Product.Name;
            product.Price = Product.Price;
            product.ManufacturingDate = Product.ManufacturingDate;
            db.SaveChanges();
            return product;
        }
    }
}



Step# 8:  Goto the Appsetting.json file and configure the connection string.

Step# 9:  Go to the Startup.cs file and configure the middle-ware as shown below.


Step# 10:  Add a new API controller named as ProductController.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MircoServiceDocker.Model;

namespace MircoServiceDocker.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        // GET: api/Product
        private Iproduct db;

        public ProductController(Iproduct db)
        {
            this.db = db;
         
        }



        [HttpGet]
        public IEnumerable<Product> Get()
        {
            return db.GetAll();
        }




        // GET: api/Product/5
        [HttpGet("{id}", Name = "Get")]
        public Product Get(int id)
        {
            return db.GetProduct(id);
        }

        // POST: api/Product
        [HttpPost]
        public void Post(Product product)
        {
            db.Add(product);
        }

        // PUT: api/Product/5
        [HttpPut("{id}")]
        public void Put(int id, Product product)
        {
            db.Update(id, product);

        }

        // DELETE: api/ApiWithActions/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
            db.Delete(id);
        }
    }
}


Step# 11:  Run the application & Open the Postman & test the Get API.
add "/Api/Product" after localhost:port in the Url.

Get All Product:


Get Product By Id:



Add New Product:
Select Content-type : application/json 





Update Product:


Delete the Product with ID 6:


Thursday, November 21, 2019

Add & Display Roles in asp.net Core Identity | Asp.net Core Idnetity


Hello & As-salam u alikum ! , In the previous articles we had discussed about Client side validations,Remote Validations & Custom Validations, There is the reference in the below link.

https://dotnetcorecommunity.blogspot.com/2019/11/emailuser-name-already-taken-remote.html

At the moment, We are going to learn about roles in asp.net core identity, Before moving towards this topic I must suggest you to see these below articles for the basic or prior knowledge to understand about this concept.


1-Implementing Asp.net Core Identity |Authentication and Authorization| Introduction To Asp.net Core Identity | asp.net core 2.0 identity tutorial

2-Implementing Login Logout & Sign up Feature in Asp.net Core Identity using Sign in Manager | Login Log out show in Navigation Bar | Session Cookie Vs Persistence Cookie

3-Authorization In Asp.net Core Identity | AllowAnonymous & Authorize Attribute in Asp.net Core | Set Authorization Globally

Step# 1:  Add a new controller named as "AdministrationController" & add an action named as "ListRoles" to show the list of role present in the database.



using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AspCoreIdentity.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace AspCoreIdentity.Controllers
{
   [Authorize(Roles ="Admin")]
    public class AdministrationController : Controller
    {
        private readonly RoleManager<IdentityRole> roleManager;
        private readonly UserManager<ApplicationUser> userManager;
        private readonly ILogger<AdministrationController> logger;

        public AdministrationController(RoleManager<IdentityRole> roleManager,UserManager<ApplicationUser> userManager, ILogger<AdministrationController> logger)
        {
            this.roleManager = roleManager;
            this.userManager = userManager;
            this.logger = logger;
        }

        [HttpGet]
        public IActionResult ListRoles()
        {
            var roles = roleManager.Roles;
            return View(roles);
        }
}

}
Step# 2:  Add a view of ListRoles and paste the following HTML.


@model IEnumerable<Microsoft.AspNetCore.Identity.IdentityRole>

@{
    ViewBag.Title = "All Roles";
}

<h1>All Roles</h1>

@if (Model.Any())
{
    <a class="btn btn-primary mb-3" style="width:auto" asp-action="CreateRole"
       asp-controller="administration">Add new role</a>



    <table class="table table-dark">
        <thead>
            <tr>
                <th>ID</th>
                <th>Role Name</th>
                <th>Edit</th>
                <th>Delete</th>

            </tr>
        </thead>
        <tbody>



            @foreach (var role in Model)
            {

                <tr>
                    <td>@role.Id</td>
                    <td>@role.Name</td>
                    <td>
                        <a asp-action="EditRole" asp-controller="Administration"
                           asp-route-id="@role.Id" class="btn btn-primary">Edit</a>
                    </td>
                    <td>

                        <form method="post" asp-action="Deleterole" asp-route-id="@role.Id">


                            <span id="confirmDeleteSpan_@role.Id" style="display:none">
                                <span>Are you sure you want to delete?</span>
                                <button type="submit" class="btn btn-danger">Yes</button>
                                <a href="#" class="btn btn-primary"
                                   onclick="confirmDelete('@role.Id', false)">No</a>
                            </span>

                            <span id="deleteSpan_@role.Id">
                                <a href="#" class="btn btn-danger"
                                   onclick="confirmDelete('@role.Id', true)">Delete</a>
                            </span>
                        </form>
                    </td>

                </tr>


            }

        </tbody>

    </table>


}
else
{
    <div class="card">
        <div class="card-header">
            No roles created yet
        </div>
        <div class="card-body">
            <h5 class="card-title">
                Use the button below to create a role
            </h5>
            <a class="btn btn-primary" style="width:auto"
               asp-controller="administration" asp-action="CreateRole">
                Create Role
            </a>
        </div>
    </div>
}

@section Scripts {
    <script src="~/js/CustomScript.js"></script>
}

Now Run the project & target the URL "https://localhost:44318/Administration/ListRoles"
you will not get any role because we didn't have created any role so the list would be empty for adding new Records we have to add a new action result Which we already had mentioned on view named as "CreateRole". This action will help us to add new role in the database.


  [HttpGet]
        public IActionResult CreateRole()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> CreateRole(CreateRoleViewModel model)
        {
            if (ModelState.IsValid)
            {
                // We just need to specify a unique role name to create a new role
                IdentityRole identityRole = new IdentityRole
                {
                    Name = model.RoleName
                };

                // Saves the role in the underlying AspNetRoles table
                IdentityResult result = await roleManager.CreateAsync(identityRole);

                if (result.Succeeded)
                {
                   
                    return RedirectToAction("ListRoles", "Administration");
                }

                foreach (IdentityError error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }

            return View(model);
        }

Add the above GET & POST methods in the Administrator Controller & add a view for this action method.



@model CreateRoleViewModel

@{
    ViewBag.Title = "Create New Role";
}

<form asp-action="CreateRole" method="post" class="mt-3">
    <div asp-validation-summary="All" class="text-danger">
    </div>
    <div class="form-group row">
        <label asp-for="RoleName" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <input asp-for="RoleName" class="form-control" placeholder="Name">
            <span asp-validation-for="RoleName" class="text-danger"></span>
        </div>
    </div>

    <div class="form-group row">
        <div class="col-sm-10">
            <button type="submit" class="btn btn-primary" style="width:auto">
                Create Role
            </button>
        </div>
    </div>
</form>

 When you run the project, you may be able to add new roles & can see the added roles on ListRole view.




Conclusion :
that's all for this blog, we have successfully
 Implement the Asp.net core Identity with Adding & displaying Role ,In the next coming articles we will discuss more details on this topic.Thank you for watching,Have a great day !


Subscribe to my Youtube