Hands-On Lab: Introduction To SQL Azure For Visual Studio 2010 Developers
Hands-On Lab: Introduction To SQL Azure For Visual Studio 2010 Developers
Contents
OVERVIEW................................................................................................................................................. 3
SUMMARY................................................................................................................................................ 62
Overview
SQL Azure makes the power of Microsoft SQL Server available in a Cloud Hosted offering. Working with
SQL Azure should be a familiar experience for most developers because, for the most part, it supports
the same tooling and development practices currently used for on premise SQL Server applications.
However, there are some small differences between working with SQL Azure and working with on-
premise SQL Server. Some of these differences are inherent in the way that SQL Azure has been
architected and some will only apply during the Community Technical Preview phase.
This hands-on lab will walk through a series of simple use cases for SQL Azure such as provisioning your
account, creating, and using a database. You will create a simple Windows Azure application to allow
you to manipulate the data in the Customer table of a database running in SQL Azure.
Objectives
In this Hands-On Lab, you will:
Use SQL Azure as a cloud hosted database platform for your applications.
Learn how to:
◦ Provision a new account in SQL Azure
◦ Create new databases within the context of your account
◦ Create new users and grant them appropriate permissions
Work with SQL Azure to:
◦ Execute Data Definition Language statements to create tables and indexes
◦ Execute Data Manipulation Language to insert and query rows
Build a simple data driven ASP.NET page using the graphical controls in Visual Studio
Connect to SQL Azure Database via Client Libraries.
Prerequisites
The following is required to complete this hands-on lab:
Microsoft .NET Framework 3.5 SP1
Microsoft Visual Studio 2010
SQL Server 2008 R2 Management Studio
Windows Azure Tools for Microsoft Visual Studio 1.1 (February 2010)
Note: To complete this hands-on lab, you need to have a SQL Azure account. To sign up, visit
http://www.microsoft.com/windowsazure/sqlazure/.
Setup
For convenience, much of the code used in this hands-on lab is available as Visual Studio code snippets.
To check the prerequisites of the lab and install the code snippets:
1. Run the SetupLab.cmd script located in the lab's Source\Setup folder to check dependencies
and install any missing prerequisites.
2. Once you have verified every prerequisite, follow the instructions to install the code
snippets.
To add this code snippet in Visual Studio, you simply place the cursor where you would like the code to
be inserted, start typing the snippet name (without spaces or hyphens), in this case
LabNameEx01RunmethodCS, watch as Intellisense picks up the snippet name, and then hit the TAB key
twice once the snippet you want is selected. The code will be inserted at the cursor location.
Figure 1
Hit TAB to select the highlighted snippet.
Figure 2
Hit TAB again and the snippet will expand
To insert a code snippet using the mouse rather than the keyboard, right-click where you want the code
snippet to be inserted, select Insert Snippet followed by My Code Snippets and then pick the relevant
snippet from the list.
To learn more about Visual Studio IntelliSense Code Snippets, including how to create your own, please
see http://msdn.microsoft.com/en-us/library/ms165392.aspx.
Exercises
This Hands-On Lab comprises the following exercises:
1. Preparing Your SQL Azure Account
2. Basic DDL and DML - Creating Tables and Indexes
3. Build a Windows Azure Application that Accesses SQL Azure
4. Connecting via Client Libraires
Figure 3
Logging into the Azure Services Portal
3. If you have not previously created a server, you will need to do so now; otherwise, you may
skip to the next step. To create a server, enter an administrator account name and password,
select a region from the location drop down list, and then click Create Server. The location
determines which datacenter the database will reside in.
Figure 4
Creating a server and administrator credentials
Note: An administrator account is a master account used to manage the new server. You
should avoid using this account in connection strings where the username and password may
be exposed.
The password policy requires that this password contain at least one number, one character
and one letter and one symbol. In addition, the password cannot be less than six characters
nor contain three consecutive characters from the username.
4. In the list of projects, select the project associated with your SQL Azure account to view the
databases on the virtual server.
Figure 5
SQL Azure projects list
5. The Server Administration page allows basic administration of the database server and
provides a quick way to view the available connection strings. Locate the Server Information
section and record the value shown for Server Name. You will need it shortly.
Note: The fully qualified domain name of the server uses the following format:
<ServerName>.database.windows.net
where <ServerName> identifies the server, for example, a9ixtp7pux.database.windows.net.
Figure 6
SQL Azure server administration page
6. The firewall feature allows you to specify a list of IP addresses that can access your SQL
Azure Server. The firewall will deny all connections by default, so be sure to configure your
allow list so that existing clients can continue to connect.
Figure 7
Configuring the firewall settings for SQL Azure
Note: Changes to your firewall settings can take a few moments to become effective.
You now have a database server created and ready for the next steps in this lab. This database
can be connected to from anywhere in the world.
Note: Please replace server name with your assigned server, which you recorded earlier when
you visited the SQL Azure portal (e.g. REPLACE_SERVER_NAME.database.windows.net.)
Figure 8
Connecting to SQL Azure with SQL Server Management Studio
9. Click Options to show additional connection settings. Then, click Connection Properties and
specify the database to connect to as master.
Figure 9
Connecting to the master database
Figure 11
Creating a New Query Window
13. You now have a query window with an active connection to your account. You can test your
connection by executing the @@version procedure. Type SELECT @@version into the query
window and press the Execute button. You will get a scalar result back, which indicates the
edition as Microsoft SQL Azure.
Figure 12
Retrieving the SQL Azure version
14. Replace the previous query with a new query SELECT * FROM sys.databases and click
Execute
Figure 13
Query results showing just the master database
15. Next, you will create a new database. One of the good things about SQL Azure is that it takes
care of much of the management of the database for you, including how to manage the
underlying data files. This means that your Create Database statement can be very simple. Type
Create Database HoLTestDB and click Execute.
Figure 14
Creating a New Database
Note: You can select which SQL Azure Database edition (Web or Business) is created during
the database provisioning process. This is surfaced both in the SQL Azure Portal and in the T-
SQL Create Database statement. For example, to create a Business Edition database the T-SQL
command would be as follows: CREATE DATABASE HolTestDB (MAXSIZE = 10GB). Once a
database has been created, its size cannot be changed.
16. Remembering from above that there is a system view called sys.databases, Execute the
query SELECT * FROM sys.databases.
Figure 15
Querying the sys.databases view
Note: The USE <database_name> command does not work with SQL Azure. Therefore, you
need to disconnect and reconnect in order to change from the Master database to the new
user database you just created.
17. Close the existing Query tab and disconnect from the master database by right clicking the
server in Object Explorer and selecting Disconnect.
Figure 16
Disconnecting from the master database
18. To start up a new connections click the New Query button. The Connect to Server dialog will
open. If necessary, retype your credentials. Click the Options button to show additional
connection settings. Switch to the Connection Properties tab and select the name of the
database for the connection as HoLTestDB. You will need to type this rather than use the drop
down list.
Figure 17
Connecting to a specific database
19. You can check that you are now in the context of your user database by executing the query
select db_name().
Figure 18
Querying the database currently in use
Note: You should choose your own password for this login account and use it where
appropriate throughout the lab. If you do not choose a unique password, you should ensure
that you DROP Login HoLUser when you finish the lab.
22. Disconnect the master database by right clicking your server in the Object Explorer and
selecting Disconnect.
23. Reconnect to the HoLTestDB database by clicking Connect->Database Engine in the Object
Explorer. Enter your admin credentials and specify the database name in the Connection
Properties tab.
24. In a New Query window, execute the following to create a user from the login HoLUser.
T-SQL
-- Create a new user from the login and execute
CREATE USER HoLTestUser FROM LOGIN HoLUser
GO
25. Add the user to the db_owner role of your HoLTestDB database by executing the following:
T-SQL
-- Add the new user to the db_owner role and execute
EXEC sp_addrolemember 'db_owner', 'HoLTestUser'
GO
Note: By making your user a member of the db_owner role, you have granted a very
extensive permission set to the user. In a real world scenario, you should be careful to ensure
that you grant users only the smallest privilege set possible.
You now have a database created that you can login into with your user. In the following
exercises, you will create some database objects such as tables in this database.
Note: This exercise makes use of the HoLTestDB database that you created in Exercise 1. If you have
not yet created this database, please complete that exercise.
32. You will test your table by inserting some rows. Execute the following query:
T-SQL
INSERT INTO HoLTestTable VALUES (1)
GO
INSERT INTO HoLTestTable VALUES (2)
GO
INSERT INTO HoLTestTable VALUES (3)
GO
33. Now query the rows back out of the database. Execute following the query:
T-SQL
SELECT * FROM HoLTestTable
Figure 20
Querying simple data from SQL Azure
34. Now, drop the HolTestTable table and create something more sophisticated. Execute the
following query:
T-SQL
DROP TABLE HoLTestTable
35. Create a Customer table by Executing the following SQL Query:
T-SQL
CREATE TABLE [Customer](
[CustomerID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
[Title] [nvarchar](8) NULL,
[FirstName] [nvarchar](50) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
[EmailAddress] [nvarchar](50) NULL,
[Phone] [nvarchar](30) NULL,
[Timestamp] [timestamp] NOT NULL
)
36. You will add an index on the EmailAddress field. To do this, Execute the following query:
T-SQL
CREATE INDEX IX_Customer_EmailAddress
ON Customer(EmailAddress)
37. Execute the following query to add a row to the new Customer table:
T-SQL
INSERT INTO [Customer]
([Title],[FirstName],[LastName],[EmailAddress],[Phone])
VALUES
('Mr','David','Alexander','[email protected]','555-1234-5555')
38. Now, query the data back out, but start by enabling the SHOWPLAN_ALL option to show the
execution plan. To do that, Execute the following query:
T-SQL
SET SHOWPLAN_ALL ON
GO
SELECT * FROM Customer WHERE EmailAddress ='[email protected]'
GO
SET SHOWPLAN_ALL OFF
Figure 21
Query execution plan for a small set
39. Add a whole bunch more rows to the database and then look at the query plan again. To do
this, Execute the following query to add a stored procedure named AddData. This stored
procedure will loop incrementing a counter each time through and add a new record with an
email address with the pattern [Counter][email protected]:
T-SQL
CREATE PROCEDURE AddData
@NumRows int
AS
DECLARE @counter int
SELECT @counter = 1
WHILE (@counter < @NumRows)
BEGIN
INSERT INTO [Customer]
([Title],[FirstName],[LastName],[EmailAddress],[Phone])
VALUES
('Mr','David','Alexander',CAST(@counter as nvarchar)
+'[email protected]','555-1234-5555')
SELECT @counter = @counter + 1
END
40. Now add 10,000 rows into the database by running the new stored procedure. Each row will
have a unique email address. Execute the following query:
T-SQL
EXEC AddData 10000
Figure 22
Query execution plan for a large set
Note: Notice that the second time around the query optimizer is likely to use the index that
you defined: This is the Index Seek line in the query plan.
42. For the most part, you can use any tool that you might have previously used with SQL Server
on-premise. For an example of this, look at the query plan graphically. In SQL Server
Management Studio press Ctrl-L to display the Estimated Execution Plan.
Figure 23
Showing the query execution plan graphically
Note: This script contains a cleaned up export script from the AdventureWorksLT2008 sample
database available for download in the Codeplex sample databases project site. SQL Azure
sample databases will be available for downloading that you could use to replace this script
file.
3. Execute the query. This may take a few minutes, as you are creating a subset of the
Adventure Works database.
4. Close the query window.
Task 2 – Creating the Visual Studio Project
In this task, you create a new Visual Studio project for a Windows Azure Web Site.
1. Open Microsoft Visual Studio 2010 in elevated administrator mode. To do this, in Start | All
Programs | Microsoft Visual Studio 2010, right-click the Microsoft Visual Studio 2010 shortcut
and choose Run as Administrator.
2. If the User Account Control dialog appears, click Continue.
3. From the File menu, choose New and then Project.
4. In the New Project dialog, expand the language of your preference (Visual C# or Visual Basic)
in the Installed Templates list and select Cloud.
5. In the Templates list, select Windows Azure Cloud Service. Set the name of the project to
“AdventureWorks” and the location to the folder for the language of your preference (Visual C#
or Visual Basic) inside Ex3-BuildingSQLAzureApp in the Source folder of the lab. Ensure that
Create directory for solution is checked and then set the name of the solution to “Begin”. Click
OK to create the project.
Figure 24
Creating a new Web Cloud Service (C#)
Figure 25
Creating a new Web Cloud Service (Visual Basic)
6. In the New Cloud Service Project dialog, inside the Roles panel, expand the tab for the
language of your choice (Visual C# or Visual Basic), select ASP.NET Web Role from the list of
available roles and click the arrow (>) to add an instance of this role to the solution. Before
closing the dialog, select the new role in the right panel, click the pencil icon and rename the
role as AdventureWorksWeb. Click OK to create the cloud service solution.
Figure 26
Adding a Web Role to the Solution (C#)
Figure 27
Adding a Web Role to the Solution (VB)
7. When the project template has finished creating items, you should be presented with the
Default.aspx page. If not, open this file.
8. Ensure that you are viewing the Default.aspx page in Design View by clicking the Design
button.
9. Drag and drop a GridView control from the Data section of the Toolbox onto the design
canvas.
Figure 28
Adding a GridView control
10. From the SmartTag on the upper right corner of the newly created GridView, choose the
New data source option on the Choose Data Source combo box.
Figure 29
Creating a new data source
11. In the Data Source Configuration Wizard, choose a data source type of Database and leave
the default ID. Click OK.
Figure 30
Choosing a Data Source
13. If prompted by a Choose data source dialog, select Microsoft SQL Server and click Continue.
14. Now, configure a connection to your SQL Azure database. In the Add Connection dialog
ensure your provider is Microsoft SQL Server (SqlClient), set the Server name to the name of
the server for your SQL Azure subscription, which you recorded in Exercise 1 when you visited
the SQL Azure portal. Next, change the authentication type to Use SQL Server Authentication.
Finally, enter HoLTestDB in the database name drop down list.
Figure 32
Configuring a connection to the HolTestDB database in SQL Azure
15. Press Test Connection. If the connection information is correct, you should receive a dialog
indicating success. Click OK to proceed.
Figure 33
Confirmation of a successful connection
Figure 34
Saving the connection string in the application configuration file
19. Select the option labeled Specify a custom SQL statement of stored procedure and then
click Next.
Figure 35
Using a custom SQL statement to query the database
Note: You cannot use the Specify columns from a table or view option because
AdventureWorks uses a named Schema (SalesLT) that you need to explicitly reference.
20. Paste the following statement into the SQL Statement box and click Next.
T-SQL
SELECT [FirstName], [LastName], [CompanyName], [EmailAddress] FROM [SalesLT].
[Customer]
Figure 36
Defining a custom SQL statement
21. Press Test Query and you should see results returned.
Figure 37
Testing the query against the database
Task 1 – Opening the Begin Solution and Exploring the Common Functionalities
You will test the different Microsoft technologies connecting to SQL Azure and performing some tasks
against a new table. To avoid spending time implementing logic that creates, inserts, queries and deletes
a table, this exercise provides a begin solution that implements these common functionalities. This
allows you to focus on learning how to connect to SQL Azure and explore the differences between the
proposed technologies.
In this task, you will open the ConnectDemoApp solution and explore the SQLAzureConnectionDemo
class. During the exercise, you will inherit from this class for each different implementation of a data
access technology.
1. Open Microsoft Visual Studio 2010 from Start | All Programs | Microsoft Visual Studio 2010
| Microsoft visual Studio 2010.
2. Open the begin solution provided for this exercise. To do this, from the File menu, choose
Open | Project/Solution. In the Open Project dialog, navigate to Ex4-
ConnectingViaClientLibraries\begin inside the Source folder of this lab. Select the folder for the
language of your preference (C# or VB), and then open the solution ConnectDemoApp.sln
inside the ConnectDemoApp folder. A solution with the following structure should open.
Figure 39
Connect Demo App solution’s structure (C#)
Figure 40
Connect Demo App solution’s structure (Visual Basic)
3. As mentioned before, you will create a class per technology inheriting from the
SQLAzureConnectionDemo abstract class. This class provides common functionality to perform
basic operations against SQL Azure using the provider that you implement in the derived class.
The table below explains each of the methods in this class to understand how it works and
determine which methods you need to implement in the derived classes:
Notice that you will only have to override the CreateConnection and CreateCommand methods
on the implementation of each technology to create a connection to SQL Azure successfully.
Visual Basic
Imports System.Data.Common
Imports System.Data.SqlClient
3. Update the class definition to make it public and to inherit from SQLAzureConnectionDemo.
The final implementation should look like the following:
Note: In Visual Basic, the template for a new class already declares the class as Public.
C#
public class AdoConnectionDemo : SQLAzureConnectionDemo
{
}
Visual Basic
Public Class AdoConnectionDemo
Inherits SQLAzureConnectionDemo
End Class
4. Implement the class constructor to retrieve the connection information and pass it as
parameters to the base class constructor:
(Code Snippet – Intro to SQL Azure - Ex4 ADO constructor – C#)
C#
public AdoConnectionDemo(string userName, string password, string dataSource,
string databaseName)
: base(userName, password, dataSource, databaseName)
{
}
return connectionStringBuilder.ToString();
}
(Code Snippet – Intro to SQL Azure - Ex4 ADO CreateAdoConnectionString method – VB)
Visual Basic
Private Function CreateAdoConnectionString(ByVal userName As String, ByVal
password As String, ByVal dataSource As String, ByVal databaseName As String)
As String
' create a new instance of the SQLConnectionStringBuilder
Dim connectionStringBuilder As SqlConnectionStringBuilder = New
SqlConnectionStringBuilder With {.DataSource = dataSource, .InitialCatalog =
databaseName, .Encrypt = True, .TrustServerCertificate = False, .UserID =
userName, .Password = password}
Return connectionStringBuilder.ToString()
End Function
7. Override the CreateCommand method to create an ADO.NET command. Remember that this
abstract method is called in the parent class to get the connection and execute the different
SQL statement samples.
(Code Snippet – Intro to SQL Azure - Ex4 ADO CreateCommand method – C#)
C#
protected override DbCommand CreateCommand(DbConnection connection)
{
return new SqlCommand() { Connection = connection as SqlConnection };
}
(Code Snippet – Intro to SQL Azure - Ex4 ADO CreateCommand method – VB)
Visual Basic
Protected Overrides Function CreateCommand(ByVal connection As DbConnection)
As DbCommand
Return New SqlCommand() With {.Connection = TryCast(connection,
SqlConnection)}
End Function
That is all the code required to use an ADO.NET connection. Now you will include some code on
the Program.cs or Module1.vb file (depending on the language of your project) to test the
connection and see how the different operations work.
8. Open the Program.cs (for Visual C# projects) or Module1.vb (for Visual Basic projects) file
double-clicking it in the Solution Explorer inside the ConnectDemoApp project.
9. Implement the logic to create an instance of the AdoConnectionDemo class and execute the
demo against SQL Azure.
(Code Snippet – Intro to SQL Azure - Ex4 ADO demo implementation – C#)
C#
static void Main(string[] args)
{
//Invoke the ADO.NET connection demo
Console.WriteLine("Starting the ADO.NET Connection Demo..");
AdoConnectionDemo demo1 = new AdoConnectionDemo(userName, password,
datasource, databaseName);
demo1.ConnectToSQLAzureDemo();
Console.WriteLine("Demo Complete.. Press any key");
Console.ReadKey();
}
(Code Snippet – Intro to SQL Azure - Ex4 ADO demo implementation – VB)
Visual Basic
Sub Main()
' Invoke the ADO.NET connection demo
Console.WriteLine("Starting the ADO.NET Connection Demo..")
Dim demo1 = New AdoConnectionDemo(_userName, _password, _datasource,
_databaseName)
demo1.ConnectToSQLAzureDemo()
Console.WriteLine("Demo Complete.. Press any key")
Console.ReadKey()
End Sub
10. Locate the member variables declared immediately above method Main and update the
placeholders with the connection information for your SQL Azure account.
Figure 41
Configuring connection parameters for SQL Azure (C#)
Figure 42
Configuring connection parameters for SQL Azure (Visual Basic)
Note: This is the information obtained during Exercise 1, when you visited the SQL Azure portal
and created a database and a user. In any case, you can use any SQL Azure account since the
demo will create a new table and then remove it right before finishing.
11. Run the application by pressing F5. You should see the following output in a console window.
Figure 43
Expected output from the ADO.NET connection demo
Visual Basic
Imports System.Data.Common
Imports System.Data.Odbc
3. Update the class definition to make it public and to inherit from SQLAzureConnectionDemo.
The final implementation should look like the following:
Note: In Visual Basic, the template for a new class already declares the class as Public.
C#
public class OdbcConnectionDemo : SQLAzureConnectionDemo
{
}
Visual Basic
Public Class OdbcConnectionDemo
Inherits SQLAzureConnectionDemo
End Class
4. Implement the class constructor to get the connection information and pass it as parameters
to the base class constructor:
(Code Snippet – Intro to SQL Azure - Ex4 ODBC constructor – C#)
C#
public OdbcConnectionDemo(string userName, string password, string dataSource,
string databaseName):
base (userName, password, dataSource, databaseName)
{
}
(Code Snippet – Intro to SQL Azure - Ex4 ODBC CreateOdbcConnectionString method – VB)
Visual Basic
Private Function CreateOdbcConnectionString(ByVal userName As String, ByVal
password As String, ByVal dataSource As String, ByVal databaseName As String)
As String
Dim serverName As String = GetServerName(dataSource)
(Code Snippet – Intro to SQL Azure - Ex4 ODBC CreateCommand method – VB)
Visual Basic
Protected Overrides Function CreateCommand(ByVal connection As DbConnection)
As DbCommand
Return New OdbcCommand() With {.Connection = TryCast(connection,
OdbcConnection)}
End Function
That is the specific code required to use an ODBC connection. Now you will include some code in
the Program.cs or Module1.vb file (depending on the language of your project) to test the
connection and see how the different operations work.
8. Open the Program.cs (for Visual C# projects) or Module1.vb (for Visual Basic projects) file
double-clicking it in the Solution Explorer inside the ConnectDemoApp project.
9. In method Main, implement the logic to create a new instance of the OdbcConnectionDemo
class and execute the demo against SQL Azure. You can add or replace the code from the
previous tasks based on whether you want to test all the technologies at once or only this one.
(Code Snippet – Intro to SQL Azure - Ex4 ODBC demo implementation – C#)
C#
static void Main(string[] args)
{
//...
(Code Snippet – Intro to SQL Azure - Ex4 ODBC demo implementation – VB)
Visual Basic
Sub Main()
' ...
10. If you have not done so before, update the value of the member variables located
immediately above method Main by replacing the placeholders with the connection
information for your SQL Azure account.
Note: This is the information obtained during Exercise 1, when you visited the SQL Azure portal
and created a database and a user. In any case, you can use any SQL Azure account since the
demo will create a new table and then remove it right before finishing.
11. Run the application by pressing F5. You should see the following output in a console window.
Figure 44
Expected output from the ODBC connection demo
Visual Basic
Imports System.Data.Common
Imports System.Data.OleDb
3. Update the class definition to make it public and to inherit from SQLAzureConnectionDemo.
It should look like the following:
Note: In Visual Basic, the template for a new class already declares the class as Public.
C#
public class OleDbConnectionDemo : SQLAzureConnectionDemo
{
}
Visual Basic
Public Class OleDbConnectionDemo
Inherits SQLAzureConnectionDemo
End Class
4. Implement the class constructor to get the connection information and pass it as parameters
to the base class constructor:
(Code Snippet – Intro to SQL Azure - Ex4 OLEDB constructor – C#)
C#
public OleDbConnectionDemo(string userName, string password, string
dataSource, string databaseName)
: base(userName, password, dataSource, databaseName)
{
}
return connectionStringBuilder.ConnectionString;
}
(Code Snippet – Intro to SQL Azure - Ex4 OLEDB CreateOleDbConnectionString method – VB)
Visual Basic
Private Function CreateOleDBConnectionString(ByVal userName As String, ByVal
password As String, ByVal dataSource As String, ByVal databaseName As String)
As String
Dim serverName As String = GetServerName(dataSource)
Return connectionStringBuilder.ConnectionString
End Function
(Code Snippet – Intro to SQL Azure - Ex4 OLEDB CreateCommand method – VB)
Visual Basic
Protected Overrides Function CreateCommand(ByVal connection As DbConnection)
As DbCommand
Return New OleDbCommand() With {.Connection = TryCast(connection,
OleDbConnection)}
End Function
That is the specific code required to use an OLEDB connection. Now you will include some code
in the Program.cs or Module1.vb file (depending on the language of your project) to test the
connection and see how the different operations work.
8. Open the Program.cs (for Visual C# projects) or Module1.vb (for Visual Basic projects) file
double-clicking it in the Solution Explorer inside the ConnectDemoApp project.
9. In method Main, implement the logic to create an instance of the OleDbConnectionDemo
class and execute the demo against SQL Azure. You can add or replace the code from the
previous tasks based on whether you want to test all the technologies at once or only this one.
(Code Snippet – Intro to SQL Azure - Ex4 OLEDB demo implementation – C#)
C#
static void Main(string[] args)
{
//...
//Invoke the OleDB connection demo
Console.WriteLine("Starting the OLEDB Connection Demo..");
OleDbConnectionDemo demo3 = new OleDbConnectionDemo(userName, password,
datasource, databaseName);
demo3.ConnectToSQLAzureDemo();
Console.WriteLine("Demo Complete.. Press any key");
Console.ReadKey();
}
(Code Snippet – Intro to SQL Azure - Ex4 OLEDB demo implementation – VB)
Visual Basic
Sub Main()
' ...
10. If you have not done so before, update the value of the member variables located
immediately above method Main by replacing the placeholders with the connection
information for your SQL Azure account.
Note: This is the information obtained during Exercise 1, when you visited the SQL Azure portal
and created a database and a user. In any case, you can use any SQL Azure account since the
demo will create a new table and then remove it right before finishing.
11. Run the application by pressing F5. You should see the following output in a console window.
Figure 45
Expected output from the OLEDB connection demo
Visual Basic
Public Class LinqToSqlConnectionDemo
End Class
3. Only for C#, make sure that you have the following namespace directives at the top of the
class:
C#
using System;
using System.Linq;
4. Add the following method to the LinqToSqlConnectionDemo class. This retrieves from the
database all the company names and prints them to the console. To do that, it takes advantage
of the AdventureWorksSqlAzureDataContext LINQ to SQL class (defined in the
AdventureWorksSqlAzure.dbml file).
(Code Snippet – Intro to SQL Azure - Ex4 LINQ ConnectToSQLAzure method – C#)
C#
/// <summary>
/// AdventureWorksSqlAzureDataContext takes care of handling your transactions
for you
/// leaving you free you use Linq to extraxt information stored up in the
cloud.
/// </summary>
public void ConnectToSQLAzureDemo()
{
AdventureWorksSqlAzureDataContext context = new
AdventureWorksSqlAzureDataContext();
(Code Snippet – Intro to SQL Azure - Ex4 LINQ ConnectToSQLAzure method – VB)
Visual Basic
''' <summary>
''' AdventureWorksSqlAzureDataContext takes care of handling your transactions
for you
''' leaving you free you use Linq to extraxt information stored up in the
cloud.
''' </summary>
Public Sub ConnectToSQLAzureDemo()
Dim context As New AdventureWorksSQLAzureDataContext()
5. Add the following code to invoke the LINQ to SQL demo in method Main of the Program.cs
file (for Visual C# projects) or Module1.vb (for Visual Basic projects) file. You can add or replace
the code from the previous tasks depending on whether you want to test all the technologies at
once or only this one.
(Code Snippet – Intro to SQL Azure - Ex4 LINQ demo implementation – C#)
C#
static void Main(string[] args)
{
//...
(Code Snippet – Intro to SQL Azure - Ex4 LINQ demo implementation – VB)
Visual Basic
Sub Main()
' ...
6. Open the App.config file and change the relevant section to point to your SQL Azure
Database, and connect using the test user created earlier in this lab.
Note: This step is required because the AdventureWorksSQLAzureDataContext class gets the
parameters to create the connection from the configuration file.
7. Press F5 to run your application. You should see a long list of company names. These are
retrieved from your database on the SQL Azure Server using LINQ to SQL.
Figure 46
Expected output from the LINQ to SQL connection demo
Connecting to SQL Azure using JDBC is also trivial. Refer to the following code.
JAVA
// Build a connection string
String connectionUrl= "jdbc:sqlserver://server.database.windows.net;" +
"database=mydatabase;encrypt=true;user=user@server;password=*****";
// Then attempt to get a connection. This will null or throw if we can't get a
connection.
sqlConn.close();
Summary
In this lab, you have looked at the basics of working with SQL Azure. If you have any SQL Server
experience, you may have found the lab familiar and that is, indeed, the point. Working with SQL Azure
should be very familiar to anyone who has worked with SQL Server.
You learned to create new databases, logins and users for those databases. You saw that for the most
part, you could simply create objects in SQL Azure as you would with an on-premise SQL Server.
In addition, you created a simple Windows Azure application that is able to consume a SQL Azure
database.
Finally, you saw that creating connections to SQL Azure using Microsoft technologies is the same as
creating connections to any normal on-premise database.