Silverlight 3 – Local Messaging Explained + Enhancement

One of the new features Silverlight 3 introduced is called Local Messaging. This feature supports communication between different Silverlight applications that are running on the same client. This is particular useful in areas like Sharepoint where you offer different parts to be positioned at all places on the screen. It’s possible to even communicate between two Slverlight applications running on different domains. For example one app is running on maindomain.com and the second app is running on maindomain.nl or even more different.

The Local Message API is very easy to use. But let’s first setup the Proof of Concept environment. I created a solution with two Silverlight Applications (SUILeft and SUIRight), a hosting project (Web) and a fourth project which is a Silverlight Class Library, we will come to that soon.

image

I combined both the “Left” and “Right” applications in one html page, like this (please remind to change the paths according to your setup).

<div id="silverlightControlHost">
    <object data="data:application/x-silverlight-2," type="application/x-silverlight-2"
        width="40%" height="100%">
        <param name="source" value="ClientBin/MM.Silverlight.SUILeft.xap" />
        <param name="onError" value="onSilverlightError" />
        <param name="background" value="white" />
        <param name="minRuntimeVersion" value="3.0.40624.0" />
        <param name="autoUpgrade" value="true" />
        <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" style="text-decoration: none">
            <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight"
                style="border-style: none" />
        </a>
    </object>
    <object data="data:application/x-silverlight-2," type="application/x-silverlight-2"
        width="40%" height="100%">
        <param name="source" value="ClientBin/MM.Silverlight.SUIRight.xap" />
        <param name="onError" value="onSilverlightError" />
        <param name="background" value="white" />
        <param name="minRuntimeVersion" value="3.0.40624.0" />
        <param name="autoUpgrade" value="true" />
        <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" style="text-decoration: none">
            <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight"
                style="border-style: none" />
        </a>
    </object>
</div>
<iframe id="_sl_historyFrame" style="visibility: hidden; height: 0px; width: 0px;
    border: 0px"></iframe>

Coding the Receiver (Sender to Receiver)

I coded the receiver in the “Left” application. In the constructor I created a new LocalMessageReceiver with the name PoC.Messaging. This name is important because also the sending applications need to know this.

private readonly LocalMessageReceiver _receiver;

public MainPage()
{
    InitializeComponent();
    _receiver = new LocalMessageReceiver("PoC.Messaging");
    _receiver.MessageReceived += _receiver_MessageReceived;
    _receiver.Listen();
}

private void _receiver_MessageReceived(object sender, MessageReceivedEventArgs e)
{
    ResultBlock.Text = e.Message;
}

 

Sending messages (Sender to Receiver)

The sender looks similar, make sure the same name is used. I added a click handler to a button to send the static “Hello World!” messag.

private readonly LocalMessageSender _sender;

public MainPage()
{
    InitializeComponent();
    _sender = new LocalMessageSender("PoC.Messaging");
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    _sender.SendAsync("Hello World!");
}

 

Respond to messages (Receiver to Sender)

After receiving a message there’s an option to reply by simply setting the response. The enhanced MessageReceived handler now looks like this:

private void _receiver_MessageReceived(object sender, MessageReceivedEventArgs e)
{
    ResultBlock.Text = e.Message;
    e.Response = "Hello to you as well!";
}

Accepting response messages (Receiver to Sender)

To enable the sender to accept response messages, a new handler needs to be added to the SendCompleted event. The complete sender code now looks like this:

private readonly LocalMessageSender _sender;

public MainPage()
{
    InitializeComponent();
    _sender = new LocalMessageSender("PoC.Messaging");
    _sender.SendCompleted += _sender_SendCompleted;
}

private void _sender_SendCompleted(object sender, SendCompletedEventArgs e)
{
    string response = e.Response;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    _sender.SendAsync("Hello World!");
}

This is all you need to do, nothing more, nothing less. But limited to only send strings from sender to receiver, and sending messages back to the sender. But we want more, we don’t want to be limited to sending strings, do we?

Enhancing Local Messaging

The idea is simple: Serialize complete objects on the sender, deserialize the strings back to objects on the receiver.

It’s not difficult at all, we have the same API available in Silverlight as we are used in the full CLR. Just add a reference to System.Xml.Serialization in both the “Left” and “Right” project. Also this is where the “Messages” project comes in to play, add a reference to this project from “Left” and “Right” as well.

This was just for preparation. The Messages project will contain the structures that are going to be serialized and deserialized, kind of a message contract. So let’s add our first structure: Customer.

public class Customer
{
    public string Name { get; set; }
    public string Country { get; set; }
}

This is still a very simple class, but this idea works with larger objects as well. But it’s important to explain there’s a limit to the size of the message that is send, it’s 40 kilobyte. It’s time for the little bit of sending magic.

private void Button_Click(object sender, RoutedEventArgs e)
{
    var customer = new Customer {Name = "Best Customer", Country = "Silverlight Island"};
    var serializer = new XmlSerializer(typeof(Customer));
    using (var sw = new StringWriter())
    {
        serializer.Serialize(sw, customer);
        _sender.SendAsync(sw.GetStringBuilder().ToString());
    }
}

And on the receiver side we need to deserialize the message, like this:

private void _receiver_MessageReceived(object sender, MessageReceivedEventArgs e)
{
    var serializer = new XmlSerializer(typeof (Customer));
    if (serializer.CanDeserialize(XmlReader.Create(new StringReader(e.Message))))
    {
        var deserializedCustomer =
            serializer.Deserialize(XmlReader.Create(new StringReader(e.Message))) as Customer;

        ResultBlock.Text = string.Format("Name:{0}, Country:{1}", deserializedCustomer.Name,
                                         deserializedCustomer.Country);
    }
}

That’s all. I’m interested to see more Silverlight applications making use of Local Messaging.
  • Gravatar DotNetBurner - Silverlight October 8th, 2009 at 01:29
    <strong>Silverlight 3 – Local Messaging Explained + Enhancement...</strong>

    DotNetBurner - burning hot .net content...
  • Gravatar Michael Washington October 22nd, 2009 at 18:41
    Oh! "var serializer = new XmlSerializer(typeof(Customer))" Thank You!
  • Gravatar korxtsupcj January 20th, 2012 at 19:56
    xiqge, Hi, you have a great site! http://www.mogtcmoxqt.com korxtsupcj , thanks!
  • Gravatar vildElish January 21st, 2012 at 17:38
    For example, a prescription for lansoprazole can be filled <a href= http://premarin.webs.com>buy premarin cream</a> Generic drug companies may also receive the benefit
  • Gravatar vildElish January 21st, 2012 at 20:55
    Although they may not be associated with a <a href= http://duphaston.webs.com>buy duphaston online canada</a> Generic manufacturers do not incur the cost of drug discovery.
  • Gravatar impfgulz January 25th, 2012 at 06:54
    plavix news plavix coupon <a href= http://onlinetabl.com>buy plavix for cheap</a> paying for plavix plavix gi bleeding
  • Gravatar rtpokmpt January 25th, 2012 at 07:19
    plavix rash plavix specifications <a href= http://onlinetabl.com>buy plavix 75mg tablets</a> why is plavix so expensive plavix nosebleeds
  • Gravatar stivibhvfh January 25th, 2012 at 15:49
    peblu, Hi, you have a great site! http://www.kmpgajlymw.com stivibhvfh , thanks!
  • Gravatar antarturi January 25th, 2012 at 21:28
    Although they may not be associated with a <a href= http://motrinn.webs.com>buy motrin ib online</a> Generic drug companies may also receive the benefit
  • Gravatar ihokkbmcsc January 25th, 2012 at 21:39
    fmovo, Hi, you have a great site! http://www.dgsrsxpvjj.com ihokkbmcsc , thanks!
  • Gravatar coocashBlogma January 26th, 2012 at 02:23
    <b>Crown Hybrid</b>

    To understand, what place occupies new Crown Hybrid among other new models of this family, it is necessary to recollect at first why Crown the previous generation has been named Zero Crown. Therefore, in particular, that it became as though from a blank leaf, without thinking about <b><a href= http://autonewreview.com/all/tuning-infiniti-fx35-unshakable/>custom fx35</a>
    </b> former traditions. And that after all that turned out: one generation Crown was replaced by another, and middle age of owners all increased and increased.

    <a href= http://autonewreview.com><img>http://autonewreview.com/wp-content/uploads/2011/11/90352.jpg</img></a>

    And after all it is known that if the average buyer of this or that <b><a href= http://autonewreview.com/all/car-nissan-tiida-latio-review-2004/>nissan tiida latio review</a>
    </b> mark of the car all becomes more senior and is more senior, at this model, as a matter of fact, there is no future.
  • Gravatar Triancererwab January 26th, 2012 at 02:42
    <b>ПРАКТИЧЕСКИЙ КУРС - "КОД ДЕНЕГ 2012"!!!</b>

    <IMG> http://www.valar.ru/gallery/0112/rgtdhtfr.jpg</IMG>

    ПРОГРЕССИВНЫЙ МЕТОД ЗАРАБАТЫВАНИЯ НА НОВУЮ КВАРТИРУ В ТЕЧЕНИЕ 365 ДНЕЙ!!!
    ЭТО КУРС ОБЩЕДОСТУПЕН И РАСЧИТАН ДАЖЕ ДЛЯ ТЕХ КТО НЕ ИМЕЕТ НАВЫКОВ РАБОТЫ В
    ИНТЕРНЕТ,А ПО ЭТОМУ КАЖДЫЙ ЖЕЛАЮЩИЙ УЖЕ СЕГОДНЯ МОЖЕТ ЗАРАБАТЫВАТЬ ПРИЛИЧНЫЕ ДЕНЬГИ В СЕТИ!
    <a href= http://wre453.kd2012.e-autopay.com>ПОДРОБНЕЕ...</a>















    зароботок,работа 2012,работа в сети,работа в интернет,видео,обучающее видео,видеокурс,КОД ДЕНЕГ 2012,практический курс,обучающий видеокурс КОД ДЕНЕГ 2012,деньги,интернет,высокооплачиваемая работа 2012.
  • Gravatar antarturi January 26th, 2012 at 15:17
    For example, a prescription for lansoprazole can be filled <a href= http://eldepryl.webs.com>buy eldepryl online</a> This allows the company to recoup the cost of developing that particular drug.
  • Gravatar nitLoateego January 26th, 2012 at 17:03
    <b>But there are also distinctions.</b>

    First, in car Crown Hybrid mode EV (electromobile) thanks to what it can move some time exclusively on an electric motor is provided. Well, and secondly, Crown Hybrid is more <b><a href= http://autonewreview.com/all/last-prime-ministers-of-summer-toyota-crown-toyota-alphard-toyota-hilux-vigo-toyota-voxy-toyota-noah-toyota-hiace-nissan-elgrand-nissan-caravan-nissan-cube-nissan-cube-cubic-daihatsu-move-l/>toyota crown comfort interior</a>
    </b> economic that at present is rather essential factor influencing a choice of the buyer.

    <a href= http://autonewreview.com><img>http://autonewreview.com/wp-content/uploads/2011/11/90374.jpg</img></a>

    Really, if Lexus GS450h in the commixed cycle runs on one litre of gasoline of 14,2 km (7 l on 100 km) at Crown Hybrid this indicator is equal 15,8 km (6,3 l on 100 km).
  • Gravatar Smeaserce January 28th, 2012 at 09:19
    <a href= http://tofranil.webs.com>GOEDKOOPSTE Tofranil CANADA ONLINE</a> - tofranil and pregnancy
  • Gravatar ProonoTor January 28th, 2012 at 16:00
    <b>ПРАКТИЧЕСКИЙ КУРС - "КОД ДЕНЕГ 2012"!!!</b>

    <IMG> http://www.valar.ru/gallery/0112/rgtdhtfr.jpg</IMG>

    ПРОГРЕССИВНЫЙ МЕТОД ЗАРАБАТЫВАНИЯ НА НОВУЮ КВАРТИРУ В ТЕЧЕНИЕ 365 ДНЕЙ!!!
    ЭТО КУРС ОБЩЕДОСТУПЕН И РАСЧИТАН ДАЖЕ ДЛЯ ТЕХ КТО НЕ ИМЕЕТ НАВЫКОВ РАБОТЫ В
    ИНТЕРНЕТ,А ПО ЭТОМУ КАЖДЫЙ ЖЕЛАЮЩИЙ УЖЕ СЕГОДНЯ МОЖЕТ ЗАРАБАТЫВАТЬ ПРИЛИЧНЫЕ ДЕНЬГИ В СЕТИ!
    <a href= http://wre453.kd2012.e-autopay.com>ПОДРОБНЕЕ...</a>















    зароботок,работа 2012,работа в сети,работа в интернет,видео,обучающее видео,видеокурс,КОД ДЕНЕГ 2012,практический курс,обучающий видеокурс КОД ДЕНЕГ 2012,деньги,интернет,высокооплачиваемая работа 2012.
  • Gravatar antarturi January 29th, 2012 at 14:52
    By extension, therefore, generics are considered <a href= http://artane.webs.com>buy artane no prescription</a> This allows the company to recoup the cost of developing that particular drug.
  • Gravatar NeibbogeNib January 30th, 2012 at 05:38
    <img> http://4x10.ru/wp-content/uploads/2011/12/100R_04_rv.jpg</img>

    В четвертом квартале 2011 года Банк России возобновил выпуск десятирублевых купюр, которые ранее планировалось полностью заменить монетами того же номинала. Об этом сообщает в четверг агентство ИТАР-ТАСС со ссылкой на первого зампреда Банка России Георгия Лунтовского.

    Оценка монет, Юбилейные монеты, Заработок на монетах: реально ли это? Какие бывают серебряные монеты? Монеты СССР

    <a href= http://4x10.ru/25-rublej-sochi-2014cvetnaya-2011g/>купить 25 рублей сочи 2014 цветная</a>

    <a href= http://4x10.ru/>сколько стоят рубли россии и ссср</a>

    <a href= http://4x10.ru/10-rublej-kasimov-2003-g/>10 рублей 2003 года касимов</a>

    <a href= http://4x10.ru/ceny-na-monety/>цены юбилейных монет россии</a>
  • Gravatar crxkursyux February 1st, 2012 at 15:14
    wxfegnbsl, http://www.jlafjyprzo.com lkugtqrrpd
  • Gravatar vildElish February 1st, 2012 at 16:04
    A generic drug must contain the same active ingredients as the <a href= http://cabergoline.webs.com>buy dostinex cabergoline</a> This allows the company to recoup the cost of developing that particular drug.
  • Gravatar antarturi February 4th, 2012 at 09:47
    Although they may not be associated with a <a href= http://neurontin.webs.com>buy neurontin no prescription</a> For as long as a drug patent lasts, a brand name company enjoys
  • Gravatar adoreinia February 4th, 2012 at 15:33
    <b>Продам дебетовые карты</b>

    Виза классик, виза голд всех востребованных банков, всегда в наличии большой выбор.
    Стоимость карт:
    виза классик 5 т.р.
    виза голд 7 т.р.
    Комплектность. Все комплекты карт содержат: данные о пользователе в виде копии паспорта, пластиковую карту, пинкод, привязанную симкарту, договор банковского обслуживания, данные для работы с интернет банком, кодовое слово, необходимые выписки, реквизиты и чеки. Все комплекты готовы к работе.
    Оплата. <b>Работаем без предоплаты.</b> Вы получаете товар, проверяете и оплачиваете заказ

    <b>icq 612576295
    мобильный 8952 285 98 19 </b>



















    (2718) продажа дебетовых карт, дебетовые карты, купить, дебетовую карту, пластик, купить пластик, обнал, обналичка, карты для обналичивания денег, дебетовая карта не дорого,купли-продажа дебетовых карт, услуги по продаже дебетовых карт, visa, master card, дебетовые карты на заказ , выгодные условия по покупке дебетовых карт, услуги по продаже готовых дебетовых карт (0172)
Gravatar