introduction to sql azure - johns hopkins...

63
Hands-On Lab SQL Azure: Introduction to SQL Azure Lab version: 1.0.3 Last updated: 4/3/2022

Upload: others

Post on 13-Apr-2020

14 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Hands-On LabSQL Azure: Introduction to SQL AzureLab version: 1.0.3

Last updated: 5/18/2023

Page 2: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Contents

OVERVIEW................................................................................................................................................. 3

EXERCISE 1: PREPARING YOUR SQL AZURE ACCOUNT...................................................................7Task 1 – Provisioning a SQL Azure Account.........................................................................................7

Task 2 – Connecting to SQL Azure and Creating a Database..............................................................11

Task 3 – Creating Logins and Database Users....................................................................................17

EXERCISE 2: WORKING WITH DATA BASIC DDL AND DML...............................................................20Task 1 – Creating Tables and Indexes................................................................................................20

EXERCISE 3: BUILD A WINDOWS AZURE APPLICATION THAT ACCESSES SQL AZURE..............24Task 1 – Loading Sample Database to your on premise SQL Database..............................................25

Task 2 – Loading Sample Database to your SQL Azure HolTestDB.....................................................25

Task 3 – Creating the Visual Studio Project........................................................................................25

EXERCISE 4: CONNECTING VIA CLIENT LIBRARIES..........................................................................36Task 1 – Opening the Begin Solution and Exploring the Common Functionalities.............................36

Task 2 – Connecting to SQL Azure Using ADO.NET............................................................................38

Task 3 – Connecting to SQL Azure Using ODBC..................................................................................43

Task 4 – Connecting to SQL Azure Using OLEDB................................................................................48

Task 5 – Connecting to SQL Azure Using Linq to SQL.........................................................................53

Task 6 – Connecting to SQL Azure via Non-Microsoft Technologies..................................................56

// Build connection string 56

SUMMARY................................................................................................................................................ 57

Page 3: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

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. We will create a simple Windows Azure application to allow us to manipulate the data in the Customer table of a database running in SQL Azure.

Objectives

In this Hands-On Lab, you will learn how to:

Use SQL Azure as a cloud hosted database platform for your applications.

You will 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

You will 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 2008

Develop against a local SQL Server/SQL Express database before connecting to SQL Azure

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 2008 SP1 (or above)

SQL Server 2008 R2 Management Studio

Page 4: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Windows Azure Tools for Microsoft Visual Studio (November 2009)

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.

Using the Code Snippets

With code snippets, you have all the code you need at your fingertips. The lab document will tell you exactly when you can use them. For example,

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.

Page 5: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 1Hit TAB to select the highlighted snippet.

Figure 2Hit 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

Page 6: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

4. Connecting via Client Libraires

Estimated time to complete this lab: 60 minutes.

Page 7: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Exercise 1: Preparing Your SQL Azure Account

In this exercise, you will step through provisioning your new SQL Azure account. You will then connect to that account and create a database, add a new user and then reconnect to SQL Azure so that you can begin working with our database. It is assumed that you already have already obtained a SQL Azure Token, if you have not you can request one from http://www.azure.com

Task 1 – Provisioning a SQL Azure Account

1. Go to the website https://sql.azure.com

2. Login to your Windows Live account.

Figure 3Logging into the Azure Services Portal

3. Type in your invitation code and then click Submit.

Page 8: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 4Entering a SQL Azure Token

4. Read the terms of use then click then Accept button.

Figure 5Accepting the Terms of Use

5. Fill in an admin account name, password and region, and then click Create Server. The Location determines which datacenter the database will reside in.

Page 9: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 6Create a server and set administrator passwords.

Note: An admin account is a master account used for administering the new server. This should not be used 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.

6. The virtual server should now be created and a list showing your projects should be displayed. To view the databases on the virtual server click the project.

Figure 7SQL Azure Projects List

7. The Server Administration screen allows basic administration of the database server and allows a quick way of viewing the available connection strings.

Page 10: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 8SQL Azure Server Management .Your server fully qualified domain name will take the following format: <ServerName>.database.windows.net.

8. The new firewall features allows a customer to specify an allow list of IP address that can access their SQL Azure Server. Your firewall will deny all connections by default, so be sure to configure your allow list so that existing clients can continue to connect.

Page 11: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 9SQL Azure Server Management – Firewall Settings

Note: The application of your firewall settings can take a few moments

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.

Task 2 – Connecting to SQL Azure and Creating a Database

1. Open SQL Server Management Studio. Start > All Programs > SQL Server 2008 R2 November CTP > SQL Server Management Studio. You will be presented with a logon dialog.

Page 12: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 10SQL Server Management Studio Default Connection Dialog

2. Enter your login information that you created in Task 1 ensuring that you selected SQL Server Authentication. SQL Azure currently only supports SQL Server Authentication. Click on the Options tab, and specify the database to connect to as master. Click Connect.

Note: Please replace server name with your assigned server, i.e. REPLACE_SERVER_NAME.database.windows.net

Page 13: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 11Connecting to SQL Azure

Figure 12Connect to master database

3. You should now see in your Object Explorer the structure of your database. Notice that your SQL Azure database is no different to an on premise relational database.

Page 14: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 13The Object Explorer

4. Click the New Query button. This will open a similar dialog requesting logon information.

Figure 14Creating a New Query Window

5. You now have a query window with an active connection to our account. You can test our 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 15Retrieving the SQL Azure version

Page 15: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

6. Replace the previous query with a new query SELECT * FROM sys.databases and click Execute

Figure 16As you can see, we just have our Master database now.

7. 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 our database for us including how to manage the underlying data files. This means that our Create Database statement can be very simple. Type Create Database HoLTestDB and click Execute

Figure 17Creating 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, the database size will not be able to be changed.

8. Remembering from above that there is a system view called sys.databases, Execute the query SELECT * FROM sys.databases

Page 16: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 18Querying 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.

9. Close the existing Query tab and disconnect from the master database by right clicking the server in the object explorer and selecting Disconnect.

Figure 19Disconnect from the master database

10. 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 expand the options panel and set Connect to Database to HoLTestDB. You will need to type this rather than using the dropdown box.

Page 17: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 20Connecting to a specific named database

11. You can check that we are now in the context of our User database executing the query select db_name()

Figure 21Querying the database currently in use.

Task 3 – Creating Logins and Database Users

Much like SQL Server, SQL Azure allows us to create additional logins and then assign those logins as users with permissions on a database. In this task, you will create a new login and then create a user that uses the new login in our HoLTestDB database.

1. Connect to the master database again. You may need to clear the Connect to Database combo box from the Options tab.

2. Create a new Login executing the following:

T-SQL

CREATE LOGIN HoLUser WITH password='Password1'

Page 18: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

GO

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 have finished the lab

3. Disconnect the HoLTestDB database by right clicking your server in the object explorer and selecting Disconnect.

4. Reconnect to the HoLTestDB by clicking Connect->Database Engine in the object explorer. Enter your admin credentials and specify the database name in the connection properties tab.

Figure 22Connecting to HoLTestDB

5. 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 executeCREATE USER HoLTestUser FROM LOGIN HoLUserGO

6. Add the user to the db_owner role of your HoLTestDB executing the following:

T-SQL

-- Add the new user to the db_owner role and executeEXEC sp_addrolemember 'db_owner', 'HoLTestUser'GO

Note: By making, our user a member of the db_owner role we have granted a very extensive permission set to the user. In a real world application you should be careful to ensure that you grant users the smallest privilege set possible.

Page 19: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

7. Close the Query tab.

8. Reconnect to the database you created (HoLTestDB) but this time using your new HoLUser login. We will be using this login for the rest of the lab.

9. Execute the following query:

T-SQL

SELECT @@version

Figure 23Querying the SQL Server version

You now have a database created that we can login into it with our user. In the following exercises, you will start creating some database objects such as tables in this database.

Page 20: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Exercise 2: Working with Data Basic DDL and DML

In this exercise, you will start working with data in our database. This means you will be creating some tables, indexing those tables appropriately, then inserting and querying data.

Note: This exercise makes use of the HoLTestDB database that was created in Exercise 1. If you have not yet created this database, please complete Exercise 1.

Task 1 – Creating Tables and Indexes

1. If you closed SQL Server Management Studio, open it again from Start > All Programs > SQL Server 2008 R2 November CTP > SQL Server Management Studio.

2. Connect to the HoLTestDB database using the HoLUser login that you created in the previous exercise.

3. Now you will add a simple table to our database. Execute the following query in a New Query window:

T-SQL

CREATE TABLE HoLTestTable(

MyRowID int PRIMARY KEY CLUSTERED)

Note: SQL Azure requires that every table have a clustered index. If you create a table without a clustered index, you will not be able to insert rows into the table until you have created one.

Because the clustered index determines the order of rows on disk, and thus affects certain queries, you may choose to place the clustered index on a column other than the primary key column.

4. You will test our table by inserting some rows. Execute the following query:

T-SQL

INSERT INTO HoLTestTable VALUES (1)GOINSERT INTO HoLTestTable VALUES (2)GOINSERT INTO HoLTestTable VALUES (3)

Page 21: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

GO

5. Now query the rows back out of the database. Execute following the query:

T-SQL

SELECT * FROM HoLTestTable

Figure 24Querying simple data from SQL Azure

6. Let’s drop that table and create something more sophisticated. Execute the following query:

T-SQL

DROP TABLE HoLTestTable

7. 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

)

8. You will add an index on the EmailAddress field. Execute the following query:

T-SQL

CREATE INDEX IX_Customer_EmailAddress

Page 22: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

ON Customer(EmailAddress)

9. 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')

10. Now let’s query the data back out, but, let’s start by enabling the SHOWPLAN_ALL option to show the execution plan. To do that, execute the following query:

T-SQL

SET SHOWPLAN_ALL ONGOSELECT * FROM Customer WHERE EmailAddress ='[email protected]'GOSET SHOWPLAN_ALL OFF

Figure 25Showing the Query Plan

11. 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 by adding 1 to the counter each time through and adding a new record with the adding an email address of [Counter][email protected]:

T-SQL

CREATE PROCEDURE AddData@NumRows int

Page 23: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

ASDECLARE @counter intSELECT @counter = 1WHILE (@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

12. Now add 10,000 rows into the database by running the newly created Stored Procedure. Each row will have a unique email address. Execute the following query:

T-SQL

EXEC AddData 10000

Note: It may take some time to generate the 10,000 rows.

13. Execute the following query again

T-SQL

SET SHOWPLAN_ALL ONGOSELECT * FROM Customer WHERE EmailAddress ='[email protected]'GOSET SHOWPLAN_ALL OFF

Page 24: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 26Showing the Query Plan

Note: Notice that the second time around the query optimizer is likely to use the Index that we defined: This is the Index Seek line in the query plan.

14. For the most part, you can use any tool that we might previously have 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 27Showing the Query Plan

Exercise 3: Build a Windows Azure Application that Accesses SQL Azure

Page 25: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

In this exercise, you will create a simple Windows Azure application to allow us to manipulate the data in the Customer table of the AdventureWorksLT2008 database.

The purpose of this exercise is to demonstrate just how simple it is to work with SQL Azure and Windows Azure using the graphical Visual Studio 'drag and drop' approaches.

There are certain system level features of SQL Server that tools like Visual Studio depend on for the graphical developer features, which are currently not supported in SQL Azure. What we will do instead is create our application against our local instance of SQL Server 2008. Then we will be able to simply change the connection string at release time. This is a useful pattern for developing Windows Azure applications that rely on SQL Azure.

Task 1 – Loading Sample Database to your on premise SQL Database

1. Open a new instance of SQL Server Management studio from Start > All Programs > SQL Server 2008 R2 November CTP > SQL Server Management Studio, and connect to your local instance SQL Server (probably it is .\SQLEXPRESS).

2. Verify that you have the AdventureWorksLT2008 database attached.

AdventureWorksLT2008 can be downloaded from here: http://www.codeplex.com/MSFTDBProdSamples

Task 2 – Loading Sample Database to your SQL Azure HolTestDB

1. Disconnect from your local instance SQL Server.

2. Connect to the HoLTestDB database on your SQL Azure Server using the HoLUser login that you created in the previous exercises.

3. Go to File | Open | File menu and navigate to the Assets folder inside the Source folder of this Lab. Select the AdventureWorks2008LT_Azure.sql file and click Open.

Note: This script contains a cleaned up export script from the AdventureWorksLT2008 sample database. Future versions of SQL Server Management Studio will have specific support for SQL Azure avoiding the need to clean up the exported scripts.

4. Execute the query. This may take some time, as you are creating a subset of the Adventure Works database.

5. Close the query window.

Task 3 – Creating the Visual Studio Project

Page 26: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

In this task you will create a new Visual Studio project for the Windows Azure Web Site:

1. Open Microsoft Visual Studio 2008 elevated as Administrator, from Start | All Programs | Microsoft Visual Studio 2008 right-click Microsoft Visual Studio 2008 and choose Run as Administrator.

2. From the File menu, choose New and then Project.

3. In the New Project dialog, expand the language of your preference (Visual C# or Visual Basic) in the project types list and select Cloud Service.

4. In the Templates list, select Windows Azure Cloud Service. Enter “AdventureWorks” for the project name and the solution name. Ensure Create directory for solution is checked. Click OK to create the project.

Figure 28Creating a new Web Cloud Service

5. 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.

Page 27: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 29Adding a Web Role to the Solution

6. When the project template has finished creating items, you should be presented with the Default.aspx page. If not open the Default.aspx page.

7. Ensure that you are viewing the Default.aspx page in Design View by clicking the Design button.

8. Drag and drop a GridView control from the Data section of the Toolbox onto the design canvas.

Figure 30Adding a Grid View

Note: Normally we would simply configure our datasource at this point using the Wizard. However, the Add Connection dialog in Visual Studio does not currently work in this ctp, so for this exercise we will need to manually create a connection string first. To simplify debugging

Page 28: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

we will start by testing against our local SQL Server 2008 instance before changing our connection string to point to SQL Azure.

9. From the SmartTag on the GridView you just created choose New data source option on the Choose Data Source combo box.

Figure 31Using the Smart Tag

10. In the Wizard choose a Data Source Type of Database and leave the default ID. Click OK.

Page 29: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 32Choosing a Data Source

11. In the Configure Data Source Wizard, click New Connection.

Page 30: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 33Creating a new Connection

12. In the Choose data source dialog, select Microsoft SQL Server and click Continue.

13. In the Add Connection dialog, configure a connection to your local copy of AdventureWorksLT2008 database.

Page 31: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 34Configuring a connection to the local server

14. Press Test Connection you should receive a dialog indicating success. Click OK.

Figure 35Confirmation of a successful connection

Page 32: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

15. Click OK to close the Add Connection dialog box.

16. Click Next to continue through the Wizard.

17. Ensure that the Yes, save this connection as is checked and use the name AdventureWorksLTConnectionString

Figure 36Saving the connection string

Note: By saving the connection string to the application configuration file we can easily return later and use the SQL Azure connection string instead.

18. Click Next.

19. Click the Specify a custom SQL statement of stored procedure radio button and then click Next.

Note: We cannot use the Specify colums from a table or view option because AdventureWorks uses a named Schema (SalesLT) that we need to explicitly reference.

Page 33: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

20. Paste the following statement into the SQL Statement box:

T-SQL

SELECT [FirstName], [LastName], [CompanyName], [EmailAddress] FROM [SalesLT].[Customer]

Figure 37Pasting the SQL string

21. Press Next.

Page 34: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

22. Press Test Query and you should see results returned.

Figure 38Testing the query

23. Click Finish.

24. Press F5 to run the application in the Development Fabric.

25. The application will execute and you will see the list of all customers in the browser:

Page 35: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 39Running against the local SQL Server instance

26. Close the browser and return to Microsoft Visual Studio.

27. Open the web.config file.

28. Find the connectionStrings section and modify the AdventureWorksLTConnectionString connectionString to the following replacing the placeholders for the SQL Azure Server Name (REPLACE_SERVER_NAME) and HoLTestUser password (REPLACE_HoLTestUser_PASSWORD).

XML

<add name="AdventureWorksLTConnectionString" connectionString="Initial Catalog=HoLTestDB;Data Source=REPLACE_SERVER_NAME.database.windows.net;encrypt=true;User ID=HoLUser;Password=REPLACE_HoLUser_PASSWORD;TrustServerCertificate=true;" providerName="System.Data.SqlClient" />

29. Press F5 to run the application once again. This time the list of Customers is being retrieved from SQL Azure.

Page 36: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Exercise 4: Connecting via Client Libraries

In this exercise, you will learn how to use ADO.NET, ODBC, OleDB and Linq to SQL technologies to connect to your SQL Azure database and perform some simple T-SQL operations. In addition, you will see how to connect to the database from other technologies like Java and PHP.

Using Microsoft Technologies, you will see that the way in which you interact with your SQL Azure database from your applications is the same as a traditional SQL database. The main differences between the technologies lie in the type of connection and the connection strings used to connect to SQL Azure. After the connection is established, you can then use the appropriate inheritor of the ‘DbCommand’ to issue your commands to SQL Azure.

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 with that common functionalities. This allows you to focus on learning how you can connect to SQL Azure and what are the differences between the proposed technologies.

In this task, you will open the ConnectDemoApp solution and explore the SQLAzureConnectionDemo class that you will inherit from for each of the different implementations per technology.

1. Open Microsoft Visual Studio 2008 from Start | All Programs | Microsoft Visual Studio 2008 | Microsoft Visual Studio 2008.

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 the Ex04-ConnectingViaClientLibraries\begin folder inside the Source folder of this Lab. Select the folder of the language of your preference (C# or VB), and open the solution ConnectDemoApp.sln inside the ConnectDemoApp folder. A solution with the following structure should open.

Page 37: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 40Connect Demo App solution’s structure (C#)

Figure 41Connect Demo App solution’s structure (VB)

3. As mentioned before, you will create a class per technology inheriting from the SQLAzureConnectionDemo abstract class. This has common functionalities to perform basic operations against SQL Azure using the provider that you implement in the derived class. Let’s explain each of the methods of this class to understand how it works and which methods you have to implement in the derived classes:

Method Type Description

Constructor

Sets the connection property based on the result of the CreateConnection abstract method that will be implemented on the derived class.

CreateConnection Abstract A derived class will be implementing this

Page 38: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

method in order to create the connection according to the underliying technology.

CreateCommand Abstract A derived class will be implementing this method to create a command according to the underlying technology.

GetServerName Returns the server name from the data source. It is a common task required to create the connection to the database.

ConnectToSQLAzureDemo Executes the demo flow against the SQL Azure Database. It gets a command from the derived class using the CreateCommand method and then executes the Execute* methods to create, fill, query and delete a demo table.

ExecuteCreateDemoTableStatement

Executes a create table statement to create the “DemoTable” table.

ExecuteInsertTestDataStatement Executes an insert statement against the “DemoTable” table.

ExecuteReadInsertedTestData Executes a select statement trying to retrieve the data inserted by the previous method and calls the ReadData method to show it in the Console.

ReadData Reads the data retrieved from the table and displays it in the Console.

ExecuteDropDemoTable Executes a delete statement removing the “DemoTable” table from the SQL Azure database.

Notice that you will only have to override the CreateConnection and CreateCommand methods on the implementation of each of the technologies to successfully create a connection to SQL Azure.

Task 2 – Connecting to SQL Azure Using ADO.NET

In this task, you will create a class that inherits from the SQLAzureConnectionDemo class and implements the methods to connect to SQL Azure using ADO.NET.

1. Add a new class to the ConnectDemoApp project called AdoConnectionDemo. To do this, right-click the ConnectDemoApp project in the Solution Explorer and select Add | Class. In the Add New Item dialog, make sure that the Class template is selected and set the name to AdoConnectionDemo.cs or AdoConnectionDemo.vb based on the language of your preference.

Page 39: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

2. Make sure that you have the following namespace directives at the top of the file:

C#

using System.Data.Common;using System.Data.SqlClient;

Visual Basic

Imports System.Data.CommonImports 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:

C#public class AdoConnectionDemo : SQLAzureConnectionDemo{}

Visual BasicPublic Class AdoConnectionDemo 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 - Ex04 ADO constructor – C#)

C#public AdoConnectionDemo(string userName, string password, string dataSource, string databaseName) : base(userName, password, dataSource, databaseName){}

(Code Snippet – Intro to SQL Azure - Ex04 ADO constructor – VB)

Visual Basic

Public Sub New(ByVal userName As String, ByVal password As String, ByVal dataSource As String, ByVal databaseName As String) MyBase.New(userName, password, dataSource, databaseName)

Page 40: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

End Sub

5. The SQLAzureConnectionDemo class delegates the connection construction to the derived class. Override the CreateConnection method to create a SqlConnection in your AdoConnectionDemo class:

(Code Snippet – Intro to SQL Azure - Ex04 ADO CreateConnection – C#)

C#protected override DbConnection CreateConnection(string userName, string password, string dataSource, string databaseName){ return new SqlConnection(CreateAdoConnectionString(userName, password, dataSource, databaseName));}

(Code Snippet – Intro to SQL Azure - Ex04 ADO CreateConnection – VB)

Visual Basic

Protected Overrides Function CreateConnection(ByVal userName As String, ByVal password As String, ByVal dataSource As String, ByVal databaseName As String) As DbConnection Return New SqlConnection(CreateAdoConnectionString(userName, password, dataSource, databaseName))End Function

6. Implement the CreateAdoConnectionString method used by the previous method. This method is responsible for building up the connection string for the ADO.NET Connection, which takes advantage of the SqlConnectionStringBuilder class in the underlying implementation.

(Code Snippet – Intro to SQL Azure - Ex04 ADO CreateAdoConnectionString method – C#)

C#

private string CreateAdoConnectionString(string userName, string password, string dataSource, string databaseName){ // create a new instance of the SQLConnectionStringBuilder SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder { DataSource = dataSource, InitialCatalog = databaseName, Encrypt = true, TrustServerCertificate = false,

Page 41: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

UserID = userName, Password = password,

}; return connectionStringBuilder.ToString();}

(Code Snippet – Intro to SQL Azure - Ex04 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 - Ex04 ADO CreateCommand method – C#)

C#

protected override DbCommand CreateCommand(DbConnection connection){ return new SqlCommand() { Connection = connection as SqlConnection };}

(Code Snippet – Intro to SQL Azure - Ex04 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

Page 42: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

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 (based on your language) 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 - Ex04 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 - Ex04 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. Update the placeholders above the main method with the information of your SQL Azure account.

Note: This information is related with Exercise 1 where you have created a SQL Azure account, a database and a user. Anyway, you can use whatever SQL Azure account since the demo will create a new table and then remove it right before finishing.

Page 43: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

11. Run the application by hitting F5. You should see the following output in a console window.

Figure 42Expected output for ADO.NET Connection Demo

Task 3 – Connecting to SQL Azure Using ODBC

In this task, you will create a class that inherits from the SQLAzureConnectionDemo class and implements the methods for connect to SQL Azure using ODBC.

1. Add a new class to the ConnectDemoApp project called OdbcConnectionDemo. To do this, right-click the ConnectDemoApp project in the solution explorer and select Add | Class. In the Add New Item dialog, make sure that the Class template is selected and set the name to OdbcConnectionDemo.cs or OdbcConnectionDemo.vb based on the language of your preference.

2. Make sure that you have the following namespace directives at the top of the file:

C#

using System.Data.Common;using System.Data.Odbc;

Visual Basic

Imports System.Data.CommonImports 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:

C#

public class OdbcConnectionDemo : SQLAzureConnectionDemo

Page 44: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

{}

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 - Ex04 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 - Ex04 ODBC constructor – VB)

Visual Basic

Public Sub New(ByVal userName As String, ByVal password As String, ByVal dataSource As String, ByVal databaseName As String) MyBase.New(userName, password, dataSource, databaseName)End Sub

5. Override the CreateConnection method to create an OdbcConnection in your OdbcConnectionDemo class:

(Code Snippet – Intro to SQL Azure - Ex04 ODBC CreateConnection – C#)

C#

protected override DbConnection CreateConnection(string userName, string password, string dataSource, string databaseName){ return new OdbcConnection(CreateOdbcConnectionString(userName, password, dataSource, databaseName));}

(Code Snippet – Intro to SQL Azure - Ex04 ODBC CreateConnection – VB)

Page 45: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Visual Basic

Protected Overrides Function CreateConnection(ByVal userName As String, ByVal password As String, ByVal dataSource As String, ByVal databaseName As String) As DbConnection Return New OdbcConnection(CreateOdbcConnectionString(userName, password, dataSource, databaseName))End Function

6. Implement the CreateOdbcConnectionString method used by the previous method. This method is responsible for building up the ODBC Drivers connection string. The proposed implementation is using SQL Server Native Client 10.0 as its driver. You can specify any other ODBC driver of your preference here.

(Code Snippet – Intro to SQL Azure - Ex04 ODBC CreateOdbcConnectionString method – C#)

C#

private string CreateOdbcConnectionString(string userName, string password, string dataSource, string databaseName){ string serverName = GetServerName(dataSource);

OdbcConnectionStringBuilder connectionStringBuilder = new OdbcConnectionStringBuilder { Driver = "SQL Server Native Client 10.0", }; connectionStringBuilder["Server"] = "tcp:" + dataSource; connectionStringBuilder["Database"] = databaseName; connectionStringBuilder["Uid"] = userName + "@" + serverName; connectionStringBuilder["Pwd"] = password; return connectionStringBuilder.ConnectionString;}

(Code Snippet – Intro to SQL Azure - Ex04 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)

Dim connectionStringBuilder As OdbcConnectionStringBuilder = New OdbcConnectionStringBuilder With {.Driver = "SQL Server Native Client 10.0"} connectionStringBuilder("Server") = "tcp:" & dataSource connectionStringBuilder("Database") = databaseName

Page 46: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

connectionStringBuilder("Uid") = userName & "@" & serverName connectionStringBuilder("Pwd") = password Return connectionStringBuilder.ConnectionStringEnd Function

7. Override the CreateCommand method to create an Odbc 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 - Ex04 ODBC CreateCommand method – C#)

C#

protected override DbCommand CreateCommand(DbConnection connection){ return new OdbcCommand() { Connection = connection as OdbcConnection };}

(Code Snippet – Intro to SQL Azure - Ex04 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 int the Program.cs or Module1.vb file (based on your language) 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 the main method, 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 if you want to test all the technologies at once or only this one.

(Code Snippet – Intro to SQL Azure - Ex04 ODBC demo implementation – C#)

C#

static void Main(string[] args){ //...

Page 47: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

//Invoke the ODBC connection demo Console.WriteLine("Starting the ODBC Connection Demo.."); OdbcConnectionDemo demo2 = new OdbcConnectionDemo(userName, password, datasource, databaseName); demo2.ConnectToSQLAzureDemo(); Console.WriteLine("Demo Complete.. Press any key"); Console.ReadKey();}

(Code Snippet – Intro to SQL Azure - Ex04 ODBC demo implementation – VB)

Visual Basic

Sub Main() ' ... ' Invoke the ODBC connection demo Console.WriteLine("Starting the ODBC Connection Demo..") Dim demo2 = New OdbcConnectionDemo(_userName, _password, _datasource, _databaseName) demo2.ConnectToSQLAzureDemo() Console.WriteLine("Demo Complete.. Press any key") Console.ReadKey()End Sub

10. If you have not done it before, update the placeholders above the main method with the information of your SQL Azure account.

Note: This information is related with Exercise 1 where you created a SQL Azure account, a database and a user. Anyway, you can use whatever SQL Azure account since the demo will create a new table and then remove it right before finishing.

11. Run the application by hitting F5. You should see the following output in a console window.

Page 48: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 43Expected output for Odbc Connection Demo

Task 4 – Connecting to SQL Azure Using OLEDB

In this task, you will create a class that inherits from the SQLAzureConnectionDemo class and implements the methods for connect to SQL Azure using OLEDB.

1. Add a new class to the ConnectDemoApp project called OleDbConnectionDemo. To do this, right-click the ConnectDemoApp project in the Solution Explorer and select Add | Class. In the Add New Item dialog, make sure that the Class template is selected and set the name to OleDbConnectionDemo.cs or OleDbConnectionDemo.vb based on the language of your preference.

2. Make sure that you have the following namespace directives at the top of the file:

C#

using System.Data.Common;using System.Data.OleDb;

Visual Basic

Imports System.Data.CommonImports System.Data.OleDb

3. Update the class definition to make it public and to inherit from SQLAzureConnectionDemo. It should look like the following:

C#

public class OleDbConnectionDemo:SQLAzureConnectionDemo{}

Page 49: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Visual Basic

Public Class OleDbConnectionDemo Inherits SQLAzureConnectionDemoEnd 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 - Ex04 OLEDB constructor – C#)

C#

public OleDbConnectionDemo(string userName, string password, string dataSource, string databaseName) : base(userName, password, dataSource, databaseName){}

(Code Snippet – Intro to SQL Azure - Ex04 OLEDB constructor – VB)

Visual Basic

Public Sub New(ByVal userName As String, ByVal password As String, ByVal dataSource As String, ByVal databaseName As String) MyBase.New(userName, password, dataSource, databaseName)End Sub

5. Override the CreateConnection method to create an OleDbConnection in your OleDbConnectionDemo class:

(Code Snippet – Intro to SQL Azure - Ex04 OLEDB CreateConnection – C#)

C#

protected override DbConnection CreateConnection(string userName, string password, string dataSource, string databaseName){ return new OleDbConnection(CreateOleDBConnectionString(userName, password, dataSource, databaseName));}

(Code Snippet – Intro to SQL Azure - Ex04 OLEDB CreateConnection – VB)

Visual Basic

Protected Overrides Function CreateConnection(ByVal userName As String, ByVal password As String, ByVal dataSource As String, ByVal databaseName As String) As DbConnection

Page 50: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Return New OleDbConnection(CreateOleDBConnectionString(userName, password, dataSource, databaseName))End Function

6. Implement the CreateOleDbConnectionString method used by the previous method. This method is responsible for building up the connection string used to create the connection to SQL Azure using OleDb.

(Code Snippet – Intro to SQL Azure - Ex04 OLEDB CreateOleDbConnectionString method – C#)

C#

private string CreateOleDBConnectionString(string userName, string password, string dataSource, string databaseName){ string serverName = GetServerName(dataSource);

OleDbConnectionStringBuilder connectionStringBuilder = new OleDbConnectionStringBuilder { Provider = "SQLOLEDB", DataSource = dataSource,

}; connectionStringBuilder["Initial Catalog"] = databaseName; connectionStringBuilder["UId"] = userName + "@" + serverName; connectionStringBuilder["Pwd"] = password;

return connectionStringBuilder.ConnectionString;}

(Code Snippet – Intro to SQL Azure - Ex04 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)

Dim connectionStringBuilder As OleDbConnectionStringBuilder = New OleDbConnectionStringBuilder With {.Provider = "SQLOLEDB", .DataSource = dataSource} connectionStringBuilder("Initial Catalog") = databaseName connectionStringBuilder("UId") = userName & "@" & serverName connectionStringBuilder("Pwd") = password

Return connectionStringBuilder.ConnectionStringEnd Function

Page 51: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

7. Override the CreateCommand method to create an OleDb 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 - Ex04 OLEDB CreateCommand method – C#)

C#

protected override DbCommand CreateCommand(DbConnection connection){ return new OleDbCommand() { Connection = connection as OleDbConnection };}

(Code Snippet – Intro to SQL Azure - Ex04 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 (based on your language) 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 the main method, 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 if you want to test all the technologies at once or only this one.

(Code Snippet – Intro to SQL Azure - Ex04 OLEDB demo implementation – C#)

C#

static void Main(string[] args){ //...

//Invoke the OleDB connection demo Console.WriteLine("Starting the OLEDB Connection Demo..");

Page 52: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

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 - Ex04 OLEDB demo implementation – VB)

Visual Basic

Sub Main() ' ...

' Invoke the OleDB connection demo Console.WriteLine("Starting the OLEDB Connection Demo..") Dim demo3 = New OleDbConnectionDemo(_userName, _password, _datasource, _databaseName) demo3.ConnectToSQLAzureDemo() Console.WriteLine("Demo Complete.. Press any key") Console.ReadKey()End Sub

10. If you did not do it before, update the placeholders above the main method with the information of your SQL Azure account.

Note: This information is related with Exercise 1 where you have created a SQL Azure account, a database and a user. Anyway, you can use whatever SQL Azure account since the demo will create a new table and then remove it right before finishing.

11. Run the application by hitting F5. You should see the following output in a console window.

Figure 44

Page 53: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Expected output for Odbc Connection Demo

Task 5 – Connecting to SQL Azure Using Linq to SQL

You have connected in three different ways to the database on SQL Azure. The last technology that you are going to try will be Linq to SQL. You will notice that the class implementation for this demo will not inherit from SQLAzureConnectionDemo class since if you use Linq to SQL, you don’t have to manage Connections and Commands, those are administer by the underlying technology and you don’t have to worry about them.

1. Add a new class to the ConnectDemoApp project called LinqToSqlConnectionDemo. To do this, right-click the ConnectDemoApp project in the Solution Explorer and select Add | Class. In the Add New Item dialog, make sure that the Class template is selected and set the name to LinqToSqlConnectionDemo.cs or LinqToSqlConnectionDemo.vb based on the language of your preference.

2. Update the class definition to make it public. It should look like the following:

C#

public class LinqToSqlConnectionDemo {}

Visual Basic

Public Class LinqToSqlConnectionDemoEnd 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 companies names and show them in 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 - Ex04 LINQ ConnectToSQLAzure method – C#)

C#

/// <summary>

Page 54: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

/// 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();

// get all company names IQueryable<string> companyNames = from customer in context.Customers select customer.CompanyName;

// display these all on the console foreach (string company in companyNames) { Console.WriteLine(company); }}

(Code Snippet – Intro to SQL Azure - Ex04 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()

' get all company names Dim companyNames As IQueryable(Of String) = From customer In context.Customers _ Select customer.CompanyName

' display these all on the console For Each company As String In companyNames Console.WriteLine(company) Next companyEnd Sub

5. Add the following code to invoke the Linq to SQL demo in the main method of the Program.cs file (for Visual C# projects) or Module1.vb (for Visual Basic projects) file. You can

Page 55: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

add or replace the code from the previous tasks based on if you want to test all the technologies at once or only this one.

(Code Snippet – Intro to SQL Azure - Ex04 LINQ demo implementation – C#)

C#

static void Main(string[] args){ //...

//Invoke the Linq to SQL connection demo Console.WriteLine("Starting the Linq to SQL Connection Demo.."); LinqToSqlConnectionDemo demo4 = new LinqToSqlConnectionDemo(); demo4.ConnectToSQLAzureDemo(); Console.WriteLine("Demo Complete.. Press any key"); Console.ReadKey();}

(Code Snippet – Intro to SQL Azure - Ex04 LINQ demo implementation – VB)

Visual BasicSub Main() ' ...

' Invoke the Linq to SQL connection demo Console.WriteLine("Starting the Linq to SQL Connection Demo..") Dim demo4 = New LinqToSqlConnectionDemo() demo4.ConnectToSQLAzureDemo() Console.WriteLine("Demo Complete.. Press any key") Console.ReadKey()End Sub

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 since 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. Those are retrieved from your database on the SQL Azure Server using Linq to SQL.

Page 56: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Figure 45Expected output for Linq to Sql Connection Demo

Task 6 – Connecting to SQL Azure via Non-Microsoft Technologies

It is trivial to connect to SQL Azure using non-windows technologies.

The following PHP version takes on a pattern that you should be familiar with from the previous task. It uses the SQL Server Native Client ODBC driver to establish a connection.

PHP

<?php  $host = "server.database.windows.net";  $dbname = "database";  $dbuser = "user@server";  $dbpwd = "password";  $driver = "{SQL Server Native Client 10.0}";

  // Build connection string

  $dsn="Driver=$driver;Server=$host;Database=$dbname;Encrypt=true;TrustServerCertificate=true";  if (!($conn = @odbc_connect($dsn, $dbuser, $dbpwd))) {      die("Connection error: " . odbc_errormsg());  }   // Got a connection, do what you will

Page 57: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

   // Free the connection  @odbc_close($conn);?>

Connecting to SQL Azure using JDBC is also trivial. Refer to the following code.

JAVA

// Build a connection stringString connectionUrl= "jdbc:sqlserver://server.database.windows.net;" + "database=mydatabase;encrypt=true;user=user@server;password=*****";

// Next, make the sure the SQL Server Driver is loaded. Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Then attempt to get a connection. This will null or throw if we can't get a connection.

Connection sqlConn = DriverManager.getConnection(connectionUrl);if (sqlConn == null){ System.out.println("Unable to obtain connection. exiting"); System.exit(1);}

// Got a connection, do what you will

// Free the 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 provision your account, 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. The approach taken was, developing first against an on premise database and then executing against SQL Azure is one that will be useful for most Windows Azure plus SQL Azure projects.

Page 58: Introduction to SQL Azure - Johns Hopkins Universityskydev.pha.jhu.edu/.../Labs/IntroToSQLAzure/Lab.docx · Web viewIntroduction to SQL Azure Description In this lab, you will walk

Finally, you saw that creating connections to SQL Azure using Microsoft technologies is the same as creating connections to any normal on premise database.