Code for Keeps:- Store Retrieve image to/from Database

One of our early blogs was about extracting images from databases, websites and showing them on the screen.

The blog(see it here) dealt with

a) Retrieving images from the www

b) Retrieving images from the database when retrieved as a binary.

We realized there are some more scenarios to take care of here

c) Save Image to the database as a byte[]

public Byte[] BufferFromImage(BitmapImage imageSource)
         MemoryStream memStream = new MemoryStream();
         JpegBitmapEncoder encoder = new JpegBitmapEncoder();
         return memStream.GetBuffer();

d) Retrieve Image from byte[]( When you use Entity Framework with the Image database type you would get it back as a byte[])

public BitmapImage ConvertToImage(byte[] rawImageData)
      MemoryStream stream = new MemoryStream(rawImageData);
      stream.Position = 0;
      BitmapImage bi = new BitmapImage();
      bi.StreamSource = stream;
      return bi; 
If you see any more scenarios do add comments and lets complete this list…

WPF/Silverlight Canvas Vs Single Cell Grid

I’ve often been asked the question of when should we use a Canvas and when a Single Celled Grid….

This is a snapshot of the an MSDN article . Our inputs are marked as [Cennest:]. The source can be read at

A single-cell Grid is just like a regular Grid except without any row or column definitions. If the Grid has only one cell, you can put multiple elements into the Grid cell and you don’t use any of the Grid’s attached properties to indicate rows or columns.

Initially, using a Canvas or a single-cell Grid seems very similar. Regardless which one you use for vector graphics, Line, Polyline, Polygon and Path elements will be positioned relative to the upper-left corner of the container based on their coordinate points.

The difference between the Canvas and the single-cell Grid is in how the container appears to the rest of the layout system. WPF and Silverlight incorporate a two-pass, top-down layout where every element interrogates the size of its children and is then responsible for arranging its children relative to itself. Within this layout system, the Canvas and the single-cell Grid are very different:

  • To its children, the Grid has the same dimensions as the dimensions of its own parent. These are usually finite dimensions, but the Canvas always appears to have infinite dimensions to its children.
  • The Grid reports the composite size of its children to its parent. 
However, the Canvas always has an apparent size of zero, regardless of the children it contains.

[Cennest:- This has an impact when you try to put the canvas in a Scrollviewer and think that the ScrollViewer will automatically show Scrollbars if the canvas starts exceeding the height and width. However you are zapped when the scroll bars just don’t show up…this is because the canvas notified its height and width as 0 to the scrollviewer which then happily did not show any scrollbars!!.

A workaround for this if you still want to use the scrollbar is to create a Custom Canvas control and override its MeasureOverride property. See this sample]

Suppose you have a bunch of Polygon elements that form some kind of cartoon-like vector graphics image. If you put all these Polygon elements in a single-cell Grid, the size of the Grid is based on the maximum horizontal and vertical coordinates of the polygons. The Grid can then be treated as a normal finite-sized element within the layout system because its size properly reflects the size of the composite image. (Actually, this works correctly only if the upper-left corner of the image is at the point (0, 0), and there are no negative coordinates.)

Put all those polygons in a Canvas, however, and the Canvas reports to the layout system that it has a size of zero. In general, when integrating a composite vector graphics image into your application, you almost certainly want the behavior of the single-cell Grid rather than the Canvas.

So is the Canvas entirely useless? Not at all. The trick is to use the peculiarities of the Canvas to your advantage. In a very real sense, the Canvas doesn’t participate in layout. Hence, you can use it whenever you need to transcend layout—to display graphics that break the bounds of the layout system and float outside it. By default the Canvas doesn’t clip its children, so even if it is very small, it can still host children outside its bounds. The Canvas is more of a reference point for displaying elements or graphics than it is a container


Hope this makes things a bit clearer!

Till next time!


Improving WPF/Silverlight- WCF Communication!

While working on a recent assignment related to establishing and optimizing duplex communication with Silverlight and WCF,we learnt quite a lot of new concepts like HttpPollingDuplex binding  with multiple messages mode Http Long Polling designs etc.

While most of these concepts were new we did get a bulb flash on how to improve basic WPF/Silverlight WCF communication!!

All WPF/ Silverlight applications share the same threading model . They have a UI thread and a rendering thread. The rendering thread takes care of the background processing while the UI thread takes care of painting the screen, resizing and the overall look and feel. Whatever happens on the UI thread is primarily synchronous and blocks the UI.

Now whenever we need to work with WCF services without blocking the UI we go for asynchronous calls(In Silverlight we have no option anyway), but the mistake we make is we call the WCF service directly from the UI thread(on say a button click). Now since the webmethod was called from the UI thread its Async Event Handler is also executed on the same thread. So this event handler becomes one of the many tasks the UI thread has to be performed and the end result is a slower UI update. An advantage here is that since we are on the UI thread we can update the UI element directly(else we would have to use a dispatcher!)

How else should we do this?:- An ideal way here would be to separate the task of the UI thread and disturb it only when needed i.e when we need to update the UI.

So basically use worker threads to invoke the webservices and handle their responses and use dispatchers  to update the User Interface! So the downside is slightly more complex code to finally update the UI but then you used WPF/Silverlight to get a great and responsive does come at a cost:-)

Hope this Bulb Flash helps you improve your app performance!!

Until some more flashes!


Monetize your Silverlight Videos!!

Silverlight streaming seems to have caught the fancy of many and a lot of sites are now streaming Silverlight videos.. however very few are making money from doing so!!..

Recently came across an Open Source Silverlight Media player called OpenVideoPlayer which lets you do just that!!..

Dynamically Insert ads into your media files with configurations like Preroll, Mid-roll and Post Roll(which basically mean, before, in between or after a video file plays) . It uses the MAST sequencing engine for sequencing of ads and VAST as the ad-connector.

For those new to the ad monetization world..VAST would dictate the “WHAT” of an ad. Its a flexible XML format which specifies links to the ad creatives and allows click through and tracking..MAST on the other hand dictates the “WHEN” of the ad,its an XML format which specifies WHEN the ad should play and links to the VAST source to indicate which one. You can set multiple trigger conditions to set off an ad!

So using these two you can control which ads are played when and where they are streamed can use Ad-Servers like Atlas or any other.

OK enough “Gyaan” as we say in India:-)…lets have some screenshots to understand what we are talking about..

Here is the Player playing a video


And here is the same video with a pre-roll ad..


and the video starts after the ad is done with image

Lets look at what this solution structure looks like..


Lets see what’s what here..

  1. OVP.xap:- The Open source Open Video Player. You can download this from here
  2. MASTSequencing.xap:- The Mast Sequencing component( defines the WHEN!!).
  3. VASTAdHandler:- the VAST component(WHAT!!)

These three are pretty standard and frankly you need to modify these…what you may want to modify are.. the

  1. Index.html:- Which holds the OVP.XAP, configures it with the plugin handlers and  specifies the media source(see feedsource)
    <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%" id="slp" >
    <param name="source" value="OVP.xap"/><param name="minRuntimeVersion" value="2.0.30923.0" /><param name="onerror" value="onSilverlightError" /><param name="background" value="black" /><param name="MaxFrameRate" value="30" />
    <a href="" style="text-decoration: none;"><img src="" alt="Get Microsoft Silverlight" style="border-style: none"/></a>
    <param name="initparams" value='showstatistics=true, autoplay=true, muted=false, playlistoverlay=true, theme=themes/Default.xaml, smfPlugins=BasicMediaPlugin.xap,plugins=MASTSequencing.xap VASTAdHandler.xap ,
    mast:sourceuri=mast.xml,stretchmode=Fit, stretchmodefullscreen=Fit, 
    feedsource=http%3A//' />

2. MAST.xml:- You can change the VAST location to specify a different ad source. You can also specify the ad timings. For example this one specifies a Pre-Roll and a Mid Roll Ad, so the ad plays before the video and again after 20 seconds. Also notice the Operator= GEQ, which means Greater or Equal , so suppose the user fast forwards the video from 10 to say 30 seconds, the ad will start showing at 30 seconds..


While we are still at it…lets also see what the VAST.xml looks like…as per this MAST.xml we are pointing to;sf=VAST_PreRoll_XML_V2;pf=FLV;br=500;strm=1

Here is what it looks like


So basically its a list of Ad addresses. What the VASTAdHandler then does is, it goes through each ad and plays the first compatible format ad which in my case happens to be wmv…since i am using a BasicMediaPlayer..

Pretty simple configurations and an excellent Open Source tool…Did i mention that its plugin based so it can be easily extended!!

Keep looking here for more insights into newer abilities!!


Silverlight:- Browsing without a Browser??

Wanna navigate to from your Silverlight application?? Just put the following code

   HtmlPage.Window.Navigate(new Uri("")

We all know THAT…so what’s this blog all about??.Now lets take this application Out of Browser



This is what you will get..


WHY???:- Because there’s no browser when running out of browser, so you can’t use the DOM and Scripting.Html Bridge is disabled when your application works on Out-Of-Browser mode

So there were pretty much no direct solution to this in SL3. But in SL4 we have a brand new and shiny Web Browser control especially for OOB setting…(infact it doesn’t even work in online mode!!)

So what you need to do is this..

Check if you app is running in OOB mode using


If running out of browser navigate to a page hosting the Web Browser control


In code behind navigate to the required url..

this.webBrowser.Navigate(new Uri(""));

and this is what you get!


There’s more:- Not only does this cool control let you browse to sites in an OOB mode, it also listens for events from those sites(something that doesn’t happen so easily in online mode)!!

The navigated page can then pass a value to the browsercontrol via a javascript text like

<html xmlns="">
<head runat="server">
     <script type="text/javascript">
         window.external.notify('hello from google!');

The Webbrowser has a ScriptNotify event which you can hook onto in your XAML page as

this.Browser.ScriptNotify += new EventHandler<NotifyEventArgs>(Browser_ScriptNotify);

 void Browser_ScriptNotify(object sender, NotifyEventArgs e)
         string value= e.Value;

Another welcome step in the direction of enabling Offline and OOB applications!!!..We recently used this for one of our projects to enable LiveID Authentication from an OOB app…pretty cool!!



MEF ,Prism and the Surrounding Confusion!!

While reading up on Prism 4…the integrated Prism which ships in .NET 4.0, i  saw people still wondering on how MEF and Prism compare…are they the same…do they complement….etc etc..Having seen these questions almost 2 years back with Prism(then called the CAG) and MEF were just announced i was surprised the confusion still exists…

Here is how i explained it to myself…hopefully it helps you too!!

The main reason everyone seems to be confused it “they both help create extensible and modular applications”!!!

MEF is primarily an “extensibility” model…it helps you make “extensible” applications by allowing your application to “import” modules dynamically at runtime. For example all you may need to do is drop the dll of your module at a specific folder and it magically becomes a part of your application!!

So it “explicitly” provides “extensibility” because you are purposely extending your application by importing modules into it , and it “implicitly” provides modularity because your application is made up of modules!!!So the MAIN reason you would go for MEF is when you want a modular application with application extensions where the extensions can be added dynamically and at runtime..


Now for Prism..

Prism is a “guidance” on how to make client applications modular. It maintains modularity by keeping all the modules of the app loosely coupled(with no knowledge of each other). The GUI defines regions where the modules are loaded dynamically. The framework provides a publish-subscribe events model via an EventsAggregator which enables the modules to communicate with each other without any tight coupling..

So Prism “Explicitly” provides modularity and implicitly supports Extensibility as a side effect of good modularity:-)

Now with Prism 4.0 we can see examples of using Prism +MEF together which will be the ultimate combination of an extensible and modular application!!

Hope this clears your confusion…it definitely cleared mine!!


Location Based Applications in Silverlight Using Bing Maps!

Going to the headquarters of Microsoft..Redmond is every developers dream…so the first time i happened to go there i was truly overjoyed!!. I tried my best to describe the entire town to my family and friends but pictures were never enough…and then came in Bing Maps…now they can virtually (pun intended:-)) walk the streets of Redmond with me…

Microsoft recently also released BingMap Control for Silverlight!…so now you can make your applications super jazzy by plugging in these controls and even making use of Bing Web Services for advanced features like Geocoding and Reverse Geocoding… I tried my hands on the BingMapSDK and was delighted to find it fairly explanatory(with some help from blogs as well…).

Trying out the basics i decided to try out the following.

1. Adding Pushpins

2. Reverse Geocoding

3. Adding Polygon

4.Adding a Polyline..

Here are some screenshots of my application


I Zeroed in on Redmond/Bellevue using the following settings

Mode=”AerialWithLabels”  Center=”47.6126490988388,-122.205053960122″ ZoomLevel=”14″

Added code to add a pushpin on mouse click and reverse geocode the address..


Mark different areas using a Polyline


Mark a region using a Polygon


There is no end to the possibilities which come with these new controls and features…It will definitely be interesting to see how people use this  new level of information;-)

If you are looking to exploit some of these potentials…get in touch and we can do it together!

Till Then!!