How to use the ebMS 3.0 MessageDecoder

by david 2. August 2010 09:20

Here is some example code for the simple MessageDecoder class that I wrote for my last blog, it takes an example ebMS 3.0 soap document from a file and loads it - giving access to the UserMessage and SignalMessage elements inside the envelope header.  I have tried it on all the examples that I extracted from the eMS 3.0 core spec and it seems to work OK. It's just a start...

using System;
using System.IO; 
using ebMS3.Soap;

namespace SoapLoaderTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string filename = "example.xml";
            FileStream file = new FileStream(filename, FileMode.Open,
                FileAccess.Read);
            ebMS3.Soap.MessageDecoder decoder = new MessageDecoder(file);
            SignalMessage[] smsgs = decoder.GetHeaderSignalMessages();
            UserMessage[] umsgs = decoder.GetHeaderUserMessages();
            file.Close();
        }
    }
}

Deserialising ebMS 3.0 Headers

by david 1. August 2010 17:25

The class below is my first attempt at being able to read the ebMS 3.0 headers in C#.  It deserialises the xml into the objects I have created from the xsd files (see previous post).  So you'll need the auto-generated C# classes to use this code.  I'll post an example useage in another blog.  So far I have tested it on all the examples extracted from the ebMS core spec and it seems to load the data OK.

using System;
using System.Collections.Generic;

using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.ServiceModel.Channels;

namespace ebMS3.Soap
{
    public class MessageDecoder
    {
        private string _xmlnamespace = null;
        public Message Message { getprivate set; } 

        public MessageDecoder(Stream stream)
        {
            _xmlnamespace = GetXmlNamespace(typeof(Messaging));
            Message = GetMessage(stream);  
        }

        public MessageDecoder(byte[] rawbytes)
        {
            _xmlnamespace = GetXmlNamespace(typeof(Messaging));
            MemoryStream ms = new MemoryStream(rawbytes); 
            Message = GetMessage(ms);
        }

        private string GetXmlNamespace(Type t)
        {
            XmlTypeAttribute[] attrs = (XmlTypeAttribute[])
                t.GetCustomAttributes(typeof(XmlTypeAttribute), true);
            if (attrs != null && attrs.Length > 0)
                return attrs[0].Namespace;
            else
                return "";
        }

        public UserMessage[] GetHeaderUserMessages()
        {
            return GetHeaderMessages<UserMessage>();
        }

        public SignalMessage[] GetHeaderSignalMessages()
        {
            return GetHeaderMessages<SignalMessage>();
        }

        private T[] GetHeaderMessages<T>() where T : class
        {
            if (Message == null || Message.Headers == nullreturn default(T[]);
            List<T> retval = new List<T>();
            XmlSerializer xs = new XmlSerializer(typeof(T), _xmlnamespace);

            XmlNode[] hdrs =
                Message.Headers.GetHeader<XmlNode[]>("Messaging", _xmlnamespace);
            foreach (XmlNode xn in hdrs)
            {
                if (xn.Name.EndsWith(typeof(T).Name))
                {
                    T um = xs.Deserialize(new XmlNodeReader(xn)) as T;
                    if (um != null) retval.Add(um);
                }
            }
            return retval.ToArray();
        }

        private Message GetMessage(Stream stream)
        {
            MessageVersion soap11 = MessageVersion.Soap11WSAddressingAugust2004;
            XmlReader xreader = XmlReader.Create(stream);
            return Message.CreateMessage(xreader, 5120, soap11); // 5Kb in headers
        }
    }
}

Turn ebMS 3.0 Headers into C# classes

by david 31. July 2010 18:40

Instructions for creating auto-generated C# classes for ebMS 3.0 headers
(we should end up with this file: ebms-header-3_0-200704_soap11_soap12.cs).

1) Download these xsd files to a folder.
ebms-header-3_0-200704.xsd:
http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/core/ebms-header-3_0-200704.xsd
soap11.xsd:
http://schemas.xmlsoap.org/soap/envelope/
soap12.xsd:
http://www.w3.org/2003/05/soap-envelope/

2) Open a Visual Studio Command Prompt
Then change to the folder where the downloaded files are located

3) Run this command:
xsd /c /n:ebMS3.Soap ebms-header-3_0-200704.xsd soap11.xsd soap12.xsd

Bubblesort in C

by david 24. June 2010 18:45

Just for fun Surprised I decided to write a bubblesort algorithm in C.  The idea is that I have a collection of rank structures and the ones with the lowest values in the errors variable will come to the top.

 

Now I have decided to keep it for posterity.  Of course, in reality I've used qsort() instead; so the code below is for recreational purposes ... or something.

 

typedef struct rank

{

  double errors;

  int element;

};

 

void swap(struct rank *array, int a, int b)

{

  struct rank temp = array[a];

  array[a] = array[b];

  array[b] = temp;

}

 

int swapIfBigger(struct rank *array, int a, int b)

{

  if (array[b].errors>=array[a].errors) return 0;

  swap(array,a,b);

  return 1;

}

 

void bubblesort(struct rank *array, int len)

{

  int t=0,count=1;

  while (count>0)

  {

    count=0;

    for (t=0; t<len-1; t++)

    {

      count += swapIfBigger(array,t, t+1);

    }

  }

}

Tags: ,

Code

Simplest ATmega168 program

by david 4. March 2010 22:17

So how would you know that your code is running?  Just about the simplest thing that you can do with a microprocessor is flash an LED on and off.  So we'll start with that.  You'll need to attach an LED and a resistor in series from pin 28 of the ATmega168 (assuming that you have the DIP format).  So take a wire from pin 28 on the ATmega and attach it to the positive pin of an LED.  Then attach the negative pin of the LED to one  wire of the resistor.  Finally, attach the other wire on the resistor to Ground.  When the program code turns on pin 28, power will flow through the LED through the resistor and then to Ground.  So the LED will come on.  Cool.

Obviously LEDs are diodes, so they only go one way round (the resistor can go any way round).  The purpose of the resistor is to limit the current and prevent the LED from burning out.  The exact resistor value does not matter in this case, anything from 200 to 1,000 (1k) Ohms should be fine.  The lower the value of the resistor the brighter the LED will be.

Don't forget to also wire up the other basic pins on the Atmega (I've blogged about that before).  Now we can get to some code.  I've put the source code here: http://www.codehosting.net/blog/files/led_blink.zip

Extract the contents of the zip file to a folder and open the files using Programmers Notepad from WinAVR.  Connect up your usbtiny programmer, ensure that the power is on and we're ready to go. 

Go to the Tools menu of Programmers Notepad and click on [WinAVR] Program.  The program should compile, get loaded onto the microprocessor and the LED should start to blink!  Woo-hoo.

NOTE: I have also used the "ponyser" serial port programmer.  This can be used as an alternative, by changing these lines of the makefile:

Put a # at the start of line 202 and remove the # from line 201:
AVRDUDE_PROGRAMMER = ponyser
#AVRDUDE_PROGRAMMER = usbtiny

Remove the # at the start of line 206 and make sure that the COM port matches the one you're using:
AVRDUDE_PORT = COM1

Finally remove the # from the start of line 227:
AVRDUDE_FLAGS += -P $(AVRDUDE_PORT)

You should now be able to use a serial port programmer instead (my example uses COM1).

Optimising StringBuilder Appending

by david 24. December 2009 17:58

I have been working on some C# code optimisation, for speed.  The code in question does a lot of work with strings, so we already use StringBuilder to make it more efficient.  But what is the fastest way to append stuff to the StringBuilder?  In this instance, we're building a lot of comma seperated lists, and even with StringBuilder there are several ways, for example:

 

Method 1, AppendFormat:

sb.AppendFormat("{0},",myStr);

 

Method 2, Multiple Append:

sb.Append(myStr);

sb.Append(",");

 

Method 3, Multiple Append (with a comma already in a string):

string sep = ",";

...

sb.Append(myStr);

sb.Append(sep);

 

Method 4, Single Append:

sb.Append(myStr+sep);

 

... so I decided to check it out.  Here are the results (in seconds), after using each technique one hundred million times (I did five tests and then averaged the results):

 

 

#1

#2

#3

#4

#5

Average

1 AppendFormat

17.20

17.56

17.36

17.58

17.55

17.45

2 Multiple Append

6.61

7.27

6.70

7.27

7.28

7.03

3 Multiple Append (comma in string)

6.65

7.20

6.75

7.20

7.20

7.00

4 Single Append

8.13

8.34

8.31

8.34

8.34

8.29

 

I was quite surprised at how much slower AppendFormat was (although I can understand why).  But it's also worth remembering that the lazy coders way of using a single Append with the + operator to attach the comma is quite a bit slower than calling two Append methods (again, you can understand why when you think about it).

 

Here is the code that I used to test:

 

static void Main(string[] args)

{

    DateTime start = DateTime.Now;

    StringBuilder sb = new StringBuilder();

    string myStr = "hi";

 

    for (int t = 0; t < 100000000; t++)

    {

        sb.AppendFormat("{0},",myStr);

        if ((t % 1000)==0) sb.Remove(0, sb.Length - 1); 

    }

    TimeSpan gap = DateTime.Now - start;

    Console.WriteLine("AppendFormat takes: {0}", gap);

    sb.Remove(0, sb.Length - 1);

 

    start = DateTime.Now;

    for (int t = 0; t < 100000000; t++)

    {

        sb.Append(myStr);

        sb.Append(",");

        if ((t % 1000) == 0) sb.Remove(0, sb.Length - 1);

    }

    gap = DateTime.Now - start;

    Console.WriteLine("Multiple Appends takes: {0}", gap);

    sb.Remove(0, sb.Length - 1);

 

    string sep = ",";

    start = DateTime.Now;

    for (int t = 0; t < 100000000; t++)

    {

        sb.Append(myStr);

        sb.Append(sep);

        if ((t % 1000) == 0) sb.Remove(0, sb.Length - 1);

    }

    gap = DateTime.Now - start;

    Console.WriteLine("Multiple Appends (comma in string) takes: {0}", gap);

    sb.Remove(0, sb.Length - 1);

 

    start = DateTime.Now;

    for (int t = 0; t < 100000000; t++)

    {

        sb.Append(myStr+sep);

        if ((t % 1000) == 0) sb.Remove(0, sb.Length - 1);

    }

    gap = DateTime.Now - start;

    Console.WriteLine("Single Append (comma in string) takes: {0}", gap);

    sb.Remove(0, sb.Length - 1);

 

    Console.ReadKey(); 

}

A new lock statement for C#

by david 2. October 2009 16:57

I'm working on a lot of multithreaded code at the moment.  In the past I have made use of the lock keyword in C#, but I'm not doing that anymore because it is much better to have a timeout.  However, I don't like having lots of sections like this in my code:

 

if (System.Threading.Monitor.TryEnter(objLock, TIMEOUT))

{

    try

    {

        // do stuff here...

    }

    finally

    {

        System.Threading.Monitor.Exit(objLock);

    }

}

 

...which is the equivalent of using the lock statement, but with a timeout specified.  Still, what I'd like to see in my code is something like this:

 

lock (objLock,TIMEOUT)

{

    // do stuff here...

}

 

Which would be more pretty.  And since I like pretty code, I decided to see how close I could get to that.  This is my current solution:

 

public static class Lock

{

    public static T Try<T>(object objLock, int timeout, Func<T> f)

    {

        if (System.Threading.Monitor.TryEnter(objLock, timeout))

        {

            try

            {

                return f.Invoke();

            }

            finally

            {

                System.Threading.Monitor.Exit(objLock);

            }

        }

        return default(T);

    }

 

    public static void Try(object objLock, int timeout, Action f)

    {

        if (System.Threading.Monitor.TryEnter(objLock, timeout))

        {

            try

            {

                f.Invoke();

            }

            finally

            {

                System.Threading.Monitor.Exit(objLock);

            }

        }

    }

}

 

So far, that is as close as I can get, it means that I can do two things:

 

Lock.Try(objLock, TIMEOUT, delegate

{

    // stuff here...

});

 

or, if I need to return a value, then this:

 

return Lock.Try<int>(objLock,TIMEOUT,delegate

{

    // stuff here...

    return 0;

});

 

Because the second example uses generics, then I can return anything I like by specifying the type inside the angled brackets.  Now I feel that my code is a lot more prettier which is a nice way to finish off on a Friday.

Round robbin

by david 25. September 2009 14:14

I was doing some simple load balancing tests on an application I'm building.  I wanted to load multiple queues from different places in my code using a simple round-robin approach.  A very simple thing to do, and this is what I came up with:

 

int index = 0, max = 10;

...

index += index >= max ? (index * -1) : 1;

 

...it will increment the index counter until it reaches the limit (10), then start back at zero again. I don't know why I find that line so beautiful, but I just do.  I like it when you can do stuff in a single line of code.

Opening WPF Windows on a new thread

by david 22. September 2009 09:01

Recently I needed to open a new WPF window on a new thread. I was helped a great deal by this article, however the window that I needed to open did not have parameterless constructor.  In the end, this is the code that I came up with:

private void NewWindowThread<T,P>(Func<P, T> constructor, P param) where T : Window

{

   Thread thread = new Thread(() =>

   {

      T w = constructor(param);

      w.Show();

      w.Closed += (sender, e) => w.Dispatcher.InvokeShutdown();

      System.Windows.Threading.Dispatcher.Run();

   });

   thread.SetApartmentState(ApartmentState.STA);

   thread.Start();

}

This method, uses generics to specify the Type of the window that you're creating as well as the Type of the parameter passed to its constructor, for example:

string t = "Hello World!";

NewWindowThread<TitleWindow, string>(c => new TitleWindow(c), t);

Would work when TitleWindow was declared like this:

public class TitleWindow : Window

{

    public TitleWindow(string title)

    {

        this.Title = title;

    }

}

Now I can open different types of window on a new thread and pass parameters to them.

About the author

David
I'm a C# developer having worked with .Net since it was in beta.  Before that I mainly worked in C and C++.  I have been developing commercial software for more than 20 years.  I also mess around with microprocesors, but that's just for fun.  I live near Cambridge, England and at the moment I'm contracted to one of the departments at Cambridge University.