Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 26 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
26
Dung lượng
294,07 KB
Nội dung
Implementing Managed Code Chapter 9 Managed code runs in the .NET CLR. SQL Server 2005 integrates CLR to allow execution of managed code within the SQL Server environment. This provides flexibility in writing the database code in multiple languages supported by .NET. Managed code also takes advantage of the programming languages to implement complex programming logic in database objects, such as stored procedures and triggers. This chapter introduces SQLCLR, which is the CLR hosted on the SQL Server. Further, it explains how to implement stored procedures, user-defined functions, triggers, and user-defined types by using managed code. In this chapter, you will learn to: Understand managed code Create managed database objects Objectives ¤NIIT Implementing Managed Code 9.3 As a database developer, you create database objects, such as procedures, functions, and triggers, to implement programming logic by using T-SQL. However, in some situations it is not possible to implement the required functionality by using the T-SQL code. For example, you need to store the credit card number in a table in an encrypted format so that it cannot be tampered. For this, you need to apply various string manipulations and mathematical calculations, which involve usage of arrays and constructs. It is very complex to do this using T-SQL code. With CLR integration in SQL Server 2005, you can create programs in any of the .NET-supported languages to implement enhanced programming logic that cannot be implemented by using T-SQL. Code that is written in any of the .NET supported languages and runs in the CLR is called managed code. You can embed these programs in your database so that they can run in the same environment in which the database exists. To implement managed code on the database server, it is important for you to know the details of CLR integration with the SQL Server. It is also important to identify situations when it is better to implement the managed code than use T-SQL code. Database developers can use T-SQL to write codes in the form of procedures and functions, but T-SQL is not a complete and comprehensive programming language. Unlike other programming languages, T-SQL does not support object-orientation, arrays, collections, for-each loops, or usage of external resources and classes. To implement a programming logic that involves complex operations in the database, SQL Server 2005 is integrated with the .NET Framework. CLR is an environment that executes codes written in any .NET programming language. CLR integration allows the database developers to create objects in any of the .NET-supported languages and embeds the objects in the database. Such a database object is called a managed database object. CLR integration provides the following benefits: Better programming model: The .NET programming languages provide a set of programming constructs that are not available in T-SQL. In addition, .NET provides a set of classes that can be used to implement a predefined functionality. For example, you need to save the data in a file in a compressed format. For this, you can use BinaryStreamReader and Binary StreamWriter classes provided by the .NET Framework base class library. Common development environment: Application developers can use the same tool, Visual Studio 2005, to create the database objects and scripts as they use to create a client-tier. Understanding Managed Code Introduction to SQL Server CLR Integration 9.4 Implementing Managed Code ¤NIIT Ability to define data types: Database developers can create user-defined data types to expand the storage capabilities of the SQL Server. For example, you need to store a set of values in a single column or variable in a pre-defined format. For this, you need to use an array. In such a case, you can create a new data type using a .NET programming language. You can use either managed code or T-SQL to implement the database programming logic. However, it is not always required to create managed code to implement a programming logic. It is essential to identify the situations where creating a managed code is a better option. You should use the T-SQL statements when you need to: Perform data access and manipulation operations that can be done using T-SQL statements. Create database objects, such as procedures, functions, or triggers, requiring basic programming logic that can be implemented by using the programming constructs provided by T-SQL. For example, T-SQL provides efficiency and ease to perform pure database oriented operations, such as joining two result sets. In comparison, creating a CLR object to apply a join involves writing code to join the data rows in one result set with the rows in another result set. In such a situation, using T-SQL is a better decision. You should use managed database objects when you need to: Implement complicated programming logic for which you can reuse the functionality provided by the .NET base class libraries. Access external resources, such as calling a Web service or accessing the file system. Implement a CPU-intensive functionality that can run more efficiently as compared to the managed code. For example, you need to extract data from a database table and store the result set in a file in the XML format. You will not be able to implement this functionality by using T-SQL. Instead, you can create a managed database object by using a .NET language to store the data in an XML file. In addition to all the preceding points, T-SQL is interpreted at the time of execution, and therefore is slow as compared to the managed code. However, the managed code is pre-compiled and faster to execute within the CLR. Identifying the Need for Managed Code ¤NIIT Implementing Managed Code 9.5 Just a minute: Which of the following is supported by .NET and not by T-SQL? 1. Writing Queries 2. Creating Procedures 3. Object-Orientation 4. Writing Triggers Answer: 3. Object-Orientation 9.6 Implementing Managed Code ¤NIIT To create managed database objects in the SQL Server, you need to first create a managed code in any of the .NET programming languages. A managed code contains classes and methods that provide a desired functionality. Next, you need to compile the code to create an assembly. An assembly can be a .dll or.exe file that contains compiled managed code. SQL Server cannot directly execute the assemblies. Therefore, before using the assemblies, you need to import and configure the assemblies in the database engine. Further, you need to create a database object based on the assembly that you imported earlier. You can import a .NET assembly, which is a .dll or an .exe, in SQL Server database engine using the CREATE ASSEMBLY statement. The syntax of the CREATE ASSEMBLY command is: CREATE ASSEMBLY assembly_name FROM { <client_assembly_specifier> | <assembly_bits> [ , n ] } [ WITH PERMISSION_SET = { SAFE | EXTERNAL_ACCESS | UNSAFE } ] where, assembly_name is the name of the assembly that you need to create in SQL Server. This name will be further used by the database objects to refer to the assembly. client_assembly_specifier specifies the local or network path of the .NET assembly that is being imported. PERMISSION_SET specifies the permission that will be given to the .NET code being imported. This parameter can accept any of the following values: SAFE: Is the most secure permission as the code will not be able to access any external resource. If no value is specified, the default value is SAFE. EXTERNAL_ACCESS: Enables the .NET code to access some external resources, such as, networks, environmental variables, and the registry. UNSAFE: Enables the .NET code to access any resource, within or outside SQL Server. Creating Managed Database Objects Importing and Configuring Assemblies ¤NIIT Implementing Managed Code 9.7 N ote Just a minute: Consider an example. You have created a managed code and created is assembly as CLRIntegration.dll. To create an assembly for this dll, you can write the following code: CREATE ASSEMBLY CLRIntegration FROM ‘C:\CLRIntegration.dll’ WITH PERMISSION_SET = SAFE In the preceding code, the database engine imports the CLRIntegration.dll assembly file from the C: drive of the local computer and creates an assembly object named CLRIntgration. Whenever you import an assembly, its details are added to the sys.assemblies system table. You can update an assembly to refer to the recent version of the assembly file or to update the permissions. For this, you can use the ALTER ASSEMBLY statement. Altering an assembly object does not affect the processes that are currently using it. Which of the following PERMISSION_SET will you use to access another database server? 1. SAFE 2. EXTERNAL_ACCESS 3. UNSAFE Answer: 2. EXTERNAL_ACCESS 9.8 Implementing Managed Code ¤NIIT N ote After importing assemblies in SQL Server, you can create managed database objects that use the managed code provided in the assembly. By default, the SQL Server does not allow running managed code on the server. Therefore, before creating a managed database object in your database, you need to enable the CLR integration feature in your database. To enable CLR, you need to use the following statements: sp_configure CLR_ENABLED, 1; GO RECONFIGURE; GO You need to be a member of sysadmin server role to enable CLR. Depending on the requirements, the database developer can create the following types of database objects: Stored procedures Functions Triggers User-Defined Types Creating Managed Stored Procedures Stored procedures are the most common and useful database code blocks. With CLR integration you can use managed code to be executed as a stored procedure. For this, you need to create a procedure that refers to an imported assembly. To create a managed function using an imported assembly, you can use the CREATE PROCEDURE command, as shown in the following syntax: CREATE PROCEDURE <Procedure Name> AS EXTERNAL NAME <Assembly Identifier>.<Type Name>.<Method Name>, where, Procedure Name is the name of the procedure you want to create. Assembly Identifier is the name of the imported assembly. Creating Managed Database Objects ¤NIIT Implementing Managed Code 9.9 Type Name is the name of the class that contains the method that will be executed through the procedure. Method Name is the name of the method that will be executed through the procedure. For example, the employee data stored in the database needs to be saved in an XML file. For this purpose, you need to create a function that will read the data from the table and write it into the XML file. For this, you need to create a managed procedure to access an external file. To provide this functionality, you have created the ConvertXML.dll assembly by using the following code: // Use the pre-defined namespaces to use the functionality provided by them using System; using System.Data; using System.Data.Sql; using Microsoft.SqlServer.Server; using System.Collections; using System.Data.SqlTypes; using System.Data.SqlClient; using System.Diagnostics; using System.IO; //Declare a namspace in which the class will be srored namespace CLRStoredProcedure { //Declare a class name XMLProc to define the functionality public class XMLProc { // Marks that the code will be used as a stored procedure [Microsoft.SqlServer.Server.SqlProcedure] //Define the function that provides functionality public static void convXml() { /* Create an object of the FileStream class that opens or creates a file named XMLEmployee.xml to write xml data */ FileStream fs = new FileStream("XMLEmployee.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite); // Creates the object of a StreamWriter class that allows to write on a stream StreamWriter sw = new StreamWriter(fs); 9.10 Implementing Managed Code ¤NIIT using (SqlConnection connection = new SqlConnection("context connection=true")) { connection.Open(); // Opens the SQL Server connection SqlCommand cmd = new SqlCommand("SELECT * FROM HumanResources.Employee FOR XML RAW", connection); // Creates a new SQLCommand SqlDataReader dr; // Creates a new data reader to read data from the data source dr = cmd.ExecuteReader(); // Read from the data set in the data reader, dr, and write on to the stream while (dr.Read()) { sw.Write(dr[0].ToString()); // Writes the data in the XML file } dr.Close(); // Closes the Data reader connection.Close(); // Closes the database connection sw.Flush(); // Closes the stream writer } } } } Using the ConvertXML.dll assembly, you need to create a managed procedure. For this, you need to perform the following steps: 1. Execute the following statement in the Query Editor window of the Microsoft SQL Server Management Studio window to create an assembly named ConvertXMLAssembly that will refer to the ConvertXML.dll file: CREATE ASSEMBLY ConvertXMLAssembly FROM ‘C:\ConvertXML.dll’ WITH PERMISSION_SET = EXTERNAL_ACCESS 2. Create a managed stored procedure by executing the following statement: CREATE PROCEDURE clrproc AS EXTERNAL NAME ConvertXMLAssembly.[CLRStoredProcedure.XMLProc].convXml [...]... zip _code; } NIIT Implementing Managed Code 9.17 public void Read(BinaryReader r) // Displaying the data to the user { zip _code = r.ReadString(); } public void Write(BinaryWriter w) // Inserting the data in the table { if (zip _code == "CA") { w.Write("State : California"); } else if (zip _code == "NY") { w.Write("State : New York"); } else { w.Write("State : Invailid, " + zip _code) ; } } } To create the managed. .. the F5 key to execute the statement Implementing Managed Code 9.23 Practice Questions 1 What is the NET Framework CLR? 2 What is the syntax of creating an assembly in the SQL Server? 3 When should you use managed code instead of T-SQL? 4 How will you enable CLR in a database? 5 Which type of connection will you use in a managed function? 9.24 Implementing Managed Code NIIT Summary In this chapter, you... EXTERNAL NAME ZipAssembly.ZipCode The data type will be associated with the default dbo 9.18 Implementing Managed Code NIIT You can execute the following statement to create a table using the ZipCode user-defined type: CREATE TABLE ManagedEmployee ( Name nvarchar(20), Zip ZipCode ) Just a minute: When will you use managed code instead of T-SQL? 1 When you need to write queries 2 When you need to access external... } public static ZipCode Null // the ZipCode property { get { ZipCode sd = new ZipCode(); sd.isNull = true; return sd; } } public ZipCode(string s) // The constructor of the structure { isNull = false; zip _code = s; } public static ZipCode Parse(SqlString s) // The parser { string value = s.Value; if (s.IsNull || value.Trim() == "") return Null; string zip = value; return new ZipCode(zip); } public... compared to the managed code By default, the SQL Server does not allow running managed code on the server Before creating a managed database object in your database, the CLR integration feature should be enabled in the database using the sp_configure stored procedure The NET code that is used to create the managed database objects are compiled in NET assemblies, dll or exe files To create a managed database... using the ZipCode.dll assembly file, you can perform the following steps: 1 Execute the following statement to create an assembly named ZipAssembly from the ZipCode.dll file: CREATE ASSEMBLY ZipAssembly FROM ‘C:\ZipCode.dll’ WITH PERMISSION_SET = UNSAFE 2 Execute the following statement to create a managed user-defined type named ZipCode: CREATE TYPE ZipCode EXTERNAL NAME ZipAssembly.ZipCode The data... System.Text; System.IO; 9.16 Implementing Managed Code NIIT using System.Runtime.InteropServices; [Serializable] [Microsoft.SqlServer.Server.SqlUserDefinedType(Format.UserDefined, MaxByteSize = 8000)] // Specifying that the code will be used as User-Defined data type public struct ZipCode : IBinarySerialize, INullable // Implementing the required interface { private string zip _code; //Declaring the private... following three permissions: SAFE EXTERNAL_ACCESS UNSAFE Managed stored procedure can be created using the CREATE PROCEDURE command Managed function can be created using the CREATE FUNCTION command Managed trigger can be created using the CREATE TRIGGER command Managed data type can be created using the CREATE TYPE command NIIT Implementing Managed Code 9.25 Exercises Exercise 1 The AdventureWorks database... SpouseDetails.dll file: CREATE ASSEMBLY SpouseDet FROM ‘C:\SpouseDetails.dll’ 9.22 Implementing Managed Code NIIT 2 Press the F5 key to execute the statement Task 3: Creating a Managed Database User-Defined Data Type To create a managed database user-defined data type, you need to perform the following steps: 1 Type the following statement to create managed user-defined type named Spouse_Details: CREATE TYPE Spouse_Details... a new employee are inserted, the zip code of the state should be converted in the state name For example, is the zip code is “CA” then it should be converted into “State: California” For this, you need to create a managed user-defined type To create the user-defined type, you have the ZipCode.dll assembly file created by the development team, using the following code: using using using using using using . compared to the managed code. However, the managed code is pre-compiled and faster to execute within the CLR. Identifying the Need for Managed Code ¤NIIT Implementing Managed Code 9.5 Just. user-defined types by using managed code. In this chapter, you will learn to: Understand managed code Create managed database objects Objectives ¤NIIT Implementing Managed Code 9.3 As a database. Object-Orientation 9.6 Implementing Managed Code ¤NIIT To create managed database objects in the SQL Server, you need to first create a managed code in any of the .NET programming languages. A managed code contains