Skip to content

Instantly share code, notes, and snippets.

@DominicFinn
Created August 19, 2014 22:57
Show Gist options
  • Save DominicFinn/09f2c5da5dcbdeecd279 to your computer and use it in GitHub Desktop.
Save DominicFinn/09f2c5da5dcbdeecd279 to your computer and use it in GitHub Desktop.
Msmq Basics in F#
#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 = "test1@test.com"}
// 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 = "test2@test.com" }
(
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