adding azure sql samples

Adding the samples content from extending the getting started website for azure specific workflows
This commit is contained in:
akatesmith
2020-09-15 12:20:56 -07:00
parent 38d2067b56
commit 50468c14d3
79 changed files with 5434 additions and 0 deletions
@@ -0,0 +1,136 @@
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.KeyVault.Models;
using Microsoft.Azure.Services.AppAuthentication;
using System;
using System.Data.SqlClient;
using System.Text;
using System.Threading.Tasks;
namespace AzureSqlColumnstoreSample
{
class Program
{
static void Main(string[] args)
{
System.Threading.Tasks.Task task = Program.DoWork(args);
// Becuase this program takes user input, have a long wait.
var result = task.Wait(TimeSpan.FromMinutes(30));
}
static async System.Threading.Tasks.Task DoWork(string[] args)
{
Console.WriteLine("*** Azure SQL Columnstore demo ***");
// Build connection string
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "your_server.database.windows.net"; // update me
builder.UserID = "your_user"; // update me
builder.Password = await GetPasswordFromKeyVault();
builder.InitialCatalog = "your_database";
// Connect to Azure SQL
Console.Write("Connecting to Azure SQL ... ");
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
string sql;
try
{
connection.Open();
string dropTable = "Drop table if exists Table_with_3M_rows";
using (SqlCommand command = new SqlCommand(dropTable, connection))
{
command.ExecuteNonQuery();
Console.WriteLine("Table cleaned up.");
}
// Insert 5 million rows into the table 'Table_with_3M_rows'
Console.Write("Inserting 3 million rows into table 'Table_with_3M_rows'. This takes ~1 minute, please wait ... ");
StringBuilder sb = new StringBuilder();
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(3000000)");
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_3M_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_3M_rows' ... ");
sql = "CREATE CLUSTERED COLUMNSTORE INDEX columnstoreindex ON Table_with_3M_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!");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
string dropTable = "Drop table if exists Table_with_3M_rows";
using (SqlCommand command = new SqlCommand(dropTable, connection))
{
command.ExecuteNonQuery();
Console.WriteLine("Table cleaned up.");
}
}
}
Console.WriteLine("All done. Press any key to finish...");
Console.ReadKey(true);
}
private static async Task<string> GetPasswordFromKeyVault()
{
Console.WriteLine("Trying to get Password from Key Vault. Press a key to continue...");
Console.ReadKey(true);
/* The next four lines of code show you how to use AppAuthentication library to fetch secrets from your key vault */
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
SecretBundle secret = await keyVaultClient.GetSecretAsync("https://your_keyvault_name.vault.azure.net/secrets/AppSecret"); // update me
return secret.Value;
}
public static double SumPrice(SqlConnection connection)
{
String sql = "SELECT SUM(Price) FROM Table_with_3M_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,22 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.SqlServer;
namespace AzureSqlEFSample
{
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,113 @@
using System;
using System.Data.SqlClient;
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.KeyVault.Models;
using Microsoft.Azure.Services.AppAuthentication;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
namespace AzureSqlEFSample
{
class Program
{
static void Main(string[] args)
{
System.Threading.Tasks.Task task = Program.DoWork(args);
// Becuase this program takes user input, have a long wait.
var result = task.Wait(TimeSpan.FromMinutes(30));
}
static async System.Threading.Tasks.Task DoWork(string[] args)
{
Console.WriteLine("** C# CRUD sample with Entity Framework and Azure SQL DB**\n");
// Build connection string
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "your_server_name.database.windows.net"; // update me
builder.UserID = "your_user"; // update me
builder.Password = await GetPasswordFromKeyVault(); // taken from Key Vault
builder.InitialCatalog = "your_db_name"; // Update me
using (EFSampleContext context = new EFSampleContext(builder.ConnectionString))
{
try
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
Console.WriteLine("Created database schema from C# classes.");
// Create demo: Create a Task instance and save it to the database
Task newTask = new Task() { Title = "Ship Helsinki", IsComplete = false, DueDate = DateTime.Parse("04-01-2017") };
context.Tasks.Add(newTask);
context.SaveChanges();
Console.WriteLine("\nCreated Task: " + newTask.ToString());
// Association demo: Assign task to user
// 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.Parse("06-30-2016");
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.Parse("12-31-2016");
List<Task> queryResults = context.Tasks.Where(t => t.DueDate < dueDate2016).ToList();
foreach (Task t in queryResults)
{
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 (SqlException e)
{
Console.WriteLine(e.ToString());
}
}
Console.WriteLine("All done. Press any key to finish...");
Console.ReadKey(true);
}
private static async Task<string> GetPasswordFromKeyVault()
{
Console.WriteLine("Trying to get Password from Key Vault. Press a key to continue...");
Console.ReadKey(true);
/* The next four lines of code show you how to use AppAuthentication library to fetch secrets from your key vault */
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
SecretBundle secret = await keyVaultClient.GetSecretAsync("https://your_keyvault_name.vault.azure.net/secrets/AppSecret"); // update me
return secret.Value;
}
}
}
@@ -0,0 +1,18 @@
using System;
namespace AzureSqlEFSample
{
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 AzureSqlEFSample
{
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,135 @@
using System;
using System.Text;
using System.Data.SqlClient;
namespace AzureSqlSample
{
class Program
{
static void Main(string[] args)
{
string sql;
// Build connection string
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "your_server_name.database.windows.net"; // update me
builder.UserID = "your_user"; // update me
builder.Password = "your_password"; // update me
builder.InitialCatalog = "your_database_name"; // update me
// Connect to Azure SQL
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
try
{
Console.WriteLine("Connect to Azure SQL and demo Create, Read, Update and Delete operations.");
// Connect to Azure SQL
Console.Write("Connecting to Azure SQL ... ");
connection.Open();
Console.WriteLine("Done.");
using (SqlCommand command = new SqlCommand("DROP TABLE IF EXISTS Employees", connection))
{
command.ExecuteNonQuery();
}
// Create a Table and insert some sample data
Console.Write("Creating sample table with data, press any key to continue...");
Console.ReadKey(true);
StringBuilder sb = new StringBuilder();
sb.Append("CREATE TABLE Employees ( ");
sb.Append(" Id INT IDENTITY(1,1) NOT NULL PRIMARY KEY, ");
sb.Append(" Name NVARCHAR(50), ");
sb.Append(" Location NVARCHAR(50) ");
sb.Append("); ");
sb.Append("INSERT INTO Employees (Name, Location) VALUES ");
sb.Append("(N'Jared', N'Australia'), ");
sb.Append("(N'Nikita', N'India'), ");
sb.Append("(N'Tom', N'Germany'); ");
sql = sb.ToString();
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.ExecuteNonQuery();
Console.WriteLine("Done.");
}
// INSERT demo
Console.Write("Inserting a new row into table, press any key to continue...");
Console.ReadKey(true);
sb.Clear();
sb.Append("INSERT Employees (Name, Location) ");
sb.Append("VALUES (@name, @location);");
sql = sb.ToString();
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@name", "Jake");
command.Parameters.AddWithValue("@location", "United States");
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine(rowsAffected + " row(s) inserted");
}
// UPDATE demo
String userToUpdate = "Nikita";
Console.Write("Updating 'Location' for user '" + userToUpdate + "', press any key to continue...");
Console.ReadKey(true);
sb.Clear();
sb.Append("UPDATE Employees SET Location = N'United States' WHERE Name = @name");
sql = sb.ToString();
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@name", userToUpdate);
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine(rowsAffected + " row(s) updated");
}
// DELETE demo
String userToDelete = "Jared";
Console.Write("Deleting user '" + userToDelete + "', press any key to continue...");
Console.ReadKey(true);
sb.Clear();
sb.Append("DELETE FROM Employees WHERE Name = @name;");
sql = sb.ToString();
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@name", userToDelete);
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine(rowsAffected + " row(s) deleted");
}
// READ demo
Console.WriteLine("Reading data from table, press any key to continue...");
Console.ReadKey(true);
sql = "SELECT Id, Name, Location FROM Employees;";
using (SqlCommand command = new SqlCommand(sql, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1} {2}", reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
}
}
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
finally
{
Console.WriteLine("Cleaning up table.");
using (SqlCommand command = new SqlCommand("DROP TABLE IF EXISTS Employees", connection))
{
command.ExecuteNonQuery();
}
}
}
Console.WriteLine("All done. Press any key to finish...");
Console.ReadKey(true);
}
}
}
@@ -0,0 +1,160 @@
using System;
using System.Text;
using System.Data.SqlClient;
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.KeyVault.Models;
using Microsoft.Azure.Services.AppAuthentication;
using System.Threading.Tasks;
namespace AzureSQLSample
{
class Program
{
static void Main(string[] args)
{
Task task = Program.DoWork(args);
// Becuase this program takes user input, have a long wait.
var result = task.Wait(TimeSpan.FromMinutes(30));
}
static async Task DoWork(string[] args)
{
string sql;
// Build connection string
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "your_server_name.database.windows.net"; // update me
builder.UserID = "your_user_id"; // update me
builder.Password = await GetPasswordFromKeyVault(); // taken from Key Vault
builder.InitialCatalog = "your_database"; // Update me
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
try
{
Console.WriteLine("Connect to Azure SQL and demo Create, Read, Update and Delete operations.");
// Connect to Azure SQL
Console.Write("Connecting to Azure SQL ... ");
connection.Open();
Console.WriteLine("Done.");
string dropTableIfExists = @"DROP TABLE IF EXISTS Employees";
using (SqlCommand command = new SqlCommand(dropTableIfExists, connection))
{
command.ExecuteNonQuery();
Console.WriteLine("Done.");
}
// Create a Table and insert some sample data
Console.Write("Creating sample table with data, press any key to continue...");
Console.ReadKey(true);
StringBuilder sb = new StringBuilder();
sb.Append("CREATE TABLE Employees ( ");
sb.Append(" Id INT IDENTITY(1,1) NOT NULL PRIMARY KEY, ");
sb.Append(" Name NVARCHAR(50), ");
sb.Append(" Location NVARCHAR(50) ");
sb.Append("); ");
sb.Append("INSERT INTO Employees (Name, Location) VALUES ");
sb.Append("(N'Jared', N'Australia'), ");
sb.Append("(N'Nikita', N'India'), ");
sb.Append("(N'Tom', N'Germany'); ");
sql = sb.ToString();
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.ExecuteNonQuery();
Console.WriteLine("Done.");
}
// INSERT demo
Console.Write("Inserting a new row into table, press any key to continue...");
Console.ReadKey(true);
sb.Clear();
sb.Append("INSERT Employees (Name, Location) ");
sb.Append("VALUES (@name, @location);");
sql = sb.ToString();
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@name", "Jake");
command.Parameters.AddWithValue("@location", "United States");
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine(rowsAffected + " row(s) inserted");
}
// UPDATE demo
String userToUpdate = "Nikita";
Console.Write("Updating 'Location' for user '" + userToUpdate + "', press any key to continue...");
Console.ReadKey(true);
sb.Clear();
sb.Append("UPDATE Employees SET Location = N'United States' WHERE Name = @name");
sql = sb.ToString();
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@name", userToUpdate);
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine(rowsAffected + " row(s) updated");
}
// DELETE demo
String userToDelete = "Jared";
Console.Write("Deleting user '" + userToDelete + "', press any key to continue...");
Console.ReadKey(true);
sb.Clear();
sb.Append("DELETE FROM Employees WHERE Name = @name;");
sql = sb.ToString();
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@name", userToDelete);
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine(rowsAffected + " row(s) deleted");
}
// READ demo
Console.WriteLine("Reading data from table, press any key to continue...");
Console.ReadKey(true);
sql = "SELECT Id, Name, Location FROM Employees;";
using (SqlCommand command = new SqlCommand(sql, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1} {2}", reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
}
}
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
finally
{
Console.WriteLine("Cleaning up table.");
string dropTableIfExists = @"DROP TABLE IF EXISTS Employees";
using (SqlCommand command = new SqlCommand(dropTableIfExists, connection))
{
command.ExecuteNonQuery();
Console.WriteLine("Done.");
}
}
}
Console.WriteLine("All done. Press any key to finish...");
Console.ReadKey(true);
}
private static async Task<string> GetPasswordFromKeyVault()
{
Console.WriteLine("Trying to get Password from Key Vault. Press a key to continue...");
Console.ReadKey(true);
/* The next four lines of code show you how to use AppAuthentication library to fetch secrets from your key vault */
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
SecretBundle secret = await keyVaultClient.GetSecretAsync("https://your_key_vault_name.vault.azure.net/secrets/AppSecret"); // update me
return secret.Value;
}
}
}
@@ -0,0 +1,11 @@
## Sample details
Please visit the [C# tutorials](https://www.microsoft.com/en-us/sql-server/developer-get-started/csharp) and select RHEL, Ubuntu, SLES, or macOs to run through the sample in full with more detail.
<a name=disclaimers></a>
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.
## 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/)