Core - Connection String
Core - Connection String
blog
ASP.NET Core
Connection String
Hans-Petter Halvorsen
Introduction
• The Connection string is used to connect to
the database
• In this tutorial we will use SQL Server, Visual
Studio, C#
• We will show how we use Connection String in
an ASP.NET Core Web Application
2
https://www.halvorsen.blog
SQL Server
Hans-Petter Halvorsen
SQL Server
• SQL Server is a Database System from
Microsoft. SQL Server comes in different
editions, for basic, personal use
• SQL Server Express is recommended because
it is simple to use, and it is free.
• Latest version is SQL Server 2019.
4
SQL Server Installation
• During the setup of SQL Server you should select
"Mixed Mode" (i.e., both "SQL Server
Authentication" and "Windows Authentication")
and enter the password for your sa user.
• "Windows Authentication" is the default option
during installation, so make sure to "Mixed Mode"
(i.e., both "SQL Server Authentication" and
"Windows Authentication") and enter the
password for your sa user
• Make sure to remember the sa password! 5
SQL Server Installation - Mixed Mode
• During Installation of SQL Server: Select
“Mixed Mode” (i.e., both SQL Server
Authentication and Windows Authentication)
• Make sure to remember the “sa” Password!
• “sa” is short for System Administrator
6
SQL Server Installation - Mixed Mode
7
https://www.halvorsen.blog
Authentication
Hans-Petter Halvorsen
Visual Studio
• In WinForm Desktop Applications you should
put the Connection String in the App.config
file
• While for ASP.NET Core Web Applications the
Connection String should be placed in the in
the appSettings.json file.
9
Authentication Methods
SQL offer 2 different Authentication methods:
• SQL Server Authentication
• Windows Authentication
10
SQL Server Authentication
Connection String - SQL Server Authentication
Using "SQL Server Authentication" the Connection String looks like this:
Replace <SQL Server Name> with the name of your SQL Server, typically
"<YourComputerName>\SQLEXPRESS" if you are using SQL Server Express.
UID is a SQL Server user, here you can create your own SQL Server user inside SQL Server
Management Studio or use the built-in sa user (sa=System Administrator). During the setup of SQL
Server you need to select "Mixed Mode" and enter the password for your sa user.
DATA SOURCE=LOCALHOST\\SQLEXPRESS;DATABASE=MEASUREMENTS;UID=sa;PWD=Password123;
13
Enable SQL Server Authentication in SSMS
You can also turn on "SQL Server Authentication" in SQL Server Management
Studio (SSMS) after installation of SQL Server.
15
Enable sa login
Then to enable the sa login, do the following steps:
1. In Object Explorer, expand Security, expand
Logins, right-click sa, and then click Properties.
2. On the General page, you might have to create
and confirm a password for the login.
3. On the Status page, in the Login section, click
Enabled, and then click OK.
Note! You must restart your computer afterwards (well, it
is enough to restart the “Sql service...”) in order to work. 16
Enable sa login
17
Enable sa login
18
Create Logins in SQL Server
• “sa” is a built-in Login in SQL Server
• You can also create your own SQL Server Logins
• Normally you should do that rather than using
the “sa” login
• “sa” have access to “everything” and in context of
Data Security that is unfortunate.
• In general, you should make your own Logins that
have access to only what's strictly necessary
19
Create Logins in SQL Server
In order to create a new Login, goto «Security» and
right-click on «Logins» and select «New Login…»
20
Create Logins in SQL Server
DATA SOURCE=DELLPCWORK\\SQLEXPRESS;DATABASE=MEASUREMENTS;Integrated
Security = True;
Localhost:
If you don't know the name of your PC or if you use multiple PC, it may be a good idea to
use "LOCALHOST" instead of your real computer name (assuming the application and the
database in located on the same computer).
23
https://www.halvorsen.blog
ASP.NET Core
Hans-Petter Halvorsen
Introduction
• appSettings.json is a configuration file used in
ASP.NET Core Web Applications
• It is typically used to store the Connection
String to the Database
• But it can be used to store lots of other
settings that you need to use in your
application
25
ASP.NET Core
If you have never used ASP.NET Core, I suggest the
following Videos:
• ASP.NET Core - Hello World
https://youtu.be/lcQsWYgQXK4
• ASP.NET Core – Introduction
https://youtu.be/zkOtiBcwo8s
Connection String in
appSettings.json
Hans-Petter Halvorsen
Connection String
Connection String
Connect
ASP.NET Core
SQL
Web Application Data
Server
"ConnectionStrings": {
"ConnectionString": "DATA SOURCE=xxx;UID=xxx;PWD=xxx;DATABASE=xxx"
}
29
Startup.cs
We need to add something to the “Startup.cs” file:
services.AddSingleton<IConfiguration>(Configuration);
}
We have added:
services.AddSingleton<IConfiguration>(Configuration);
30
Example
Example
SQL Server
SQL Server
• We will use SQL Server in this example as our
database.
• You should have SQL Server locally installed on
your computer
• SQL Server Express is recommended.
33
Example
Database
SQL Server - Create Database
35
Database Table
You can use SQL Server Management Studio in order to run this SQL Script
36
Initial Data
37
Example
Visual Studio
ASP.NET Core Web Application
NuGet
Make sure to install the necessary NuGet package(s). We will use the System.Data.SqlClient
39
{
"Logging": { appSettings.json
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ConnectionString": "DATA SOURCE=xxx\\SQLEXPRESS;DATABASE=xxx;UID=sa;PWD=xxx"
}
}
40
…
using Microsoft.Extensions.Configuration;
public class xxxModel : PageModel
C# Code
{
readonly IConfiguration _configuration;
}
41
ASP.NET Core Web Application
The following Application will be
demonstrated here:
We will retrieve
these data from a
SQL Server Database
42
Create Database Class
• We start by creating a Models
folder in our project using the
Solutions Explorer
• Then we create a new Class
(“Measurement.cs”)
• Then we create C# Code for
retrieving data from the
Database
43
using System.Data.SqlClient;
namespace MeasurementApp.Model
{
public class Measurement “Measurement.cs”
{
public int MeasurementId { get; set; }
public string MeasurementName { get; set; }
public string MeasurementUnit { get; set; }
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr != null)
{
while (dr.Read())
{
Measurement measurmentParameter = new Measurement();
measurmentParameter.MeasurementId = Convert.ToInt32(dr["MeasurementId"]);
measurmentParameter.MeasurementName = dr["MeasurementName"].ToString();
measurmentParameter.MeasurementUnit = dr["Unit"].ToString();
measurementParameterList.Add(measurmentParameter);
}
}
return measurementParameterList;
}
}
} 44
An ASP.NET Core Web Page consist of the
following:
• “Database.cshtml” - HTML/Razor code
• “Database.cshtml.cs” - Page Model (Code
behind C# File)
45
…
using Microsoft.Extensions.Configuration;
using AppSettingsApp.Models;
“Database.cshtml.cs”
namespace AppSettingsApp.Pages
{
public class DatabaseModel : PageModel
{
readonly IConfiguration _configuration;
void GetData()
{
Measurement measurement = new Measurement();
connectionString = _configuration.GetConnectionString("ConnectionString");
measurementParameterList = measurement.GetMeasurmentParameters(connectionString);
}
}
} 46
…
<div> “Database.cshtml”
<h1>Measurement Parameters</h1>
Below you see all the Measurement Names registered in the Database:
<table class="table">
<thead>
<tr>
<th>MeasurementId</th>
<th>Measurement Name</th>
<th>Unit</th>
</tr>
</thead>
<tbody>
@foreach (var measurement in Model.measurementParameterList)
{
<tr>
<td> @measurement.MeasurementId</td>
<td> @measurement.MeasurementName</td>
<td> @measurement.MeasurementUnit</td>
</tr>
}
</tbody>
</table>
</div>
47
Run the Application
Now we can run the Application
48
Resources
• https://docs.microsoft.com/en-
us/dotnet/framework/data/adonet/connectio
n-string-syntax
• https://docs.microsoft.com/en-
us/aspnet/core/fundamentals/configuration
49
Hans-Petter Halvorsen
University of South-Eastern Norway
www.usn.no
E-mail: [email protected]
Web: https://www.halvorsen.blog