You are on page 1of 16

Computer and Information System Coursework Assessment 202220

Course Data Driven Web Technologies

Assessment Method

Group Project

Task 1:

Choosing an appropriate template is the first step in creating an ASP.Net Core MVC
web application a business that the web application that will be designed. This could
be any business of our choice, such as an online order system, online booking system,
Systems for customer service, human resources, real estate agencies, vehicle rentals,
or any other business you might be interested in.

The following stage is to write an introduction to the project after selecting a


company. This introduction should provide a written description of the business case,
web application, and its features. You should describe the purpose of the web
application and what it is designed to accomplish. This should include a brief
overview of the functionality that the web application will include, include user
registration, login/logout, product/service catalogue listing, transaction, and security
features.

The next step is to create a site map showing the hierarchy of the pages in the web
application navigation. This will help to ensure that the website is easy to navigate
and that all necessary pages are included. The site map should be well-organized and
should clearly show the relationships between the different pages.

The security plan is another important aspect of the project. The security plan should
list all the views of the web application and show which pages require
authentication/authorization (with associated roles). This will help to ensure that the
website is secure and that only authorized users can access certain pages. You should
identify which pages require login credentials, and what level of access each type of
user should have.

After you have completed the initial planning for the project, the next step is to create
a class diagram. This should be created after implementation and will show the
relationships between the different classes in the web application. This will make it
more likely that the code will be clear and well-organized.

Since the models provide the features and organization of the data to be utilized in the
web app, they are a crucial component of the project. All model files containing the
model's properties should be coded in C# and included with the models. This will aid
in making sure the data is structured and straightforward to use.

The views are the user's first point of contact with the web app, thus it's crucial that
they be attractive and straightforward to use. Both the view's Razor code and a
snapshot of the view in preview mode (with the app running) are required. This will
aid in making the site seem nice and be simple to navigate.

Finally, the controllers are responsible for handling the user inputs and managing the
flow of data within the web application. The controllers should include the C# code of
each controller file. This will help to ensure that the website functions properly and
that all user inputs are properly validated and handled.

In summary, as a student developing an ASP.Net Core MVC web application, you


should first choose a business for the web application. Then you should create an
introduction to the project, a site map, and a security plan. After that, you should
create a class diagram, models, views, and controllers

public class Product


{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
public class ProductController : Controller
{
private readonly ProductService _productService;

public ProductController(ProductService productService)


{
_productService = productService;
}

public IActionResult Index()


{
var products = _productService.GetAllProducts();
return View(products);
}

public IActionResult Create()


{
return View();
}

[HttpPost]
public IActionResult Create(Product product)
{
if (ModelState.IsValid)
{
_productService.CreateProduct(product);
return RedirectToAction("Index");
}

return View(product);
}

Result

Task 2:

The frontend components of web application:

MVC App Setup with Default Routing Pattern:

You may utilise the "MVC" template that is included with Visual Studio when you
create a new ASP.NET Core web application project routing pattern. All the files and
directories required for an MVC app, including a basic routing pattern that binds
URLs to controller actions, will be created automatically.
HTML/CSS Template Design:

You may design your HTML/CSS template by adding HTML and CSS code to a new
layout file in your project's "Views/Shared" folder to specify the organisation and
style of your web pages. Here is an example of a simple layout file with navigation
links, a login/register link, and a content section for the material that is unique to each
page:

<!DOCTYPE html><html><head>
<title>@ViewData["Title"] - My Web App</title>
<link rel="stylesheet" href="~/css/site.css" /></head><body>
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/Products">Products</a></li>
<li><a href="/Orders">Orders</a></li>
<li><a href="/Contact">Contact Us</a></li>
</ul>
</nav>
<div>
<a href="/Account/Login">Login</a> / <a
href="/Account/Register">Register</a>
</div>
</header>
<main>
@RenderBody()
</main>
<footer>
&copy; 2023 My Web App
Tas

</footer></body></html>
then create individual views for each page of your web application and specify the
layout each view file using the file at the top "@{ Layout = "_Layout"; }" command.

Global and Local Exception Handling:

To handle global exceptions, you can use the "UseExceptionHandler" middleware the
user to a specific error page and catch any unhandled exceptions in the "Startup.cs"
file. Here is an illustration of how to accomplish it:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)


{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}

// other middleware configurations


}
To handle local exceptions, you can use try-catch blocks in your controller actions “to
catch any exceptions that occur during” the processing of a request and return an
appropriate error message to the user.

Input Validation:

You may utilise the data annotations offered by ASP.NET Core in your model classes
to check user input. When checking that a property is not empty or null, for instance,
you may use the "Required" attribute. When checking that a string property has a
minimum and/or maximum length, you can use the "StringLength" attribute. Here is
an example of how to use these qualities:

public class Product


{
public int Id { get; set; }

[Required]
[StringLength(50)]
public string Name { get; set; }

[StringLength(200)]
public string Description { get; set; }

[Range(0, 1000)]
public decimal Price { get; set; }
} then verify whether the model is valid using the "ModelState.IsValid" property in
your controller methods, and handle any validation issues appropriately.

Task 3:

To complete Task-3 of the project, will need use Entity Framework Core and
ASP.NET Core to build the web app's backend. The procedure is as follows:

Create a database schema: Depending on the conditions, design the database


schema for the application. Identify the tables, their columns, primary keys, foreign
keys, and relationships between tables. Here is an example of a schema for an online
store:

1.
 Customers (CustomerId PK, FirstName, LastName, Email, Password)
 Products (ProductId PK, Name, Description, Price)
 Orders (OrderId PK, CustomerId FK, OrderDate, TotalAmount)
 Detail of orders (OrderDetailId PK, OrderId FK, ProductId FK,
Quantity, Amount)
2.
Open Visual Studio and create a new ASP.NET Core project by selecting the MVC
template. The necessary packages for Entity Framework Core should be included.

Establishing model classes The database tables should be represented by C# classes.


To define primary keys, foreign keys, and connections between tables, use attributes.
Here is an example of a Customer model:

public class Customer


{
public int CustomerId { get; set; }

[Required]
public string FirstName { get; set; }

[Required]
public string LastName { get; set; }

[Required]
[EmailAddress]
public string Email { get; set; }

[Required]
[DataType(DataType.Password)]
public string Password { get; set; }

public ICollection<Order> Orders { get; set; }


}
1. Make a class called DbContext: Make a DbContext class that inherits from the
Entity Framework Core's DbContext class. Configure the connections between the
tables by overriding the OnModelCreating function..

public class StoreContext : DbContext


{
public StoreContext(DbContextOptions<StoreContext> options)
: base(options)
{
}

public DbSet<Customer> Customers { get; set; }


public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.Entity<Customer>()
.HasMany(c => c.Orders) hi
.WithOne(o => o.Customer)
.HasForeignKey(o => o.CustomerId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Order>()
.HasMany(o => o.OrderDetails)
.WithOne(od => od.Order)
.HasForeignKey(od => od.OrderId)
.OnDelete(DeleteBehavior.Cascade);

modelBuilder.Entity<Product>()
.HasMany(p => p.OrderDetails)
.WithOne(od => od.Product)
.HasForeignKey(od => od.ProductId)

.OnDelete(DeleteBehavior.Restrict);
}
}
Then, insert a connection string into the appsettings.json file. The connection string
specifies the server name, database name, and credentials to access the database.
j
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\
mssqllocaldb;Database=Store;Trusted_Connection=True;MultipleActiveResultSets=t
rue"}
1-Create database using migrations: Create the database using Migrations in the
Entity Framework Core. To use this command, launch the Package Management
Console.:
Add-Migration InitialCreate
The database structure is created through a migration file, which is produced by this
command. The following command must be executed to effect the migration:

Update-Database

This command creates the database and the tables.

Create repository classes: Create repository classes that implement the CRUD
operations for each entity.

Task 4:

To the web application's security measures, do the following:

Prevent common attacks: Use measures to protect against widespread threats like
CSRF (CSRF) and SQL injection. This can be done by using libraries like
AntiForgeryToken and SqlParameter in ASP.NET Core.

1.

Online registration: Create a registration form for users to create an account on the
website. Validate the inputs and save the user information to the database.

2.

Login operations: Create a login form where users can enter their credentials. Validate
the credentials against the database and set a cookie to keep the user logged in.

3.

Authentication: Use ASP.NET Core authentication middleware to authenticate users.


This will allow only logged-in users to perform business transactions and view
previous transactions.

4.
Role-based access: Create roles such as admin and user. Use role-based authorization
to restrict access to certain pages or actions based on the user's role. For example, an
admin can access the dashboard while a regular user can only view their transactions.

5.

Here's some sample code to implement these security measures:

1. To prevent CSRF attacks, add the following attribute to the form in the view:
@Html.AntiForgeryToken()

1. To prevent SQL injection, use parameterized queries like this:

var query = "SELECT * FROM Users WHERE username=@username AND


password=@password";using (var cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@password", passwo

rd);

// execute the query


}
First, create a view containing the form's required input fields and then add the
following code to the controller.:

[HttpPost]
public IActionResult Register(User model)
{
if (ModelState.IsValid)
{
// save the user information to the database
return RedirectToAction("Index", "Home");
}
return View(model);

}
1-First, create a view with the required fields for the login form, and then add the
following code to the controller:
[HttpPost]
public IActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
// validate the credentials against the database
if (validCredentials)
{
// set a cookie to keep the user logged in
return RedirectToAction("Index", "Home");
}
}
return View(model);
ni
}
1. To restrict access based on roles, add the following attribute to the action
method:

[Authorize(Roles = "admin")]public IActionResult Dashboard()

// return the view for the dashboard


}

You might also like