
USE SodaDB
GO


DECLARE @h UNIQUEIDENTIFIER;
DECLARE @invreq XML;
SET @invreq = '
<InventoryReq xmlns="http://www.company.com/inventoryRequest">
  <order>1</order>
  <product>1040</product>
  <units>6</units>
  <status>Req</status>
</InventoryReq>
';

BEGIN TRY
BEGIN TRANSACTION;
BEGIN DIALOG CONVERSATION @h
 FROM SERVICE InvInitiator_L9A
 TO SERVICE 'InvService_L9A'
 ON CONTRACT InvContract_L9A
 WITH ENCRYPTION = OFF;

-- request for product 1040
SEND ON CONVERSATION @h 
 MESSAGE TYPE InvRequestMsg_L9A (@invreq);
COMMIT;
END TRY
BEGIN CATCH
	PRINT ERROR_MESSAGE()
    ROLLBACK;
END CATCH
GO


--
-- Step 2: Receive message and return the reply
-- This happens at the target. Just send <OK/> this time.
--

DECLARE @h UNIQUEIDENTIFIER;
DECLARE @invreq XML;
DECLARE @invresp XML

BEGIN TRANSACTION;
RECEIVE TOP(1)
 @invreq = CAST(message_body AS XML),
 @h = conversation_handle
 FROM InvRequestQueue_L9A;
-- PRINT CONVERT(VARCHAR(4000), @invreq);
SAVE TRANSACTION afterreceive;

BEGIN TRY;
-- UPDATE the Inventory table with the values extracted from the XML
WITH XMLNAMESPACES(DEFAULT 'http://www.company.com/inventoryRequest') 
UPDATE Inventory 
  SET units_in_stock = units_in_stock - @invreq.value('(/InventoryReq/units)[1]', 'int') 
  WHERE product_id = @invreq.value('(/InventoryReq/product)[1]', 'int');

  SET @invreq.modify('
     declare default element namespace "http://www.company.com/inventoryRequest";
     replace value of (/InventoryReq/status/text())[1] with "OK" '); 
END TRY
BEGIN CATCH
  ROLLBACK TRANSACTION afterreceive
  SET @invreq.modify('
     declare default element namespace "http://www.company.com/inventoryRequest";
     replace value of (/InventoryReq/status/text())[1] with "Backordered" ');
  -- Queue up a request to the ordering system here
END CATCH;

SEND ON CONVERSATION @h
 MESSAGE TYPE InvResponseMsg_L9A (@invreq);
END CONVERSATION @h
COMMIT;
GO

--
-- Step 3: Receive the response and end the conversation
-- This happens at the initiator.
--

DECLARE @h UNIQUEIDENTIFIER;
DECLARE @resp XML;

BEGIN TRANSACTION;
RECEIVE TOP(1)
 @resp = CAST(message_body AS XML),
 @h = conversation_handle
 FROM InvResponseQueue_L9A;
PRINT CONVERT(VARCHAR(4000),@resp);
-- You don't need to read the end conversation message
-- You can decide to unconditionally end the conversation
END CONVERSATION @h
COMMIT;
GO

SELECT * FROM Inventory
