™ Programming A Programming A Distributed Message Distributed Message Queue Application Queue Application Raphi Renous Raphi Renous Software Development Software Development Engineer Engineer Desktop And Business Desktop And Business Systems Division Systems Division Microsoft Corporation Microsoft Corporation
39
Embed
Programming A Distributed Message Queue Application Raphi Renous Software Development Engineer Desktop And Business Systems Division Microsoft Corporation.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
™
Programming A Programming A Distributed Message Distributed Message Queue ApplicationQueue Application
Raphi RenousRaphi RenousSoftware Development EngineerSoftware Development EngineerDesktop And Business Desktop And Business Systems DivisionSystems DivisionMicrosoft CorporationMicrosoft Corporation
AgendaAgenda
““Falcon” (MSMQ) featuresFalcon” (MSMQ) features Distributed whiteboard demoDistributed whiteboard demo C/C++ APIC/C++ API ActiveXActiveX™™ Components Components SummarySummary Questions?Questions?
““Falcon” (MSMQ) FeaturesFalcon” (MSMQ) Features
Sessionless with asynchronous Sessionless with asynchronous send and receivesend and receive
Protocol and platform-independent APIProtocol and platform-independent API Scalable to large number of nodesScalable to large number of nodes Robust: reliable, guaranteed, transactional Robust: reliable, guaranteed, transactional Integrated securityIntegrated security System-wide priority policySystem-wide priority policy Advanced logging and trackingAdvanced logging and tracking Multireader, multisender, multithreaded Multireader, multisender, multithreaded Support for legacy systemsSupport for legacy systems SDK: C/C++ API, ActiveX ComponentsSDK: C/C++ API, ActiveX Components
Message and queue objects Message and queue objects represented using properties represented using properties
Use MQ.H, MQRT.LIBUse MQ.H, MQRT.LIB
PropertiesProperties
Properties associated with queuesProperties associated with queuesand messagesand messages
Each property consists of ID, type, valueEach property consists of ID, type, value Property setProperty set
CountCount Array of IDsArray of IDs Array of variants (tagged union) containing Array of variants (tagged union) containing
type and valuetype and value Array of status codes (optional)Array of status codes (optional)
ID names: ID names: PROPID_Q_*PROPID_Q_* or or PROPID_M_*PROPID_M_*
Usage OverviewUsage Overview
Queue creationQueue creation Form queue property setForm queue property set CallCall MQCreateQueue() MQCreateQueue()with property setwith property set
Queue openingQueue opening Obtain queue format nameObtain queue format name
By creating the queueBy creating the queue From the queue location functionFrom the queue location function Set by the applicationSet by the application
Call Call MQOpenQueue()MQOpenQueue()with format namewith format name
Usage OverviewUsage Overview
Message receptionMessage reception Open queue for receive accessOpen queue for receive access Determine message property set to be receivedDetermine message property set to be received CallCall MQReceiveMessage() MQReceiveMessage() with open queue with open queue
handle and property sethandle and property set If asynchronous, write code to handle If asynchronous, write code to handle
message arrivalmessage arrival
Message sendingMessage sending Open queue for send accessOpen queue for send access Form message property setForm message property set CallCall MQSendMessage() MQSendMessage() with open with open
queue handle and property setqueue handle and property set
Queue ManipulationQueue Manipulation
Default security: get properties/permissions and sendDefault security: get properties/permissions and send Queue propertiesQueue properties
Stored in MSMQ Information Service database Stored in MSMQ Information Service database ““MachineName\QueueName”MachineName\QueueName”
PrivatePrivate Stored on disk of local machineStored on disk of local machine ““MachineName\Private$\QueueName”MachineName\Private$\QueueName”
HRESULT HRESULT MQCreateQueueMQCreateQueue(IN PSECURITY_DESCRIPTOR (IN PSECURITY_DESCRIPTOR pSecurityDescpSecurityDesc,, IN OUT MQQUEUEPROPS IN OUT MQQUEUEPROPS *pQueueProps*pQueueProps,,
OUT LPWSTR OUT LPWSTR lpwcsFormatNamelpwcsFormatName,, IN OUT LPDWORD IN OUT LPDWORD lpdwFormatNameLengthlpdwFormatNameLength))
HRESULT HRESULT MQDeleteQueueMQDeleteQueue(IN LPWSTR (IN LPWSTR lpwcsFormatNamelpwcsFormatName))
Format nameFormat name Specifies how to get to a queueSpecifies how to get to a queue
Not a propertyNot a property Returned byReturned by MQCreateQueue() MQCreateQueue() Obtained from the properties returnedObtained from the properties returned
by the queue location functionsby the queue location functions Formed by the applicationFormed by the application
Queue ManipulationQueue Manipulation
Subject to queue securitySubject to queue security One type of access per queue handleOne type of access per queue handle
Share modeShare mode 00 - available to everyone (must be used for peek and send) - available to everyone (must be used for peek and send) MQ_DENY_RECEIVE_SHARE MQ_DENY_RECEIVE_SHARE - only this process can receive- only this process can receive
HRESULT HRESULT MQOpenQueueMQOpenQueue(IN LPWSTR (IN LPWSTR lpwcsFormatNamelpwcsFormatName,, IN DWORD IN DWORD dwAccessdwAccess,, IN DWORD IN DWORD dwShareModedwShareMode,, OUT LPQUEUEHANDLE OUT LPQUEUEHANDLE phQueuephQueue))
HRESULT HRESULT MQCloseQueueMQCloseQueue(IN QUEUEHANDLE (IN QUEUEHANDLE hQueuehQueue))
Powerful - do not need to know exact location of queuePowerful - do not need to know exact location of queue Context - starting point in name space (currently Context - starting point in name space (currently NULLNULL)) Restriction setRestriction set
Property information (ID, type, value)Property information (ID, type, value) Comparison operation for each propertyComparison operation for each property
Column set - queue properties to be returned by queryColumn set - queue properties to be returned by query Sort set - sort order for results (optional)Sort set - sort order for results (optional)
Property IDs from column setProperty IDs from column set Order for each property IDOrder for each property ID
Returns enumeration handle (does not retrieve results)Returns enumeration handle (does not retrieve results)
HRESULT HRESULT MQLocateBeginMQLocateBegin(IN LPCWSTR (IN LPCWSTR lpwcsContextlpwcsContext,, IN MQRESTRICTION IN MQRESTRICTION *pRestriction*pRestriction,,
IN MQCOLUMNSET IN MQCOLUMNSET *pColumns*pColumns,, IN MQSORTSET IN MQSORTSET *pSort*pSort,, OUT PHANDLE OUT PHANDLE phEnumphEnum))
Call MQLocateNext() until (*pcProps) Call MQLocateNext() until (*pcProps) on output < (*pcProps) on inputon output < (*pcProps) on input
Returns as many “complete” results as possibleReturns as many “complete” results as possible Must free memory allocated by “Falcon” (if any) Must free memory allocated by “Falcon” (if any)
using MQFreeMemory()using MQFreeMemory()
HRESULT HRESULT MQLocateNextMQLocateNext(IN HANDLE (IN HANDLE hEnumhEnum,, IN OUT DWORD IN OUT DWORD *pcProps*pcProps,, OUT PROPVARIANT OUT PROPVARIANT aPropVar[]aPropVar[]))
HRESULT HRESULT MQLocateEndMQLocateEnd(IN HANDLE (IN HANDLE hEnumhEnum))
to specify time limit for message to reach destinationto specify time limit for message to reach destination
Transaction interfaceTransaction interface Get from MSGet from MS®® DTC DTC
HRESULT HRESULT MQSendMessageMQSendMessage(IN QUEUEHANDLE (IN QUEUEHANDLE hDestinationQueuehDestinationQueue,, IN MQMSGPROPS IN MQMSGPROPS ** pMessagePropspMessageProps,, IN ITransaction IN ITransaction ** pTransactionpTransaction))
Callback function, Win32Callback function, Win32®® event, Windows NT event, Windows NT®® completion port completion port Cursor used to traverse messages in queueCursor used to traverse messages in queue Transaction interfaceTransaction interface
Get from MS DTCGet from MS DTC
HRESULT HRESULT MQReceiveMessageMQReceiveMessage(IN QUEUEHANDLE (IN QUEUEHANDLE hSourceQueuehSourceQueue, , IN DWORD IN DWORD dwTimeOutdwTimeOut,, IN DWORD IN DWORD dwActiondwAction, , IN OUT MQMSGPROPS IN OUT MQMSGPROPS *pMessageProps*pMessageProps,, IN OUT LPOVERLAPPED IN OUT LPOVERLAPPED lpOverlappedlpOverlapped,, IN PMQRECEIVECALLBACK IN PMQRECEIVECALLBACK fnReceiveCallbackfnReceiveCallback,, IN HANDLE IN HANDLE hCursor,hCursor, IN ITransaction IN ITransaction ** pTransactionpTransaction))
Support early (vtable) and late (Support early (vtable) and late (IDispatchIDispatch) binding) binding Direct support for most “Falcon” functionalityDirect support for most “Falcon” functionality
within the object modelwithin the object model No UI required No UI required Usable by any ActiveX Server controller, for example,Usable by any ActiveX Server controller, for example,
mqQueue mqQueue = queue opened with send access= queue opened with send access Set properties inSet properties in mqMessage mqMessage instance instance CallCall mqMessage.Send(mqQueue) mqMessage.Send(mqQueue)
MSMQQueueInfoMSMQQueueInfo
Describes a queue objectDescribes a queue object MethodsMethods
Create, DeleteCreate, Delete Open(access, sharemode) as MSMQQueueOpen(access, sharemode) as MSMQQueue
ExampleExample‘ Create queue for my instance‘ Create queue for my instanceDim qrec As New MSMQQueueInfoDim qrec As New MSMQQueueInfoqinfo.strPathName = "machine\queue"qinfo.strPathName = "machine\queue"qinfo.strLabel = "My Draw Queue"qinfo.strLabel = "My Draw Queue"qinfo.Createqinfo.Create
MSMQQueueMSMQQueue
Describes an open queue instanceDescribes an open queue instance A queue can be concurrently open A queue can be concurrently open
multiple timesmultiple times One-to-many mapping from One-to-many mapping from
MSMQQueueInfoMSMQQueueInfo to to MSMQQueueMSMQQueue Analogy: Analogy: MSMQQueueInfoMSMQQueueInfo is to is to
MSMQQueueMSMQQueue as as FileFile is to is to FileHandleFileHandle Provides asynchronous Provides asynchronous
message handlingmessage handling Manages collection of messagesManages collection of messages
MSMQQueueMSMQQueue
MethodsMethods IsOpen() as BooleanIsOpen() as Boolean CloseClose Receive() as MSMQMessageReceive() as MSMQMessage
Synchronous message receptionSynchronous message reception Peek() as MSMQMessagePeek() as MSMQMessage
Synchronous message peekingSynchronous message peeking EnableNotification(qevent as MSMQEvent)EnableNotification(qevent as MSMQEvent)
Turns on asynchronous message notificationTurns on asynchronous message notification Message arrival to queue will now fire Message arrival to queue will now fire qevent_qevent_
Resets message collection to startResets message collection to start ReceiveNext() / PeekNext() as MSMQMessageReceiveNext() / PeekNext() as MSMQMessage
Cursor based synchronous reception/peekCursor based synchronous reception/peek
lHandlelHandle Error event fired if timeout expires while synchronously Error event fired if timeout expires while synchronously
waiting to receive messagewaiting to receive message
ExampleExample‘ Create and open a queue for synchronous reception‘ Create and open a queue for synchronous receptionDim qinfo As New MSMQQueueInfoDim qinfo As New MSMQQueueInfoDim myQ As MSMQQueue Dim myQ As MSMQQueue qinfo.strPathName = "machine\queue" qinfo.strPathName = "machine\queue" qinfo.Createqinfo.CreateSet myQ = qinfo.Open(MQMSG_RECEIVE_ACCESS, Set myQ = qinfo.Open(MQMSG_RECEIVE_ACCESS, MQ_DENY_NONE)MQ_DENY_NONE)
MSMQEventMSMQEvent
Allows user to write single generic Allows user to write single generic event handler to manage message event handler to manage message arrival notification of multiple queuesarrival notification of multiple queues
EventsEvents Arrived(byval pdispQueue as Object)Arrived(byval pdispQueue as Object)
Fired when a new message arrives Fired when a new message arrives at queueat queue
ArrivedError(byval pdispQueue as Object, ArrivedError(byval pdispQueue as Object, byval error as Long)byval error as Long) Fired to indicate message error Fired to indicate message error
in receptionin reception
MSMQQueryMSMQQuery
Provides filtered queue location Provides filtered queue location Returns collection of queue objectsReturns collection of queue objects MethodMethod
LookupQueue(<selection criteria>) as MSMQQueueInfosLookupQueue(<selection criteria>) as MSMQQueueInfos
ExampleExample‘ Locate the friend queue‘ Locate the friend queueDim queryFriend As New MqQueryDim queryFriend As New MqQueryDim qinfosResult As MSMQQueueInfosDim qinfosResult As MSMQQueueInfosSet qinfosResult = queryFriend.LookupQueue(Set qinfosResult = queryFriend.LookupQueue(
Manages collection of Manages collection of MSMQQueueInfoMSMQQueueInfo objects produced by objects produced by MSMQQueryMSMQQuery
MethodsMethods ResetReset Next() as MSMQQueueInfoNext() as MSMQQueueInfo
ExampleExample‘ ‘ Display the queue label for all the queuesDisplay the queue label for all the queuesDim queryAll As New MSMQQueryDim queryAll As New MSMQQueryDim qinfos As MSMQQueueInfosDim qinfos As MSMQQueueInfosDim qinfoCurrent As MSMQQueueInfoDim qinfoCurrent As MSMQQueueInfoSet qinfos = queryAll.LookupQueueSet qinfos = queryAll.LookupQueueqinfos.Resetqinfos.ResetSet qinfoCurrent = qinfos.NextSet qinfoCurrent = qinfos.NextWhile Not qinfoCurrent Is NothingWhile Not qinfoCurrent Is Nothing MsgBox qinfoCurrent.strLabel MsgBox qinfoCurrent.strLabel Set qinfoCurrent = qinfos.Next Set qinfoCurrent = qinfos.NextWendWend
MSMQMessageMSMQMessage
Describes a messageDescribes a message MethodMethod
ExampleExample‘ Send the keystroke to the friend‘ Send the keystroke to the friendDim OutMsg as New MSMQMessageDim OutMsg as New MSMQMessageOutMsg.lPriority = 4OutMsg.lPriority = 4OutMsg.strBody = Chr(KeyAscii)OutMsg.strBody = Chr(KeyAscii)OutMsg.strLabel = "Key: " + OutMsg.strBodyOutMsg.strLabel = "Key: " + OutMsg.strBodyOutMsg.Send FriendQOutMsg.Send FriendQ
MSMQMessage.bodyMSMQMessage.body
The The bodybody property allows you property allows you to send/receive typed messagesto send/receive typed messages
Messages can be:Messages can be: StringsStrings Arrays of bytesArrays of bytes Persistent ActiveX objectsPersistent ActiveX objects
Support Support IDispatch IDispatch and and IPersistStreamIPersistStream or or IPersistStorageIPersistStorage
if TypeOf mReceive.body Is Excel.Workbook Then ‘ do XL stuff to message body set xl = mReceive.bodyend if
LimitationsLimitations
Only Visual Basic 5.0 supports user-defined Only Visual Basic 5.0 supports user-defined event handlers to ActiveX Serversevent handlers to ActiveX Servers Use Use WithEventsWithEvents keyword in declaration keyword in declaration
Visual Basic 4.0 can use every other featureVisual Basic 4.0 can use every other feature Visual Basic 5.0 example:Visual Basic 5.0 example:
‘ Open an existing queue for asynchronous reception‘ Open an existing queue for asynchronous receptionDim WithEvents qevent As MSMQEventDim WithEvents qevent As MSMQEventSub OpenExistingQueue()Sub OpenExistingQueue() Dim qinfo As New MSMQQueueInfo Dim qinfo As New MSMQQueueInfo qinfo.strPathName = "machine\queue" qinfo.strPathName = "machine\queue" Set qPeek = qrec.Open(MQMSG_PEEK_ACCESS, 0) Set qPeek = qrec.Open(MQMSG_PEEK_ACCESS, 0) Set qevent = New MSMQEvent Set qevent = New MSMQEvent qPeek.EnableNotification qevent qPeek.EnableNotification qeventEnd SubEnd SubPrivate Sub qevent_Arrived(byval q as Object)Private Sub qevent_Arrived(byval q as Object) Dim m As MSMQMessage Dim m As MSMQMessage Set m = q.PeekNext Set m = q.PeekNext MsgBox "Arrived: " + m.strBody MsgBox "Arrived: " + m.strBody
q.EnableNotification qevent q.EnableNotification qeventEnd SubEnd Sub
SummarySummary
Your missionYour mission Today: try Beta2Today: try Beta2
Run the samples (c_draw and oa_draw)Run the samples (c_draw and oa_draw) Write applications using the C/C++ API Write applications using the C/C++ API