ASP.NET CORE Archives - Tech Insights Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Fri, 05 Jan 2024 06:04:17 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 ASP.NET CORE Archives - Tech Insights 32 32 230003556 .NET 8: ASP.Net Core Web API CRUD Operations https://reactconf.org/net-8-asp-net-core-web-api-crud-operations/ https://reactconf.org/net-8-asp-net-core-web-api-crud-operations/#comments Tue, 02 Jan 2024 10:40:14 +0000 https://reactconf.org/?p=245 In .NET 8, Developing a CRUD (Create, Read, Update, Delete) API using In-memory collection is a common task in web development. In this article, we will explore building a complete …

The post .NET 8: ASP.Net Core Web API CRUD Operations appeared first on Tech Insights.

]]>
In .NET 8, Developing a CRUD (Create, Read, Update, Delete) API using In-memory collection is a common task in web development. In this article, we will explore building a complete .NET 8 ASP.NET Core Web API CRUD Operations. With a practical use case.

What is an API?

  • API stands for Application Programming Interface.
  • API is a software intermediary that allows different software applications to communicate and exchange data.

What is RESTful API?

  1. REST stands for Representational State Transfer.
  2. REST is a software architecture that imposes conditions on how an API should work.
  3. RESTful API is an interface that two computer systems use to exchange information securely over the internet.

Create an Asp.NET Core Web API Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project

  1. Open the visual studio (IDE).
  2. Click on the “Create new project” option.
  3. Choose “ASP.NET Core Web API” from the list of available templates.
  4. Click the Next button.
  5. The configure a new project, specify the name and location of your project.
  6. Click the “Next” button.
  7. Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  8. Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  9. Click the “Create” button

Once the project is created, let’s delete the existing WeatherForecast controller and model file.

Let’s create a folder in the project named

  • Model
  • Services

Right-click on Solution -> Add-> New Folder

Creating a Model

Right-click on Model Folder and select Add then click on New Item then enter class Name (Department.cs) and press the Add button.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {

        public int Id { get; set; }
        public required string DepartmentName { get; set; }
        public string Description { get; set; } = string.Empty;
        public bool IsActive { get; set; } = true;
    }
}

For Adding and updating the department list create another model AddUpdatedepartment.cs

namespace dotNet8CRUDWebAPI.Model
{
    public class AddUpdateDepartment
    {

        public required string DepartmentName { get; set; }
        public string Description { get; set; } = string.Empty;
        public bool IsActive { get; set; } = true;
    }
}

Create Services

Create an interface, Right click on Services Folder select Add, and click on New Item then select an interface and enter Interface Name(IDepartment.cs), and press the Add button.

In the interface, we are going to define business logic.

using dotNet8CRUDWebAPI.Model;

namespace dotNet8CRUDWebAPI.Services
{
    public interface IDepartment
    {
        List<Department> GetAllList(bool? IsActive);
        Department? GetById(int id);
        Department AddDeparement(AddUpdateDepartment DeptObj);
        Department? UpdateDepartment(int id, AddUpdateDepartment DeptObj);
        bool DeleteDepartmentById(int id);

    }
}

Create a concrete class, Right click on Services Folder and select Add, and click on New Item then select the class and enter class Name(DepartmentServices.cs) and press the Add button.

In the concrete class, we are going to implement the interface.


using dotNet8CRUDWebAPI.Model;

namespace dotNet8CRUDWebAPI.Services
{
    public class DepartmentServices : IDepartment
    {
        private readonly List<Department> _departmentList;

        public DepartmentServices()
        {
            _departmentList = new List<Department>()
            {
                new Department()
                {
                    Id = 1,
                    DepartmentName= "Computer Science",
                    Description = "Head of Department",
                    IsActive = true,


                }
            };
        }
        public List<Department> GetAllList(bool? IsActive)
        {
            return IsActive== null ? _departmentList : _departmentList.Where(dept=>dept.IsActive==IsActive).ToList();
        }

        public Department? GetById(int id)
        {
            return _departmentList.FirstOrDefault(dept=>dept.Id==id);
         }


        public Department AddDeparement(AddUpdateDepartment DeptObj)
        {
            var AddDepartment = new Department()
            {
                Id = _departmentList.Max(id=> id.Id) + 1,
                DepartmentName = DeptObj.DepartmentName,
                Description = DeptObj.Description,
                IsActive =DeptObj.IsActive
            };
            _departmentList.Add(AddDepartment);

            return AddDepartment;
        }
              
        
        
        public Department? UpdateDepartment(int id, AddUpdateDepartment DeptObj)
        {
            var Deptindex = _departmentList.FindIndex(idx => idx.Id==id);

            if(Deptindex>0)
            {
                var Dept = _departmentList[Deptindex];
                Dept.DepartmentName = DeptObj.DepartmentName;
                Dept.Description = DeptObj.Description;
                Dept.IsActive = DeptObj.IsActive;

                _departmentList[Deptindex] = Dept;

                return Dept;

            }
            else
            {
                return null;
            }

        }

        public bool DeleteDepartmentById(int id)
        {
            var deptindex = _departmentList.FindIndex(idx => idx.Id == id);
            if (deptindex>0)
            {
                _departmentList.RemoveAt(deptindex);
            }
            return deptindex>0;
        }

    }
}

Creating a  Controller

Create a Controller, Right-click on Controller Folder select Add -> Controller -> API -> API Controller, and enter controller Name (DepartmentController.cs) and press the Add button.

  • Open the DepartmentController file
  • Create a constructor and inject the IDepartment interface
  • Create action methods
    • GET
    • POST
    • PUT
    • Delete
using dotNet8CRUDWebAPI.Model;
using dotNet8CRUDWebAPI.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace dotNet8CRUDWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DepartmentController : ControllerBase
    {
        private readonly IDepartment _department;

        public DepartmentController(IDepartment department)
        {
           _department = department;
        }

        [HttpGet]
        public IActionResult Get([FromQuery] bool? isActive=null)
        {
            return Ok(_department.GetAllList(isActive));
        }
        [HttpGet]
        [Route("{id}")]
        public  IActionResult Get(int id)
        {
            var dept = _department.GetById(id);
            if (dept == null)
            {
                return NotFound();
            }
            return Ok(dept);

        }

        [HttpPost]
        public IActionResult Post(AddUpdateDepartment obj)
        {
            var dept = _department.AddDeparement(obj);
            if(dept == null)
            {
                return BadRequest();
            }
            return Ok(new
            {
                message = "Deparment Created Successfully...!",
                id = dept!.Id
            });
        }

        [HttpPut]
        [Route("{id}")]
        public IActionResult Put([FromRoute] int id, [FromBody]  AddUpdateDepartment obj)
        {
            var dept = _department.UpdateDepartment(id, obj);
            if (dept == null)
            {
                return NotFound();
            }
            return Ok(new
            {
                message = "Deparement Updated Successfully...!",
                id = dept!.Id
            });
        }

        [HttpDelete]
        [Route("{id}")]
        public IActionResult Delete([FromRoute]int id)
        {
            
            if (!_department.DeleteDepartmentById(id))
            {
                return NotFound();
            }
            return Ok(new {
                message = "Department Deleted Successfully..!",
                id = id
            });
        }
    }
}

Register services

Open the Program.cs file and register IDepartment and DepartmentServices as an AddSingleton.

using dotNet8CRUDWebAPI.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

builder.Services.AddSingleton<IDepartment,DepartmentServices>();
var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Run the API Project

Get All Department List

Adding a Deparments

.NET 8: ASP.Net Core Web API CRUD Operations

Updating Department

.NET 8: ASP.Net Core Web API CRUD Operations

Delete a Department

.NET 8: ASP.Net Core Web API CRUD Operations

See More: How to Avoid Data Overload in EF Core

The post .NET 8: ASP.Net Core Web API CRUD Operations appeared first on Tech Insights.

]]>
https://reactconf.org/net-8-asp-net-core-web-api-crud-operations/feed/ 1 245
How to create Login Page using Asp.net Core MVC C# With Database https://reactconf.org/how-to-create-login-page-using-asp-net-core-mvc-c-with-database/ https://reactconf.org/how-to-create-login-page-using-asp-net-core-mvc-c-with-database/#comments Fri, 09 Dec 2022 17:51:03 +0000 https://labpys.com/?p=481 Authentication is mandatory for security in any type of application. One of the fundamental requirements for an application is a login page, which is why many application development processes begin …

The post How to create Login Page using Asp.net Core MVC C# With Database appeared first on Tech Insights.

]]>
Authentication is mandatory for security in any type of application. One of the fundamental requirements for an application is a login page, which is why many application development processes begin with implementing an authentication module. In this article, we’ll learn how to create login page using asp.net core MVC C# With Database.

Pre-requisite

  • NET Core SDK from here
  • Visual Studio or Visual Studio Code from here
  • SQL Server database from here

Create an ASP.NET Core MVC Project

Go to the File menu and click on New and select Project. In the new project window, select ASP.NET Core Web App(Model-View-Controller).

Document

More Related Article

Then set the project location and project name.

Install NuGet package

Once the new project is created install NuGet Packages for that right click on Solution and select Manage NuGet Packages for the solution  

  • Microsoft Entity Framework Core SQL Server
  • Microsoft Entity Framework Core Tools

Configure appsettings.json

The connection string “connectionstr” is saved in appSettings.json , you can change it as per your need

"ConnectionStrings": {
    "connectionstr": "Server=(local)\\MSSQL;Database=Login_Auth;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

Create Model

Creating a model is an essential step in developing an ASP.NET Core application. A model is a representation of the data that our application will use and manipulate. By creating a model, we define the structure of the data and its relationships with other models. This allows us to easily work with data in our application and perform CRUD (Create, Read, Update, Delete) operations on it

using System.ComponentModel.DataAnnotations;
namespace Auth_Login.Models
{
    public class UserLogin
    {
        [Key]
        public int id { get; set; }

        [Required(ErrorMessage ="Please Enter Username")]
        [Display(Name = "Please Enter Username")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "Please Enter Password")]
        [Display(Name = "Please Enter Password")]
        public string passcode { get; set; }
        public int isActive { get; set; }

    }
}

Create Dbcontext Class

DbContext is class in Entity Framework API. It is a bridge between your domain class and the database. DbContext is the class that is responsible for interacting with the database. As per Microsoft  “A DbContext instance represents a combination of the Unit Of Work and Repository pattern such that it can be used to query from a database”

using Microsoft.EntityFrameworkCore;

namespace Auth_Login.Models
{
    public class LoginDbcontext : DbContext 
    {
        public LoginDbcontext(DbContextOptions<LoginDbcontext> options)
            :base(options)
        {

        }

        public DbSet<UserLogin> UserLogin { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            builder.Entity<UserLogin>(entity=> {
                entity.HasKey(k=>k.id);
                });
        }
    }
}

Create a Repository and interface

Now create a repository folder, in this folder create two class, Create Interface  ILogin.cs file and AuthenticateLogin.cs

ILogin.cs

using System.Collections.Generic;
using System.Threading.Tasks;
using Auth_Login.Models;

namespace Auth_Login.Repository
{
    public interface ILogin
    {
        Task<IEnumerable<UserLogin>> getuser();
        Task<UserLogin> AuthenticateUser(string username,string passcode);
    }
}

AuthenticateLogin.cs

using Auth_Login.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace Auth_Login.Repository
{
    public class AuthenticateLogin : ILogin
    {
        private readonly LoginDbcontext _context;

        public AuthenticateLogin(LoginDbcontext context)
        {
            _context = context; 
        }
        public async Task<UserLogin> AuthenticateUser(string username, string passcode)
        {
           var succeeded = await _context.UserLogin.FirstOrDefaultAsync(authUser => authUser.UserName == username && authUser.passcode == passcode);
           return succeeded;
        }

        public async Task<IEnumerable<UserLogin>> getuser()
        {
             return await _context.UserLogin.ToListAsync(); 
        }
    }
}

Configure Startup Class

Update startup class with database connection and as well as inject services.
Startup.cs

using Microsoft.EntityFrameworkCore;
using Auth_Login.Models;
using Auth_Login.Repository;
public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<LoginDbcontext>(conn => conn.UseSqlServer(Configuration.GetConnectionString("connectionstr")));
            services.AddScoped<ILogin, AuthenticateLogin>();

            services.AddControllersWithViews();
        }

Migration

Then create a Database through Migration. Go to Tools>NuGet Package Manager>Package Manager Console then execute the following commands.

Add-Migration “Initial Create”

Update-Database

Create Controller

Now create IActionResult Index Method with the parameter

using Auth_Login.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Auth_Login.Repository;

namespace Auth_Login.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogin _loginUser;

        public HomeController(ILogin loguser)
        {
            _loginUser = loguser;   
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Index(string username,string passcode)
        {
            var issuccess = _loginUser.AuthenticateUser(username, passcode);


            if (issuccess.Result != null)
            {
                ViewBag.username = string.Format("Successfully logged-in", username);

                TempData["username"] = "Ahmed";
                return RedirectToAction("Index", "Layout"); 
            }
            else {
                ViewBag.username = string.Format("Login Failed ", username);
                return View();
            } 
        } 
       
    }
}

Customize View Index

Go to Views>Home>Index cshtml file update.

<html>
<head>

 <link rel="stylesheet" href="~/css/Style.css" />
</head>

<body>
<div class="login">
  <h1>Login to Web App</h1>

  <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index" >
    <p><input type="text" name="username" value="" placeholder="Username or Email" required></p>     
    <p><input type="password" name="passcode" value="" placeholder="Password" required></p>     
    <p class="remember_me">
      <label>
        <input type="checkbox" name="remember_me" id="remember_me">
        Remember me on this computer
      </label>
    </p>
    <p class="submit"><input type="submit" name="commit" value="Login"></p>
    <hr/>
    @ViewBag.username
  </form>
</div> 
</body>
</html>

Create style.css  file in  wwwroot>css>style.css

body {
    font: 13px/20px "Lucida Grande", Tahoma, Verdana, sans-serif;
    color: #404040;
    background: #0ca3d2;
}

.login {
    position: relative;
    margin: 30px auto;
    padding: 20px 20px 20px;
    margin-top : 200px;
    width: 310px;
    background: white;
    border-radius: 3px;
    -webkit-box-shadow: 0 0 200px rgba(255, 255, 255, 0.5), 0 1px 2px rgba(0, 0, 0, 0.3);
    box-shadow: 0 0 200px rgba(255, 255, 255, 0.5), 0 1px 2px rgba(0, 0, 0, 0.3);
}
 

    .login:before {
        content: '';
        position: absolute;
        top: -8px;
        right: -8px;
        bottom: -8px;
        left: -8px;
        z-index: -1;
        background: rgba(0, 0, 0, 0.08);
        border-radius: 4px;
    }

    .login h1 {
        margin: -20px -20px 21px;
        line-height: 40px;
        font-size: 15px;
        font-weight: bold;
        color: #555;
        text-align: center;
        text-shadow: 0 1px white;
        background: #f3f3f3;
        border-bottom: 1px solid #cfcfcf;
        border-radius: 3px 3px 0 0;
        background-image: -webkit-linear-gradient(top, whiteffd, #eef2f5);
        background-image: -moz-linear-gradient(top, whiteffd, #eef2f5);
        background-image: -o-linear-gradient(top, whiteffd, #eef2f5);
        background-image: linear-gradient(to bottom, whiteffd, #eef2f5);
        -webkit-box-shadow: 0 1px whitesmoke;
        box-shadow: 0 1px whitesmoke;
    }

    .login p {
        margin: 20px 0 0;
    }

        .login p:first-child {
            margin-top: 0;
        }

    .login input[type=text], .login input[type=password] {
        width: 278px;
    }

    .login p.remember_me {
        float: left;
        line-height: 31px;
    }

        .login p.remember_me label {
            font-size: 12px;
            color: #777;
            cursor: pointer;
        }

        .login p.remember_me input {
            position: relative;
            bottom: 1px;
            margin-right: 4px;
            vertical-align: middle;
        }

    .login p.submit {
        text-align: right;
    }

.login-help {
    margin: 20px 0;
    font-size: 11px;
    color: white;
    text-align: center;
    text-shadow: 0 1px #2a85a1;
}

    .login-help a {
        color: #cce7fa;
        text-decoration: none;
    }

        .login-help a:hover {
            text-decoration: underline;
        }

:-moz-placeholder {
    color: #c9c9c9 !important;
    font-size: 13px;
}

::-webkit-input-placeholder {
    color: #ccc;
    font-size: 13px;
}

input {
    font-family: 'Lucida Grande', Tahoma, Verdana, sans-serif;
    font-size: 14px;
}

    input[type=text], input[type=password] {
        margin: 5px;
        padding: 0 10px;
        width: 200px;
        height: 34px;
        color: #404040;
        background: white;
        border: 1px solid;
        border-color: #c4c4c4 #d1d1d1 #d4d4d4;
        border-radius: 2px;
        outline: 5px solid #eff4f7;
        -moz-outline-radius: 3px;
        -webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.12);
        box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.12);
    }

        input[type=text]:focus, input[type=password]:focus {
            border-color: #7dc9e2;
            outline-color: #dceefc;
            outline-offset: 0;
        }

    input[type=submit] {
        padding: 0 18px;
        height: 29px;
        font-size: 12px;
        font-weight: bold;
        color: #527881;
        text-shadow: 0 1px #e3f1f1;
        background: #cde5ef;
        border: 1px solid;
        border-color: #b4ccce #b3c0c8 #9eb9c2;
        border-radius: 16px;
        outline: 0;
        -webkit-box-sizing: content-box;
        -moz-box-sizing: content-box;
        box-sizing: content-box;
        background-image: -webkit-linear-gradient(top, #edf5f8, #cde5ef);
        background-image: -moz-linear-gradient(top, #edf5f8, #cde5ef);
        background-image: -o-linear-gradient(top, #edf5f8, #cde5ef);
        background-image: linear-gradient(to bottom, #edf5f8, #cde5ef);
        -webkit-box-shadow: inset 0 1px white, 0 1px 2px rgba(0, 0, 0, 0.15);
        box-shadow: inset 0 1px white, 0 1px 2px rgba(0, 0, 0, 0.15);
    }

        input[type=submit]:active {
            background: #cde5ef;
            border-color: #9eb9c2 #b3c0c8 #b4ccce;
            -webkit-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);
            box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);
        }

.lt-ie9 input[type=text], .lt-ie9 input[type=password] {
    line-height: 34px;
}

 Then build the project and Execute it.

The post How to create Login Page using Asp.net Core MVC C# With Database appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-create-login-page-using-asp-net-core-mvc-c-with-database/feed/ 5 481
How To Connect SQL Database using Asp.net Core https://reactconf.org/how-to-connect-sql-database-using-asp-net-core/ https://reactconf.org/how-to-connect-sql-database-using-asp-net-core/#respond Sun, 14 Jun 2020 17:36:00 +0000 https://reactconf.org/how-to-connect-sql-database-using-asp-net-core/ In this tutorial, we will see how to connect SQL database using Asp.net core. Steps Create New Project Select  ASP.net Core Web Application Select  Location Select Web Application MVC (Model …

The post How To Connect SQL Database using Asp.net Core appeared first on Tech Insights.

]]>

In this tutorial, we will see how to connect SQL database using Asp.net core.

Steps

  • Create New Project
  • Select  ASP.net Core Web Application
  • Select  Location
  • Select Web Application MVC (Model -> View -> Controller)

Add some necessary NuGet Packages

  •  Right Click On  project
  •  Select  Manage NuGet Packages
  •  Select  these packages one by one  Microsoft.EntityFrameworkCore.SqlServer, Microsoft.EntityFrameworkCore.Tools, Microsoft.Visual Studio.Web.CodeGeneration.Design
  • Then Click Install

After that get the connection string and open appsetting.json at the root directory of the application.

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
 
 
    "database": {
        "connection": "Data Source=.;Initial Catalog=schoolDB;Trusted_Connection=True;"
    },
 
    "AllowedHosts": "*"
}
 

Open startup.cs at the root directory of the application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using sample.Models;
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;
 
namespace sample
{
    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.AddControllersWithViews();
           
            services.AddDbContext<SchoolDBContext>(option => option.UseSqlServer(Configuration["database:connection"]));
            services.AddMvc().AddXmlDataContractSerializerFormatters();
        }
 
        // 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");
                
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
 
            app.UseRouting();
 
            app.UseAuthorization();
 
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

The post How To Connect SQL Database using Asp.net Core appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-connect-sql-database-using-asp-net-core/feed/ 0 2244