Bhaktapur Multiple Campus
Dudhpati-7, Bhaktapur, Nepal
Lab Assignment-5
Net Centric Computing (CSC 367)
Prepared By:
Suman Khadka
B.Sc. CSIT 076 Batch, 6th Semester
Roll no: 54 (section-B)
Submitted To:
Ramesh Kharbuja
Lecturer, Net Centric Computing
CSIT Department
Web API Application
A Web API application is a type of web application that exposes a set of HTTP endpoints or
"API endpoints" that can be consumed by clients over the internet. These API endpoints can be
used to retrieve, create, update, or delete data from a server or to perform other types of actions.
A Web API application typically follows the principles of REST (Representational State
Transfer) architecture, which is a standard for building scalable and maintainable web services.
RESTful Web API applications are built using HTTP verbs such as GET, POST, PUT, DELETE
and PATCH and support data formats such as JSON and XML.
Web API applications can be built using a variety of web technologies and frameworks such as
ASP.NET, Node.js, Django, Flask, Ruby on Rails, and many more. These frameworks provide
tools and libraries for building and consuming APIs.
Web API applications are used in a wide range of applications such as e-commerce, social
media, mobile applications, IoT (Internet of Things), and many more. By providing a standard
way to communicate with a server over the internet, Web APIs enable developers to build
scalable and secure applications that can be consumed by a wide range of clients.
ASP.NET Core Web API
ASP.NET Core Web API is a framework for building RESTful web services using the ASP.NET
Core platform. RESTful web services allow clients to interact with the server using HTTP verbs
such as GET, POST, PUT, DELETE, etc. and support data formats such as JSON and XML.
ASP.NET Core Web API provides a lightweight, scalable and cross-platform framework for
building APIs that can run on Windows, Linux, or macOS. It is a part of the ASP.NET Core
framework, which provides a set of tools and libraries for building web applications and services.
ASP.NET Core Web API is a powerful framework for building RESTful web services, and it
provides many features to help developers build robust and scalable APIs. Some of the key
features available in ASP.NET Core Web API include:
1. Cross-platform support: ASP.NET Core Web API can run on Windows, Linux, and
macOS, making it easy to build and deploy APIs on a wide range of platforms.
2. Model binding: ASP.NET Core Web API includes built-in support for model binding,
which allows developers to map incoming HTTP request data to the parameters of a
controller action.
3. Routing: ASP.NET Core Web API uses attribute routing, which allows developers to
define routes directly on the controller actions, making it easy to map incoming HTTP
requests to the appropriate controller action.
4. Serialization: ASP.NET Core Web API includes built-in support for JSON and XML
serialization, making it easy to convert data into a format that can be transmitted over the
network.
5. Dependency injection: ASP.NET Core Web API includes built-in support for
dependency injection, which makes it easy to manage dependencies and promote
testability.
6. Middleware: ASP.NET Core Web API includes built-in middleware components for
many common scenarios, such as authentication, caching, and logging.
7. Swagger/OpenAPI support: ASP.NET Core Web API includes built-in support for
Swagger/OpenAPI, which allows developers to document their API and generate client
code in a variety of programming languages.
8. Filters: ASP.NET Core Web API includes built-in support for filters, which allow
developers to add cross-cutting concerns such as authorization and validation to their
API.
9. Response caching: ASP.NET Core Web API includes built-in support for response
caching, which can improve performance by caching responses to common requests.
10. SignalR support: ASP.NET Core Web API includes built-in support for SignalR, which
allows developers to add real-time functionality to their API.
Creating Web APIs in ASP.NET Core is very straightforward, you create three things:
1. They should have [ApiController] attribute on them. This attribute tells that the controller
will server HTTP API Responses.
2. They should derive from ControllerBase class insead of Controller class.
As, ControllerBase is an abstract base class that provides basic functionality for building
web APIs, while Controller is a derived class that provides additional functionality for
building web applications that require both API and view-related functionality.
3. They should have attribute routing applied on them like
[Route(“someURL/[controller]”)].
The controller of a Web API looks like:
[Route("api/[controller]")]
[ApiController]
public class WebAPIController : ControllerBase
API controllers
API Controllers are classes in ASP.NET Core that process incoming requests from clients and
return appropriate responses. They are responsible for handling business logic and interacting
with data models to provide requested information.
API Controllers are created by creating a class that inherits from either the ControllerBase or
Controller class, and then adding methods that define the API endpoints. These methods are
typically decorated with attributes that specify the HTTP verb and routing information.
For example:
To create an API endpoint that responds to a GET request at the URL /api/WebAPI, you could
create a WebAPIController class that derives from the ControllerBase class and add a method
called GetUsers that is decorated with the [HttpGet] attribute and returns a list of user objects.
ASP.NET Core Web API can display data in various formats, including JSON, XML, and others.
By default, ASP.NET Core Web API returns data in JSON format, which is a popular format for
transmitting data between web servers and clients.
Creating a new API Controller with read/write actions.
WebAPIController.cs
using Microsoft.AspNetCore.Mvc;
namespace webMVC.Controllers
{
[Route("api/[controller]/[action]")] //to call specific action, placing action
in route
[ApiController]
public class WebAPIController : ControllerBase
{
// GET: api/<WebAPIController>
[HttpGet]
public object Getdata()
{
//return new string[] { "value1", "value2" };
return new { Name = "Suman", Address = "Kathmandu" }; //displays in json
format
}
public List<object> GetUsers()
{
List<object> list = new List<object>(); //creating new list
list.Add(new { name = "Eren", anime = "AOT" });
list.Add(new { name = "Mash", anime = "Mashle" });
list.Add(new { name = "Asta", anime = "Black Clover" });
return list; // displays json data in a list
}
}
}
Output
For Getdata() action:
For GetUsers() action:
Dependency Injection
In ASP.NET Core Web API, Dependency Injection (DI) is a built-in feature that allows for the
management of dependencies between different components of a web application. With DI,
components can be loosely coupled, making it easier to change, test and maintain the application.
ASP.NET Core Web API uses a built-in DI container to manage dependencies. The DI container
is responsible for creating instances of classes and providing those instances to classes that need
them. The container also manages the lifetime of the created instances, ensuring that instances
are created and destroyed appropriately.
To use DI in ASP.NET Core Web API, you can register your dependencies with the built-in
container using the AddTransient, AddScoped, and AddSingleton methods, depending on the
desired lifetime of the dependency. Once registered, you can then inject your dependencies into
your controller or other components through the constructor or method parameters.
In ASP.NET Core Web API, there are three service lifetimes available in the built-in
Dependency Injection container:
1. Transient: A new instance of the service is created every time it is requested from the
container. This lifetime is suitable for lightweight, stateless services that can be created
quickly and easily, and that do not hold any state between calls.
2. Scoped: A single instance of the service is created and used within a single HTTP
request. This lifetime is suitable for services that hold state that is specific to a single
request, such as a database context or a repository.
3. Singleton: A single instance of the service is created and used throughout the entire
lifetime of the application. This lifetime is suitable for services that are expensive to
create, or that need to be shared across multiple components of the application.
Let us see how the dependency injection is carried out:
First, Creating a GetDate() action in DateService class in controller folder which gives English
date as a result.
DateService.cs
namespace webMVC.Controllers
{
public class DateService : IDateService
{
public DateTime GetDate()
{
return System.DateTime.Now;
}
}
}
Calling GetDate() through student controller.
StudentController.cs
using Microsoft.AspNetCore.Mvc;
using webMVC.Models;
namespace webMVC.Controllers
{
public class StudentController : Controller
{
public IActionResult GetDate()
{
DateService dateService = new DateService();
return Content(dateService.GetDate().ToString());
}
}
}
Output:
Suppose if we have this code part in different actions of the student controller which displays
English date and now we want Nepali date format, we have to visit every actions and change
each parts of code, which is referred as tightly coupled.
So in order to decouple or perform loose couple, we use dependency injection.
For this, creating a new DateService Interface as
IDateService.cs
namespace webMVC.Controllers
{
public interface IDateService
{
DateTime GetDate();
}
}
Now creating a DateService class for Nepali date:
NDateService.cs
namespace webMVC.Controllers
{
public class NDateService:IDateService
{
public DateTime GetDate()
{
return System.DateTime.Now.AddYears(56).AddMonths(9).AddDays(18);
}
}
}
Now, to allow changes be made all at once in every section, we need to register the dependencies
with the built-in container using the Transient service lifetime in the program.cs file
Program.cs
using webMVC.Controllers;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddTransient<IDateService, NDateService>();
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();
Once, we register a service, the built-in container automatically performs constructor injection if
a service type is include as a parameter in a constructor.
StudentController.cs
using Microsoft.AspNetCore.Mvc;
using webMVC.Models;
namespace webMVC.Controllers
{
public class StudentController : Controller
{
IDateService _service;
public StudentController(IDateService dateService)
{
_service = dateService;
}
public IActionResult GetDate()
{
//DateService dateService = new DateService();
return Content(_service.GetDate().ToString());
}
}
}
Output
Working on Database
A database is a collection of organized data that is stored and accessed electronically. It is
designed to allow efficient storage, retrieval, and management of data. A database is typically
used to store large amounts of data that can be accessed and manipulated by multiple users or
applications.
A database can be organized in various ways, but it typically consists of tables that store related
data. Each table contains a set of columns that define the data that can be stored, and a set of
rows that contain the actual data. Data in a database can be queried, updated, or deleted using a
query language like SQL (Structured Query Language).
Databases are used in a wide variety of applications, from small-scale applications like personal
finance managers to large-scale enterprise applications like online shopping websites or airline
reservation systems. Databases can be hosted on a single computer or distributed across multiple
computers in a network, and can be managed by a database management system (DBMS) like
MySQL, PostgreSQL, SQL Server, or Oracle.
SQL Server
SQL Server is a relational database management system (RDBMS) developed by Microsoft. It is
a software product that is used to store and retrieve data as requested by other software
applications. SQL Server supports the SQL (Structured Query Language) standard, which is used
to manage and manipulate data stored in the database.
SQL Server can be used to manage both small and large-scale databases. It provides features like
transaction management, data indexing, data replication, security, and backup and restore
options. SQL Server is often used in enterprise-level applications and data warehouses due to its
scalability, reliability, and security features.
SQL Server can be installed on a physical server or in the cloud, and it can be accessed by other
software applications using APIs or drivers. It also provides several tools for managing the
database, such as SQL Server Management Studio and SQL Server Data Tools.
ADO.NET
ADO stands for Microsoft ActiveX Data Objects. ADO.NET is a library that is included in the
.NET Framework. It provides a set of classes that developers can use to interact with databases,
including classes for creating database connections, executing SQL commands, and retrieving
data. These classes are available in the System.Data and System.Data.SqlClient namespaces in
the .NET Framework, and can be used in any .NET application, including ASP.NET Core web
applications.
.NET applications that use ADO.NET to connect to a database, execute commands, and retrieve
data from the database are:
• ASP.NET Web Applications
• Console Applications
• Windows Applications
Important classes in ADO.NET
1. Connection class is used to establish a connection to a database. You can use it to open
and close the connection, as well as to manage transactions.
2. Command class is used to execute SQL statements or stored procedures against a
database. You can use it to set the command text, add parameters, and execute the
command. It can execute various types of commands such as SQL statements, stored
procedures, and table-valued functions. Here are some of the important commands that
can be executed by the Command class:
a. ExecuteNonQuery(): This method is used to execute a command that doesn't
return any data, such as an INSERT, UPDATE, or DELETE statement.
b. ExecuteScalar(): This method is used to execute a command that returns a single
value, such as a SELECT statement that returns a single aggregate value.
c. ExecuteReader(): This method is used to execute a command that returns a result
set, such as a SELECT statement. It returns a DataReader object that can be used
to read the rows of the result set.
d. ExecuteXmlReader(): This method is used to execute a command that returns an
XML result set, such as a SELECT statement that includes a FOR XML clause. It
returns an XmlReader object that can be used to read the XML data.
3. DataReader class provides a fast, forward-only way to read data from a database. It is
used to retrieve large amounts of data that are not suitable for in-memory caching.
4. DataAdapter class is used to fill a DataSet or DataTable with data from a database. It
provides methods for executing commands and updating the database with changes made
to the data in the DataSet or DataTable. It is used to connect DataSets to databases.
5. DataSet class is an in-memory cache of data retrieved from a database. It consists of a
collection of DataTable objects that can be related to each other. You can use the DataSet
to manipulate the data in memory, as well as to update the database with changes made to
the data. It is the heart of ADO.NET.
Connecting to a Database using ADO.NET and storing the data filled in student model form in
the database table.
First creating the model and view,
StudentsModel.cs
namespace webMVC.Models
{
public class StudentsModel
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public string Address { get; set; }
public string Course { get; set; }
}
}
In student controller, we create the templates for model and view :
using Microsoft.AspNetCore.Mvc;
using System.Data.SqlClient;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class StudentController : Controller
{
public IActionResult Students()
{
List<StudentsModel> students = new List<StudentsModel>();
return View(students); //creates Students.cshtml
}
[HttpGet]
public IActionResult AddStudent()
{
return View(); //creates AddStudent.cshtml
}
}
}
Students.cshtml : (created with list template)
@model IEnumerable<webMVC.Models.StudentsModel>
@{
ViewData["Title"] = "Students";
}
<h1>Students</h1>
<p>
<a asp-action="AddStudent">Add Student</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.StudentId)
</th>
<th>
@Html.DisplayNameFor(model => model.StudentName)
</th>
<th>
@Html.DisplayNameFor(model => model.Address)
</th>
<th>
@Html.DisplayNameFor(model => model.Course)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.StudentId)
</td>
<td>
@Html.DisplayFor(modelItem => item.StudentName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.Course)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey
*/ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */
})
</td>
</tr>
}
</tbody>
</table>
AddStudent.cshtml: (Created with create template)
@model webMVC.Models.StudentsModel
@{
ViewData["Title"] = "AddStudent";
}
<h1>AddStudent</h1>
<h4>StudentsModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="AddToDatabase"> @*Redirects the data to the database*@
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="StudentId" class="control-label"></label>
<input asp-for="StudentId" class="form-control" />
<span asp-validation-for="StudentId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="StudentName" class="control-label"></label>
<input asp-for="StudentName" class="form-control" />
<span asp-validation-for="StudentName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Address" class="control-label"></label>
<input asp-for="Address" class="form-control" />
<span asp-validation-for="Address" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Course" class="control-label"></label>
<input asp-for="Course" class="form-control" />
<span asp-validation-for="Course" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Students">Back to List</a>
</div>
Creating ‘bmc’ database through SQL Server Object Explorer in visual studio:
Inside bmc database, we create a new table named ‘Students’ using CREATE TABLE statement.
dbo.Students.sql (table saved as)
CREATE TABLE [dbo].[Students]
(
[Id] INT NOT NULL PRIMARY KEY,
[StudentName] varchar(50) not NULL,
[Address] varchar (50),
[Course] varchar(50)
)
Now, we after writing the sql statements, we update the table.
After this, we work on the StudentController file to connect the database as:
StudentController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Data.SqlClient;
using webMVC.Models;
namespace webMVC.Controllers
{
public class StudentController : Controller
{
public IActionResult Students()
{
List<StudentsModel> students = new List<StudentsModel>();
return View(students);
}
[HttpGet]
public IActionResult AddStudent()
{
return View();
}
//making action to save to db
//form always uses POST
[HttpPost]
public IActionResult AddToDatabase(StudentsModel students)
{
//1. connection string
string connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial
Catalog=BMCdb;Integrated Security=True;Connect Timeout=30;Encrypt=False;";
SqlConnection conn = new SqlConnection (connectionString); //2.
connection
conn.Open(); // 3.open connection
string command = "Insert into Students (Id, StudentName, Address,
Course) Values (1, 'Suman', 'Kathmandu', 'CSIT'), (2, 'John', 'New York',
'Engineering'), (3, 'Mary', 'London', 'Business')";
SqlCommand cmd = new SqlCommand (command, conn); //4. sql command- this
turns string above to sql command
cmd.ExecuteNonQuery (); //5. because its not a query now
conn.Close(); //6.
return View();
}
}
}
We run the program.
First Students interface is shown.
After clicking Add Student:
Filling up the data,
After clicking create, the database code is executed and the data is stored in the table
‘dbo.Students’.