Created
August 19, 2014 22:57
-
-
Save DominicFinn/09f2c5da5dcbdeecd279 to your computer and use it in GitHub Desktop.
Msmq Basics in F#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#r "C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.5\\System.Messaging.dll" | |
// reference system.messaging, no external dependencies required. | |
open System.Messaging | |
// delete the queues if you are playing about and need them again | |
//MessageQueue.Delete(@".\private$\doms-fsi-queue-1") | |
//MessageQueue.Delete(@".\private$\doms-fsi-queue-2") | |
// create a queue with all the defaults | |
let queue1 = MessageQueue.Create(@".\private$\doms-fsi-queue-1") | |
// create a transactional queue | |
let queue2 = MessageQueue.Create(@".\private$\doms-fsi-queue-2", true) | |
// anything can be sent, by default it is serialized as xml | |
// in f# you need to make the record / type mutable unless you want to supply a parameterless constructor and other foolery | |
[<CLIMutable>] | |
type CreateUserCommand = {id:int; email:string} | |
let command1 = { id = 1; email = "[email protected]"} | |
// send a message on the queue | |
queue1.Send(command1) | |
// set all messages to be recoverable (saved to disk) by default. Adds a good bit of overhead | |
queue1.DefaultPropertiesToSend.Recoverable <- true | |
// send a message within a transaction | |
let sendWithinATransaction() = | |
let command2 = { id = 2; email = "[email protected]" } | |
( | |
use tx = new MessageQueueTransaction() | |
tx.Begin() | |
queue2.Send(command2, tx) | |
tx.Commit() | |
) | |
sendWithinATransaction() | |
// cleans out the queue | |
queue1.Purge() | |
// deserialize a message back to the object you wanted using the default xml method | |
let deserializeMessage(message : Message) = | |
let xs = new System.Xml.Serialization.XmlSerializer(typedefof<CreateUserCommand>) | |
let body = xs.Deserialize(message.BodyStream) | |
(body :?> CreateUserCommand) | |
// get the message at the front of the queue | |
let message1 = queue1.Receive() | |
let command1_Deserialized = deserializeMessage message1 | |
// recieve within a transaction, locks the message but if the deserialize failed or something else went wrong, the message would be left on the queue | |
let recieveWithinATransaction() = | |
use tx = new MessageQueueTransaction() | |
tx.Begin() | |
let message2 = queue2.Receive(tx) | |
let command2_DeserializedResult = deserializeMessage message2 | |
tx.Commit() | |
command2_DeserializedResult | |
let command2_Deserialized = recieveWithinATransaction() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment