Complete Signup-Login System Using Dependency

Introduction

There are various methods available to create a login system but here I'm introducing a way to design complete signup and login system using dependencies in asp.net core with SQL database.

What is a dependency?

The term dependency means to depend on anyone else which means if an object is dependent on other objects that are called a dependency. Dependency is a relationship between a component or class that can be thought of as a uses relationship generally the parameterized constructor that provides an object for a needed class. If you have more than one class that class is dependent on each other that is dependency. The dependency is injected into a parameterized constructor.

Step 1

Create a database from MSSQL. To follow the SQL q

create database dependencylogin
use dependencylogin;
create table users(id int primary key, Name varchar(50), Email varchar(50), Password varchar(50));
select * from users

Step 2

Create a table from the database and id is the primary key as well as identity with autoincrement.

Step 3

Open visual studio 2022 and click create a new project.

Step 4

Select ASP.Net core web App project and click on the Next button.

Step 5

Write the name of the project and click on the Next button.

Step 6

Click on the Create button for creating a project.

Step 7

Now my project is ready for use.

Step 8

Here create a new folder on solution explorer. Right-click on the project name in solution explorer and select Add option then select the new folder option then write the name of the folder.

Write the folder name as Models.

Step 9

In the Models, folder right-click to choose to Add option and move to the class option, create a class with the class name as a connection.

Step 10

To make a property connection string name then create a constructor and pass the connection string.

namespace signuploginproject.Models
{
    public class connection
    {
        public string ConnectionString { get; set; }
        public connection()
        {
            this.ConnectionString = @"Data Source=LAPTOP-2L6RE54T;Initial Catalog=dependencylogin;Integrated Security=True";

        }
    }
}

Step 11

To install the System.Data.SqlClient package from NuGet Package Manager. To right-click on the dependencies folder on solution explorer and choose the NuGet Package Manager. In a NuGet click Browse and search to System.Data.SqlClient and click to Install.

Step 12

Similar to creating another class on the Models folder the class name is DAL. Make a connection class object and pass it under the constructor. Here constructor provides the object to a connection class that's why injecting the dependency. In this class, we create two different types of functions.

  1. GetValue - The GetValue function is working for login time and in the GetValue function to create the SqlConnection object it uses the System.Data.SqlClient library then we create the SqlCommand object, then maintain the SqlConnection and call the SQL command then we open the SqlConnetion and store the resultant in a res variable then close the connection and return the results.
  2. SetValue - The SetValue function is working for signup time and it stores the user's values into a SQL database. Similarly in this function, we make the SqlConnection object then we create the SqlCommand object, then maintain the SqlConnection and call the SQL command then we open the SqlConnetion and Call the ExecteNonQuery() method and close the connection.
using System.Data.SqlClient;
namespace signuploginproject.Models
{
    public class DAL
    {
        connection conn;
        public DAL(connection conn)
        {
            this.conn = conn;
               
        }
        public string GetValue(string query)
        {
            SqlConnection sqlconnection = new SqlConnection(conn.ConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = sqlconnection;
            cmd.CommandText = query;
            sqlconnection.Open();
            var res = cmd.ExecuteScalar();
            sqlconnection.Close();
            return res.ToString();
        }
        public void SetValue(string query)
        {
            SqlConnection sqlconnection = new SqlConnection(conn.ConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = sqlconnection;
            cmd.CommandText = query;
            sqlconnection.Open();
            cmd.ExecuteNonQuery();
            sqlconnection.Close();

        }
    }
}

Step 13

Similarly, create one more class in the Models folder. The class name is Logics. Make a DAL class object and pass it under the Logic constructor. Here constructor provides the object to a DAL class and also injects the dependency. In this class, we create two different types of functions.

In the Login function we pass email and password as parameters in the function and create a query variable for storing the resultant SQL query, call the DAL class GetValue function and make the return value to the password.

In the Submitdata function, we pass the name, email, and password as a parameter in the function and create a query variable for storing the SQL query resultant, call the DAL class Submitdata function, and return the message.

namespace signuploginproject.Models
{
    public class Logics
    {
        DAL DL;
        public Logics(DAL dl)
        {
            DL = dl;
        }
        public bool Login(string email, string password)
        {
            string query = $"select password from users where email='{email}'";
            var res = DL.GetValue(query);
            return res == password;
        }
        public string submitdata(string name, string email, string password)
        {
            string query = $"insert into users (name,email,password) values ('{name}','{email}','{password}')";
            DL.SetValue(query);
            return "Data submitted";

        }
    }
}

Step 14

Design an Index page for the Login page using HTML and CSS

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}
<div class="container" style="width:30%">
  <center>
    <h2>Login</h2>
  </center>
  <form method="post">
    <div class="mb-3">
      <label class="form-label">Email</label>
      <input type="email" name="email" class="form-control">
    </div>
    <div class="mb-3">
      <label class="form-label">Password</label>
      <input type="password" name="password" class="form-control">
    </div>
    <div class="btn-group" style="margin-top:15px;">
      <button type="submit" class="btn btn-success">Submit</button>
    </div>
  </form>
  <center>
    <p>if you don't have an account to click <a href="/Signup"> Signup</a>
    </p>
  </center>
</div>

Login page 

Step 15

Write a code on the Index model page. In the index model page constructor, we pass the Logics class with the object for injecting dependency, then creates the IActionResult OnPost function, and pass the email and password as a parameter. In the IActionResult OnPost function, call the Login function from Logic Class and all results will be stored in the res bool type variable then we check whether the result is true or not. If it is true redirect the dashboard page otherwise it returns the error page. The error page is already available on solution explorer.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using signuploginproject.Models;
namespace signuploginproject.Pages {
    public class IndexModel: PageModel {
        private readonly ILogger < IndexModel > _logger;
        public IndexModel(ILogger < IndexModel > logger, Logics logic) {
            _logger = logger;
            this.logi = logic;
        }
        public void OnGet() {}
        Logics logi;
        public IActionResult OnPost(string email, string password) {
            bool res = logi.Login(email, password);
            if (res == true) {
                return Redirect("/dashboard");
            } else {
                return Redirect("/error");
            }
        }
    }
}

Step 16

Create a new razor page for signup and design a signup form using HTML and CSS.

@page
@model signuploginproject.Pages.signupModel
@{
}
<div class="container" style="width:30%">
  <center>
    <h2>Signup</h2>
  </center>
  <form method="post">
    <div class="mb-3">
      <label class="form-label">Name</label>
      <input type="text" name="name" class="form-control">
    </div>
    <div class="mb-3">
      <label class="form-label">Email</label>
      <input type="email" name="email" class="form-control">
    </div>
    <div class="mb-3">
      <label class="form-label">Password</label>
      <input type="password" name="password" class="form-control">
    </div>
    <div class="btn-group" style="margin-top:15px;">
      <button type="submit" class="btn btn-success">Submit</button>
    </div>
  </form>
  <center>
    <p>Have an account to click <a href="/Index"> Login</a>
    </p>
  </center>
</div>

Signup Page

Step 17

Write a code on the Signup model page. In the signup model page constructor, we pass the Logics class with the object for injecting dependency, then creates the IActionResult OnPost function, and pass the name, email, and password as a parameter. In the IActionResult OnPost function, call the Submitdata function from Logic Class and all results will be stored in the rees variable and then return a redirect to the index page.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using signuploginproject.Models;
namespace signuploginproject.Pages {
    public class signupModel: PageModel {
        public signupModel(Logics logic) {
            this.logi = logic;
        }
        public void OnGet() {}
        Logics logi;
        public IActionResult OnPost(string name, string email, string password) {
            var rees = logi.submitdata(name, email, password);
            return Redirect("/index");
        }
    }
}

Step 18

Create a new razor page for the dashboard page using HTML and CSS.

@page
@model signuploginproject.Pages.dashboardModel
@{
}
<h1>Dashboard</h1>

Dashboard Page

Step 19

Add the services to the program.cs file for providing a class object when needed. To click on the program.cs file and write the code on container services.

To build and execute the project.

Final Output

Conclusion

A Dependency Injection helps in reducing class coupling and Increases the reusability of the code.

A Dependency Injection to improve the code maintainability.

A Dependency Injection makes it feasible to conduct unit testing.


Similar Articles