Silverlight 3 – Local Messaging Explained + Enhancement
TweetOne 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.
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);
}
}




DotNetBurner - burning hot .net content...
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.
<IMG> http://www.valar.ru/gallery/0112/rgtdhtfr.jpg</IMG>
ПРОГРЕССИВНЫЙ МЕТОД ЗАРАБАТЫВАНИЯ НА НОВУЮ КВАРТИРУ В ТЕЧЕНИЕ 365 ДНЕЙ!!!
ЭТО КУРС ОБЩЕДОСТУПЕН И РАСЧИТАН ДАЖЕ ДЛЯ ТЕХ КТО НЕ ИМЕЕТ НАВЫКОВ РАБОТЫ В
ИНТЕРНЕТ,А ПО ЭТОМУ КАЖДЫЙ ЖЕЛАЮЩИЙ УЖЕ СЕГОДНЯ МОЖЕТ ЗАРАБАТЫВАТЬ ПРИЛИЧНЫЕ ДЕНЬГИ В СЕТИ!
<a href= http://wre453.kd2012.e-autopay.com>ПОДРОБНЕЕ...</a>
зароботок,работа 2012,работа в сети,работа в интернет,видео,обучающее видео,видеокурс,КОД ДЕНЕГ 2012,практический курс,обучающий видеокурс КОД ДЕНЕГ 2012,деньги,интернет,высокооплачиваемая работа 2012.
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).
<IMG> http://www.valar.ru/gallery/0112/rgtdhtfr.jpg</IMG>
ПРОГРЕССИВНЫЙ МЕТОД ЗАРАБАТЫВАНИЯ НА НОВУЮ КВАРТИРУ В ТЕЧЕНИЕ 365 ДНЕЙ!!!
ЭТО КУРС ОБЩЕДОСТУПЕН И РАСЧИТАН ДАЖЕ ДЛЯ ТЕХ КТО НЕ ИМЕЕТ НАВЫКОВ РАБОТЫ В
ИНТЕРНЕТ,А ПО ЭТОМУ КАЖДЫЙ ЖЕЛАЮЩИЙ УЖЕ СЕГОДНЯ МОЖЕТ ЗАРАБАТЫВАТЬ ПРИЛИЧНЫЕ ДЕНЬГИ В СЕТИ!
<a href= http://wre453.kd2012.e-autopay.com>ПОДРОБНЕЕ...</a>
зароботок,работа 2012,работа в сети,работа в интернет,видео,обучающее видео,видеокурс,КОД ДЕНЕГ 2012,практический курс,обучающий видеокурс КОД ДЕНЕГ 2012,деньги,интернет,высокооплачиваемая работа 2012.
В четвертом квартале 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>
Виза классик, виза голд всех востребованных банков, всегда в наличии большой выбор.
Стоимость карт:
виза классик 5 т.р.
виза голд 7 т.р.
Комплектность. Все комплекты карт содержат: данные о пользователе в виде копии паспорта, пластиковую карту, пинкод, привязанную симкарту, договор банковского обслуживания, данные для работы с интернет банком, кодовое слово, необходимые выписки, реквизиты и чеки. Все комплекты готовы к работе.
Оплата. <b>Работаем без предоплаты.</b> Вы получаете товар, проверяете и оплачиваете заказ
<b>icq 612576295
мобильный 8952 285 98 19 </b>
(2718) продажа дебетовых карт, дебетовые карты, купить, дебетовую карту, пластик, купить пластик, обнал, обналичка, карты для обналичивания денег, дебетовая карта не дорого,купли-продажа дебетовых карт, услуги по продаже дебетовых карт, visa, master card, дебетовые карты на заказ , выгодные условия по покупке дебетовых карт, услуги по продаже готовых дебетовых карт (0172)