87
Hands-On Lab Data-tier Applications in SQL Server 2008 R2 and Visual Studio 2010 Lab version: 1.1 Last updated: 6/7/2022

Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Embed Size (px)

Citation preview

Page 1: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Hands-On LabData-tier Applications in SQL Server 2008 R2 and Visual Studio 2010

Lab version: 1.1

Last updated: 4/10/2023

Page 2: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

CONTENTS

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

EXERCISE 1: CREATING A DATA-TIER APPLICATION FROM VISUAL STUDIO 2010.........................6Task 1 – Creating and Exploring a Data-tier Application Project..........................................................7

Task 2 – Adding Database Objects to a Data-tier Application Project..................................................9

EXERCISE 2: USING NEW FEATURES IN VISUAL STUDIO 2010 FOR T-SQL....................................20Task 1 – Refactoring T-SQL Code.......................................................................................................20

Task 2 – Running Static Code Analysis on T-SQL Code.......................................................................27

Task 3 – Creating Custom Static Code Analysis Rules for T-SQL Code................................................33

EXERCISE 3: DEPLOYING AND MONITORING A DATA-TIER APPLICATION....................................45Task 1 – Declaring Policies for the Deployment Intent from Visual Studio 2010...............................46

Task 2 – Deploying a Data-tier Application from Visual Studio 2010.................................................48

Task 3 – Debugging a Deployed Data-tier Application from Visual Studio 2010................................56

Task 4 – Monitoring a Data-tier Application Using the SQL Server Utility Control Point (Optional). .62

EXERCISE 4: UPGRADING A DATA-TIER APPLICATION....................................................................68Task 1 – Modifying the Schema of a Data-tier Application................................................................69

Task 2 – Upgrading a Data-tier Application from Visual Studio 2010................................................71

SUMMARY................................................................................................................................................ 75

Page 3: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Overview

A Data-tier Application (DAC) is an entity that contains all of the database and instance objects that are required to support an application, like stored procedures, tables, views, logins, etc.

SQL Server developers today want to create a data-tier application they can test and declaratively deploy across multiple instances while the system deals with version upgrades. SQL Server DBAs, on the other hand, want to know deployment requirements a priori and they also want the system to perform some of the mechanical upgrade operations instead of managing data-tier applications via a bunch of scripts. So, if we organize these motivations, we come out with the following three areas of challenges:

Development: There was not really a uniform DB project system and workflow in Visual Studio to develop Data-tier Applications, and the developers had to deal with multiple ways to create them. Another point was the absence of the ability to capture deployment intent declaratively in Visual Studio, to specify how the data-tier application should be deployed. Finally, the T-SQL developer experience in Visual Studio was lacking.

Deployment: The database administrators (DBAs) and developers continued to essentially work in silos. Once the application was deployed, it was very difficult to define a clear containment for it, which made that the changes to a deployed application was a time consuming and error prone task.

Management: It was really difficult to centrally control the deployed environment. For example, deploying the same version of a data-tier application in a database farm with 50 managed instances was a very big challenge.

Microsoft’s investments in the SQL Server Data-tier Application space for the previous challenges can also be arranged in the same areas:

Development: Several new features and enhancements were added in Visual Studio 2010:

◦ Introduced the notion of the new Data-tier Application project system.

◦ Brand new Transact-SQL Editor experience.

◦ Integrated editor, debugger, offline and online IntelliSense, language services and policy designer.

◦ Static code analysis and build services.

Deployment: A new unit of deployment, the DACPAC, was introduced to make easier the deployment and upgrade processes of data-tier applications from Visual Studio 2010 and SQL Server Management Studio. The DACPAC package captures both the data-tier application itself and the policies specifying the deployment intent.

Management: SQL Server 2008 R2 introduces the notion of the SQL Server Utility Control Point (SQL Server Utility) to make the management of several SQL Server instance a lot simpler. You

Page 4: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

can take SQL Server instances and enroll them into an existing SQL Server Utility to monitor its performance and configuration at both the instance and application level. This helps you doing trend analysis to improve resources utilization and eventually reduce costs.

Note: We will get into more detail about each of these topics in the exercises of this lab.

In this hands-on lab, you will learn how to perform the basic steps in creating, developing, deploying, managing and upgrading a Data-tier Application (DAC) using the new features in Microsoft SQL Server 2008 R2 and Microsoft Visual Studio 2010. You will also explore some of the new IDE tools and enhancements included in Microsoft Visual Studio 2010 when working with database projects.

Note: For more general information about Data-tier Applications, see Designing and Implementing Data-tier Applications.

Objectives

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

Create a Data-tier Application from scratch.

Use the new IDE features included in Microsoft Visual Studio 2010 for database projects.

Deploy a Data-tier Application from Visual Studio 2010 and SQL Server Management Studio.

Monitor the Data-tier Application using the Utility Explorer in SQL Server Management Studio

Upgrade a Data-tier Application.

System Requirements

You must have the following requisites to complete this lab:

Microsoft Visual Studio 2010

Microsoft SQL Server 2008 R2

Microsoft SQL Server Management Studio

Setup

All the requisites for this lab are verified using the Configuration Wizard. To make sure that everything is properly configured, follow these steps.

Page 5: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Note: To perform the setup steps you need to run the scripts in a command window with administrator privileges.

1. Launch the Configuration Wizard for this Lab by running the Setup.cmd script located under the Setup folder in the Source folder of this lab. Install any pre-requisites that are missing (rescanning if necessary) and complete the wizard.

Note: The Configuration Wizard also creates the 'SQLServerTrainingKitAlias' sever alias used to establish a connection with the database server.

Exercises

The following exercises make up this Hands-on Lab:

1. Creating a Data-tier Application from Visual Studio 2010

2. Using the new features in Visual Studio 2010

3. Deploying and Monitoring a Data-tier Application

4. Upgrading a Data-tier Application

Note: Each exercise is accompanied by a starting or begin solution. These solutions are missing some code sections that are completed through each exercise and therefore will not work if running them directly.

Inside each exercise, you will also find an end folder containing completed solution. You can use this solution as a guide if you need additional help working through the exercises.

Estimated time to complete this lab: 60 minutes.

Page 6: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Exercise 1: Creating a Data-tier Application from Visual Studio 2010

As mentioned earlier, each Data-tier Application operates as a single unit of management throughout the development, test and production lifecycle of the associated application. This allows tighter integration of data-tier development with the development of the associated application code. A database developer authors the DAC by using the Data-tier Application project in Visual Studio 2010. The DAC project can be integrated into the overall development solution for the application also in Visual Studio 2010. As the application developers write the application code, the database developer codes the data-tier object definitions in the DAC project.

Microsoft Visual Studio 2010 delivers several new or enhanced Database project templates in the Professional, Premium and Ultimate editions:

Database Project: Database project templates are available for SQL Server 2005 and SQL Server 2008. They may be used to define databases for mission critical and business critical applications. All objects implemented by the respective SQL Server version are supported in database projects.

Server Project: Server project templates are available for SQL Server 2005 and SQL Server 2008. They may be used to define server level objects as well as modifications to the SQL master database. Examples of server level objects are Logins and custom error messages.

Data-tier Application: Data-tier application (DAC) projects may be used to implement databases that target departmental applications. A DAC is a self-contained unit of management that defines and bundles database objects, SQL Server instance objects that are associated with the database, and deployment requirements of an application.

Note: Data-tier Application projects support the most commonly used SQL Server Database Engine objects. For a complete list of the features supported by DAC projects, see Features Supported in Data-tier Applications.

The Data-tier Applications can be implemented using one of two processes:

A DAC can be authored and built using the Data-tier Application project in Microsoft Visual Studio 2010.

A DAC can be extracted from an existing database by using the Extract Data-tier Application Wizard in SQL Server Management Studio.

In this exercise, you will learn how to create and develop a Data-tier Application from scratch using the new Data-tier Application project and the Item Templates available in Microsoft Visual Studio 2010.

Page 7: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Task 1 – Creating and Exploring a Data-tier Application Project

1. Start Microsoft Visual Studio 2010 from Start | All Programs | Microsoft Visual Studio 2010.

2. Create a new Data-tier Application. To do this, point to New on the File menu, and then click Project. In the Installed Templates list, click SQL Server under the Database node. In the project templates pane, click SQL Server Data-tier Application. Finally, set the project's name to SampleDatatierApp, set the name of the solution to Begin, select the Create directory for solution option, set the location to Ex1-CreatingDatatierApp in the Source folder of this lab, and then click OK.

Figure 1Creating a Data-tier Application project

3. Explore the structure of the SampleDatatierApp project. To do this, press CTRL+W+S to open Solution Explorer. You will find the following types of objects:

◦ Properties: contains property values that let you control how your project is deployed.

◦ Data Generation Plans: contains information about how you want to generate realistic and representative test data for a database that you intend to deploy or update.

Page 8: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

◦ Schema Comparisons: A schema comparison contains information about a specific comparison between your project and another schema. You can re-compare your project to that schema by re-opening the SCMP file and refreshing the comparison.

◦ Schema Objects: Schema objects are defined in a collection of SQL files that are stored in the project folder. Most objects are defined in separate files (except for columns in a table and parameters for a stored procedure/function which are stored in the definition for the table and the stored procedure/function respectively).

◦ Scripts: contains pre-deployment and post-deployment scripts, in addition to any scripts that you might use to manage your database or server.

Figure 2Exploring the structure of a Data-tier Application project

Note: If you are familiar with Database projects, you may notice that the layout of a Data-tier application project is very similar to a Database project. The idea is that you can leverage the same knowledge with the new Data-tier Application project.

4. Review the options available in the Data-tier Application projects to import database and instance objects. To do this, right-click the SampleDatatierApp project in Solution Explorer and check the following options:

◦ Import Script: This option launches a wizard which lets you import SQL script files into your project. These scripts are interpreted, and the database objects defined inside them are added to your project. The import process does not change the script files that you import.

◦ Import Data-tier Application: This option launches a wizard which lets you import objects from an existing database or DACPAC (the data-tier application package) to your Data-tier Application project.

Page 9: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 3Reviewing the Import options of the Data-tier Application projects

Note: For the purpose of this lab we will not import any objects into the project. We will create them from scratch using the item templates provided by Visual Studio.

Task 2 – Adding Database Objects to a Data-tier Application Project

In this task you will add two tables, a view and a stored procedure to the SampleDatatierApp project using the appropriate Item Templates. The following figure shows the columns and relationship of the tables you are going to create.

Figure 4

Page 10: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Table relationship in the SampleDatatierApp project

Note: The Product and ProductPhoto tables are a modified and simplified version of tables included in the AdventureWorks2008R2 sample database.

1. Create a new table called Product to store the name, price and size of the products. To do this, in Solution Explorer right-click the Tables folder located under the Schema Objects\Schemas\dbo folder of the SampleDatatierApp project, point to Add, and then click Table.

Figure 5Adding a table to a Data-tier Application project

2. In the Add New Item dialog, set the table name to Product and then click Add. The Product.table.sql file should be added to the project and opened in the Transact-SQL Editor.

Page 11: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 6Adding the Product table to the SampleDatatierApp project

3. Replace the code in the Product.table.sql file with the following one.

T-SQL

CREATE TABLE [dbo].[Product] ( [ID] [INT] IDENTITY(1,1) NOT NULL, [Name] [NVARCHAR](50) NOT NULL, [ListPrice] [MONEY] NOT NULL, [Size] [NVARCHAR](5) NULL,CONSTRAINT [PK_Product_ProductID] PRIMARY KEY CLUSTERED ( [ID] ASC ))

4. Create another table called ProductPhoto to store the thumbnail images for the products. To do this, in Solution Explorer right-click the Tables folder located under the Schema Objects\Schemas\dbo folder of the SampleDatatierApp project, point to Add, and then click Table. Type ProductPhoto in the Name text box and then click Add. The ProductPhoto.table.sql file should be added to the project and opened in the Transact-SQL Editor.

Page 12: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 7Adding the ProductPhoto table to the SampleDatatierApp project

5. Replace the code in the ProductPhoto.table.sql file with the following one.

T-SQL

CREATE TABLE [dbo].[ProductPhoto] ( [ID] [int] IDENTITY(1,1) NOT NULL, [ProductID] [int] NOT NULL, [ThumbNailPhoto] [varbinary](MAX) NOT NULL,CONSTRAINT [PK_ProductPhoto_ProductID_ProductPhotoID] PRIMARY KEY CLUSTERED ( [ProductID] ASC, [ID] ASC),CONSTRAINT [FK_ProductPhoto_Product_ProductID] FOREIGN KEY ([ProductID]) REFERENCES [Product] ([ID]))

6. Create a new view called ProductAndPhoto to get the information of the products with their thumbnails. To do this, in Solution Explorer right-click the Views folder located under the

Page 13: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Schema Objects\Schemas\dbo folder of the SampleDatatierApp project, point to Add, and then click View.

Figure 8Adding a view to a Data-tier Application project

7. In the Add New Item dialog, set the view name to ProductAndPhoto and then click Add. The ProductAndPhoto.view.sql file should be added to the project and opened in the Transact-SQL Editor.

Page 14: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 9Adding the ProductAndPhoto view to the SampleDatatierApp project

8. Replace the code in the ProductAndPhoto.view.sql file with the following one.

T-SQL

CREATE VIEW [dbo].[ProductAndPhoto]AS SELECT product.*, photo.[ThumbNailPhoto] FROM [dbo].[Product] AS product JOIN [dbo].[ProductPhoto] AS photo ON product.[ID] = photo.[ProductID]

9. Notice as you write the code in the Transact-SQL Editor that you now have IntelliSense support. This kind of IntelliSense is called Offline IntelliSense because you are still not connected to a Database Instance. The identifiers that are listed in the completion list are enumerated by querying the in-memory model representing the contents of your project. A subset of the SQL Server 2008 types is also supported by Offline IntelliSense.

Page 15: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 10Offline IntelliSense in the Transact-SQL Editor of Visual Studio 2010

Note: Unlike C# or Visual Basic IntelliSense, T-SQL Offline IntelliSense does not support syntax auto-completion. For example, after typing CREATE TABLE MyTable, IntelliSense will not auto-complete the remainder of the syntax for defining a table.

10. Finally, create a new stored procedure called RetrieveProducts to get all the products. To do this, in Solution Explorer right-click the Stored Procedures folder located under the Schema Objects\Schemas\dbo\Programmability folder of the SampleDatatierApp project, point to Add, and then click Stored Procedure.

Page 16: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 11Adding a stored procedure to a Data-tier Application project

11. In the Add New Item dialog, set the stored procedure name to RetrieveProducts and then click Add. The RetrieveProducts.proc.sql file should be added to the project and opened in the Transact-SQL Editor.

Page 17: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 12Adding the RetrieveProducts stored procedure to the SampleDatatierApp project

12. Replace the code in the RetrieveProducts.proc.sql file with the following one.

T-SQL

CREATE PROCEDURE [dbo].[RetrieveProducts] @param1 int = 3300AS SELECT * FROM [dbo].[Product] WHERE [ListPrice] >= 3300 ORDER BY [ID] DESCRETURN 0

Page 18: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

13. Press CTRL+SHIFT+B to build the solution. Check in the Output window that the SampleDatatierApp.dacpac has been successfully generated.

Figure 13Output window showing the generated DACPAC file after building the solution

Note: The DACPAC is a single unit of deployment that captures both the data-tier application itself and the policies specifying the deployment intent. You can think of it as something analogous to an MSI for a data-tier application.

14. Navigate to the output folder, change the extension of the SampleDatatierApp.dacpac file to ZIP and double-click the renamed file to open it. A DACPAC package contains XML files with a manifest that defines all the Database Engine objects used by the application.

Figure 14Exploring the content of a DACPAC file

Page 19: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Exercise 2: Using New Features in Visual Studio 2010 for T-SQL

Microsoft Visual Studio 2010 brings a lot of new features that combine a first-class Transact-SQL IDE with a new project template to produce a comprehensive model of the objects, policies and runtime resources required by a data-tier application. The improvements in the Transact-SQL Editor experience let you use the same tools available to application developers when writing your T-SQL code:

Online and Offline IntelliSense: The Transact-SQL Editor suggests values while you type your T-SQL code. Depending if you are connected or not to a database instance, it fetches in the already defined objects of the project system or asks to the connected instance for IntelliSense information.

Debugging: Debug your stored procedures, functions and scripts from the Transact-SQL Editor using the standard debugging tools (Call Stacks, Locals, Watch, etc).

Refactoring: Rename an object and have all the uses of that object name changed throughout your database design. Visual Studio 2010 will display all the places that will be impacted by the change and you can then apply the changes once you are satisfied.

Unit testing: Implement unit tests written in T-SQL to verify your stored procedures and functions.

Static Code Analysis: Run Code Analysis Rules to identify potential bugs in your T-SQL code.

Source Code Control integration: For example, use the Shelf Set functionality in Team Foundation Server to collaborate with the rest of your team before attempting to deploy the changes to a production environment.

Automate Build and Deployment to an integration test environment: For example, use the Build Agent of the Team Foundation Server to automatically build and deploy database schema changes as well as any changes to the other tiers of your N-tier application. Then automatically run unit tests for each tier to identify any potential issues.

In this exercise you will learn how to refactor your T-SQL code by performing some renaming in database objects. You will also run static code analysis rules against your T-SQL code to identify and fix potential bugs. In the , after you deploy the data-tier application to a Database instance, you will explore some of the other features like the online IntelliSense and the T-SQL debugger.

Task 1 – Refactoring T-SQL Code

Page 20: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

By using refactoring, you can update references throughout the database project without manually tracking which objects depend on each other and then updating references one at a time. In Visual Studio 2010 Premium and Ultimate, you manage refactoring by using the Schema View pane which shows the offline representation of the database schema.

In this task, you will rename one column in the Product table and another column in the ProductPhoto table.

1. Start Microsoft Visual Studio 2010 from Start | All Programs | Microsoft Visual Studio 2010.

2. In the File menu, choose Open and then Project/Solution. In the Open Project dialog, browse to Ex2-NewFeaturesInVS2010\Begin in the Source folder of this lab, select Begin.sln and click Open. Alternatively, you may continue working with the solution obtained after completing the previous exercise.

3. Open the Schema View of the project. To do this, in Solution Explorer click the Database

Schema View button ( ) located at the top.

4. Explore the objects in your database schema. Notice that all the objects that were defined using T-SQL code in the previous exercise are present.

Page 21: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 15Exploring the database schema using the Schema View

Note: The Schema View shows the offline representation of the database schema. The Schema View is to database objects what Class View is to .NET code objects.

5. Rename the ID column of the Product table to ProductID. To do this, in the Schema View right-click the ID column of the Product table, point to Refactor and click Rename. This will open the Rename dialog.

Figure 16Renaming a database object from the Schema View

Note: You can also use refactoring to fully-qualify the names of database objects in your project by selecting the Fully-qualify Names options in the Refactor context menu. By fully qualifying all references to database objects, you can improve the design of your database code and make it easier for others to understand and maintain. You can also prevent errors when you copy code from one location to another, such as between database projects.

Page 22: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

6. In the Rename dialog, type [ProductID], make sure to select the Preview changes check box and then click OK.

Figure 17Renaming the ID column of the Product table to ProductID

7. In the Preview Changes dialog, verify that the column was renamed in the right places of your T-SQL code and click Apply.

Page 23: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 18Previewing the changes made by the renaming

Page 24: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

8. Now rename the ID column of the ProductPhoto table to ProductPhotoID. To do this, in the Schema View right-click the ID column of the ProductPhoto table, point to Refactor and click Rename. In the Rename dialog, type [ProductPhotoID] and make sure to select the Preview changes check box and click OK. In the Preview Changes dialog, verify that the column was renamed in the right places of your T-SQL code and finally click Apply.

Figure 19Previewing the changes made by the renaming

9. After performing the renaming of both columns, switch back to Solution Explorer and notice that the SampleDatatierApp.refactorlog file was added to the root of your SampleDatatierApp project.

Page 25: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 20Showing the SampleDatatierApp.refactorlog file added after the renaming

10. Explore the content of the SampleDatatierApp.refactorlog file. To do this, double-click the SampleDatatierApp.refactorlog file in Solution Explorer to open it. Notice that the log is maintained in an XML format and contains only information about refactoring operations that require special treatment during deployment.

Figure 21

Page 26: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Exploring the content of the SampleDatatierApp.refactorlog file

Note: When you rename a database object, an entry is added to the refactoring log for your database project. When you deploy your changes, this log contributes the process to ensure that the corresponding object in the target environment is renamed as you intended. Otherwise, the existing object would be dropped, and an object would be added with the new name.

Make sure to check in this file to your version control system if you are using one.

11. Click Save All ( ) in the toolbar or press CTRL+SHIFT+S to save all the changes.

Note: For more information about renaming database objects, see Rename All References to a Database Object.

Task 2 – Running Static Code Analysis on T-SQL Code

By analyzing your T-SQL code you can eliminate potential design and naming problems and avoid performance pitfalls. The concepts are very similar to performing static analysis to detect and correct defects in managed code. You configure which analysis rules you want to apply to your database code, analyze the code, and then correct or ignore the issues that you have identified.

In this task, you will explore the static code analysis rules that are available in Visual Studio 2010. You will also analyze the T-SQL code in your project and correct the errors.

1. Explore the available static code analysis rules. To do this, in Solution Explorer click the SampleDatatierApp project to select it. On the Data menu of Visual Studio, point to Static Code Analysis, and then click Configure. The project properties window will open, displaying the Code Analysis tab.

Page 27: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 22Exploring the available static code analysis rules

Note: If you want static code analysis to run after every successful build of the database project, select the Enable Code Analysis on Build check box. By default, code analysis issues are treated as warnings. You can change this by selecting the Treat Warning as Error check box for the rules according to your needs.

By performing static code analysis, you can identify problems that fall into the following categories:

◦ Design Issues: Include code that might not behave the way in which you expect, deprecated syntax, and issues that could cause problems when the design of your database changes. For more information, see Transact-SQL Design Issues.

◦ Naming Issues: Arise when the name of a database object might cause unexpected problems or violate generally accepted conventions. For more information, see Transact-SQL Naming Issues.

◦ Performance Issues: Include code that might noticeably reduce the speed in which database operations are completed. Many of these issues identify code that will cause a table scan when the code is executed. For more information, see Transact-SQL Performance Issues.

Page 28: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

2. Run code analysis for the SampleDatatierApp project. To do this, on the Data menu of Visual Studio, point to Static Code Analysis, and click Run.

3. Review the code analysis warnings. To do this, in the Error List view check the two warnings related to the usage of wildcards (*) in the SELECT statements of the RetrieveProducts stored procedure and the ProductAndPhoto view.

Figure 23Reviewing the code analysis warnings

4. Double-click the warning in the Error List view related to the RetrieveProducts stored procedure. The RetrieveProducts.proc.sql file should be opened with the cursor pointing to the SELECT statement.

5. Hover over the wildcard (*) of the SELECT statement. You will see a suggestion to fix the warning.

Figure 24Reviewing the suggestions to fix the code analysis warning

6. Expand the wildcards (*) in the SELECT statements of the RetrieveProducts stored procedure. To do this, right-click the RetrieveProducts.proc.sql file in Solution Explorer, point to Refactor and click Expand Wildcards. This will open the Preview Changes dialog.

Page 29: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 25Expanding wildcards in the RetrieveProducts stored procedure

7. In the Preview Changes dialog, verify that the wildcard (*) was replaced for all the columns in the Product table and click Apply.

Page 30: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 26Previewing the changes made by the expansion of the wildcards

8. Expand the wildcards (*) in the SELECT statements of the ProductAndPhoto view. To do this, in Solution Explorer right-click the ProductAndPhoto.view.sql file located under the Schema Objects\Schemas\dbo\Views folder, point to Refactor and then click Expand Wildcards. In the resulting Preview Changes dialog click Apply.

Page 31: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 27Previewing the changes made by the expansion of the wildcards

9. Run code analysis again for the SampleDatatierApp project to verify that the errors were fixed. To do this, on the Data menu of Visual Studio, point to Static Code Analysis, and click Run. This time there should be no errors/warnings in the Error List view.

Figure 28No errors after running static code analysis

Page 32: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

10. Click Save All ( ) in the toolbar or press CTRL+SHIFT+S to save all the changes.

Note: For more information about static code analysis in T-SQL, see Improving Database Code with Static Analysis.

Task 3 – Creating Custom Static Code Analysis Rules for T-SQL Code

As shown in the previous task, Visual Studio 2010 Premium and Ultimate include code analysis rules to report on Transact-SQL design issues, naming issues, and performance warnings in your database code. Visual Studio 2010 provides a predefined set of built-in code analysis rules for most of the common scenarios, however, you can create your custom rules by extending the T-SQL code analysis rules feature.

In this task, you will learn how to create, register and deploy custom code analysis rules for T-SQL by developing a custom rule to check if the tables in a database project have a Primary Key.

Note: To perform this task you need to run Visual Studio with Administrator privileges.

1. Add a new class library project to the solution. To do this, point to New on the File menu, and then click Project. In the Installed Templates list, click Windows in the Visual C# node. In the project templates pane click Class Library, set the project name to CustomTSQLCodeAnalysisRules, select Add to solution in the Solution dropdown list and then click OK.

Page 33: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 29Adding a new class library project for implementing the custom static code analysis rules

2. Enable signing for the CustomTSQLCodeAnalysisRules project. To do this, in Solution Explorer right-click the CustomTSQLCodeAnalysisRules project and click Properties. In the properties windows of the project, click the Signing tab and follow these steps:

a. Check the Sign the assembly check box.

b. In the Choose a strong name key file drop-down list, select <New...>. The Create Strong Name Key dialog box should appear.

c. In the Create Strong Name Key dialog box, type CustomTSQLCodeAnalysisRules in the Key file name textbox, uncheck the Protect my key file with a password check box and finally click OK.

Page 34: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 30Creating a strong name key file

d. Click Save All ( ) in the toolbar or press CTRL+SHIFT+S to save all the changes and close the properties windows of the CustomTSQLCodeAnalysisRules project.

Figure 31

Page 35: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Properties windows of the CustomTSQLCodeAnalysisRules project

3. Add a reference to the Microsoft.Data.Schema assemblies. To do this, in Solution Explorer right-click the CustomTSQLCodeAnalysisRules project and select Add Reference. In the Add Reference dialog box, point to the .NET tab and select the following assemblies:

◦ Microsoft.Data.Schema

◦ Microsoft.Data.Schema.Sql

◦ Microsoft.Data.Schema.ScriptDom

◦ Microsoft.Data.Schema.ScriptDom.Sql

Press CTRL while clicking to select multiple components and finally click OK when you have selected all.

Figure 32Adding references to Microsoft.Data.Schema assemblies

4. Add a resources file to the project. To do this, in Solution Explorer right-click the CustomTSQLCodeAnalysisRules project, point to Add and then click New Item. In the Add New Item dialog, select Resources File from the list, set the file name to CustomTSQLCodeAnalysisRules.resx and finally click Add.

Page 36: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 33Adding a resources file to the project

Note: We will use a resources file for storing some of the properties of our new rule, like the name, the category, etc. By using resources, the rule could be easily localization aware.

5. Add three string resources. To do this, double-click the CustomTSQLCodeAnalysisRules.resx if it is not already opened, and add the following string entries:

Name Value

PrimaryKeyRequiredForAllTables_RuleName Consider creating a Primary Key in all the tables of your

project.

PrimaryKeyRequiredForAllTables_ProblemDescription Table [{0}].[{1}] does not have a primary key.

CategorySamples SamplesCategory

Page 37: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 34Adding three string resources

6. Rename the Class1.cs file to PrimaryKeyRequiredForAllTablesRule.cs. To do this, in Solution Explorer right-click the Class1.cs file and click Rename. Type PrimaryKeyRequiredForAllTablesRule.cs and then press ENTER. Finally click Yes in the dialog asking if you want to rename all the references to the code element Class1.

Figure 35CustomTSQLCodeAnalysisRules project in Solution Explorer

7. Open the PrimaryKeyRequiredForAllTablesRule.cs file and add the following using statements at the top of the file.

Page 38: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

C#

using System.Globalization;using Microsoft.Data.Schema.Extensibility;using Microsoft.Data.Schema.SchemaModel;using Microsoft.Data.Schema.Sql.SchemaModel;using Microsoft.Data.Schema.Sql;using Microsoft.Data.Schema.StaticCodeAnalysis;

8. Make the PrimaryKeyRequiredForAllTablesRule class inherit from the StaticCodeAnalysisRule base class:

C#

public class PrimaryKeyRequiredForAllTablesRule : StaticCodeAnalysisRule{}

Note: The StaticCodeAnalysisRule class provides a base class for a group or category of similar rules.

9. Add the DatabaseSchemaProviderCompatibility, DataRuleAttribute, and SupportedElementType attributes to the definition of the PrimaryKeyRequiredForAllTablesRule class. To do this, paste the following code above the definition of the PrimaryKeyRequiredForAllTablesRule class.

C#

[DatabaseSchemaProviderCompatibility(typeof(SqlDatabaseSchemaProvider))][DataRuleAttribute("CustomTSQLCodeAnalysisRules", "SR1001", "CustomTSQLCodeAnalysisRules.CustomTSQLCodeAnalysisRules", "PrimaryKeyRequiredForAllTables_RuleName", "CategorySamples", DescriptionResourceId = "PrimaryKeyRequiredForAllTables_ProblemDescription")][SupportedElementType(typeof(ISqlTable))]public class PrimaryKeyRequiredForAllTablesRule : StaticCodeAnalysisRule{}

Page 39: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

The DataRuleAttribute specifies information that appears in Visual Studio when you configure database code analysis rules, like the ID of the rule, the name, the description of the error, etc. The SupportedElementType attribute defines the types of elements to which this rule will be applied. In this case, the rule will be applied to tables (ISqlTable).

10. Override the Analyze method to check if a table has a Primary Key Constraint. To do this, paste the following bolded method inside the definition of the PrimaryKeyRequiredForAllTablesRule class.

C#

public override IList<DataRuleProblem> Analyze(DataRuleSetting ruleSetting, DataRuleExecutionContext context){ if (context.ModelElement.Name == null) { return null; }

var sqlTable = (ISqlTable)context.ModelElement; var hasPrimaryKey = false;

foreach (var sqlConstraint in sqlTable.Constraints) { if (sqlConstraint is ISqlPrimaryKeyConstraint) { hasPrimaryKey = true; break; } }

var problems = new List<DataRuleProblem>(); if (!hasPrimaryKey) { var problem = new DataRuleProblem(this, string.Format(CultureInfo.CurrentCulture, this.RuleProperties.Description, context.ModelElement.Name.Parts[0], context.ModelElement.Name.Parts[1]), sqlTable); problem.FileName = sqlTable.PrimarySource.SourceName; problem.StartLine = sqlTable.PrimarySource.StartLine; problem.StartColumn = sqlTable.PrimarySource.StartColumn;

problems.Add(problem); }

Page 40: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

return problems;}

The Analyze method uses the DataRuleSetting and DataRuleExecutionContext as input parameters. The ModelElement property of the DataRuleExecutionContext parameter contains the database object that will be analyzed by the rule. This method iterates through all the constraints in the table looking for a Primary Key Constraint. If no Primary Key Constraint is found in the table, the method returns a DataRuleProblem.

11. Press CTRL+SHIFT+B to build the solution.

12. Find out the PublicKeyToken of your CustomTSQLCodeAnalysisRules assembly. To do this, open a Visual Studio Command Prompt from Start | All Programs | Microsoft Visual Studio 2010 | Visual Studio Tools | Visual Studio Command Prompt (2010), navigate to the output folder of your CustomTSQLCodeAnalysisRules project and run the following command. Take note of the public key token shown by the output of the command.

Command Prompt

sn.exe -T CustomTSQLCodeAnalysisRules.dll

Figure 36Getting the Public Key Token of the CustomTSQLCodeAnalysisRules assembly

Note: The public key token will be used in the next step to register the new rule.

13. Create an XML file with the information required to register the feature extension. To do this, in Solution Explorer right-click the CustomTSQLCodeAnalysisRules project, point to Add and then click New Item. In the Add New Item dialog, select XML File from the list, set the file’s name to CustomTSQLCodeAnalysisRules.Extensions.xml and finally click Add.

Page 41: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 37Adding the CustomTSQLCodeAnalysisRules.Extensions.xml file to the project

14. Open the CustomTSQLCodeAnalysisRules.Extensions.xml file, if it is not already opened, and update it to match the following XML. Make sure to replace the PublicKeyToken value with the one retrieved in Step 12.

XML

<?xml version="1.0" encoding="utf-8"?><extensions assembly="" version="1" xmlns="urn:Microsoft.Data.Schema.Extensions" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:Microsoft.Data.Schema.Extensions Microsoft.Data.Schema.Extensions.xsd"> <extension type="CustomTSQLCodeAnalysisRules.PrimaryKeyRequiredForAllTablesRule" assembly="CustomTSQLCodeAnalysisRules, Version=1.0.0.0, Culture=neutral, PublicKeyToken=%YOURPUBLICKEYTOKEN%" enabled="true"/></extensions>

Page 42: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Note: In order to register the rule within the system, we need this XML file which follows the naming convention of AssemblyName.Extensions.xml.

15. Add two post build events to make sure that the CustomTSQLStaticCodeAnalysisRules assembly is copied to the proper location and that the extension manager will pick it up and load accordingly. To do this, in Solution Explorer right-click the CustomTSQLCodeAnalysisRules project and click Properties. In the properties windows of the project, click the Build Events tab and paste the following commands in the Post-build event command line text area.

Post-build Events

copy "$(TargetDir)$(TargetName)$(TargetExt)" "$(ProgramFiles)\Microsoft Visual Studio 10.0\VSTSDB\Extensions\$(TargetName)$(TargetExt)" /Ycopy "$(ProjectDir)$(TargetName).Extensions.xml" "$(ProgramFiles)\Microsoft Visual Studio 10.0\VSTSDB\Extensions\$(TargetName).Extensions.xml" /Y

The first event copies the generated assembly to the VSTSDB\Extensions directory and the second one copies the XML file that makes the extension available to the system. Inside the post-build event editor it should look like the following figure.

Figure 38Adding post build events to copy the assembly and the extensions XML to the appropriate folder

16. Click Save All ( ) in the toolbar to save all the changes and then press CTRL+SHIFT+B to build the solution. Check in the Output window that the assembly and XML files were successfully copied to the target directory.

Page 43: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 39Output windows after building the solution

17. Close all Visual Studio 2010 instances and re-open your Begin solution. This is required to let Visual Studio load the new assembly before running again the Code Analysis rules.

18. Check that our new rule is available when running Code Analysis. To do this, in Solution Explorer click the SampleDatatierApp project to select it. On the Data menu of Visual Studio, point to Static Code Analysis, and then click Configure. The Code Analysis tab of the project properties window will open, displaying our new custom rule.

Figure 40Our new static code analysis rule is now available in Visual Studio 2010

19. Run code analysis for the SampleDatatierApp project. To do this, on the Data menu of Visual Studio, point to Static Code Analysis, and click Run. There should be no errors/warnings in the Error List view because all the tables in our project do have a Primary Key Constraint.

Page 44: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

20. Create a table in the SampleDatatierApp project that does not pass the new rule. To do this, in Solution Explorer right-click the SampleDatatierApp project, point to Add, and then click Table. Leave the default values in the Add New Item dialog and then click Add.

21. Run code analysis again for the SampleDatatierApp project. To do this, on the Data menu of Visual Studio, point to Static Code Analysis, and click Run. Now there should be one warning in the Error List view saying that the Table1 does not have a primary key.

Figure 41Code analysis warning thrown our custom rule

22. Remove the Table1.table.sql file added in the Step 20 from the SampleDatatierApp project. To do this, in Solution Explorer click the Table1.table.sql file to select it and then press DELETE. Click OK in the resulting dialog to permanently delete the file.

Note: For more information about extending the rules for code analysis, see Create and Register Additional Rules for Analyzing Database Code.

Exercise 3: Deploying and Monitoring a Data-tier Application

When a data-tier application is ready to be deployed, it is built into a DACPAC package, which is a file that contains the DAC definition and the SQL Server selection policies with the deployment intent. The DACPAC is a single unit of deployment, much the same way a Windows installer (MSI) file is the unit of deployment for application code. A DAC package is usually built in conjunction with an MSI file. When the system administrators deploy the MSI file to the application tier or client computers, the database administrators deploy the associated DACPAC package to an instance of the Database Engine. This DACPAC package can be deployed from SQL Server Management Studio using the Deploy Data-tier Application wizard or can also be deployed from Visual Studio 2010.

Page 45: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Note: For the purpose of this lab, we will only cover the deployment using Visual Studio 2010.

In this exercise you will learn how to declare the deployment intent and perform a quick deploy from Visual Studio. You will also see how to run T-SQL scripts and debug them against your deployed data-tier application also in Visual Studio. Finally, you will check the SQL Server Utility Control Point to monitor the data-tier application from SQL Server Management Studio.

Task 1 – Declaring Policies for the Deployment Intent from Visual Studio 2010

In this task, we will declare the deployment intent by modifying a facet property in the server selection policies of our data-tier application.

1. Start Microsoft Visual Studio 2010 from Start | All Programs | Microsoft Visual Studio 2010.

2. In the File menu, choose Open and then Project/Solution. In the Open Project dialog, browse to Ex3-DeployingDatatierApp\Begin in the Source folder of this lab, select Begin.sln and click Open. Alternatively, you may continue working with the solution obtained after completing the previous exercise.

3. Open the SQ L Server selection policies of the SampleDatatierApp project. To do this, in Solution Explorer double-click the ServerSelection.sqlpolicy file located under the Properties folder of the SampleDatatierApp project.

Figure 42Opening the ServerSelection.sqlpolicy file

Note: The SQL Server Selection policy defines the requirements that an instance of SQL Server must meet to host the Data-tier Application.

Page 46: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

4. Add a condition for the VersionMajor facet property. To do this, scroll down the Facet Properties list in the ServerSelection.sqlpolicy view and double-click the VersionMajor property. In the Edit Values dialog, set the Value text box to “9”, make sure the Comparison operator dropdown list is set to “is equal to” and then click OK.

Figure 43Editing the condition and values of a facet property

By doing this, we are declaring that the SampleDatatierApp data-tier application must be deployed to instances of SQL Server with a version major equal to 9.

Page 47: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 44Setting a condition and values for the VersionMajor facet property

5. Click Save All ( ) in the toolbar or press CTRL+SHIFT+S to save all the changes.

Task 2 – Deploying a Data-tier Application from Visual Studio 2010

In this task, you will deploy the data-tier application to a SQL Server instance using Visual Studio. You will also add a post-deployment script to populate the database once it is deployed. Finally you will consume the data-tier application from a sample web application to perform basic CRUD operations.

1. Add a post-deployment script to the SampleDatatierApp project to populate the database with some initial data. To do this, in Solution Explorer right-click the Post-Deployment folder located under the Scripts folder of the SampleDatatierApp project, point to Add and click Existing Item. In the Add Existing Item dialog, browse to Assets in the Source folder of this lab and select the PopulateSampleDatatierApp.sql file.

Page 48: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 45Adding the PopulateSampleDatatierApp.sql post-deployment script

Note: The PopulateSampleDatatierApp.sql script performs some INSERTs operations against the Product and ProductPhoto tables.

2. Remove the Script.PostDeployment.sql file of the project. To do this, in Solution Explorer select the Script.PostDeployment.sql file located under the Scripts\Post-Deployment folder of the SampleDatatierApp project and press DELETE. Click OK in the resulting dialog to permanently delete the file.

3. Change the Build Action property of the PopulateSampleDatatierApp.sql file to PostDeploy. To do this, in Solution Explorer select the PopulateSampleDatatierApp.sql file located under the Scripts\Post-Deployment folder of the SampleDatatierApp project, press F4 to open the Properties pane and change the Build Action property to PostDeploy.

Page 49: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 46Changing the Build Action of the PopulateSampleDatatierApp.sql file

Note: Take into account that you can add only one post-deployment script in a database project.

4. Deploy the SampleDatatierApp project. To do this, in Solution Explorer right-click the SampleDatatierApp project and select Deploy. This should fail because you have not set the destination connection string of the SQL Server instance yet.

Page 50: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 47Deploy failed because there is not any connection string specified for the project yet

5. Set the destination connection string for the SampleDatatierApp project. To do this, in Solution Explorer right-click the SampleDatatierApp project and select Properties. In the project properties windows select the Deploy tab and click Edit to open the Connect to Server dialog. Type “SqlServerTrainingKitAlias” in the Server name text box and finally click OK.

Figure 48Editing the destination connection string

The project properties windows should look like the following figure.

Page 51: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 49Properties windows of the SampleDatatierApp project

6. Deploy one more time the SampleDatatierApp project. To do this, in Solution Explorer right-click the SampleDatatierApp project and select Deploy. This should fail again because the target SQL Server instance does not satisfy the selection policy specified in the previous Tasks.

Figure 50Deploy failed because the target SQL Server instance does not satisfy the selection policy

Note: Our target SQL Server instance is a SQL Server 2008 R2 which its Version Major number is 10. This does not satisfy the condition we added in the previous task, therefore the deploy fails.

7. Modify the condition of the VersionMajor facet property in the server selection policies. To do this, in Solution Explorer double-click the ServerSelection.sqlpolicy file located under the

Page 52: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Properties folder of the SampleDatatierApp project. Click the “VersionMajor is equal to 9” link to open the Edit Values dialog, select the “is greater than or equal to” option in the Comparison operator dropdown list and then click OK.

Figure 51Modifying the condition for the VersionMajor facet property

The SQL Server selection policies window should look like the following figure.

Page 53: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 52Sever Selection policies view after modifying the condition for the VersionMajor facet property

8. Deploy the SampleDatatierApp project. To do this, in Solution Explorer right-click the SampleDatatierApp project and select Deploy. Now the deployment should be successful.

Figure 53Successful deployment of the data-tier application

Note: You can also deploy your data-tier application from SQL Server Management Studio. For more information, see Deploying Data-tier Applications.

9. Let us consume the data-tier application just deployed from a sample web application. To do this, in Solution Explorer right-click the solution node, point to Add and select Existing Project.

Page 54: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

In the Add Existing Project dialog, browse to Assets\ListProducts in the Source folder of this lab, select the ListProducts.csproj project and click Open.

Figure 54Adding the ListProducts web application project

Note: The ListProducts web application is a modified version of the application built during the How to build your first Web Application with SQL Server and ASP.NET hands-on lab. It allows performing CRUD operations against the SampleDatatierApp database.

10. Open the Web.config of the ListProducts web application and explore the connection string. Notice that the Initial Catalog points to the SampleDatatierApp database.

Web.config

…<connectionStrings> <add name="AdventureWorks" connectionString="Data Source=SQLServerTrainingKitAlias;Integrated Security=True;Initial Catalog=SampleDatatierApp"/></connectionStrings>…

Page 55: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

11. Run the ListProducts web application and perform some CRUD operations. To do this, in Solution Explorer right-click the ListProducts project, point to Debug and click Start new instance. Try to add, edit and modify some of the products using the application.

Figure 55Running the ListProducts web application that uses our data-tier application

Task 3 – Debugging a Deployed Data-tier Application from Visual Studio 2010

Now that we have our data-tier application deployed to a SQL Server instance, we are now able to show some other features in Visual Studio 2010, like the Online IntelliSense, the improvements in the Transact-SQL Editor and the Debugging capabilities.

1. Add a new script file to the SampleDatatierApp project. To do this, in Solution Explorer right-click the Scripts folder of the SampleDatatierApp project, point to Add and click Script. Leave the default values in the Add New Item dialog and then click Add. The Script1.sql file should be added to the project and opened in the Transact-SQL Editor.

Page 56: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 56Adding a script to the SampleDatatierApp project

2. Connect to a SQL Server instance from Visual Studio. To do this, make sure that the Script1.sql

file is open in the Transact-SQL Editor and click the Connect button ( ) in the Visual Studio toolbar. In the Connect to Database Engine dialog type your server name and SQL Server instance name as the Server name. For example, if you have installed a default SQL Server instance in your local machine, you could use localhost.

Note: It is important that you connect to SQL Server using your server name (and the instance name if necessary). If you use "." or the "SqlServerTrainingKitAlias" server alias to connect, you could get the following error: Unable to start T-SQL Debugging. Could not connect to computer '.'. The requested name is valid, but no data of the requested type was found.

Page 57: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 57Connecting to a Database Engine

3. Type the following T-SQL code in the Script1.sql file.

T-SQL

USE [SampleDatatierApp]

EXEC [dbo].[RetrieveProducts]

4. Notice as you write the code in the Transact-SQL Editor, you have now IntelliSense. This kind of IntelliSense is called Online IntelliSense because you are connected to a database instance. The identifiers that are listed in the completion list are enumerated by querying the database that is currently selected in the editor’s toolbar. All the SQL Server 2008 types are supported by the Online IntelliSense.

Note: Online IntelliSense is not supported if you are connecting to a SQL Server Express instance.

Page 58: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 58Online IntelliSense in the Transact-SQL Editor of Visual Studio 2010

5. Run the T-SQL script and show the execution plan from Visual Studio. To do this, click the

Include Actual Execution Plan button ( ) and then click the Execute SQL button ( ). Wait for the query to finish the execution and select the Execution Plan tab. All this information that was only available through SQL Server Management Studio is now also accessible using Visual Studio 2010.

Page 59: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 59Running a T-SQL script and showing the Execution Plan from Visual Studio 2010

6. Let us debug the T-SQL script from Visual Studio. To do this, add a breakpoint in the EXEC statement of the Script1.sql file and then press F5. Once the breakpoint gets hit, press F11 to step into the RetrieveProducts stored procedure and notice that you have all the standard debugging tools available like Call Stack, Locals and Watch.

Page 60: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 60Debugging the RetrieveProducts stored procedure from Visual Studio 2010

Depending on your current configuration, when debugging starts, Visual Studio might display one or more messages prompting for firewall configuration settings required to enable remote debugging. If you are debugging against a local instance of SQL Server, you can select the first option labeled 'Cancel remote debugging'; otherwise, you will need to enable remote debugging through the firewall. Select a suitable option and click OK to start the debugging session.

Page 61: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 61Configuring the firewall for remote debugging

7. Click the Stop Debugging button ( ) in the toolbar and press CTRL+SHIFT+S to save all the changes.

Task 4 – Monitoring a Data-tier Application Using the SQL Server Utility Control Point (Optional)

A data-tier application (DAC) can be monitored using the Utility Explorer and Object Explorer panes in SQL Server Management Studio (SSMS), along with system views and tables. In addition, all objects in the database contained in the DAC can be monitored using standard database and Database Engine monitoring techniques.

In this task, you will learn how to monitor and view information about the data-tier application deployed in the previous task.

Note: This task requires you to create a Utility Control Point (UCP) and enroll the SQL Server instance where your DAC was deployed. Before following the steps within this task, make sure to create a UCP by following the instructions described in this article: How to: Create a SQL Server Utility Control Point (SQL Server Utility).

Notice that this Task is optional. You can skip it and move on with the next Exercise without the need to create the UCP.

1. Open SQL Server Management Studio from Start | All Programs | Microsoft SQL Server 2008 R2.

2. Connect to the Database Engine where your data-tier application was deployed. To do this, in the Connect to Server dialog select Database Engine, type SqlServerTrainingKitAlias as the Server name and click Connect.

Page 62: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 62Connecting to a Database Engine from SQL Server Management Studio

3. Explore the Object Explorer pane. To do this, expand the Databases and Management node.

◦ Inside the Databases folder you will find the SampleDatatierApp database which was created during the deployment process. You can use all the standard database monitoring techniques with the objects in this database.

◦ Inside the Management folder you will find the Data-tier Applications node containing all the available data-tier applications in that database instance. In there, you will find the SampleDatatierApp node which represents the DAC package deployed in the previous task. You can delete and upgrade your package right from this node.

Page 63: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 63Monitoring the SampleDatatierApp data-tier application from the Object Explorer

4. In the Object Explorer, select the SampleDatatierApp node located inside the Management\Data-tier Applications node and press F7 to open the Object Explorer Details pane. There you will see the DAC name, version and description along with the date the DAC was created.

Page 64: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 64Reviewing the information in the Object Explorer Details pane for the SampleDatatierApp

5. Explore the Utility Explorer pane. To do this, in the View menu click Utility Explorer. In the

Utility Control pane, click the Connect to Utility button ( ) to open the Connect to Server dialog.

6. In the Connect to Server dialog, connect to your Utility Control Point (UCP).

Page 65: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 65Connecting to the Utility Control Point (UCP)

Note: To perform this step and the following ones in this Task, you will need to have previously created a Utility Control Point (UCP) and have already enrolled the SQL Server instance where your DAC was deployed.

7. Wait for the Utility Management Data Warehouse (UMDW) upload interval to expire.

Note: Information about the data-tier application you deployed in the previous Task will not appear in the Utility Explorer until the data has been uploaded into the Utility Management Data Warehouse (UMDW). The default upload interval is 15 minutes, but can be tailored using the Utility Administration details page.

8. In the Utility Explorer pane, select the Deployed Data-tier Applications node. The Utility Explorer Content page should open displaying a dashboard that reports the resource utilization of all DACs that have been deployed to managed instances of the Database Engine as shown in the following figure. The top pane of this page lists each deployed DAC with visual indicators showing whether their utilization of CPU and file resources are outside the policies defined for the SQL Server Utility. If you select any DAC in the list view, for example our SampleDatatierApp, further details are displayed in tabs in the bottom pane of the page.

Page 66: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 66Exploring the dashboard of the SampleDatatierApp in the Utility Explorer Content page

Note: After using the Utility Explorer Content page to quickly identify any DACs that are either under-utilizing or stressing their hardware resources, you can make plans to address any problems. Multiple DACs that are not fully utilizing their current hardware resources could be consolidated to a single server, freeing some of the servers for other uses. If a DAC is stressing the resources on its current server, the DAC can be moved to a larger server, or additional resources can be added to the current server.

9. Select the row of the SampleDatatierApp DAC at the top of the Utility Explorer Content page and perform the following steps:

a. Select the CPU Utilization tab to view charts of CPU usage trends.

b. Select the Storage Utilization tab to view usage details for all of the data and log files along with charts of file usage trends.

c. Select the Policy Details tab to view the policies associated with the DAC.

d. Select the Property Details tab to view properties such as collation and recovery model.

Page 67: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 67Exploring the tabs in the Utility Explorer Content page for the SampleDatatierApp data-tier applications

10. Close SQL Server Management Studio.

Note: For more information, see Monitoring Data-tier Applications.

Exercise 4: Upgrading a Data-tier Application

The process of upgrading a deployed data-tier application (DAC) to a new version is simpler than when using scripts to deploy databases or database changes. The database developer only has to build a DACPAC package that describes the schema and properties of the new version. The DAC upgrade

Page 68: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

process compares the new schema to the existing deployed schema and then dynamically performs the actions required to change to the new schema.

The upgrade process is a side-by-side upgrade; it preserves a copy of the existing database while building a new database that has the schema defined in the new version of the DAC. The upgrade process first deploys the new version of the DAC by creating a new database with the new schema, then sets the current database to read-only and copies the data from the current database to the new version. After the data transfer completes, the original database is renamed, and the new database is set to the original database name.

In this exercise, you will perform some modifications to the data-tier application and then upgrade the DAC that was deployed in the previous exercise.

Note: For the purpose of this lab, we will only cover the upgrade from Visual Studio. If you want to learn how to upgrade a data-tier application from SQL Server Management Studio using the Upgrade Data-tier Application wizard, see How to: Upgrade a Data-tier Application.

Task 1 – Modifying the Schema of a Data-tier Application

In this task, you will modify the schema of the ProductPhoto table and perform a schema compare against the deployed data-tier application from Visual Studio.

1. Start Microsoft Visual Studio 2010 from Start | All Programs | Microsoft Visual Studio 2010.

2. In the File menu, choose Open and then Project/Solution. In the Open Project dialog, browse to Ex4-UpgradingDatatierApp\Begin in the Source folder of this lab, select Begin.sln and click Open. Alternatively, you may continue working with the solution obtained after completing the previous exercise.

3. Open the ProductPhoto.table.sql file in the Transact-SQL Editor. To do this, double-click the ProductPhoto.table.sql file located under the Schema Objects\Schema\dbo\Tables folder of the SampleDatatierApp project.

4. Change the definition of the ThumbNailPhoto column from NOT NULL to NULL. To do this, replace the definition of the ThumbNailPhoto column with the following code shown in bold.

T-SQL

CREATE TABLE [dbo].[ProductPhoto] ( [ProductPhotoID] [INT] IDENTITY(1,1) NOT NULL, [ProductID] [INT] NOT NULL, [ThumbNailPhoto] [varbinary](MAX) NULL,CONSTRAINT [PK_ProductPhoto_ProductID_ProductPhotoID] PRIMARY KEY CLUSTERED ( [ProductID] ASC, [ProductPhotoID] ASC),

Page 69: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

CONSTRAINT [FK_ProductPhoto_Product_ProductID] FOREIGN KEY ([ProductID]) REFERENCES [dbo].[Product] ([ProductID]))

5. Click Save All ( ) in the toolbar or press CTRL+SHIFT+S to save all the changes.

6. Perform a schema comparison between the SampleDatatierApp project and the data-tier application deployed in the previous exercise. To do this, on the Data menu of Visual Studio, point to Schema Compare, and click New Schema Comparison. In the resulting New Schema Comparison dialog, make sure that the Source Schema is set to the SampleDatatierApp project and then set the Target Schema to the SampleDatatierApp database deployed in the previous exercise (you may need to connect to the database engine first). Finally click OK.

Figure 68Selecting the Source Schema and Target Schema for the schema comparison

Note: By using Visual Studio 2010 Premium or Ultimate, you can compare two database schemas. Those schemas might be represented by a database, a data-tier application project, a database project, or the build output from a database project (a DBSCHEMA file). The entities that you compare are known as the source and the target. When the schema comparison finishes, the results appear in the Schema Compare window.

7. Review the results of the schema compare. Notice that the only database object that has a different definition is the ProductPhoto table that we modified in the Step 4. If you expand the node of the ProductPhoto table you will notice that the ThumbNailPhoto column shows a different definition.

Page 70: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 69Reviewing the results of the schema comparison

8. Close the Schema Compare window without saving the changes.

Task 2 – Upgrading a Data-tier Application from Visual Studio 2010

In this task, you will upgrade the SampleDatatierApp data-tier application from Visual Studio to include the changes made in the previous task.

1. Remove the PopulateSampleDatatierApp.sql file from the SampleDatatierApp project. To do this, select the PopulateSampleDatatierApp.sql file located under the Scripts\Post-Deployment folder of the SampleDatatierApp project and then press DELETE. Click OK in the resulting dialog to permanently delete the file.

Note: We are removing the PopulateSampleDatatierApp.sql file because the SampleDatatierApp deployed in the previous exercise was already populated with the initial data. In this way we can show that the upgrade process takes care of the data migration.

Page 71: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

2. Upgrade the SampleDatatierApp data-tier application. To do this, in Solution Explorer right-click the SampleDatatierApp project and select Deploy.

3. Press CTRL+W+O to open the Output window and review the output of the upgrade process.

Figure 70Reviewing the Output window after upgrading the SampleDatatierApp data-tier application

The following steps illustrate the upgrade progress shown in the previous figure:

◦ Verifies that the deployed DAC and the DAC project both have their application names set to SampleDatatierApp. It also evaluates whether the instance of the Database Engine meets the requirements specified in the server selection policy.

◦ Deploys the new version of the SampleDatatierApp DAC. This creates a new database with a temporary name.

◦ Sets the original SampleDatatierApp database to read-only if it is not already in read-only mode, and disconnects all the users.

◦ Copies all the data from the original database to the new database.

Page 72: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

◦ The original database is renamed by appending a string to the end of the database name.

◦ The new database is assigned the original database name: SampleDatatierApp.

4. Close Visual Studio.

5. Open SQL Server Management Studio from Start | All Programs | Microsoft SQL Server 2008 R2.

6. Connect to the Database Engine where your data-tier application was deployed. To do this, in the Connect to Server dialog select Database Engine, type SqlServerTrainingKitAlias as the Server name and click Connect.

Figure 71Connecting to a Database Engine from SQL Server Management Studio

7. Explore the databases in the Object Explorer pane. Check that the new SampleDatatierApp database has the updated schema for the ProductPhoto table. Also notice that the original database was renamed by appending a string to the end of the name.

Page 73: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 72Exploring the new and original databases in SQL Server Management Studio after upgrading

Note: After the database administrator has confirmed that the new database is operating correctly, the original database can be archived.

8. Check that the data was migrated to the new database. To do this, in Object Explorer right-click the ProductPhoto table of the SampleDatatierApp database and click Select Top 1000 Rows. You should see at least three rows.

Page 74: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Figure 73Checking that the data was migrated from the original database to the new one

9. Close SQL Server Management Studio.

Important: A database is said to have drifted from its associated DAC if changes are made to the database by using some mechanism other than upgrading the DAC. Examples include using a CREATE statement to add a new object, or using an ALTER TABLE statement to change the structure of a table from SQL Server Management Studio. Some types of changes may prevent the upgrade process from transferring data to the upgraded database. Also, any database object, such as a stored procedure or a view, which exists in the database but does not exist in the new version of the DAC will not be transferred. The objects and data are retained in the renamed original database, and can be transferred to the new database manually.

Therefore, is highly recommendable that all the modifications to a data-tier application are made from the Visual Studio project, and then perform the upgrade process.

Summary

By completing this hands-on lab you have learned how to perform the basic steps in creating, developing, deploying, managing and upgrading a Data-tier Application (DAC) using the new features in

Page 75: Aplicacion en Capas SQL Server 20008 R2 y Visual Studio 2010

Microsoft SQL Server 2008 R2 and Microsoft Visual Studio 2010. You have also seen some of the new IDE features and enhancements included in Microsoft Visual Studio 2010 to work with database projects.