Merge pull request #339 from SebastianPfliegel/csharp_sles

Add C# SLES tutorials
This commit is contained in:
Umachandar Jayachandran
2019-01-29 14:47:22 -08:00
committed by GitHub
10 changed files with 431 additions and 0 deletions
+77
View File
@@ -0,0 +1,77 @@
# Get started with SQL Server and C# on SLES
Get started quickly with developing applications in C# on SLES with SQL Server
### Contents
[About this sample](#about-this-sample)<br/>
[Before you begin](#before-you-begin)<br/>
[Run this sample](#run-this-sample)<br/>
[Sample details](#sample-details)<br/>
[Disclaimers](#disclaimers)<br/>
[Related links](#related-links)<br/>
<a name=about-this-sample></a>
## About this sample
- **Applies to:** SQL Server 2016 (or higher)
- **Workload:**
- CRUD with .NET Core
- CRUD with Entity Framework Core
- Performance improvements with Columnstore
- **Programming Language:** C#
- **Authors:** ajlam
<a name=before-you-begin></a>
## Before you begin
To run this sample, you need the following prerequisites.
**Software prerequisites:**
1. SQL Server 2016 (or higher)
2. .NET Core 2.0
3. Entity Framework Core 2.0
4. A text editor
## Run this sample
1. Select the specific tutorial you want to run through.
2. From your favorite text editor, open the Program.cs file corresponding to the tutorial you wish to run through. Update the connection string username and password with your own.
3. From your terminal, change directories to the tutorial folder (ex. SqlServerSample) you're running through. Restore the .NET Core dependencies by performing the following command:
```
dotnet restore
```
4. Run the program by performing the following command:
```
dotnet run
```
5. Repeat the above steps for any of the other tutorials provided.
<a name=sample-details></a>
## Sample details
Please visit the [C# on SLES tutorial](https://www.microsoft.com/en-us/sql-server/developer-get-started/csharp/sles/) to run through the sample in full with more detail.
<a name=disclaimers></a>
## Disclaimers
The scripts and this guide are provided as samples. They are not part of any Azure service and are not covered by any SLA or other Azure-related agreements. They are provided as-is with no warranties express or implied. Microsoft takes no responsibility for the use of the scripts or the accuracy of this document. Familiarize yourself with the scripts before using them.
<a name=related-links></a>
## Related Links
For more information, see these articles:
* To see more getting started tutorials, visit our [tutorials page](https://www.microsoft.com/en-us/sql-server/developer-get-started/)
@@ -0,0 +1,110 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlServerColumnstoreSample
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("*** SQL Server Columnstore demo ***");
// Build connection string
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "localhost"; // update me
builder.UserID = "sa"; // update me
builder.Password = "your_password"; // update me
builder.InitialCatalog = "master";
// Connect to SQL
Console.Write("Connecting to SQL Server ... ");
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
connection.Open();
Console.WriteLine("Done.");
// Create a sample database
Console.Write("Dropping and creating database 'SampleDB' ... ");
String sql = "DROP DATABASE IF EXISTS [SampleDB]; CREATE DATABASE [SampleDB]";
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.ExecuteNonQuery();
Console.WriteLine("Done.");
}
// Insert 5 million rows into the table 'Table_with_5M_rows'
Console.Write("Inserting 5 million rows into table 'Table_with_5M_rows'. This takes ~1 minute, please wait ... ");
StringBuilder sb = new StringBuilder();
sb.Append("USE SampleDB; ");
sb.Append("WITH a AS (SELECT * FROM (VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) AS a(a))");
sb.Append("SELECT TOP(5000000)");
sb.Append("ROW_NUMBER() OVER (ORDER BY a.a) AS OrderItemId ");
sb.Append(",a.a + b.a + c.a + d.a + e.a + f.a + g.a + h.a AS OrderId ");
sb.Append(",a.a * 10 AS Price ");
sb.Append(",CONCAT(a.a, N' ', b.a, N' ', c.a, N' ', d.a, N' ', e.a, N' ', f.a, N' ', g.a, N' ', h.a) AS ProductName ");
sb.Append("INTO Table_with_5M_rows ");
sb.Append("FROM a, a AS b, a AS c, a AS d, a AS e, a AS f, a AS g, a AS h;");
sql = sb.ToString();
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.ExecuteNonQuery();
Console.WriteLine("Done.");
}
// Execute SQL query without columnstore index
double elapsedTimeWithoutIndex = SumPrice(connection);
Console.WriteLine("Query time WITHOUT columnstore index: " + elapsedTimeWithoutIndex + "ms");
// Add a Columnstore Index
Console.Write("Adding a columnstore to table 'Table_with_5M_rows' ... ");
sql = "CREATE CLUSTERED COLUMNSTORE INDEX columnstoreindex ON Table_with_5M_rows;";
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.ExecuteNonQuery();
Console.WriteLine("Done.");
}
// Execute the same SQL query again after columnstore index was added
double elapsedTimeWithIndex = SumPrice(connection);
Console.WriteLine("Query time WITH columnstore index: " + elapsedTimeWithIndex + "ms");
// Calculate performance gain from adding columnstore index
Console.WriteLine("Performance improvement with columnstore index: "
+ Math.Round(elapsedTimeWithoutIndex / elapsedTimeWithIndex) + "x!");
}
Console.WriteLine("All done. Press any key to finish...");
Console.ReadKey(true);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static double SumPrice(SqlConnection connection)
{
String sql = "SELECT SUM(Price) FROM Table_with_5M_rows";
long startTicks = DateTime.Now.Ticks;
using (SqlCommand command = new SqlCommand(sql, connection))
{
try
{
var sum = command.ExecuteScalar();
TimeSpan elapsed = TimeSpan.FromTicks(DateTime.Now.Ticks) - TimeSpan.FromTicks(startTicks);
return elapsed.TotalMilliseconds;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
return 0;
}
}
}
@@ -0,0 +1,21 @@
{
"version": "1.0.0-*",
"buildOptions": {
"debugType": "portable",
"emitEntryPoint": true
},
"dependencies": {
"System.Data.SqlClient": "4.1.0"
},
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
}
},
"imports": "dnxcore50"
}
}
}
@@ -0,0 +1,20 @@
using Microsoft.EntityFrameworkCore;
namespace SqlServerEFSample
{
public class EFSampleContext : DbContext
{
string _connectionString;
public EFSampleContext(string connectionString)
{
this._connectionString = connectionString;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(this._connectionString);
}
public DbSet<User> Users { get; set; }
public DbSet<Task> Tasks { get; set; }
}
}
@@ -0,0 +1,101 @@
using System;
using System.Linq;
using System.Data.SqlClient;
using System.Collections.Generic;
namespace SqlServerEFSample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("** C# CRUD sample with Entity Framework Core and SQL Server **\n");
try
{
// Build connection string
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "localhost"; // update me
builder.UserID = "sa"; // update me
builder.Password = "your_password"; // update me
builder.InitialCatalog = "EFSampleDB";
using (EFSampleContext context = new EFSampleContext(builder.ConnectionString))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
Console.WriteLine("Created database schema from C# classes.");
// Create demo: Create a User instance and save it to the database
User newUser = new User { FirstName = "Anna", LastName = "Shrestinian" };
context.Users.Add(newUser);
context.SaveChanges();
Console.WriteLine("\nCreated User: " + newUser.ToString());
// Create demo: Create a Task instance and save it to the database
Task newTask = new Task() { Title = "Ship Helsinki", IsComplete = false, DueDate = DateTime.ParseExact("04-01-2017", "MM-dd-yyyy", CultureInfo.InvariantCulture) };
context.Tasks.Add(newTask);
context.SaveChanges();
Console.WriteLine("\nCreated Task: " + newTask.ToString());
// Association demo: Assign task to user
newTask.AssignedTo = newUser;
context.SaveChanges();
Console.WriteLine("\nAssigned Task: '" + newTask.Title + "' to user '" + newUser.GetFullName() + "'");
// Read demo: find incomplete tasks assigned to user 'Anna'
Console.WriteLine("\nIncomplete tasks assigned to 'Anna':");
var query = from t in context.Tasks
where t.IsComplete == false &&
t.AssignedTo.FirstName.Equals("Anna")
select t;
foreach(var t in query)
{
Console.WriteLine(t.ToString());
}
// Update demo: change the 'dueDate' of a task
Task taskToUpdate = context.Tasks.First(); // get the first task
Console.WriteLine("\nUpdating task: " + taskToUpdate.ToString());
taskToUpdate.DueDate = DateTime.ParseExact("06-30-2016", "MM-dd-yyyy", CultureInfo.InvariantCulture);
context.SaveChanges();
Console.WriteLine("dueDate changed: " + taskToUpdate.ToString());
// Delete demo: delete all tasks with a dueDate in 2016
Console.WriteLine("\nDeleting all tasks with a dueDate in 2016");
DateTime dueDate2016 = DateTime.ParseExact("12-31-2016", "MM-dd-yyyy", CultureInfo.InvariantCulture);
query = from t in context.Tasks
where t.DueDate < dueDate2016
select t;
foreach(Task t in query)
{
Console.WriteLine("Deleting task: " + t.ToString());
context.Tasks.Remove(t);
}
context.SaveChanges();
// Show tasks after the 'Delete' operation - there should be 0 tasks
Console.WriteLine("\nTasks after delete:");
List<Task> tasksAfterDelete = (from t in context.Tasks select t).ToList<Task>();
if (tasksAfterDelete.Count == 0)
{
Console.WriteLine("[None]");
}
else
{
foreach (Task t in query)
{
Console.WriteLine(t.ToString());
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("All done. Press any key to finish...");
Console.ReadKey(true);
}
}
}
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Data.SqlClient" Version="4.4.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
</ItemGroup>
</Project>
@@ -0,0 +1,18 @@
using System;
namespace SqlServerEFSample
{
public class Task
{
public int TaskId { get; set; }
public string Title { get; set; }
public DateTime DueDate { get; set; }
public bool IsComplete { get; set; }
public virtual User AssignedTo { get; set; }
public override string ToString()
{
return "Task [id=" + this.TaskId + ", title=" + this.Title + ", dueDate=" + this.DueDate.ToString() + ", IsComplete=" + this.IsComplete + "]";
}
}
}
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
namespace SqlServerEFSample
{
public class User
{
public int UserId { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public virtual IList<Task> Tasks { get; set; }
public String GetFullName()
{
return this.FirstName + " " + this.LastName;
}
public override string ToString()
{
return "User [id=" + this.UserId + ", name=" + this.GetFullName() + "]";
}
}
}
@@ -0,0 +1,37 @@
using System;
using System.Text;
using System.Data.SqlClient;
namespace SqlServerSample
{
class Program
{
static void Main(string[] args)
{
try
{
// Build connection string
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "localhost"; // update me
builder.UserID = "sa"; // update me
builder.Password = "your_password"; // update me
builder.InitialCatalog = "master";
// Connect to SQL
Console.Write("Connecting to SQL Server ... ");
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
connection.Open();
Console.WriteLine("Done.");
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("All done. Press any key to finish...");
Console.ReadKey(true);
}
}
}
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Data.SqlClient" Version="4.4.0" />
</ItemGroup>
</Project>