Asp.net webform and ADO.Net Simple Login and Registration

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="CompanyPage.Login" %>

<!DOCTYPE html>


///Login Page///

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

    <title></title>
        <style type="text/css">
         .center 
         {
    margin-left:400px; 
    margin-right:auto;
    margin-top:150px;

          }
            </style>
   </head>
  <body style="background-color:#E6E6FA">
   <form id="form1" runat="server">
        
 
   <table class="center">

        <tr>
            <td colspan="2"><h3 align="center">Login Page</h3></td>
        </tr>
         <tr>
            <td colspan="2"><asp:Label ID="lblResult" runat="server" Text=""></asp:Label></td>
        </tr>
        
         <tr>
            <td>Email Id :</td>
            <td><asp:TextBox ID="txtLogin" runat="server"></asp:TextBox></td>
                
        </tr>
         <tr>
            <td>Password :</td>
            <td><asp:TextBox ID="txtPassword" runat="server" ></asp:TextBox></td>
        </tr>
         <tr>
            <td><asp:Button ID="btnSubmit" runat="server" Text="Submit" 
                    onclick="btnSubmit_Click" /></td>
            <td><asp:Button ID="btnReset" runat="server" Text="Reset" /></td>
        </tr>
         <tr>
            <td>
                <asp:HyperLink ID="hlRegistration" runat="server" NavigateUrl="RegistrationDetail.aspx">New                  Registration</asp:HyperLink>
             </td>
            <td>
                <asp:HyperLink ID="hlForgotPassword" runat="server" 
                    NavigateUrl="~/ForgotPassword.aspx">Forgot Password</asp:HyperLink>
             </td>
        </tr>
    </table>
       </form>
        </body>
    </html>




namespace CompanyPage
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
             SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings                                       ["LoginConnectionString"].ConnectionString);
              conn.Open();
                string checkPasswordQuery = "select password from login where password='" + txtPassword.Text + "'";
                SqlCommand passComm = new SqlCommand(checkPasswordQuery, conn);
                string password = passComm.ExecuteScalar().ToString();
                if (password == txtPassword.Text)
                {
                    Session["New"] = txtPassword.Text;
                    Response.Write("Password is correct");
                    Response.Redirect("Main.aspx");
                    Server.Transfer("Main.aspx");
                }
                else
                {
                    Response.Write("Password is not correct");
                }
            }
        }

       
    }



 ///Registration Page///

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RegistrationDetail.aspx.cs" Inherits="CompanyPage.Registration_Detail" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style>
         .center {
    margin-left:400px; 
    margin-right:auto;
    margin-top:100px;
    border-width:2px;
  }
</style>
</head>
<body style="background-color:#EEE8AA">
    <form id="form1" runat="server">
     <table class ="center">
            <tr>
                <td class="style1" colspan="2">
                    <h1 style="color:blue;"><strong>Registration Details</strong></h1></td>
            </tr>
             <tr>
                <td class="style1" colspan="2">
                    </td>
            </tr>
         
            <tr>
                <td class="style2">
                    Name :</td>
                <td class="style3">
                    <asp:TextBox ID="txtname" runat="server" Text=""></asp:TextBox>
                            </td>
            </tr>
            <tr>
                <td>
                    DOB :</td>
                <td class="style4">
                    <asp:TextBox ID="txtDOB" runat="server" Text=""></asp:TextBox>
                </td>
            </tr>
           
            <tr>
                <td>
                    Gender :</td>
                <td class="style4">
                    <asp:TextBox ID="txtGender" runat="server" Text=""></asp:TextBox>
                </td>
            </tr>
                   <tr>
                <td>
                    Email ID :</td>
                <td class="style4">
                    <asp:TextBox ID="txtEmail" runat="server" Text=""></asp:TextBox>
                   
                </td>
            </tr>
            <tr>
                <td>
                    Password :</td>
                <td>
                    <asp:TextBox ID="txtPassword" runat="server" Text=""></asp:TextBox>
                                    </td>
            </tr>
         <tr>
           <td><asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
         </td>
            </tr>
        </table>
    </form>
</body>
</html>



namespace CompanyPage
{
    public partial class Registration_Detail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings                                ["RegistrationConnectionString"].ConnectionString);
                conn.Open();
                string checkuser = "select count (*) from UserData where Email='" + txtEmail.Text + "'";
                SqlCommand com = new SqlCommand(checkuser, conn);
                int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
                if (temp == 1)
                {
                    Response.Write("User Exists");
                }
                conn.Close();
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings                 ["RegistrationConnectionString"].ConnectionString);
                conn.Open();
                string insertQuery = "insert into UserData(Name,Email,Password,Gender) values                                 (@name,@email,@password,@gender)";
                SqlCommand com = new SqlCommand(insertQuery, conn);
                com.Parameters.AddWithValue("@name", txtname.Text);
                com.Parameters.AddWithValue("@email", txtEmail.Text);
                com.Parameters.AddWithValue("@password", txtPassword.Text);
                com.Parameters.AddWithValue("@gender", txtGender.Text);

                com.ExecuteNonQuery();
                Response.Write("Registration Successful");
                Response.Redirect("Employee.aspx");
                Server.Transfer("Employee.aspx");
                conn.Close();

            }
            catch (Exception ex)
            {
                Response.Write("Error:" +ex.ToString());
            }
               
             }
         }
      }

What is Program.cs in ASP.NET Core 7?

Program.cs

The Program class is the entry point for the ASP.NET Core application. It contains the application startup code.

It Configure and register the services required by the appRegister middleware components and configure the app’s request handling pipeline.

What is a host?

On startup, ASP.NET Core apps configure and launch a host. It is responsible for the startup and lifetime management of the application. The host contains the application configuration and the Kestrel server (an HTTP server) that listens for requests and sends responses.

It also sets up the logging, dependency injection, configuration, request processing pipeline, etc.

There are three different hosts capable of running an ASP.NET Core app.

  • WebApplication (or Minimal Host)
  • Generic Host
  • WebHost

WebHost was used in the initial versions of ASP.NET Core. Generic Host replaced it in ASP.NET Core 3.0. WebApplication was introduced in ASP.NET Core 6.0.

What is WebApplication (Minimal Host)

The WebApplication is the core of your ASP.NET Core application. It contains the application configuration and the HTTP server (Kestrel) that listens for requests and sends responses.

WebApplication behaves similarly to the Generic Host, exposing many of the same interfaces but requiring fewer configure callbacks.

We need to configure the WebApplication before we run it. There are two essential tasks that we need to perform before running the app.

  1. Configure and add the services for dependency injection.
  2. Configure the request pipeline, which handles all requests made to the application.

We do all these things in the program.cs

Understanding program.cs

Create a new ASP.NET core application using the ASP.NET Core Empty template. Open the program.cs and you will see the following lines.

var builder = WebApplication.CreateBuilder(args);var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();

These four lines contain all the initialization code you need to create a web server and start listening for requests.

The first thing you notice in this file is that no main method exists. The main method is the entry point of every C# program. But C#9 introduced the top-level statements feature, where you do not have to specify a main method. This feature allows us to create one top-level file containing only statements. It will not have to declare the main method or namespace. That top-level file will become the entry point of our program.

The program file creates the web application in three stages. CreateBuild, and Run

The earlier versions of ASP.NET Core created two files. One is program.cs and the other is startup.cs (known as startup class).

The program.cs is where we configured the host, and the startup class is where we used to configure the application. Since ASP.NET core 6, both processes and simplified and merged into a program.cs.

Create

The first line of the code creates an instance of the WebApplication builder.
var builder = WebApplication.CreateBuilder(args);

The CreateBuilder is a static method of WebApplication class.
It sets up a few basic features of the ASP.NET platform by default, including

  1. Sets up HTTP server (Kestrel)
  2. Logging
  3. Configuration
  4. Dependency injection container
  5. Adds the following framework-provided services

This method returns a new instance of the WebApplicationBuilder class.

We use the WebApplicationBuilder object to configure & register additional services.

WebApplicationBuilder exposes the ConfigurationManager type, which exposes all the current configuration values. We can also add new configuration sources.

It also exposes an IServiceCollection directly for adding services to the DI container.

We then call the build method.

Build

The build method of the WebApplicationBuilder class creates a new instance of the WebApplication class.

We use the instance of the WebApplication to setup the middleware’s and endpoints.

The template has set up one middleware component using the MapGet extension method.

app.MapGet(“/”, () => “Hello World!”);

Run

The run method of the WebApplication instance starts the application and listens to http requests.

Program.cs in Various Project Templates

.NET SDK Provides several project templates for creating a new ASP.NET core application. The most commonly used templates are

  • ASP.NET Core Empty
  • ASP.NET Core Web App (Razor pages)
  • ASP.NET Core Web App (Model-View-Controller)
  • ASP.NET Core Web API

ASP.NET Core Web App (Model View Controller)
The following program class is from the template ASP.NET Core Web App (Model View Controller).

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
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.MapControllerRoute(
name: “default”,
pattern: “{controller=Home}/{action=Index}/{id?}”);

app.Run();

ASP.NET Core Web API

var builder = WebApplication.CreateBuilder(args); //Create

// Add services to the container.

builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build(); //Build

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run(); //Run

Create a web API using .NET Core 7 with the Unit of Work pattern and a generic repository.

Here’s an example of how you can create a web API using .NET Core 7 with the Unit of Work pattern and a generic repository.

First, let’s define the generic repository and the unit of work:

// Generic Repository Interface
public interface IRepository<TEntity> where TEntity : class
{
    TEntity GetById(int id);
    IEnumerable<TEntity> GetAll();
    void Add(TEntity entity);
    void Update(TEntity entity);
    void Delete(TEntity entity);
}

// Unit of Work Interface
public interface IUnitOfWork : IDisposable
{
    IRepository<TEntity> GetRepository<TEntity>() where TEntity : class;
    void SaveChanges();
}

Next, we’ll implement the generic repository and the unit of work:

// Generic Repository Implementation
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
    private DbContext _context;
    private DbSet<TEntity> _dbSet;

    public Repository(DbContext context)
    {
        _context = context;
        _dbSet = context.Set<TEntity>();
    }

    public TEntity GetById(int id)
    {
        return _dbSet.Find(id);
    }

    public IEnumerable<TEntity> GetAll()
    {
        return _dbSet.ToList();
    }

    public void Add(TEntity entity)
    {
        _dbSet.Add(entity);
    }

    public void Update(TEntity entity)
    {
        _dbSet.Update(entity);
    }

    public void Delete(TEntity entity)
    {
        _dbSet.Remove(entity);
    }
}

// Unit of Work Implementation
public class UnitOfWork : IUnitOfWork
{
    private DbContext _context;
    private Dictionary<Type, object> _repositories;

    public UnitOfWork(DbContext context)
    {
        _context = context;
        _repositories = new Dictionary<Type, object>();
    }

    public IRepository<TEntity> GetRepository<TEntity>() where TEntity : class
    {
        if (!_repositories.ContainsKey(typeof(TEntity)))
        {
            var repository = new Repository<TEntity>(_context);
            _repositories.Add(typeof(TEntity), repository);
        }

        return (IRepository<TEntity>)_repositories[typeof(TEntity)];
    }

    public void SaveChanges()
    {
        _context.SaveChanges();
    }

    public void Dispose()
    {
        _context.Dispose();
    }
}

Now, let’s create a sample entity and a web API controller that uses the unit of work and repository:

// Sample Entity
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    // other properties
}

// Web API Controller
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
    private IUnitOfWork _unitOfWork;
    private IRepository<Product> _productRepository;

    public ProductsController(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
        _productRepository = _unitOfWork.GetRepository<Product>();
    }

    // GET api/products
    [HttpGet]
    public IActionResult Get()
    {
        var products = _productRepository.GetAll();
        return Ok(products);
    }

    // GET api/products/{id}
    [HttpGet("{id}")]
    public IActionResult Get(int id)
    {
        var product = _productRepository.GetById(id);
        if (product == null)
        {
            return NotFound();
        }
        return Ok(product);
    }

    // POST api/products
    [HttpPost]
    public IActionResult Post([FromBody] Product product)
    {
        if (product == null)
        {
            return BadRequest();
        }

        _productRepository.Add(product);
        _unitOfWork.SaveChanges();

        return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
    }

    // PUT api/products/{id}
    [HttpPut("{id}")]
    public IActionResult Put(int id

, [FromBody] Product product)
    {
        if (product == null || id != product.Id)
        {
            return BadRequest();
        }

        var existingProduct = _productRepository.GetById(id);
        if (existingProduct == null)
        {
            return NotFound();
        }

        existingProduct.Name = product.Name;
        // update other properties

        _productRepository.Update(existingProduct);
        _unitOfWork.SaveChanges();

        return NoContent();
    }

    // DELETE api/products/{id}
    [HttpDelete("{id}")]
    public IActionResult Delete(int id)
    {
        var product = _productRepository.GetById(id);
        if (product == null)
        {
            return NotFound();
        }

        _productRepository.Delete(product);
        _unitOfWork.SaveChanges();

        return NoContent();
    }
}

In this example, we have a Product entity, and we create a web API controller named ProductsController. The controller receives an instance of IUnitOfWork in its constructor, which provides access to the unit of work and the generic repository.

Within the controller actions, we use the repository methods to perform CRUD operations on the Product entity. The unit of work manages the transaction and ensures that changes are saved atomically.

.NET 7 with Entity Framework Database First approach

In .NET 7, the preferred approach for working with Entity Framework (EF) is using the Code First approach rather than the Database First approach. However, you can still use the Database First approach in .NET 7 if you prefer.

To use the Database First approach in .NET 7 with Entity Framework, follow these steps:

  1. Install the necessary packages: Make sure you have the required EF packages installed in your project. You will need the Microsoft.EntityFrameworkCore package and the database provider package for your specific database (e.g., Microsoft.EntityFrameworkCore.SqlServer for SQL Server). You can install these packages using NuGet.
  2. Add a reference to your database: In your project, add a reference to your existing database. This can be done by adding a connection string to the appsettings.json file or through the DbContextOptionsBuilder in your code.
  3. Scaffold the models: Use the EF command-line tools (or the Package Manager Console) to scaffold the models based on your existing database. Open the terminal and navigate to the project’s root directory, then run the following command:
dotnet ef dbcontext scaffold "YourConnectionString" Microsoft.EntityFrameworkCore.SqlServer -o Models

Replace "YourConnectionString" with the actual connection string to your database. This command will generate the entity classes based on your database schema and place them in the “Models” folder.

  1. Use the generated models: You can now use the generated entity classes in your code to query and manipulate the database. Make sure to configure your DbContext class to use the correct connection string and database provider.

Keep in mind that the Code First approach is generally recommended because it provides better control and flexibility over the database schema. However, if you have an existing database and prefer the Database First approach, the steps above should help you get started with Entity Framework in .NET 7.

Integrate a Bootstrap 5 template into a .NET 7 layout

To integrate a Bootstrap 5 template into a .NET 7 layout, you’ll need to follow these general steps:

  1. Create a new .NET 7 project: Start by creating a new .NET 7 project in your preferred development environment, such as Visual Studio.
  2. Add Bootstrap 5 files: Download the Bootstrap 5 files from the official website (https://getbootstrap.com/) or a trusted source. Extract the contents of the downloaded ZIP file.
  3. Add Bootstrap CSS and JavaScript references: In your .NET project, navigate to the appropriate location to add static files, such as the wwwroot folder. Copy the Bootstrap CSS (bootstrap.min.css) and JavaScript (bootstrap.min.js) files into the corresponding folders within your project, such as wwwroot/css and wwwroot/js.
  4. Include Bootstrap references in the layout: Open the layout file (usually named _Layout.cshtml or similar) in your project. Add the following lines within the <head> section to reference the Bootstrap CSS file:
<link rel="stylesheet" href="~/css/bootstrap.min.css" />

And add the following line before the closing </body> tag to reference the Bootstrap JavaScript file:

<script src="~/js/bootstrap.min.js"></script>
  1. Customize layout markup: Modify the layout markup to match the structure and elements of the Bootstrap 5 template you want to integrate. Replace or modify the existing HTML elements to include the necessary Bootstrap classes, components, and structure.
  2. Link CSS and JavaScript files: Ensure that any custom CSS or JavaScript files required by the Bootstrap template are properly linked within the layout file. Add them within the <head> section or at the end of the <body> section, depending on the template’s requirements.
  3. Use Bootstrap components: Utilize Bootstrap’s CSS classes and components throughout your application’s views and pages. Update your existing views or create new ones, taking advantage of Bootstrap’s responsive grid system, typography, forms, buttons, navigation, and other components.
  4. Test and refine: Run your .NET project and test the integration of the Bootstrap 5 template. Make any necessary adjustments to ensure proper rendering and functionality.

These steps provide a general guideline for integrating a Bootstrap 5 template into a .NET 7 layout. The specific implementation may vary depending on your project structure and requirements.