Programando SQL Server 2005 con el CLR Integración SQLCLR.

Slides:



Advertisements
Similar presentations
Using the SQL Access Advisor
Advertisements

Aprovechando XML dentro de la base de datos con SQL Server 2005.
1 Senn, Information Technology, 3 rd Edition © 2004 Pearson Prentice Hall James A. Senns Information Technology, 3 rd Edition Chapter 7 Enterprise Databases.
1 Concurrency: Deadlock and Starvation Chapter 6.
Distributed Systems Architectures
Copyright © 2003 Pearson Education, Inc. Slide 8-1 Created by Cheryl M. Hughes, Harvard University Extension School Cambridge, MA The Web Wizards Guide.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Introduction to ASP.NET.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Yukon – What is New Rajesh Gala. Yukon – What is new.NET Framework Programming Data Types Exception Handling Batches Databases Database Engine Administration.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 5: Repetition and Loop Statements Problem Solving & Program.
17. Data Access ADO.Net Architecture New Features of ADO.NET
12 Copyright © 2005, Oracle. All rights reserved. Query Rewrite.
18 Copyright © 2005, Oracle. All rights reserved. Distributing Modular Applications: Introduction to Web Services.
1 Copyright © 2005, Oracle. All rights reserved. Introducing the Java and Oracle Platforms.
9 Copyright © 2005, Oracle. All rights reserved. Modularizing JavaServer Pages Development with Tags.
1 Term 2, 2004, Lecture 6, Views and SecurityMarian Ursu, Department of Computing, Goldsmiths College Views and Security 3.
Chapter 6 File Systems 6.1 Files 6.2 Directories
Server Access The REST of the Story David Cleary
13 Copyright © 2005, Oracle. All rights reserved. Monitoring and Improving Performance.
Database Performance Tuning and Query Optimization
Pharos Uniprint 8.3 Training
Campaign Overview Mailers Mailing Lists
Chapter 1 Object Oriented Programming 1. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
MySQL Access Privilege System
1 Web-Enabled Decision Support Systems Access Introduction: Touring Access Prof. Name Position (123) University Name.
1 tRelational/DPS Overview. 2 ADABAS Data Transfer: business needs and issues tRelational & DPS Overview Summary Questions? Demo Agenda.
ADO.NET 2.0 y SQL Server SQL Server 2005 para desarrolladores Solid Quality Learning Adolfo Wiernik Microsoft Regional Director.
1 What is JavaScript? JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight.
4 Oracle Data Integrator First Project – Simple Transformations: One source, one target 3-1.
Database System Concepts and Architecture
31242/32549 Advanced Internet Programming Advanced Java Programming
Chapter 9: The Client/Server Database Environment
Executional Architecture
Using.NET Platform Note: Most of the material of these slides have been taken & extended from Nakov’s excellent overview for.NET framework, MSDN and wikipedia.
Chapter 9 Interactive Multimedia Authoring with Flash Introduction to Programming 1.
PSSA Preparation.
Chapter 13 The Data Warehouse
©Ian Sommerville 2004Software Engineering, 7th edition. Chapter 13 Slide 1 Application architectures.
South Dakota Library Network MetaLib User Interface South Dakota Library Network 1200 University, Unit 9672 Spearfish, SD © South Dakota.
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
1 Programming Languages (CS 550) Mini Language Interpreter Jeremy R. Johnson.
SSRS 2008 Architecture Improvements Scale-out SSRS 2008 Report Engine Scalability Improvements.
ASP.NET Best Practices Dawit Wubshet Park University.
Advantage Data Dictionary. agenda Creating and Managing Data Dictionaries –Tables, Indexes, Fields, and Triggers –Defining Referential Integrity –Defining.
Managing and Monitoring SQL Server 2005 Shankar Pal Program Manager SQL Server, Redmond.
Windows.Net Programming Series Preview. Course Schedule CourseDate Microsoft.Net Fundamentals 01/13/2014 Microsoft Windows/Web Fundamentals 01/20/2014.
Architecture Of ASP.NET. What is ASP?  Server-side scripting technology.  Files containing HTML and scripting code.  Access via HTTP requests.  Scripting.
Rationale Aspiring Database Developers should be able to efficiently query and maintain databases. This module will help students learn the Structured.
Programming the CLR in SQL Server 2005 Mark Blomsma Develop-One Session Code: DB.08.
Database Design for DNN Developers Sebastian Leupold.
An Introduction To CLR Integration in SQL Server 2005 (Yukon) Dr Greg Low.
Native Support for Web Services  Native Web services access  Enables cross platform interoperability  Reduces middle-tier dependency (no IIS)  Simplifies.
Chapter 6 : Designing SQL Server Service-Level Security MCITP Administrator: Microsoft SQL Server 2005 Database Server Infrastructure Design Study Guide.
DBSQL 14-1 Copyright © Genetic Computer School 2009 Chapter 14 Microsoft SQL Server.
Security David Frommer Principal Architect Business Intelligence Microsoft Partner of the Year 2005 & 2007.
5/24/01 Leveraging SQL Server 2000 in ColdFusion Applications December 9, 2003 Chris Lomvardias SRA International
Database Design and Management CPTG /23/2015Chapter 12 of 38 Functions of a Database Store data Store data School: student records, class schedules,
ASP.NET OPTIMIZATION. Why Optimize? $$$ Whether you build applications for customers or not, enhanced applications save money.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
IT System Administration Lesson 3 Dr Jeffrey A Robinson.
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
SQL Server 2005 Implementation and Maintenance Chapter 6: Security and SQL Server 2005.
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
SQL Triggers, Functions & Stored Procedures Programming Operations.
In this session, you will learn to: Understand managed code Create managed database objects Define the Hypertext Transfer Protocol endpoints Implement.
SQL Server 2005:.NET Framework Programming in the Database Tim Sneath Architectural Engineer, Microsoft
Module 10: Implementing Managed Code in the Database
Chapter 8 Advanced SQL.
Presentation transcript:

Programando SQL Server 2005 con el CLR Integración SQLCLR

2 SQL Server 2005 para desarrolladores Solid Quality Learning Adolfo Wiernik Microsoft Regional Director - Mentor Solid Quality Learning - Fundador, Costa Rica User Group.NET - Orador INETA Latinoamérica - Blog - Jose Ricardo Ribeiro En Microsoft desde 1998 Desde el Regional Program Manager SQL Server Latinoamérica

3 SQL Server 2005 para desarrolladores Solid Quality Learning Series de Webcasts Introducción a SQL Server 2005 para desarrolladores Viernes, 22 de Julio de :00 p.m.(GMT) e=es-MX e=es-MX Nuevas características del lenguaje T-SQL en SQL Server 2005 Lunes, 25 de Julio de :00 p.m.(GMT) e=es-MX e=es-MX Aprovechando XML dentro de la base de datos con SQL Server 2005 Viernes, 29 de Julio de :00 p.m.(GMT) e=es-MX e=es-MX Programando SQL Server 2005 con el CLR – Integración SQL-CLR Lunes, 01 de Agosto de :00 p.m.(GMT) e=es-MX e=es-MX Nuevas características en ADO.NET 2.0 Viernes, 05 de Agosto de :00 p.m.(GMT) e=es-MX e=es-MX

4 SQL Server 2005 para desarrolladores Solid Quality Learning Agenda Integración SQL Server - Common Language Runtime Beneficios Ventajas Porque Objetivos de Diseño Arquitectura Catalogando Assemblies Construyendo objetos SQLCLR User Defined Functions User Defined Aggregate Functions User Defined Types CLR Stored Procedures CLR Triggers

5 SQL Server 2005 para desarrolladores Solid Quality Learning.NET Framework Common Language Runtime Integration User-defined Aggregates User-defined Data Types User-defined Functions SQL Server.NET Data Provider Extended Triggers Data Types Managed SQL Types New XML Datatype Varchar (MAX) Varbinary (MAX) XML XQUERY Support XML Data Manipulation Language FOR XML Enhancements XML Schema (XSD) Support MSXML 6.0 (Native).Net XML Framework Full-text Search Indexing of XML Datatype MDAC SNAC Microsoft Installer base setup ADO.NET 2.0 Notification Support Object Model enhancements SQL Client.NET Data Provider Server Cursor Support Asynchronous Execution System.Transactions Security Separation of Users and Schema Data encryption primitives Administration SQL Management Objects (SMO) Analysis Management Objects (AMO) Replication Management Objects (RMO) T-SQL Recursive Queries Common Table Expressions PIVOT – UNPIVOT Operators APPLY Operator Exception Handling SQL Server Engine SQL Service Broker HTTP Support (Native HTTP) Multiple Active Result Sets (MARS) Snapshot Isolation Level Reporting Services Multiple Output Formats Parameters (Static, Dynamic, Hierarchical) Bulk Delivery of Personalized Content Support Multiple Data Sources STS (Web Parts, Doc Libraries) Visual Design Tool Charting, Sorting, Filtering, Drill- Through Scheduling, Caching Complete Scripting Engine Scale Out architecture Open XML Report Definition Notification Services SQL Server Mobile Edition Nuevas Características para Desarrollo

6 SQL Server 2005 para desarrolladores Solid Quality Learning SQL Server as a runtime host Using assemblies Procedural code or Transact-SQL Writing.NET procedural code.NET data types and System.Data.SqlTypes Attributes Agenda

7 SQL Server 2005 para desarrolladores Solid Quality Learning Benefits Better programming model Improved safety and security Ability to define data types and aggregate functions Streamlined development through a standardized environment Potential for improved performance and scalability

8 SQL Server 2005 para desarrolladores Solid Quality Learning Advantages? When to use Transact-SQL: designed for direct data access and manipulation in the database Transact-SQL does not support : arrays Collections for-each loops bit shifting classes When to use Managed Code: Calculations complicated execution logic extensive support for many complex tasks including string handling and regular expressions, advanced math operations, file access, cryptography access to thousands of pre-built classes and routines

9 SQL Server 2005 para desarrolladores Solid Quality Learning Why? You can author (in managed code) stored procedures Triggers user-defined functions user-defined types user-defined aggregates

10 SQL Server 2005 para desarrolladores Solid Quality Learning Design Goals for SQL CLR Integration Reliability User code should not be allowed to perform operations that compromise the integrity of the database engine process or overwrite database engine memory buffers or internal data structures Scalability ensure that the scalability of the system is not compromised by user code calling application programming interfaces (APIs) for threading, memory, and synchronization primitives directly Security User code must follow SQL Server authentication and authorization rules when accessing database objects such as tables and columns, database administrators should be able to control access to operating system resources from user code Performance must perform as well or better than equivalent implementations by native database engine functionality or through Transact- SQL

11 SQL Server 2005 para desarrolladores Solid Quality Learning SQL CLR Integration Architecture CLR calls low-level routines implemented by SQL Server for threading, scheduling, synchronization, and memory management Same primitives that the rest of the SQL Server engine uses Enforce: Scalability, Reliability, Security & Performance Win32 API Windows OS Low level routines SQL Server JIT Compiler Common Language Runtime Metadata MSIL Assembly

12 SQL Server 2005 para desarrolladores Solid Quality Learning Scalability Memory Management: CLR calls SQL Server primitives for allocating and de-allocating its memory ensures that the CLR and SQL Server are not competing with each other for memory This allows SQL Server memory manager to: reject CLR memory requests when system memory is constrained ask CLR to reduce its memory use when other tasks need memory Threading CLR calls SQL Server APIs for creating threads Both for running user code and for its own internal use To synchronize, CLR calls SQL Server synchronization objects This allows the SQL Server scheduler to control threading, for example: schedule other tasks when a thread is waiting on a synchronization object (for example, while GC) detect deadlocks that involve locks taken by CLR synchronization objects ability to detect and stop threads that have not yielded for a significant amount of time identify "runaway" threads in the CLR and manage their priority

13 SQL Server 2005 para desarrolladores Solid Quality Learning Reliability Programming Model: The programming model for managed code in SQL Server involves writing functions, procedures, and types which typically do not require the use of state held across multiple invocations or the sharing of state across multiple user sessions. The presence of shared state can cause critical exceptions that impact the scalability and the reliability of the application. Avoid the use of static variables and static data members of classes used in SQL Server. For SAFE and EXTERNAL-ACCESS assemblies, SQL Server examines the metadata of the assembly at CREATE ASSEMBLY time, and fails the creation of such assemblies if it finds the use of static data members and variables SAFE and EXTERNAL ACCESS assemblies cannot be annotated with some custom attributes Example: System.Security.SuppressUnmanagedCodeSecurityAttribute, System.ContextStaticAttribute System.MTAThreadAttribute Check complete list in BOL Depend only on blessed list of assemblies Hard coded list of revised assemblies List can not be extended

14 SQL Server 2005 para desarrolladores Solid Quality Learning Security Code Access Security (CAS) Machine Policy User Policy specific to the Windows account that the SQL Server service is set up to run as Host Policy (SQL Server) The permissions granted to code in SQL Server is the intersection of permissions granted by the above three policy levels The set of CAS permissions granted to assemblies by the SQL Server Host policy level is determined by the permission set specified when creating the assembly SAFE EXTERNAL_ACCESS UNSAFE Microsoft Frameworks assemblies and SQL Server system assemblies use a fixed policy that grants them full trust

15 SQL Server 2005 para desarrolladores Solid Quality Learning Security - SAFE Default permission set Code cannot access external system resources: files, the network, environment variables, or the registry can only access data from the local SQL Server databases And perform any computation on that data Recommended permission set

16 SQL Server 2005 para desarrolladores Solid Quality Learning Security – EXTERNAL_ACCESS Allows access to certain external system resources files, networks, web services, environmental variables, and the registry Can only access assemblies that are verifiably type-safe Only SQL Server logins with EXTERNAL ACCESS permissions can create EXTERNAL_ACCESS assemblies Code in EXTERNAL_ACCESS assemblies runs by default under the SQL Server service account and accesses external resources under that account (unless the code explicitly impersonates the caller). Permission to create EXTERNAL_ACCESS assemblies should be granted only to logins who are trusted to execute code under the SQL Server service account

17 SQL Server 2005 para desarrolladores Solid Quality Learning Security - UNSAFE Unrestricted access to resources, both within and outside SQL Server Can call unmanaged code Can execute type-unsafe code Should be granted only to highly trusted assemblies Only members of the sysadmin fixed server role can create UNSAFE assemblies

18 SQL Server 2005 para desarrolladores Solid Quality Learning Enabling CLR Integration Off by default EXEC sp_configure 'show advanced options', 1 GO RECONFIGURE GO sp_configure 'clr enabled', 1 GO RECONFIGURE GO

19 SQL Server 2005 para desarrolladores Solid Quality Learning Cataloging assemblies CREATE ASSEMBLY is used to catalog an assembly bits can be loaded from disk or stream assembly is assigned a symbolic name bits are stored in system table SQL Server principal running create must have assembly catalog permissions file system access to the code CREATE ASSEMBLY math FROM 'c:\types\math.dll' symbolic name assembly name

20 SQL Server 2005 para desarrolladores Solid Quality Learning Removing assemblies DROP ASSEMBLY removes an assembly from catalog dependent sprocs, udfs, triggers, udts must be dropped first includes tables and computed columns that use them will fail if another assembly depends on it DROP ASSEMBLY math removes math assembly

21 SQL Server 2005 para desarrolladores Solid Quality Learning Assembly metadata information SQL Server has revised system metadata views no direct access to system metadata assembly information lives in sys.assemblies sys.assembly_files sys.assembly_references

22 SQL Server 2005 para desarrolladores Solid Quality Learning What can be built? User Defined Functions (UDFs) ¤ Scalar valued (scalar UDF) Table valued (TVF) User Defined Procedures (UDP) ¤ User Defined Types (UDTs) ŧ User Defined Triggers ¤ User Defined Aggregates ŧ ¤ Mapped to public static function ŧ Mapped to entire class

23 SQL Server 2005 para desarrolladores Solid Quality Learning Basics Needed namespaces: System.Data System.Data.Sql Microsoft.SqlServer.Server Server-side provider SqlContext System.Data.SqlTypes

24 SQL Server 2005 para desarrolladores Solid Quality Learning System.Data.SqlTypes Provides data types with same semantics & precision as in SQL Server NULL values Not supported for value types in.NET 1.*.NET 2.* presents Nullable generic Boolean values with 3 values True, False & Unknown IsTrue(), IsFalse(), IsNull() in SqlBoolean Arithmetic & Bitwise Operators should accept null values Overflow detection off by default in.NET, on by default on SqlTypes

25 SQL Server 2005 para desarrolladores Solid Quality Learning User Defined Functions Implemented as public static method in class Can take parameters Should return a result Type of UDFs: Scalar, returns a single value Table, returns result set Benefits: Allow modular programming Allow faster execution Can reduce network traffic Can be invoked on WHERE to filter rows sent to client

26 SQL Server 2005 para desarrolladores Solid Quality Learning User Defined Functions Scalar UDFs : Can return any scalar data type except text, ntext, image TVFs, return type is IEnumerable / IEnumerator Returns a streaming result set Results can be consumed as soon as first row is available Results dont have to be loaded in memory as a whole

27 SQL Server 2005 para desarrolladores Solid Quality Learning User Defined Functions Steps for scalar UDFs: 1.Create a class with public static method Mark method with SqlFunction attribute 2.Register assembly CREATE ASSEMBLY asm_Calculos FROM 'Calculos.dll' 3.Register function CREATE FUNCTION int) RETURNS int AS EXTERNAL NAME asm_Calculos.[FuncionesCalculos].GetList

28 SQL Server 2005 para desarrolladores Solid Quality Learning User Defined Aggregate Functions Operate on a set of input scalars Generate a single aggregate result Examples: SUM, AVG, MAX Previously one needed to write complex cursor logic (either client side or server side) Query processor manages iteration Magnitud faster than using cursors

29 SQL Server 2005 para desarrolladores Solid Quality Learning User Defined Aggregate Functions CLR must: Mark type with SqlUserDefinedAggregate attribute IsInvariantToDuplicates {true, false} Example: MIN, MAX IsInvariantToNulls {true, false} Example: AVG, MIN, SUM, MAX IsInvariantToOrder {true, false} Example: AVG, MIN, SUM, MAX IsNullIfEmpty {true, false} Have a public constructor Special aggregation methods Init() Accumulate() Merge() Terminate()

30 SQL Server 2005 para desarrolladores Solid Quality Learning User Defined Aggregate Functions CREATE AGGREGATE name (input params) RETURNS out param EXTERNAL NAME assembly.class name

31 SQL Server 2005 para desarrolladores Solid Quality Learning User Defined Types Can be used wherever a SQL Server type can be used Tip :: create it as a structure, although class is also supported Requirements: Mark with SqlUserDefinedType attribute Must have a public constructor Restrictions: Name must be less than 128 characters No method overloading (except constructor) No support for inheritance Static members cant be mutable (must be const or readonly)

32 SQL Server 2005 para desarrolladores Solid Quality Learning User Defined Type Things to keep in mind: Nullability Serialization Binary, for comparisons, indexing, contraining, etc. XML, for exchanging and searching String comparisons Validation & Comparisons

33 SQL Server 2005 para desarrolladores Solid Quality Learning User Defined Type CREATE TYPE name [NULL | NOT NULL] EXTERNAL NAME assembly.class Assembly and type are registered per database If want to share between databases, then it must be registered in all databases Assembly must be equivalent strong name match If want to use UDT in tempDB, then it must be registered also in tempDB

34 SQL Server 2005 para desarrolladores Solid Quality Learning CLR Stored Procedures Cant be used in scalar expressions Can return: Output Parameters Use byref parameters in CLR Tabular Results Use SqlContext.Pipe.Execute() Most efficient, sends stream directly to client Use SqlContext.Pipe.Send() Allows for manipulation of results before sending to client Can return SqlDataReader SqlDataRecord Allows for dynamic result sets, manually populated Send through SqlContext.Pipe.Send Messages Use SqlContenxt.Pipe.Send() Same as PRINT CREATE PROCEDURE name AS EXTERNAL NAME Assembly.Class.Metodo

35 SQL Server 2005 para desarrolladores Solid Quality Learning CLR Triggers With CLR triggers, you can: Reference data in the INSERTED and DELETED tables Determine which columns have been modified as a result of an UPDATE operation Access information about database objects affected by the execution of DDL statements SqlContext.GetTriggerContext() is a factory for SqlTriggerContext class Provides context information about the trigger Type of action that triggered Modified columns in UPDATE If DDL, XML EventData structure with description of operation

36 SQL Server 2005 para desarrolladores Solid Quality Learning CLR Trigger CREATE TRIGGER triggerName ON DBObject FOR INSERT{action} AS EXTERNAL NAME assembly.class.method

37 SQL Server 2005 para desarrolladores Solid Quality Learning Conclusiones Integración SQL Server - Common Language Runtime Beneficios Ventajas Porque Objetivos de Diseño Arquitectura Catalogando Assemblies Construyendo objetos SQLCLR User Defined Functions User Defined Aggregate Functions User Defined Types CLR Stored Procedures CLR Triggers

SQL Server 2005 para desarrolladores Solid Quality Learning 38 Recursos SQL Server 2005 – Laboratorios Virtuales (only supports SQL 2000) SQL Server SQL Server Express Visual Studio

39 SQL Server 2005 para desarrolladores Solid Quality Learning Series de Webcasts Introducción a SQL Server 2005 para desarrolladores Viernes, 22 de Julio de :00 p.m.(GMT) e=es-MX e=es-MX Nuevas características del lenguaje T-SQL en SQL Server 2005 Lunes, 25 de Julio de :00 p.m.(GMT) e=es-MX e=es-MX Aprovechando XML dentro de la base de datos con SQL Server 2005 Viernes, 29 de Julio de :00 p.m.(GMT) e=es-MX e=es-MX Programando SQL Server 2005 con el CLR – Integración SQL-CLR Lunes, 01 de Agosto de :00 p.m.(GMT) e=es-MX e=es-MX Nuevas características en ADO.NET 2.0 Viernes, 05 de Agosto de :00 p.m.(GMT) e=es-MX e=es-MX

Gracias Weblog: