Skip to content

Commit d26c0af

Browse files
authored
Merge pull request #818 from akatesmith/addingsampleskatsmith
Addingsampleskatsmith
2 parents 5d3a35e + 70bc287 commit d26c0af

80 files changed

Lines changed: 5437 additions & 0 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Developing applications with C# and Azure SQL
2+
3+
Pick a platform below to get started:
4+
* [unix-based (Includes macOS, RHEL, Ubuntu, SLES](https://github.com/Microsoft/sql-server-samples/tree/master/samples/tutorials/AzureSqlGettingStartedSamples/csharp/Unix-based)
5+
* [Windows](https://github.com/Microsoft/sql-server-samples/tree/master/samples/tutorials/AzureSqlGettingStartedSamples/csharp/Windows)
6+
7+
Please visit our [getting started tutorials](https://www.microsoft.com/en-us/sql-server/developer-get-started/)
Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
using Microsoft.Azure.KeyVault;
2+
using Microsoft.Azure.KeyVault.Models;
3+
using Microsoft.Azure.Services.AppAuthentication;
4+
using System;
5+
using System.Data.SqlClient;
6+
using System.Text;
7+
using System.Threading.Tasks;
8+
9+
namespace AzureSqlColumnstoreSample
10+
{
11+
class Program
12+
{
13+
static void Main(string[] args)
14+
{
15+
System.Threading.Tasks.Task task = Program.DoWork(args);
16+
// Becuase this program takes user input, have a long wait.
17+
var result = task.Wait(TimeSpan.FromMinutes(30));
18+
}
19+
20+
static async System.Threading.Tasks.Task DoWork(string[] args)
21+
{
22+
23+
Console.WriteLine("*** Azure SQL Columnstore demo ***");
24+
25+
// Build connection string
26+
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
27+
builder.DataSource = "your_server.database.windows.net"; // update me
28+
builder.UserID = "your_user"; // update me
29+
builder.Password = await GetPasswordFromKeyVault();
30+
builder.InitialCatalog = "your_database";
31+
32+
// Connect to Azure SQL
33+
Console.Write("Connecting to Azure SQL ... ");
34+
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
35+
{
36+
string sql;
37+
try
38+
{
39+
connection.Open();
40+
string dropTable = "Drop table if exists Table_with_3M_rows";
41+
using (SqlCommand command = new SqlCommand(dropTable, connection))
42+
{
43+
command.ExecuteNonQuery();
44+
Console.WriteLine("Table cleaned up.");
45+
}
46+
47+
// Insert 5 million rows into the table 'Table_with_3M_rows'
48+
Console.Write("Inserting 3 million rows into table 'Table_with_3M_rows'. This takes ~1 minute, please wait ... ");
49+
StringBuilder sb = new StringBuilder();
50+
sb.Append("WITH a AS (SELECT * FROM (VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) AS a(a))");
51+
sb.Append("SELECT TOP(3000000)");
52+
sb.Append("ROW_NUMBER() OVER (ORDER BY a.a) AS OrderItemId ");
53+
sb.Append(",a.a + b.a + c.a + d.a + e.a + f.a + g.a + h.a AS OrderId ");
54+
sb.Append(",a.a * 10 AS Price ");
55+
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 ");
56+
sb.Append("INTO Table_with_3M_rows ");
57+
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;");
58+
sql = sb.ToString();
59+
using (SqlCommand command = new SqlCommand(sql, connection))
60+
{
61+
command.ExecuteNonQuery();
62+
Console.WriteLine("Done.");
63+
}
64+
65+
// Execute SQL query without columnstore index
66+
double elapsedTimeWithoutIndex = SumPrice(connection);
67+
Console.WriteLine("Query time WITHOUT columnstore index: " + elapsedTimeWithoutIndex + "ms");
68+
69+
// Add a Columnstore Index
70+
Console.Write("Adding a columnstore to table 'Table_with_3M_rows' ... ");
71+
sql = "CREATE CLUSTERED COLUMNSTORE INDEX columnstoreindex ON Table_with_3M_rows;";
72+
using (SqlCommand command = new SqlCommand(sql, connection))
73+
{
74+
command.ExecuteNonQuery();
75+
Console.WriteLine("Done.");
76+
}
77+
78+
// Execute the same SQL query again after columnstore index was added
79+
double elapsedTimeWithIndex = SumPrice(connection);
80+
Console.WriteLine("Query time WITH columnstore index: " + elapsedTimeWithIndex + "ms");
81+
82+
// Calculate performance gain from adding columnstore index
83+
Console.WriteLine("Performance improvement with columnstore index: "
84+
+ Math.Round(elapsedTimeWithoutIndex / elapsedTimeWithIndex) + "x!");
85+
}
86+
87+
catch (Exception e)
88+
{
89+
Console.WriteLine(e.ToString());
90+
}
91+
finally
92+
{
93+
string dropTable = "Drop table if exists Table_with_3M_rows";
94+
using (SqlCommand command = new SqlCommand(dropTable, connection))
95+
{
96+
command.ExecuteNonQuery();
97+
Console.WriteLine("Table cleaned up.");
98+
}
99+
}
100+
}
101+
Console.WriteLine("All done. Press any key to finish...");
102+
Console.ReadKey(true);
103+
}
104+
105+
private static async Task<string> GetPasswordFromKeyVault()
106+
{
107+
Console.WriteLine("Trying to get Password from Key Vault. Press a key to continue...");
108+
Console.ReadKey(true);
109+
/* The next four lines of code show you how to use AppAuthentication library to fetch secrets from your key vault */
110+
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
111+
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
112+
SecretBundle secret = await keyVaultClient.GetSecretAsync("https://your_keyvault_name.vault.azure.net/secrets/AppSecret"); // update me
113+
return secret.Value;
114+
}
115+
116+
public static double SumPrice(SqlConnection connection)
117+
{
118+
String sql = "SELECT SUM(Price) FROM Table_with_3M_rows";
119+
long startTicks = DateTime.Now.Ticks;
120+
using (SqlCommand command = new SqlCommand(sql, connection))
121+
{
122+
try
123+
{
124+
var sum = command.ExecuteScalar();
125+
TimeSpan elapsed = TimeSpan.FromTicks(DateTime.Now.Ticks) - TimeSpan.FromTicks(startTicks);
126+
return elapsed.TotalMilliseconds;
127+
}
128+
catch (Exception e)
129+
{
130+
Console.WriteLine(e.ToString());
131+
}
132+
}
133+
return 0;
134+
}
135+
}
136+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
using Microsoft.EntityFrameworkCore;
2+
using Microsoft.EntityFrameworkCore.SqlServer;
3+
4+
namespace AzureSqlEFSample
5+
{
6+
public class EFSampleContext : DbContext
7+
{
8+
string _connectionString;
9+
public EFSampleContext(string connectionString)
10+
{
11+
this._connectionString = connectionString;
12+
13+
}
14+
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
15+
{
16+
optionsBuilder.UseSqlServer(this._connectionString);
17+
}
18+
19+
public DbSet<User> Users { get; set; }
20+
public DbSet<Task> Tasks { get; set; }
21+
}
22+
}
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
using System;
2+
using System.Data.SqlClient;
3+
using Microsoft.Azure.KeyVault;
4+
using Microsoft.Azure.KeyVault.Models;
5+
using Microsoft.Azure.Services.AppAuthentication;
6+
using System.Threading.Tasks;
7+
using System.Collections.Generic;
8+
using System.Linq;
9+
10+
namespace AzureSqlEFSample
11+
{
12+
class Program
13+
{
14+
static void Main(string[] args)
15+
{
16+
System.Threading.Tasks.Task task = Program.DoWork(args);
17+
// Becuase this program takes user input, have a long wait.
18+
var result = task.Wait(TimeSpan.FromMinutes(30));
19+
}
20+
21+
static async System.Threading.Tasks.Task DoWork(string[] args)
22+
{
23+
Console.WriteLine("** C# CRUD sample with Entity Framework and Azure SQL DB**\n");
24+
25+
// Build connection string
26+
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
27+
builder.DataSource = "your_server_name.database.windows.net"; // update me
28+
builder.UserID = "your_user"; // update me
29+
builder.Password = await GetPasswordFromKeyVault(); // taken from Key Vault
30+
builder.InitialCatalog = "your_db_name"; // Update me
31+
32+
using (EFSampleContext context = new EFSampleContext(builder.ConnectionString))
33+
{
34+
try
35+
{
36+
context.Database.EnsureDeleted();
37+
context.Database.EnsureCreated();
38+
Console.WriteLine("Created database schema from C# classes.");
39+
40+
// Create demo: Create a Task instance and save it to the database
41+
Task newTask = new Task() { Title = "Ship Helsinki", IsComplete = false, DueDate = DateTime.Parse("04-01-2017") };
42+
context.Tasks.Add(newTask);
43+
context.SaveChanges();
44+
Console.WriteLine("\nCreated Task: " + newTask.ToString());
45+
46+
// Association demo: Assign task to user
47+
48+
// Read demo: find incomplete tasks assigned to user 'Anna'
49+
Console.WriteLine("\nIncomplete tasks assigned to 'Anna':");
50+
var query = from t in context.Tasks
51+
where t.IsComplete == false &&
52+
t.AssignedTo.FirstName.Equals("Anna")
53+
select t;
54+
foreach (var t in query)
55+
{
56+
Console.WriteLine(t.ToString());
57+
}
58+
59+
// Update demo: change the 'dueDate' of a task
60+
Task taskToUpdate = context.Tasks.First(); // get the first task
61+
Console.WriteLine("\nUpdating task: " + taskToUpdate.ToString());
62+
taskToUpdate.DueDate = DateTime.Parse("06-30-2016");
63+
context.SaveChanges();
64+
Console.WriteLine("dueDate changed: " + taskToUpdate.ToString());
65+
66+
// Delete demo: delete all tasks with a dueDate in 2016
67+
Console.WriteLine("\nDeleting all tasks with a dueDate in 2016");
68+
DateTime dueDate2016 = DateTime.Parse("12-31-2016");
69+
List<Task> queryResults = context.Tasks.Where(t => t.DueDate < dueDate2016).ToList();
70+
foreach (Task t in queryResults)
71+
{
72+
Console.WriteLine("Deleting task: " + t.ToString());
73+
context.Tasks.Remove(t);
74+
}
75+
context.SaveChanges();
76+
77+
// Show tasks after the 'Delete' operation - there should be 0 tasks
78+
Console.WriteLine("\nTasks after delete:");
79+
List<Task> tasksAfterDelete = (from t in context.Tasks select t).ToList<Task>();
80+
if (tasksAfterDelete.Count == 0)
81+
{
82+
Console.WriteLine("[None]");
83+
}
84+
else
85+
{
86+
foreach (Task t in query)
87+
{
88+
Console.WriteLine(t.ToString());
89+
}
90+
}
91+
}
92+
catch (SqlException e)
93+
{
94+
Console.WriteLine(e.ToString());
95+
}
96+
}
97+
98+
Console.WriteLine("All done. Press any key to finish...");
99+
Console.ReadKey(true);
100+
}
101+
102+
private static async Task<string> GetPasswordFromKeyVault()
103+
{
104+
Console.WriteLine("Trying to get Password from Key Vault. Press a key to continue...");
105+
Console.ReadKey(true);
106+
/* The next four lines of code show you how to use AppAuthentication library to fetch secrets from your key vault */
107+
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
108+
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
109+
SecretBundle secret = await keyVaultClient.GetSecretAsync("https://your_keyvault_name.vault.azure.net/secrets/AppSecret"); // update me
110+
return secret.Value;
111+
}
112+
}
113+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
using System;
2+
3+
namespace AzureSqlEFSample
4+
{
5+
public class Task
6+
{
7+
public int TaskId { get; set; }
8+
public string Title { get; set; }
9+
public DateTime DueDate { get; set; }
10+
public bool IsComplete { get; set; }
11+
public virtual User AssignedTo { get; set; }
12+
13+
public override string ToString()
14+
{
15+
return "Task [id=" + this.TaskId + ", title=" + this.Title + ", dueDate=" + this.DueDate.ToString() + ", IsComplete=" + this.IsComplete + "]";
16+
}
17+
}
18+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
using System;
2+
using System.Collections.Generic;
3+
4+
namespace AzureSqlEFSample
5+
{
6+
public class User
7+
{
8+
public int UserId { get; set; }
9+
public String FirstName { get; set; }
10+
public String LastName { get; set; }
11+
public virtual IList<Task> Tasks { get; set; }
12+
13+
public String GetFullName()
14+
{
15+
return this.FirstName + " " + this.LastName;
16+
}
17+
public override string ToString()
18+
{
19+
return "User [id=" + this.UserId + ", name=" + this.GetFullName() + "]";
20+
}
21+
}
22+
}

0 commit comments

Comments
 (0)