Module 9Using Service BrokerContents:Lesson 1: Service Broker Overview              9-2Lesson 2: Creating Service Broker O...
Information in this document, including URL and other Internet Web site references, is subject to changewithout notice. Un...
Module 9: Using Service Broker   9–1**************************************** Illegal for non-trainer use *****************...
9–2      Module 9: Using Service BrokerLesson 1: Service Broker Overview**************************************** Illegal f...
Module 9: Using Service Broker    9–3What Is Service Broker?**************************************** Illegal for non-train...
9–4       Module 9: Using Service Broker                            For More Information For more information about the ad...
Module 9: Using Service Broker     9–5Service Broker System Architecture**************************************** Illegal f...
9–6       Module 9: Using Service Broker                            For More Information For more information about contra...
Module 9: Using Service Broker    9–7Service Broker Conversation Architecture**************************************** Ille...
9–8      Module 9: Using Service BrokerDialog conversation        All messages sent by Service Broker are part of a conver...
Module 9: Using Service Broker     9–9Remote service binding   A remote service binding establishes a relationship between...
9–10     Module 9: Using Service BrokerService Broker Conversation Process**************************************** Illegal...
Module 9: Using Service Broker   9–117. The SubmitExpense service receives the ClaimResponse message and places the   mess...
9–12      Module 9: Using Service BrokerService Broker Security Architecture**************************************** Illeg...
Module 9: Using Service Broker    9–13Transport security   Service Broker uses transport security to establish a secure, a...
9–14     Module 9: Using Service BrokerLesson 2: Creating Service Broker Objects**************************************** I...
Module 9: Using Service Broker    9–15Syntax for Creating Message Types**************************************** Illegal fo...
9–16    Module 9: Using Service Broker                          For More Information For more information about XML schema...
Module 9: Using Service Broker    9–17Syntax for Creating Contracts**************************************** Illegal for no...
9–18    Module 9: Using Service Broker                          Specifying the DEFAULT option indicates that this contract...
Module 9: Using Service Broker   9–19Syntax for Creating Queues**************************************** Illegal for non-tr...
9–20    Module 9: Using Service Broker                          Parameter                    Description                  ...
Module 9: Using Service Broker     9–21Syntax for Creating Services**************************************** Illegal for no...
9–22   Module 9: Using Service Broker                            CREATE SERVICE [//Adventure-Works.com/SubmitExpense]     ...
Module 9: Using Service Broker   9–23Demonstration: Creating Service Broker Objects***************************************...
9–24   Module 9: Using Service Broker                                  ●     Enable Service Broker in the AdventureWorks d...
Module 9: Using Service Broker   9–25Lesson 3: Sending and Receiving Messages**************************************** Ille...
9–26     Module 9: Using Service BrokerSyntax for Sending Messages**************************************** Illegal for non...
Module 9: Using Service Broker   9–27The following table summarizes the parameters of the BEGIN DIALOG statement.Parameter...
9–28    Module 9: Using Service BrokerSending the message       Once you have a dialog handle identifier, you can send you...
Module 9: Using Service Broker   9–29Syntax for Receiving Messages**************************************** Illegal for non...
9–30   Module 9: Using Service Broker                         that has the same service instance identifier. RECEIVE remov...
Module 9: Using Service Broker    9–31Checking the message      To ensure that you are dealing with the correct type of me...
9–32     Module 9: Using Service BrokerDemonstration: Sending and Receiving Messages**************************************...
Module 9: Using Service Broker   9–334. Select and execute the following EXECUTE statement to send a message to the   Emai...
9–34       Module 9: Using Service BrokerLab: Implementing a Service Broker Solution**************************************...
Module 9: Using Service Broker    9–35■   Use the following details to create a message type that will be used to pass    ...
9–36     Module 9: Using Service Broker                             ■   After you have created the EMailSvc.uspSendCustome...
Module 9: Using Service Broker   9–37Preparation   Ensure that virtual machine 2779A-MIA-SQL-09 is running and that you ar...
9–38     Module 9: Using Service BrokerExercise 1: Creating Service Broker ObjectsCreating Service Brokerobjects in the   ...
Module 9: Using Service Broker    9–39Exercise 2: Implementing the Initiating ServiceImplementing theCustomerService servi...
9–40     Module 9: Using Service BrokerExercise 3: Implementing the Target ServiceImplementing theEmailService service    ...
9767409 - Using Service Broker
9767409 - Using Service Broker
Upcoming SlideShare
Loading in...5
×

9767409 - Using Service Broker

2,109

Published on

SQL - Using Service Broker

Published in: Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,109
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

9767409 - Using Service Broker

  1. 1. Module 9Using Service BrokerContents:Lesson 1: Service Broker Overview 9-2Lesson 2: Creating Service Broker Objects 9-14Lesson 3: Sending and Receiving Messages 9-25Lab: Implementing a Service Broker Solution 9-34
  2. 2. Information in this document, including URL and other Internet Web site references, is subject to changewithout notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with anyreal company, organization, product, domain name, e-mail address, logo, person, place or event is intended orshould be inferred. Complying with all applicable copyright laws is the responsibility of the user. Withoutlimiting the rights under copyright, no part of this document may be reproduced, stored in or introduced intoa retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying,recording, or otherwise), or for any purpose, without the express written permission of MicrosoftCorporation.The names of manufacturers, products, or URLs are provided for informational purposes only and Microsoftmakes no representations and warranties, either expressed, implied, or statutory, regarding thesemanufacturers or the use of the products with any Microsoft technologies. The inclusion of a manufacturer orproduct does not imply endorsement of Microsoft of the manufacturer or product. Links are provided tothird party sites. Such sites are not under the control of Microsoft and Microsoft is not responsible for thecontents of any linked site or any link contained in a linked site, or any changes or updates to such sites.Microsoft is not responsible for webcasting or any other form of transmission received from any linked site.Microsoft is providing these links to you only as a convenience, and the inclusion of any link does not implyendorsement of Microsoft of the site or the products contained therein.Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rightscovering subject matter in this document. Except as expressly provided in any written license agreementfrom Microsoft, the furnishing of this document does not give you any license to these patents, trademarks,copyrights, or other intellectual property.©2006 Microsoft Corporation. All rights reserved.Microsoft, JScript, MSDN, Outlook, PowerPoint, Visual Basic, Visual C#, Visual C++, Visual FoxPro, Windows,and Windows Server are either registered tradmarks or trademarks of Microsoft Corporation in the UnitedStates and/or other countries.The names of actual companies and products mentioned herein may be the trademarks of their respectiveowners.
  3. 3. Module 9: Using Service Broker 9–1**************************************** Illegal for non-trainer use ***************************************Module objectives After completing this module, students will be able to: ■ Describe Service Broker functionality and architecture. ■ Create Service Broker objects. ■ Send and receive Service Broker messages.Introduction Service-oriented architecture (SOA) has become an important concept in the design of large-scale distributed applications. The ability of services to communicate using a reliable message-based mechanism is central to SOA. This module introduces Microsoft® SQL Server™ 2005 Service Broker, a message-based platform for building service-oriented database solutions. The module summarizes the architecture and functionality of Service Broker, explains how to create Service Broker objects, and describes how to send and receive Service Broker messages.
  4. 4. 9–2 Module 9: Using Service BrokerLesson 1: Service Broker Overview**************************************** Illegal for non-trainer use ***************************************Lesson objectives After completing this lesson, students will be able to: ■ Describe the purpose of Service Broker. ■ Describe the Service Broker system architecture. ■ Describe the Service Broker conversation architecture. ■ Describe the Service Broker conversation process. ■ Describe the Service Broker security architecture.Introduction As a SQL Server database developer, you might need to build service-oriented solutions that are highly scalable and require asynchronous communication between services. SQL Server 2005 includes Service Broker, a platform for message-based solutions. This lesson provides an introduction to Service Broker. The lesson describes what Service Broker is, its architecture, and the process it uses to manage message-based conversations.
  5. 5. Module 9: Using Service Broker 9–3What Is Service Broker?**************************************** Illegal for non-trainer use ***************************************Introduction Service Broker is a platform for building secure, reliable, and scalable applications in SQL Server 2005. Service Broker reduces application development time by providing much of the infrastructure that is necessary to build distributed applications and makes it easy to scale your application to accommodate the amount of traffic the application receives. Service Broker helps developers to compose applications from independent, self- contained components called services. Applications that require the functionality of these services use messages to interact with them. Service Broker uses Transmission Control Protocol/Internet Protocol (TCP/IP) to exchange messages between instances and includes features to help prevent unauthorized access from the network and to encrypt messages sent over the network.Advantages of Service Service Broker is applicable both for applications that use a single SQL Server instanceBroker and applications that distribute work across multiple instances. Within a single SQL Server instance, Service Broker provides a robust asynchronous programming model. Between SQL Server instances, Service Broker provides a secure and reliable messaging infrastructure. Service Broker features provide the following benefits to database applications: ■ Database integration that enhances application performance and simplifies administration ■ Message ordering and coordination for simplified application development ■ Loose application coupling that provides workload flexibility ■ Related message locking that allows more than one instance of an application to process messages from the same queue without explicit synchronization ■ Automatic activation that allows applications to scale with the message volume
  6. 6. 9–4 Module 9: Using Service Broker For More Information For more information about the advantages of Service Broker, see “Advantages of Service Broker” in SQL Server Books Online.Typical uses of Service Service Broker can be useful for any application that needs to perform processingBroker asynchronously or that needs to distribute processing across a number of computers. Typical uses of Service Broker include the following: ■ Asynchronous triggers ■ Reliable query processing ■ Reliable data collection ■ Distributed server-side processing for client applications ■ Data consolidation for client applications ■ Large-scale batch processing For More Information For more information about the uses of Service Broker, see “Typical Uses of Service Broker” in SQL Server Books Online.
  7. 7. Module 9: Using Service Broker 9–5Service Broker System Architecture**************************************** Illegal for non-trainer use ***************************************Introduction Service Broker applications are made up of the following Service Broker database object types, and one or more service programs that use those objects: ■ Message type ■ Contract ■ Queue ■ ServiceMessage type Applications that use Service Broker communicate by sending messages to one another as part of a conversation. The participants in a conversation must agree on the name and content of each message. A message type object defines a name for a message type and defines the type of data that the message contains. Message types persist in the database in which the message type is created. You must create an identical message type in each database that participates in a conversation. For More Information For more information about message types, see “Message Types [Service Broker]” in SQL Server Books Online.Contract A contract is an agreement between two services about which messages each service sends to accomplish a particular task. The contract also specifies which participant in the conversation can use each message type. Some message types can be sent by either participant; other message types are restricted and can be sent only by the initiator or only by the target. A contract must define at least one message type sent by the initiator or a message type sent by either conversation participant; otherwise, there is no way for the initiator to begin a conversation that uses the contract. Contract definitions persist in the database in which the contract is created. You must create an identical contract in each database that participates in a conversation.
  8. 8. 9–6 Module 9: Using Service Broker For More Information For more information about contracts, see “Contracts [Service Broker]” in SQL Server Books Online.Queue Queues store messages. Each service is associated with one queue. When a message arrives for a service, Service Broker places the message in the queue associated with that service. To get messages that have been sent to the service, an application retrieves messages from the queue. Service Broker manages queues and presents a view of a queue that is similar to a table. Each message is a row in the queue. The row contains the content of the message as well as information about the message type, the service targeted by the message, the contract that the message follows, the validation performed on the message, the conversation that the message is a part of, and information internal to the queue. An application uses the information in the message row to identify each message uniquely and process the message appropriately. For More Information For more information about queues, see “Queues [Service Broker]” in SQL Server Books Online.Service A service object represents the addressable endpoint for a service. The service object defines the name of the queue that will hold the messages for the service and specifies the contracts for which this service can be a provider. If the service does not specify a contract, the service can only initiate a conversation and cannot be a provider. For More Information For more information about services, see “Services [Service Broker]” in SQL Server Books Online.Service program A service program processes the messages sent to a service and provides the logic of the service. Service Broker can automatically activate the service program when each message arrives. Alternatively, you can schedule an event to activate the service program, or you can execute it manually. A service program will often need to send a response message to the initiator of the conversation to complete a task. This response will be part of the same conversation so that the initiator can associate the response with the original request message. For More Information For more information about service programs, see “Building Applications with Service Broker” in SQL Server Books Online.
  9. 9. Module 9: Using Service Broker 9–7Service Broker Conversation Architecture**************************************** Illegal for non-trainer use ***************************************Introduction All Service Broker applications communicate through conversations that are reliable, long-running, asynchronous exchanges of messages. To develop Service Broker applications, you must understand these constructs: ■ Message ■ Dialog conversation ■ Conversation group ■ Route ■ Remote service bindingMessage Messages are the information exchanged between applications that use Service Broker. Each message is part of a conversation. A message has a specific message type, which is determined by the application that sends the message. Each message has a unique conversation identity, as well as a sequence number within the conversation. When receiving messages, Service Broker uses the conversation identity and the sequence number of the message to enforce message ordering. The content of a message is determined by the message type, and the message type is determined by the application. When a message is received, Service Broker validates the content of the message to ensure that the content is valid for the message type. Regardless of the message type, SQL Server stores the content of the message as varbinary(max) in the service’s message queue. Therefore, a message can contain any data that can be converted to varbinary(max). For More Information For more information about messages, see “Messages [Service Broker]” in SQL Server Books Online.
  10. 10. 9–8 Module 9: Using Service BrokerDialog conversation All messages sent by Service Broker are part of a conversation. A dialog conversation, or dialog, is a conversation between two services. A dialog conversation has two participants. The initiator begins the conversation. The target accepts a conversation begun by the initiator. Whether a participant begins the conversation determines the messages that the participant can send, as specified in the contract for the conversation. Dialogs provide exactly-once-in-order (EOIO) message delivery. Dialogs use the conversation identifier and sequence numbers that are contained in each message to identify related messages and deliver messages in the correct order. A dialog is a reliable, persistent stream of messages between two services. When SQL Server receives a message for a dialog, SQL Server places the message in the queue for the dialog. The application receives the message from the queue and processes the message as necessary. As part of the processing, the application can send messages to the other participant in the dialog. The dialog continues until each service program explicitly ends the dialog or an error occurs. You can use a dialog timeout that guarantees that the dialog cannot continue beyond the specified limit. For More Information For more information about dialog conversations, see “Dialog Conversations [Service Broker]” in SQL Server Books Online.Conversation group A conversation group identifies a group of related conversations. A conversation group allows an application to easily coordinate conversations involved in a specific business task. Every conversation belongs to one conversation group. Every conversation group is associated with a specific service, and all conversations in the group are conversations to or from that service. A conversation group can contain any number of conversations. SQL Server uses conversation groups to provide EOIO access to messages that are related to a specific business task. When an application sends or receives a message, SQL Server locks the conversation group to which the message belongs. Thus, only one session at a time can receive messages for the conversation group. The conversation group lock guarantees EOIO processing of messages on each conversation. Because a conversation group can contain more than one conversation, an application can use conversation groups to identify messages related to the same business task and process those messages together. A conversation group is not shared between participants in a conversation. Therefore, each participant in a conversation is free to group that conversation as appropriate. An application can manage complex interactions among services without requiring any special support from the services. For More Information For more information about conversation groups, see “Conversation Groups [Service Broker]” in SQL Server Books Online.Route Service Broker uses a route to direct messages when conversations take place between different instances of SQL Server. This level of redirection allows you to change the SQL Server instance without affecting the conversations. The route provides an address for a specified service that includes a network address and an optional service name. If you do not specify a service name, the route is known as the default route. Service Broker uses this route for nonlocal services only when no other route matches. For More Information For more information about routes, see “Routes [Service Broker]” and “Routing [Service Broker]” in SQL Server Books Online.
  11. 11. Module 9: Using Service Broker 9–9Remote service binding A remote service binding establishes a relationship between a local database user, the certificate for the user, and the name of a remote service. Service Broker uses the remote service binding to provide dialog security for conversations that target the remote service. For More Information For more information about remote service bindings, see “Remote Service Bindings [Service Broker]” in SQL Server Books Online.
  12. 12. 9–10 Module 9: Using Service BrokerService Broker Conversation Process**************************************** Illegal for non-trainer use ***************************************Introduction Service Broker applications will typically be required to do more than send individual messages to a service provider. Often the service consumer will expect to receive a response from the provider to complete a task. A task can extend across multiple conversations and take hours, or even days, to complete.Conversation process The slide shows an example conversation between the SubmitExpense service and theexample ProcessExpense service using a contract named ProcessExpense. The contract specifies two message types, ExpenseClaim and ClaimResponse. The two services are located in different databases within the same instance of SQL Server. The example conversation follows these steps: 1. An employee submits an expense by using a client application such as a Microsoft ASP.NET Web page. The page uses Microsoft ADO.NET to call the SubmitExpense stored procedure. 2. The SubmitExpense stored procedure begins a dialog conversation between the two services and sends an ExpenseClaim message asynchronously to the target endpoint. The SubmitExpense stored procedure ends. 3. The ProcessExpense target service receives the ExpenseClaim message, creates a service instance identifier, and places the message in the ExpenseQueue queue. 4. The arrival of the message in the queue activates the ProcessExpense stored procedure. 5. The processing of the expense begins within the ProcessExpense stored procedure. 6. The ProcessExpense stored procedure sends a ClaimResponse message as part of the same conversation and an EndDialog message to finish the conversation. The ProcessExpense stored procedure ends.
  13. 13. Module 9: Using Service Broker 9–117. The SubmitExpense service receives the ClaimResponse message and places the message in the Expenses queue.8. The arrival of the ClaimResponse message in the queue activates the ExpenseResult stored procedure. The procedure checks the contents of the message and looks for an EndDialog message. If it finds an EndDialog message, the conversation ends and the stored procedure exits.
  14. 14. 9–12 Module 9: Using Service BrokerService Broker Security Architecture**************************************** Illegal for non-trainer use ***************************************Introduction Service Broker helps you to write highly scalable database applications that are also secure and reliable. Service Broker security allows services hosted by different SQL Server instances to communicate securely, even when the instances are on different computers that have no other trust relationship or when the source and destination computers are not connected to the same network at the same time. Service Broker provides two distinct types of security—dialog security and transport security. Understanding these two types of security, and how they work together, will help you to design, deploy, and administer Service Broker applications. For More Information For more information about Service Broker security, see “Security Considerations for Service Broker” in SQL Server Books Online.Certificates Service Broker security can use certificates to verify the identity of a remote database. To verify the identity of a remote server, SQL Server must receive information that can be decrypted by using the public key in a certificate owned by a local database principal. If SQL Server can successfully decrypt the information, the remote database contains the private key that corresponds to the public key in the local certificate. After SQL Server verifies the identity of a remote database, the remote database can act with the permissions of the local database principal. For More Information For more information about Service Broker’s use of certificates, see “Certificates and Service Broker” in SQL Server Books Online. You install a certificate in a database by using the CREATE CERTIFICATE Transact-SQL statement. For More Information For more information about the CREATE CERTIFICATE statement, see “CREATE CERTIFICATE (Transact-SQL)” in SQL Server Books Online.
  15. 15. Module 9: Using Service Broker 9–13Transport security Service Broker uses transport security to establish a secure, authenticated connection between two services engaged in a conversation. Services communicate by sending messages to a Hypertext Transfer Protocol (HTTP) endpoint on the remote server. Endpoints are created by using the CREATE ENDPOINT Transact-SQL statement, and the AUTHENTICATION clause determines which authentication mechanisms the endpoint will support. You can specify that the endpoint will use Microsoft Windows® authentication or certificate-based authentication. For More Information For more information about the CREATE ENDPOINT statement, see “CREATE ENDPOINT (Transact-SQL)” in SQL Server Books Online. For More Information For more information about transport security, see “Service Broker Transport Security” in SQL Server Books Online.Dialog security Service Broker uses dialog security to encrypt messages between remote services and authenticate remote users. Dialog security can be implemented in two ways: full dialog security and anonymous dialog security. For full dialog security, both the database from which the conversation is initiated and the database in which the called service is implemented must contain two users—one with which to send messages to the remote service, and the other to represent the user in the remote database that will send messages to this service. Each service in the conversation must contain a remote service binding that maps the user account for the remote database user to the remote service. A certificate must be associated with each user to authenticate the users. Anonymous dialog security works in the same way as full dialog security, but it does not require that the target service explicitly permits access to a remote user. When anonymous dialog security is used, the target service allows access through a guest account. Regardless of the type of dialog security used, messages are always encrypted with a session key, and the session key itself is encrypted with the database master key. For this reason, any Service Broker conversation between two databases requires that both databases contain a master key. For More Information For more information about dialog security, see “Service Broker Dialog Security” in SQL Server Books Online.
  16. 16. 9–14 Module 9: Using Service BrokerLesson 2: Creating Service Broker Objects**************************************** Illegal for non-trainer use ***************************************Lesson objectives After completing this lesson, students will be able to: ■ Describe the syntax for creating message types. ■ Describe the syntax for creating contracts. ■ Describe the syntax for creating queues. ■ Describe the syntax for creating services. ■ Create service broker objects.Introduction This lesson describes how to create the various objects required when building a simple Service Broker application. This includes the syntax for creating message types, contracts, queues, and services. For More Information For more information about creating service broker applications, see “Service Broker Programming” in SQL Server Books Online.
  17. 17. Module 9: Using Service Broker 9–15Syntax for Creating Message Types**************************************** Illegal for non-trainer use ***************************************Syntax of the CREATE The message type defines the type of data that you will send between your services. YouMESSAGE TYPE Transact- must create at least one message type in a Service Broker application, and you must re-SQL statement create each message type in each database that is involved in the conversation. You define a message type by using the CREATE MESSAGE TYPE Transact-SQL statement, which has the following syntax. CREATE MESSAGE TYPE message_type_name[AUTHORIZATION owner_name] [VALIDATION = {NONE | EMPTY | WELL_FORMED_XML | VALID_XML WITH SCHEMA COLLECTION schema_collection_name}] The message_type_name can be up to 128 characters and cannot be the same as an existing server, database, or schema. The AUTHORIZATION clause sets the owner of the message type to the name of a database user or role. When this clause is omitted, the message type belongs to the current user. The VALIDATION clause specifies the type of data that the message will contain. The following table summarizes the possible values. Value Description NONE No validation is performed. The message body can contain any data or can be NULL. EMPTY The message body must be NULL. WELL_FORMED_ The message body must contain well-formed Extensible Markup XML Language (XML). VALID_XML The message body must contain XML that conforms to a schema in the specified schema collection. The schema_collection_name must be the name of an existing XML schema collection.
  18. 18. 9–16 Module 9: Using Service Broker For More Information For more information about XML schemas, see “Managing XML Schema Collections on the Server” in SQL Server Books Online. For more information about the CREATE MESSAGE TYPE statement, see “CREATE MESSAGE TYPE (Transact-SQL)” in SQL Server Books Online.Using the CREATE The following example shows the definition of two message types in theMESSAGE TYPE AdventureWorks database. The first message type can contain any well-formed XMLstatement data, but the second can contain only XML that is valid according to the XML schema collection awschemas. USE AdventureWorks GO CREATE MESSAGE TYPE [//Adventure-Works.com/Expenses/ExpenseClaim] VALIDATION = WELL_FORMED_XML CREATE MESSAGE TYPE [//Adventure-Works.com/Expenses/ClaimResponse] VALIDATION = VALID_XML WITH SCHEMA COLLECTION awschemas By default, all databases contain a message type named DEFAULT, which is defined as follows. CREATE MESSAGE TYPE DEFAULT AUTHORIZATION dbo VALIDATION = NONE For More Information For more information about creating message types, see “Creating Service Broker Message Types” in SQL Server Books Online.
  19. 19. Module 9: Using Service Broker 9–17Syntax for Creating Contracts**************************************** Illegal for non-trainer use ***************************************Syntax of the CREATE A contract defines the message types that a service can use in a conversation and theCONTRACT Transact-SQL direction in which the message types can be sent. You define a contract by using thestatement CREATE CONTRACT Transact-SQL statement, which has the following syntax. CREATE CONTRACT contract_name [ AUTHORIZATION owner_name ] ( { message_type_name SENT BY { INITIATOR | TARGET | ANY } | [ DEFAULT ] } [ ,...n] ) [ ; ] The contract_name can be up to 128 characters and cannot be the same as an existing server, database, or schema. The AUTHORIZATION clause sets the owner of the contract to the name of a database user or role. When this clause is omitted, the contract belongs to the current user. The message_type_name specifies the name of a preexisting message type, and SENT BY specifies the direction that the message type can travel in a conversation. The following table summarizes the possible values of the SENT BY clause. Value Description INITIATOR Indicates that only the initiator of the conversation can send messages of the specified message type. A service that begins a conversation is referred to as the initiator of the conversation. TARGET Indicates that only the target of the conversation can send messages of the specified message type. A service that accepts a conversation that was started by another service is referred to as the target of the conversation. ANY Indicates that messages of this type can be sent by both the initiator and the target.
  20. 20. 9–18 Module 9: Using Service Broker Specifying the DEFAULT option indicates that this contract supports messages of the DEFAULT message type in any direction. For More Information For more information about the CREATE CONTRACT statement, see “CREATE CONTRACT (Transact-SQL)” in SQL Server Books Online.Using the CREATE The following example shows the definition of a contract named //Adventure-CONTRACT statement Works.com/Expenses/ExpenseSubmission in the AdventureWorks database. The contract specifies support for two message types: the //Adventure-Works.com/ Expenses/ExpenseClaim message type can be sent only by the initiator, and the // Adventure-Works.com/Expenses/ClaimResponse can be sent only by the target. USE AdventureWorks GO CREATE CONTRACT [//Adventure-Works.com/Expenses/ExpenseSubmission] ( [//Adventure-Works.com/Expenses/ExpenseClaim] SENT BY INITIATOR, [//Adventure-Works.com/Expenses/ClaimResponse] SENT BY TARGET ) By default, all databases contain a contract named DEFAULT, which is defined as follows. CREATE CONTRACT DEFAULT AUTHORIZATION dbo ([DEFAULT] SENT BY ANY) For More Information For more information about creating contracts, see “Creating Service Broker Contracts” in SQL Server Books Online.
  21. 21. Module 9: Using Service Broker 9–19Syntax for Creating Queues**************************************** Illegal for non-trainer use ***************************************Syntax of the CREATE The queue defines a location where Service Broker can store messages until a serviceQUEUE Transact-SQL program becomes available to handle the message. You define a queue by using thestatement CREATE QUEUE Transact-SQL statement, which has the following syntax. CREATE QUEUE [database_name.[schema_name].|schema_name.] queue_name [ WITH [ STATUS = { ON | OFF } [ , ] ] [ RETENTION = { ON | OFF } [ , ] ] [ ACTIVATION ( [ STATUS = { ON | OFF } , ] PROCEDURE_NAME = stored_procedure_name, MAX_QUEUE_READERS = max_readers , EXECUTE AS { SELF | user_name | OWNER } ) ] ] [ ON { filegroup | [ DEFAULT ] } ] [ ; ] The following table summarizes the parameters of the CREATE QUEUE statement. Parameter Description queue_name Specifies the name of the queue. The queue name must meet the standard requirements of a SQL Server identifier. STATUS Specifies whether the queue is enabled or disabled. Setting this value to OFF also stops any service program from removing messages from the queue. A queue is ON by default if you do not specify a status value. You can change the status of an existing queue by using the ALTER QUEUE Transact-SQL statement.
  22. 22. 9–20 Module 9: Using Service Broker Parameter Description RETENTION Specifies whether the queue should keep all messages in the queue until the conversation ends. The default setting is OFF; setting this option to ON can lead to reduced performance. ACTIVATION Specifies what happens when a message arrives in the queue. Specifying a PROCEDURE_NAME enables Service Broker to activate a stored procedure automatically as the service program. You can temporarily disable the activation feature by setting the activation status to OFF by using the ALTER QUEUE statement. If the queue uses activation, the stored procedure must exist in the same database as the queue. The stored procedure must already exist when you create the queue. MAX_QUEUE_READERS Specifies the maximum number of service program instances that Service Broker will allow to run simultaneously. EXECUTE AS Specifies the database user account under which the activated stored procedure runs. You can specify a user_name; the value SELF, which specifies that the procedure will run under the current user account; or OWNER, which specifies that the procedure will run under the account that creates the queue. ON Specifies on which file group SQL Server should create the queue. For More Information For more information about the CREATE QUEUE statement, see “CREATE QUEUE (Transact-SQL)” in SQL Server Books Online.Using the CREATE QUEUE The following example shows the definition of two queues named ExpenseQueue andstatement ExpenseQueueWithActivation in the AdventureWorks database. The ExpenseQueue queue does not perform service program activation and is available immediately to store messages. However, a service program must manually read the messages from the queue. The ExpenseQueueWithActivation queue activates the ProcessExpense stored procedure as soon as a message arrives. A maximum of five instances of the stored procedure can exist at any one time. The queue is initially unavailable, and an ALTER QUEUE statement must change the STATUS value before the queue can receive messages. When the procedure does run, it will run as if the user who created the queue were executing the procedure. USE AdventureWorks GO CREATE QUEUE ExpenseQueue GO CREATE QUEUE ExpenseQueueWithActivation WITH STATUS = OFF, ACTIVATION ( PROCEDURE_NAME = ProcessExpense, MAX_QUEUE_READERS = 5, EXECUTE AS SELF) For More Information For more information about creating queues, see “Creating Service Broker Queues” in SQL Server Books Online.
  23. 23. Module 9: Using Service Broker 9–21Syntax for Creating Services**************************************** Illegal for non-trainer use ***************************************Syntax of the CREATE Services link your service consumer and service provider together. A service is involvedSERVICE Transact-SQL from the moment you begin a conversation until you end the conversation. You define astatement service by using the CREATE SERVICE Transact-SQL statement, which has the following syntax. CREATE SERVICE service_name [ AUTHORIZATION owner_name ] ON QUEUE [ schema_name. ]queue_name [ ( contract_name | [DEFAULT] [ ,...n ] ) ] [ ; ] The service_name must be a valid sysname and cannot be the same as an existing server, database, or schema. The AUTHORIZATION clause sets the owner of the service to the name of a database user or role. When this clause is omitted, the service belongs to the current user. The ON QUEUE clause identifies the queue where the service will store incoming messages, and the contract_name parameter specifies zero or more contracts for which the service is a provider. If you do not specify at least one contract, the service can only initiate conversations. For More Information For more information about the CREATE SERVICE statement, see “CREATE SERVICE (Transact-SQL)” in SQL Server Books Online.Using the CREATE The following example shows the definition of two services named //Adventure-SERVICE statement Works.com/SubmitExpense and //Adventure-Works.com/ProcessExpense in the AdventureWorks database. Both services use the //Adventure-Works.com/Expenses/ ProcessExpense contract but different queues. USE AdventureWorks GO
  24. 24. 9–22 Module 9: Using Service Broker CREATE SERVICE [//Adventure-Works.com/SubmitExpense] ON QUEUE ExpensesInitiator ( [//Adventure-Works.com/Expenses/ProcessExpense] ) CREATE SERVICE [//Adventure-Works.com/ProcessExpense] ON QUEUE ExpensesTarget ( [//Adventure-Works.com/Expenses/ProcessExpense] ) For More Information For more information about creating services, see “Creating Service Broker Services” in SQL Server Books Online.
  25. 25. Module 9: Using Service Broker 9–23Demonstration: Creating Service Broker Objects**************************************** Illegal for non-trainer use ***************************************Introduction In this demonstration, you will see how to create Service Broker objects by using Transact-SQL.Preparation Ensure that virtual machine 2779A-MIA-SQL-09 is running and that you are logged on as Student. If a virtual machine has not been started, perform the following steps: 1. Close any other running virtual machines. 2. Start the virtual machine. 3. In the Log On to Windows dialog box, complete the logon procedure by using the user name Student and the password Pa$$w0rd.To create Service Broker Perform the following procedure to create Service Broker objects:objects 1. Click Start, point to All Programs, point to Microsoft SQL Server 2005, and then click SQL Server Management Studio. 2. In the Connect to Server dialog box, specify the values in the following table, and then click Connect. Property Value Server type Database Engine Server name MIAMI Authentication Windows Authentication 3. On the File menu, point to Open, and then click Project/Solution. 4. Open the AW_ServiceBroker.ssmssln solution in the D:DemocodeAW_ServiceBroker folder. 5. In Solution Explorer, double-click PrepareDatabase.sql to view the script. The script performs the following tasks:
  26. 26. 9–24 Module 9: Using Service Broker ● Enable Service Broker in the AdventureWorks database. ● Create a master key in the AdventureWorks database. ● Create a new schema named EMail in the AdventureWorks database. ● Create a new table named EMail.EmailLog in the AdventureWorks database. 6. Click the Execute button on the toolbar to execute the query. 7. In Solution Explorer, double-click CreateServiceBrokerObjects.sql to view the script. The script creates the following objects. Object Description //Adventure-Works.com/EMail/CustomerDetails A message type that will be used to pass customer data to the EmailService service //Adventure-Works.com/EMail/SendCustomerDetails A contract that will be supported by the EmailService service Sales.NewCustomerQueue A queue that will be used by the CustomerService service EMail.NewCustomerEmailQueue A queue that will be used by the EmailService service //Adventure-Works.com/Sales/CustomerService The CustomerService service, which calls the EmailService service to send an e-mail message to a new customer //Adventure-Works.com/EMail/EmailService The EmailService service, which sends an e-mail message to a new customer 8. Click the Execute button on the toolbar to execute the query. 9. If Object Explorer is not visible, click Object Explorer on the View menu. 10. In Object Explorer, expand Databases, AdventureWorks, and Service Broker. Expand Message Types, Contracts, Queues, and Services, and then show the various objects that you just created. 11. Keep SQL Server Management Studio open. You will use it in the next demonstration.
  27. 27. Module 9: Using Service Broker 9–25Lesson 3: Sending and Receiving Messages**************************************** Illegal for non-trainer use ***************************************Lesson objectives After completing this lesson, students will be able to: ■ Describe the syntax used to send messages. ■ Describe the syntax used to receive messages. ■ Send and receive messages.Introduction This lesson describes how to send and receive Service Broker messages. For More Information For more information about creating Service Broker applications, see “Service Broker Programming” in SQL Server Books Online.
  28. 28. 9–26 Module 9: Using Service BrokerSyntax for Sending Messages**************************************** Illegal for non-trainer use ***************************************Requirements for Sending a message from a service consumer to a service provider is one of the mostsending messages common activities you will perform in a Service Broker application. However, you can send a message only after you have created all of the Service Broker objects described earlier, including message types, contracts, queues, and services. After the necessary objects are defined, you must perform the following steps to send a message: 1. Declare a dialog handle variable. 2. Begin a dialog conversation. 3. Send the message by using the dialog handle variable and the message type.Declaring a dialog Before you can send your message, you must declare a dialog handle identifier variable.handle variable This variable is used to store the system-generated dialog handle for the new conversation. You must create this variable as a uniqueidentifier type, as shown here. DECLARE @dialog_handle uniqueidentifierBeginning the Use the BEGIN DIALOG Transact-SQL statement to start a conversation, which has theconversation following syntax. EGIN DIALOG [ CONVERSATION ] @dialog_handle FROM SERVICE initiator_service_name TO SERVICE target_service_name [ , { service_broker_guid | CURRENT DATABASE } ] [ ON CONTRACT contract_name ] [ WITH [ { RELATED_CONVERSATION = related_conversation_handle | RELATED_CONVERSATION_GROUP = related_conversation_group_id } ] [ [ , ] LIFETIME = dialog_lifetime ] [ [ , ] ENCRYPTION = { ON | OFF } ] ] [ ; ]
  29. 29. Module 9: Using Service Broker 9–27The following table summarizes the parameters of the BEGIN DIALOG statement.Parameter Descriptiondialog_handle Returns the handle to the newly created dialog identifier. Use your dialog handle variable to store this new identifier.FROM SERVICE Specifies the service that is sending the message. The name specified must be the name of a service in the current database. The queue that the service specifies (in the CREATE SERVICE statement) will receive any messages returned by the target service.TO SERVICE Specifies the name of the service with which to initiate the dialog. The name specified is of type nvarchar(256) and is case-sensitive.service_broker_guid Specifies the database that hosts the target service. When more than one database hosts an instance of the target service, you can communicate with a specific database by providing a service_broker_guid. A value of CURRENT DATABASE specifies that the conversation uses the service_broker_guid for the current database.ON CONTRACT Specifies the contract name that you want to use when communicating with the service. If the target service does not accept new conversations on the contract specified, Service Broker returns an error message on the conversation. When this clause is omitted, the conversation follows the contract named DEFAULT.WITH Allows you to relate the new dialog with an existing conversation by using either RELATED_CONVERSATION or RELATED_CONVERSATION_GROUP identifiers. You can also specify a maximum amount of time in seconds that the conversation will remain open by using the LIFETIME option. If you do not specify the LIFETIME option, both endpoints must end the conversation explicitly.ENCRYPTION Allows you to encrypt messages sent and received on this dialog. The default option is that Service Broker encrypts messages between different SQL Server instances. Encryption never occurs during conversations between services on the same SQL Server instance.The following example shows how to begin a simple dialog conversation. BEGIN DIALOG @dialog_handle FROM SERVICE [//Adventure-Works.com/SubmitExpense] TO SERVICE //Adventure-Works.com/ProcessExpense ON CONTRACT [//Adventure-Works.com/Expenses/ProcessExpense]For More Information For more information about the BEGIN DIALOG statement,see “BEGIN DIALOG CONVERSATION (Transact-SQL)” in SQL Server Books Online.
  30. 30. 9–28 Module 9: Using Service BrokerSending the message Once you have a dialog handle identifier, you can send your message by using the SEND Transact-SQL statement, which has the following syntax. SEND ON CONVERSATION conversation_handle [ MESSAGE TYPE message_type_name ] [ ( message_body_expression ) ] [ ; ] If you are initiating a message, the conversation_handle is the uniqueidentifier returned by the BEGIN DIALOG statement. If you are responding to a message, conversation_handle is available from the incoming message. The MESSAGE TYPE value must match a message type that the current endpoint can send as defined in the contract associated with the dialog. If the current endpoint is the initiator, this will include message types marked as SENT BY INITIATOR or SENT BY ANY. If the current endpoint is the target, this will include message types marked as SENT BY TARGET or SENT BY ANY. The message_body_expression is the data that is sent in the body of the message. This must match the message type definition. The following example shows how to send a message. The example assumes that the message expects an XML body. When you work with XML-formatted strings, you must ensure that the string includes a byte-order mark preceding the XML data. The NCHAR value 0xFEFF represents a byte-order mark. You must use the semicolon (;) Transact- SQL delimiter if the SEND statement is not the first statement in a batch or stored procedure. DECLARE @msgString NVARCHAR(MAX) SET @msgString = NCHAR(0xFEFF) + N<root>xml data</root> ;SEND ON CONVERSATION @dialog_handle MESSAGE TYPE [//Adventure-Works.com/Expenses/ExpenseClaim] (@msgString) For More Information For more information about the SEND statement, see “SEND (Transact-SQL)” in SQL Server Books Online.
  31. 31. Module 9: Using Service Broker 9–29Syntax for Receiving Messages**************************************** Illegal for non-trainer use ***************************************Introduction After you have sent a message, a service program needs to read the message from the queue and process the message body. Precisely when the service program reads the message depends on how you chose to set up the queue. However, the basic steps for receiving a message do not change. To receive a message, you must perform the following steps: 1. Declare variables for storing message details. 2. Call the RECEIVE Transact-SQL statement. 3. Check the message type, and then process the message accordingly. 4. If the conversation is completed, call END CONVERSATION.Declaring local variables You need to create local variables so that you can store individual columns from the message. Common columns that you might want to work with include conversation_handle, message_type_name, and message_body. The following example demonstrates the declaration of three local variables. DECLARE @conversation UNIQUEIDENTIFIER DECLARE @msg NVARCHAR(MAX) DECLARE @msgType NVARCHAR(256)Calling the RECEIVE The RECEIVE statement removes one or more messages from a specified queue so thatstatement you can work with the message as you would with any other table-based result set. The statement removes all messages belonging to the same service instance identifier unless you include the TOP parameter in the statement. During this time, no other service program instance can work with the messages you receive or with any other message
  32. 32. 9–30 Module 9: Using Service Broker that has the same service instance identifier. RECEIVE removes messages in order based on the message_sequence_order value for each message in a conversation. The RECEIVE statement has the following syntax. [ WAITFOR ( ] RECEIVE [ TOP ( n ) ] <column_specifier> [ ,...n ] FROM <queue> [ INTO table_variable ] [ WHERE { conversation_handle = conversation_handle | conversation_group_id = conversation_group_id } ] [ ) ] [ , TIMEOUT timeout ] [ ; ] The following table summarizes the parameters of the RECEIVE statement. Parameter Description WAITFOR Blocks processing of the RECEIVE statement until a message arrives in the queue. If you specify a TIMEOUT value in milliseconds, RECEIVE will wait only for the given length of time before returning an empty result set if no message arrives. Omitting the time-out parameter or setting it to –1 causes the RECEIVE statement to wait until a message arrives. TOP Specifies how many messages to receive from the queue. If you do not specify the TOP parameter, you will receive all of the messages that match a single service instance identifier. Often you will specify the value 1 to work with individual messages. column_specifier Specifies the list of columns to include in the result set. FROM Specifies the name of the queue where you want to check for messages. INTO Allows you to store the result set in a table rather than in local variables. You should use this approach when you want to work with multiple messages simultaneously. WHERE Allows you to limit the returned messages to a specific conversation handle or conversation group identifier. The following example shows how to receive a single message and store three columns from the message in local variables. You should check @@ROWCOUNT after a RECEIVE statement to ensure that a message was found. If @@ROWCOUNT equals zero, the queue did not contain any messages. ;RECEIVE TOP(1) @conversation = conversation_handle, @msgType = message_type_name, @msg = message_body FROM ExpenseQueue For More Information For more information about the RECEIVE statement, see “RECEIVE (Transact-SQL)” in SQL Server Books Online.
  33. 33. Module 9: Using Service Broker 9–31Checking the message To ensure that you are dealing with the correct type of message, you can check thetype and processing the message_type_name column from the message result set by using a combination of IFmessage statements. Possible message types include: ■ The expected message type ■ An error message of the message type http://schemas.microsoft.com/SQL/ ServiceBroker/Error ■ A dialog time-out message of the message type http://schemas.microsoft.com/ SQL/ServiceBroker/DialogTimer ■ An end dialog message of the message type http://schemas.microsoft.com/ SQL/ServiceBroker/EndDialog ■ An unknown or unexpected message type The following example checks the type of a received message to process it appropriately. If the message is an error message or an end dialog message as predefined by Service Broker, the example simply ends the conversation. Any unexpected message type results in the end of the conversation and an error message being returned to the service consumer. IF (@msgType = //Adventure-Works.com/Expenses/ExpenseClaim) -- process @msg ... ELSE IF (@msgType = http://schemas.microsoft.com/SQL/ServiceBroker/Error) OR (@msgType = http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog) END CONVERSATION @conversation ELSE END CONVERSATION @conversation WITH ERROR = 500 DESCRIPTION = Invalid message type. Another common action when processing a message is to send a new message either in response to the incoming message or on to another service provider. If the new message should be included as part of the same conversation, use the RELATED_CONVERSATION parameter in the BEGIN DIALOG CONVERSATION statement by using the current message’s conversation handle.Ending the conversation If the service provider task is complete, you can end the conversation by using the END CONVERSATION Transact-SQL statement, which has the following syntax. END CONVERSATION conversation_handle [ [ WITH ERROR = failure_code DESCRIPTION = failure_text ] [ WITH CLEANUP ] ] [ ; ] The conversation_handle parameter is the identifier of the conversation that you want to end. You can specify an optional error code and description by using the WITH ERROR clause. The WITH CLEANUP clause removes all messages and metadata for this side of the conversation without notifying the other side of the conversation. SQL Server drops the conversation endpoint, all messages for the conversation in the transmission queue, and all messages for the conversation in the service queue. For More Information For more information about the END CONVERSATION statement, see “END CONVERSATION (Transact-SQL)” in SQL Server Books Online.
  34. 34. 9–32 Module 9: Using Service BrokerDemonstration: Sending and Receiving Messages**************************************** Illegal for non-trainer use ***************************************Introduction In this demonstration, you will see how to implement stored procedures that send, receive, and process Service Broker messages.Preparation Ensure that virtual machine 2779A-MIA-SQL-09 is running and that you are logged on as Student. If a virtual machine has not been started, perform the following steps: 1. Close any other running virtual machines. 2. Start the virtual machine. 3. In the Log On to Windows dialog box, complete the logon procedure by using the user name Student and the password Pa$$w0rd. 4. Start SQL Server Management Studio, connecting to MIAMI by using Windows authentication when prompted. Then open the AW_ServiceBroker.ssmssln solution in the D:DemocodeAW_ServiceBroker folder.Sending and receiving To send and receive Service Broker messages:Service Broker messages 1. In Solution Explorer, double-click SendReceiveMessages.sql to view the script. The script creates the following objects. Object Description Sales.uspEmailNewCustomer Sends messages from the CustomerService service to the EmailService service EMail.uspSendCustomerEmail Processes messages received by the EmailService service 2. Click the Execute button on the toolbar to execute the query. 3. In Solution Explorer, double-click TestService.sql to view the script.
  35. 35. Module 9: Using Service Broker 9–334. Select and execute the following EXECUTE statement to send a message to the EmailService service. EXECUTE AdventureWorks.Sales.uspEmailNewCustomer @firstName = Greg, @lastName = Guzik, @emailAddress = greg@treyresearch.com5. Select and execute the following SELECT statement to show that the EmailService service has processed the message. SELECT * FROM AdventureWorks.EMail.EmailLog6. Close SQL Server Management Studio.
  36. 36. 9–34 Module 9: Using Service BrokerLab: Implementing a Service Broker Solution**************************************** Illegal for non-trainer use ***************************************Scenario The Marketing department at Adventure Works wants to send a welcome e-mail message to new customers who register on the company’s Web site. To minimize the impact to the site’s scalability, the senior database developer has decided to implement this functionality through a service that will be invoked asynchronously when a new user registers. You will create two Service Broker services: CustomerService will initiate a conversation with an EmailService, which will send an e-mail message to a newly registered customer. When your work is complete, the senior database developer will modify the customer registration process to use the services you create. The senior database developer has provided the following specifications for the solution: ■ The EmailService service must send e-mail messages by using Database Mail. The database administrator has provided a batch file named LabSetup.cmd to configure Database Mail on your development computer. ■ You must enable Service Broker in the AdventureWorks database by using the ALTER DATABASE statement. To enable secure communication between services, you must also create a master key with a secure password in the AdventureWorks database. ■ You must create schemas named EmailSvc and CustomerSvc in the AdventureWorks database, and then create a table named EmailLog in the EmailSvc schema. The EmailLog table should have the following definition: CREATE TABLE EMailSvc.EmailLog ( Date datetime NOT NULL, [Event] nvarchar(50) NOT NULL, CustomerData xml )
  37. 37. Module 9: Using Service Broker 9–35■ Use the following details to create a message type that will be used to pass customer data to the EmailService service. Property Value Name //AW/EMail/CustomerDetails Validation WELL_FORMED_XML■ Use the following details to create a contract that will be supported by the EmailService service. Property Value Name //AW/EMail/SendCustomerDetails Message type //AW/EMail/CustomerDetails Message Direction SENT BY INITIATOR■ Use the following details to create a queue that will be used by the CustomerService service. Property Value Name CustomerSvc.NewCustomerQueue Queue status ON■ Use the following details to create a queue that will be used by the EmailService service. The queue should initially be disabled until you create the stored procedure that the queue will activate. Property Value Name EMailSvc.NewCustomerEmailQueue Queue status OFF■ Use the following details to create the CustomerService service. Property Value Name //AW/Sales/CustomerService Queue CustomerSvc.NewCustomerQueue■ Use the following details to create the EmailService service. Property Value Name //AW/EMail/EmailService Queue EMailSvc.NewCustomerEmailQueue Contract //AW/EMail/SendCustomerDetails■ The senior database developer has provided Transact-SQL scripts to create the CustomerSvc.uspEmailNewCustomer and EMailSvc.uspSendCustomerEmail stored procedures used by the services.
  38. 38. 9–36 Module 9: Using Service Broker ■ After you have created the EMailSvc.uspSendCustomerEmail stored procedure, you must alter the queue used by the EmailService service to make it activate the EMailSvc.uspSendCustomerEmail stored procedure whenever a message is received. Use the following settings. Property Value Name EMailSvc.NewCustomerEmailQueue Queue status ON Activation status ON Procedure name AdventureWorks.EMailSvc.uspSendCustomerEmail Maximum readers 5 Execute as OWNERAdditional information When performing database development tasks, it can be helpful to use SQL Server Management Studio to create a SQL Server Scripts project, and use it to document the Transact-SQL code necessary to re-create the solution if necessary. Use the following procedure to create a SQL Server Scripts project: 1. Open SQL Server Management Studio, connecting to the server you want to manage. 2. On the File menu, point to New, and then click Project. 3. Select the SQL Server Scripts template and enter a suitable name and location for the project. Note that you can create a solution that contains multiple projects, but in many cases a single project per solution is appropriate. To add a query file to a project: 1. Click New Query on the Project menu, or right-click the Queries folder in Solution Explorer and click New Query. If Solution Explorer is not visible, you can display it by clicking Solution Explorer on the View menu. 2. When prompted, connect to the server on which you want to execute the query. This will add a connection object to the project. 3. Change the name of the query file from the default name (SQLQuery1.sql) by right-clicking it in Solution Explorer and clicking Rename. Although you can perform all administrative tasks by executing Transact-SQL statements, it is often easier to use the graphical user interface in SQL Server Management Studio. However, you should generate the corresponding Transact-SQL scripts and save them in the project for future reference. Often, you can generate the Transact-SQL script for an action before clicking OK in the Properties dialog box used to perform the action. Many Properties dialog boxes include a Script drop-down list with which you can script the action to a new query window, a file, the Clipboard, or a SQL Server Agent job. A common technique is to add a blank query file to a project, and then script each action to the Clipboard as it is performed and paste the generated script into the query file. You can also generate scripts for many existing objects, such as databases and tables. To generate a script, right-click the object in Object Explorer and script the CREATE action. If Object Explorer is not visible, you can display it by clicking Object Explorer on the View menu.
  39. 39. Module 9: Using Service Broker 9–37Preparation Ensure that virtual machine 2779A-MIA-SQL-09 is running and that you are logged on as Student. If a virtual machine has not been started, perform the following steps: 1. Close any other running virtual machines. 2. Start the virtual machine. 3. In the Log On to Windows dialog box, complete the logon procedure by using the user name Student and the password Pa$$w0rd.
  40. 40. 9–38 Module 9: Using Service BrokerExercise 1: Creating Service Broker ObjectsCreating Service Brokerobjects in the Task Supporting informationAdventureWorksdatabase Configure Database 1. In Windows Explorer, view the contents of the Mail. D:LabfilesStarter folder. 2. Double-click LabSetup.cmd to run the script that configures Database Mail. Create the 1. Start SQL Server Management Studio. Connect to AW_ServiceBroker SQL MIAMI by using Windows authentication when Server Scripts project. prompted. 2. Create a new SQL Server Scripts project named AW_ServiceBroker in the D:LabfilesStarter folder. Configure the 1. Add a new query file to the project. Connect to MIAMI AdventureWorks by using Windows authentication when prompted. database for Service 2. Rename the query file to PrepareDatabase.sql. Broker. 3. Add Transact-SQL code to the PrepareDatabase.sql query to perform the following tasks: ● Enable Service Broker in the AdventureWorks database. ● Create a master key in the AdventureWorks database. ● Create the EmailSvc and CustomerSvc schemas and the EmailLog table in the AdventureWorks database. 4. Execute the query, and then save the query file. Create the Service 1. Add a new query file to the project. Connect to MIAMI Broker objects required by using Windows authentication when prompted. for the customer e-mail 2. Rename the query file to solution. CreateServiceBrokerObjects.sql. 3. Add Transact-SQL code to the PrepareDatabase.sql query to create the following Service Broker objects in the AdventureWorks database: ● The //AW/EMail/CustomerDetails message type ● The //AW/EMail/SendCustomerDetails contract ● The CustomerSvc.NewCustomerQueue queue ● The EMailSvc.NewCustomerEmailQueue queue ● The //AW/Sales/CustomerService service ● The //AW/EMail/EmailService service 4. Execute the query, and then save the query file. 5. Use Object Explorer to verify that the Service Broker objects have been created. 6. Keep SQL Server Management Studio open. You will use it in the next exercise.
  41. 41. Module 9: Using Service Broker 9–39Exercise 2: Implementing the Initiating ServiceImplementing theCustomerService service Task Supporting information Add the 1. On the project menu, click Add Existing CreateEmailNewCustomerSP.sql Item. query file to the AW_ServiceBroker 2. Browse to the D:LabfilesStarter folder project. and add the CreateEmailNewCustomerSP.sql query file. Connect to MIAMI by using Windows authentication when prompted. Implement the CustomerService 1. Examine the code in the service. CreateEmailNewCustomerSP.sql query file and notice that it contains Transact- SQL statements to send messages from the CustomerService service to the EmailService service in the AdventureWorks database. 2. Execute the query, and then save the query file. 3. Use Object Explorer to verify that the stored procedure has been created. 4. Keep SQL Server Management Studio open. You will use it in the next exercise.
  42. 42. 9–40 Module 9: Using Service BrokerExercise 3: Implementing the Target ServiceImplementing theEmailService service Task Supporting information Add the CreateSendEmailSP.sql 1. On the Project menu, click Add Existing query file to the Item. AW_ServiceBroker project. 2. Browse to the D:LabfilesStarter folder and add the CreateSendEmailSP.sql query file. Connect to MIAMI by using Windows authentication when prompted. Implement the EmailService 1. Examine the code in the service. CreateSendEmailSP.sql query file and notice that it contains Transact-SQL statements to create a stored procedure to receive and process messages in the EmailService service in the AdventureWorks database. 2. Execute the query, and then save the query file. 3. Use Object Explorer to verify that the stored procedure has been created. Configure the target service for 1. Create a new query file in the project. When automatic activation. prompted, connect to MIAMI. 2. Rename the new query file to AlterServiceBrokerQueue.sql. 3. In the query window, type the appropriate ALTER QUEUE Transact-SQL statement to make the EMailSvc.NewCustomerEmailQueue queue activate the EMailSvc.uspSendCustomerEmail stored procedure. 4. Execute the query, and then save the query file. Test the EmailService service. 1. On the Project menu, click Add Existing Item. 2. Browse to the D:LabfilesStarter folder and add the TestEmailService.sql query file. Connect to MIAMI by using Windows authentication when prompted. 3. Examine the TestEmailService.sql query file, and notice that it contains Transact-SQL statement to execute the CustomerSvc.uspEmailNewCustomer stored procedure and then query the Email.EmailLog table. 4. Execute the query, and verify that the message is logged in the EMailSvc.EmailLog table. 5. Open Microsoft Outlook Express, and verify that the EmailService has sent an e-mail message. 6. Close SQL Server Management Studio.

×