Saturday 21 July 2018

Reading WCF messages in MSMQ queues in Powershell

The last article looked at displaying MSMQ contents for a MSMQ queue used with NetMsmqBinding using Powershell. The message queues contained characters that were unreadable. That is because the message queue items contains actually ready to consume WCF messages. This article will present a new Powershell script where the MSMQ body contents is finally readable using Powershell and .NET WCF classes in System.ServiceModel. Here is how the contents looks using regular methods to extract the MSMQ Message queue items with garbled contents. This is as noted due to the MSMQ queue items each containing a corresponding WCF message.
Let's fix this up by using System.ServiceModel classes!
[System.Reflection.Assembly]::LoadWithPartialName("System.Messaging") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("System.Xml") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("System.ServiceModel") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("System.IO") | Out-Null


$queuePath = ".\private$\demoqueue4"

Write-Host "Powershell MSMQ queue WCF inspector v0.1. Inspecting queue contents of the queue: $queuePath"
Write-Host ""


Run-MainDemoIterateMsmq $queuePath



Function Get-XmlFromWcfMessage([System.Messaging.Message] $msg) {
   
    $doc = New-Object System.Xml.XmlDocument;
    $messageLength = [int] $msg.BodyStream.Length


    $buffer = New-Object byte[] $messageLength

    
    $msg.BodyStream.Read($buffer, 0, $messageLength)

    $envelopeStart = Find-SoapEnvelopeStart($buffer);

    $envelopeLength = $($buffer.Length - $envelopeStart)
    #Write-Host $envelopeStart


    $stream = New-Object System.IO.MemoryStream($buffer, $envelopeStart, $envelopeLength)

    $elm = New-Object System.ServiceModel.Channels.BinaryMessageEncodingBindingElement
    $elm.ReaderQuotas.MaxStringContentLength = 10000000
    $elm.ReaderQuotas.MaxBytesPerRead = 10000000


    $msg1 = $elm.CreateMessageEncoderFactory().Encoder.ReadMessage($stream, 10000000);

    $doc.Load($msg1.GetReaderAtBodyContents());

    $msg.BodyStream.Position = 0;



    return $doc;
}

Function Find-SoapEnvelopeStart([byte[]] $stream)
{
    $i = 0;
    $j = 0;
    $prevByte = $stream[$i];
    $curByte = [byte]$j;
    for ($i = 0; $i -lt $stream.Length; $i++)
    {
        $curByte = $stream[$i];
        if ($curByte -eq [byte] 0x02 -and $prevByte -eq [byte] 0x56) {
            break;
        }
        $prevByte = $curByte;
    }
    return $i - 1;
}


Function Run-MainDemoIterateMsmq([string] $queuePath) {

$queue = New-Object System.Messaging.MessageQueue $queuePath

foreach ($message in $queue.GetAllMessages()){
  $xmlDoc = Get-XmlFromWcfMessage $message 
  Write-Host $xmlDoc.OuterXml
 } 


}
The soap envelope is found looking after the escape sequence "V" followed with the special ANSI character 0x02 (STX = Start of Text). From this point on, the rest of the WCF Message is our SOAP body! We then get readable output!
Finally, the WCF messages inside the MSMQ queue that is filled up using NetMsmqBinding is readable! In my next article I will present a demo solution of how to use NetMsmqBinding in WCF! Until then, you can clone the solution already from here: git clone git@bitbucket.org:toreaurstad/demonetmsmqwcfgit.git

Reading MSMQ contents with Powershell

This article will present two ways to read a MSMQ (Microsoft Message Queue) using Powershell. First, the queue will be read using the GetString method of System.Text.UTF8Encoding:

[System.Reflection.Assembly]::LoadWithPartialName("System.Messaging") | Out-Null
 
$queuePath = ".\private$\myqueue"

$queue = New-Object System.Messaging.MessageQueue $queuePath

foreach ($message in $queue.GetAllMessages()){

 Write-Host (New-Object System.Text.UTF8Encoding).GetString($message.BodyStream.ToArray())

 Write-Host $msg 
}

As an alternative, it is also possible to use the StreamReader (more ceremony really):

[System.Reflection.Assembly]::LoadWithPartialName("System.Messaging") | Out-Null
 
$queuePath = ".\private$\myqueue"

$queue = New-Object System.Messaging.MessageQueue $queuePath

foreach ($message in $queue.GetAllMessages()){

 Write-Host ([Environment]::NewLine)

 $sr = New-Object System.IO.StreamReader($message.BodyStream)

 $message.Formatter = New-Object System.Messaging.XmlMessageFormatter(@(""));
 
 $msg = "";

 while ($sr.Peek() -ge 0){
  $msg += $sr.ReadLine()
 }

 Write-Host $msg 
}

Actually, I was needing a simple way to look at some messages sent with the NetMsmqBinding in WCF, so making a Powershell script seemed the quickest way! WCF does some strange formatting on the message that is sent through the wire, you can though see that our two alternatives gives also a bit different formatting, the first alternative being the most clean and with shortest syntax.
As the reader can see, the contents of the MSMQ queue that the NetMsmqBinding uses shows unreadable characters. That is because the MSMQ message item are containing actually WCF Messages. QueueExplorer showed me this fact, so next article will present a more lengthy version where the content can be properly decoded using Powershell to the rescue!

Tuesday 3 July 2018

Basic WCF solution in Monodevelop

Basic WCF Solution in Monodevelop

I created a basic solution with a WCF Servicehost and client in Monodevelop today using MX Linux 17 "Horizon". To check it out, clone the following repository:
git clone https://bitbucket.org/toreaurstad/hellowcfmono
The source code is small and can be seen in a browser here: HelloWcfMono source code
If you have not installed Monodevelop in Linux yet, it is available as package "Monodevelop", "Monodevel" or "Monodevelop-complete", for example in MX-Linux I used:
apt-get install monodevel

The HelloWcf solution consists of three projects. The Service project is a console project, running the ServiceHost through the console. You will want to tweak Monodevelop to use External Console by right clicking and selecting Options=>Run=>General: "Run on external console". I just installed xterm to use the console as it is (apt get install xterm). In case Monodevelop crashes when you open the .sln file, another problem with Monodevelop, you can run the following command to open the .sln file directly in the root folder of the cloned repository.: monodevelop HelloWcf.sln
To run the WCF sample, right click on the Host project and choose Set as Startup project Choose first to Rebuild all (Ctrl+F8) to build the Service, Host and Client projects. Now press F5 to debug the Host project. The terminal window should show up, indicating that the WCF Service is running:



Now, switch over to a new terminal window and navigate to the Client project. Go to the bin folder, then the Debug folder. If you did not build Client, there are no files here, so do this now by right clicking on the Client project in Monodevelop and choose build. Now a file called Client.exe should pop up in your console. To run the client, enter: mono Client.exe Then you provide the Service a string through a call WCF service call with the proxy (Client) and get a reply. This project is really the basic set up of a client to get started coding WCF Servicehost and a proxy supporting BasicHttpBinding in .NET System.ServiceModel (which Mono actually supports). Developers can now use Linux and Monodevelop for example and commit code, while other developers use other platforms. The same .sln file can be openened in Visual Studio in Windows for example, while front-end guys use Apple to do their bit. Monodevelop is truly a possible bridge and will you will save money on license costs and freedom to add a lot of free software to use to build your projects. So what are you waiting for, grab hold of Monodevelop today and Linux and try it out! Nice thing to see that Mono framework supports WCF, much can be developed for .NET in Linux!