You are on page 1of 8

Module 9 Lab: Implementing a Service Broker Solution

Exercise 1: Creating Service Broker Objects


Lab Answer Key

Configuring Database Mail


You must perform the following steps to configure Database Mail:

1. In Windows Explorer, view the contents of the D:\Labfiles\Starter folder.


2. Double-click LabSetup.cmd to run the script that configures Database Mail.

Creating the AW_ServiceBroker SQL Server Scripts project


You must perform the following steps to create the AW_ServiceBroker SQL Server
Scripts project:

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 New, and then click Project.


4. In the New Project dialog box, specify the values in the following table, and then click OK.
Property Value or action
Name AW_ServiceBroker
Location D:\Labfiles\Starter
Create directory for Clear the check box.
solution
Configuring the AdventureWorks database for Service Broker
You must perform the following steps to configure the AdventureWorks database for
Service Broker:

1. On the Project menu, click New Query to add a new query file to the project. Connect to
MIAMI by using Windows authentication when prompted.
2. If Solution Explorer is not visible, click Solution Explorer on the View menu.
3. In Solution Explorer, right-click SQLQuery1.sql, and then click Rename. Rename the file to
PrepareDatabase.sql.
4. Add the following Transact-SQL code to the PrepareDatabase.sql query.
USE master
GO

-- Enable Service Broker in the AdventureWorks database


ALTER DATABASE AdventureWorks SET ENABLE_BROKER

-- Configure the AdventureWorks database


USE AdventureWorks
GO
IF NOT EXISTS
(SELECT * FROM sys.symmetric_keys
WHERE name = '##MS_DatabaseMasterKey##')
CREATE MASTER KEY ENCRYPTION BY PASSWORD = '23987hxJ#KL95234nl0zBe'
GO

CREATE SCHEMA EMailSvc


GO

CREATE SCHEMA CustomerSvc


GO

-- Create a table to log details of the customer e-mails sent


CREATE TABLE EMailSvc.EmailLog
(
Date datetime NOT NULL,
[Event] nvarchar(50) NOT NULL,
CustomerData xml
)
5. Click the Execute button on the toolbar to execute the query.
6. On the File menu, click Save All.
Creating the Service Broker objects required for the customer e-mail solution
You must perform the following steps to create the required Service Broker objects:

1. On the Project menu, click New Query. Connect to MIAMI by using Windows
authentication when prompted.
2. In Solution Explorer, right-click SQLQuery1.sql, and then click Rename. Rename the file to
CreateServiceBrokerObjects.sql.
3. In the query window, type the following Transact-SQL code to create the message type,
contract, queues, and services.

USE AdventureWorks
GO

-- Create message types


CREATE MESSAGE TYPE [//AW/EMail/CustomerDetails]
VALIDATION = WELL_FORMED_XML
GO

-- Create contracts
CREATE CONTRACT [//AW/EMail/SendCustomerDetails]
(
[//AW/EMail/CustomerDetails]
SENT BY INITIATOR
)
GO

-- Create queues
CREATE QUEUE CustomerSvc.NewCustomerQueue
WITH STATUS = ON

CREATE QUEUE EMailSvc.NewCustomerEmailQueue


WITH STATUS = OFF
GO

-- Create services
CREATE SERVICE [//AW/Sales/CustomerService]
ON QUEUE CustomerSvc.NewCustomerQueue

CREATE SERVICE [//AW/EMail/EmailService]


ON QUEUE EMailSvc.NewCustomerEmailQueue
([//AW/EMail/SendCustomerDetails])

4. Click the Execute button on the toolbar to execute the query.


5. On the File menu, click Save All.
6. If Object Explorer is not visible, click Object Explorer on the View menu.
7. In Object Explorer, expand Databases, AdventureWorks, and Service Broker. Expand
Message Types, Contracts, Queues, and Services, and then verify that the necessary Service
Broker objects are listed.
8. Keep SQL Server Management Studio open. You will use it in the next exercise.
Exercise 2: Implementing the Initiating Service
Lab Answer Key

Adding the CreateEmailNewCustomerSP.sql query file to the AW_ServiceBroker


project
You must perform the following procedure to add the CreateEmailNewCustomerSP.sql
query file to the AW_ServiceBroker project:

1. On the Project menu, click Add Existing Item.


2. Browse to the D:\Labfiles\Starter folder and add the CreateEmailNewCustomerSP.sql
query file. Connect to MIAMI by using Windows authentication when prompted.

Implementing the CustomerService service


You must perform the following steps to create the CustomerService service:

1. Examine the following Transact-SQL code in the CreateEmailNewCustomerSP.sql query


file. Notice that it contains Transact-SQL statements to create a stored procedure that sends
messages from the CustomerService service to the EmailService service in the
AdventureWorks database.

USE AdventureWorks
GO

CREATE PROCEDURE CustomerSvc.uspEmailNewCustomer


@firstName nvarchar(50),
@lastName nvarchar(50),
@emailAddress nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;

-- Create message body to pass to SendMail service.


DECLARE @message xml

SET @message = NCHAR(0xFEFF)


+ '<Customer>'
+ '<CustomerName>' + @firstName + ' ' + @lastName +
'</CustomerName>'
+ '<EmailAddress>' + @emailAddress + '</EmailAddress>'
+ '</Customer>'

DECLARE @dialogHandle UNIQUEIDENTIFIER

BEGIN DIALOG @dialogHandle


FROM SERVICE [//AW/Sales/CustomerService]
TO SERVICE '//AW/EMail/EmailService'
ON CONTRACT [//AW/EMail/SendCustomerDetails];

SEND ON CONVERSATION @dialogHandle


MESSAGE TYPE [//AW/EMail/CustomerDetails] (@message)

END CONVERSATION @dialogHandle


END;
2. Click the Execute button on the toolbar to execute the query.
3. On the File menu, click Save All.
4. In Object Explorer, expand Databases, AdventureWorks, Programmability, and Stored
Procedures, and then verify that the CustomerSvc.uspEmailNewCustomer stored
procedure is listed.
5. Keep SQL Server Management Studio open. You will use it in the next exercise.
Exercise 3: Implementing the Target Service
Lab Answer Key

Adding the CreateSendEmailSP.sql query file to the AW_ServiceBroker project


You must perform the following procedure to add the CreateSendEmailSP.sql query file
to the AW_ServiceBroker project:

1. On the Project menu, click Add Existing Item.


2. Browse to the D:\Labfiles\Starter folder and add the CreateSendEmailSP.sql query file.
Connect to MIAMI by using Windows authentication when prompted.

Implementing the EmailService service


You must perform the following procedure to implement the EmailService service:

1. Examine the following Transact-SQL code in the CreateSendEmailSP.sql query file. 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.

USE AdventureWorks
GO

CREATE PROCEDURE EMailSvc.uspSendCustomerEmail


WITH EXECUTE AS OWNER
AS
BEGIN
SET NOCOUNT ON;

DECLARE @conversation UNIQUEIDENTIFIER


DECLARE @msg NVARCHAR(MAX)
DECLARE @msgType NVARCHAR(256)

;RECEIVE TOP(1)
@conversation = conversation_handle,
@msgType = message_type_name,
@msg = message_body
FROM AdventureWorks.EMailSvc.NewCustomerEmailQueue

IF (@@ROWCOUNT = 0) RETURN

IF (@msgType = '//AW/EMail/CustomerDetails')
BEGIN

-- Extract the e-mail address


DECLARE @emailAddress nvarchar(30)
DECLARE @hDoc int
EXECUTE sp_xml_preparedocument @hdoc OUTPUT, @msg
SELECT @emailAddress = EmailAddress
FROM OPENXML(@hDoc, 'Customer', 2)
WITH
(EmailAddress nvarchar(30))
EXECUTE sp_xml_removedocument @hDoc

-- Send the e-mail


EXECUTE msdb.dbo.sp_send_dbmail @recipients =
@emailAddress,
@subject = 'Welcome to Adventure Works',
@body = 'We would like to welcome you to Adventure Works.'

-- Log the e-mail


INSERT INTO AdventureWorks.EMailSvc.EmailLog
(Date, [Event], CustomerData)
VALUES
(getdate(), 'Email sent to ' + @emailAddress, @msg);
END

ELSE IF (@msgType =
'http://schemas.microsoft.com/SQL/ServiceBroker/Error') OR
(@msgType =
'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog')

END CONVERSATION @conversation

ELSE
BEGIN
END CONVERSATION @conversation
WITH ERROR = 500 DESCRIPTION = 'Invalid message type.';

INSERT INTO AdventureWorks.EMailSvc.EmailLog (Date,


[Event], CustomerData)
VALUES (getdate(), 'Invalid message type', @msg);
END
END;
2. Click the Execute button on the toolbar to execute the query.
3. On the File menu, click Save All.
4. In Object Explorer, refresh Databases, AdventureWorks, Programmability, and Stored
Procedures, and then verify that the EMailSvc.uspSendCustomerEmail stored procedure is
listed.
Configuring the target service for automatic activation
You must perform the following procedure to configure the target service for automatic
activation:

1. On the Project menu, click New Query. When prompted, use Windows authentication to
connect to MIAMI.
2. In Solution Explorer, right-click SQLQuery1.sql, and then click Rename. Rename the file
AlterServiceBrokerQueue.sql.
3. In the query window, type the following Transact-SQL statement to make the
EMailSvc.NewCustomerEmailQueue queue activate the
EMailSvc.uspSendCustomerEmail stored procedure.
USE AdventureWorks
GO

ALTER QUEUE EMailSvc.NewCustomerEmailQueue


WITH STATUS = ON,
ACTIVATION (
STATUS = ON,
PROCEDURE_NAME = AdventureWorks.EMailSvc.uspSendCustomerEmail,
MAX_QUEUE_READERS = 5,
EXECUTE AS OWNER)

4. Click the Execute button on the toolbar to execute the query.


5. On the File menu, click Save All.

Testing the EmailService service


You must perform the following procedure to test the EmailService service:

1. On the Project menu, click Add Existing Item.


2. Browse to the D:\Labfiles\Starter 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
statements to execute the CustomerSvc.uspEmailNewCustomer stored procedure and then
query the EMailSvc.EmailLog table.
4. Click the Execute button on the toolbar to execute the query.
5. Review the result set returned from the EMailSvc.EmailLog table, and verify that it contains
the customer data sent to the EmailService service (if the table contains no records, wait a
few seconds, and then select the SELECT statement and re-execute it).
6. On the File menu, click Save All.
7. Click Start, point to All Programs, and click Outlook Express.
8. Verify that an e-mail message has been sent to student@adventure-works.com by the
EmailService service. If the e-mail message is not in the inbox, wait a few seconds and click
the Send/Recv button.
9. Close Outlook Express and SQL Server Management Studio.

You might also like