Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Developing applications with C# and Azure SQL

Pick a platform below to get started:
* [unix-based (Includes macOS, RHEL, Ubuntu, SLES](https://github.com/Microsoft/sql-server-samples/tree/master/samples/tutorials/AzureSqlGettingStartedSamples/csharp/Unix-based)
* [Windows](https://github.com/Microsoft/sql-server-samples/tree/master/samples/tutorials/AzureSqlGettingStartedSamples/csharp/Windows)

Please visit our [getting started tutorials](https://www.microsoft.com/en-us/sql-server/developer-get-started/)
Original file line number Diff line number Diff line change
@@ -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;
}
}
}
Original file line number Diff line number Diff line change
@@ -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; }
}
}
Original file line number Diff line number Diff line change
@@ -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;
}
}
}
Original file line number Diff line number Diff line change
@@ -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 + "]";
}
}
}
Original file line number Diff line number Diff line change
@@ -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() + "]";
}
}
}
Loading