Display Image from Stream in Windows 8 and Windows Phone 8

The alternative title could also have been “Converting Stream to  IRandomAccessStream in windows store apps and windows phone 8.”

Frequently we might need to extract an image from a stream and display it in a XAML control,also called Image.

Typically the Stream can come from WebResponse or through any other source.

Stream stream= response1.GetResponseStream();

Where response1 is the WebResponse.Now it’s a daunting task to extract the image from the stream in Windows RT and Windows Phone 8 specially since we do not have access to system.imaging and related namespaces. So how do we go about it ?

Step 1:

Convert Stream to Memory Stream.The reason for this is that later,we need to convert Stream to IRandomAccessStream section.Memory Stream inherits from Stream.Memory Stream is a special class for accessing and storing the data in memory.

The MemoryStream class creates streams that have memory as a backing store instead of a disk or a network connection

MemoryStream ms = new MemoryStream();

Step 2:Convert MemoryStream to IRandomAccessStream.

This is the trickiest part as because there is no built in simple of way of doing this.IRandomAccessStream ia windows RT stream for random access of data.While coding,you might need to convert to and fro between .NET streams and Windows RT streams.For doing that,there are extension methods . These are AsInputStream and AsOutputStream .The problem with AsInputStream is that it converts a Stream to an IInputStream.  What we need is a Stream converted to an IRandomAccessStream

Lets see how this is done,

We implement an user defined function for doing so


 public static async Task<IRandomAccessStream> ConvertToRandomAccessStream(MemoryStream memoryStream)
            var randomAccessStream = new InMemoryRandomAccessStream();
            var outputStream = randomAccessStream.GetOutputStreamAt(0);
            var dw = new DataWriter(outputStream);
            var task = Task.Factory.StartNew(() => dw.WriteBytes(memoryStream.ToArray()));
                await task;
                await dw.StoreAsync();
                await outputStream.FlushAsync();
            return randomAccessStream;

What this basically does is creates a new InMemoryRandomAccessStream which implements IRandomAccessStream.Then we point to the location in the output stream at which to begin through the GetOutputStreamAt function..Then we create the Datawriter and manually asynchronously copy the data from the memory stream to the output stream and store it.

step 3:

we set the source of the bitmapImage

IRandomAccessStream a1 = await ConvertToRandomAccessStream(ms);
await bitmapImage.SetSourceAsync(a1);

Step 4: Finally

imageBox1.Source = bitmapImage;

We set the source property of the XAML image control and set it to the bitmap image.

Here’s the consolidated code.

Stream stream= response1.GetResponseStream();
BitmapImage bitmapImage= new BitmapImage();
MemoryStream ms = new MemoryStream();
 IRandomAccessStream a1 = await ConvertToRandomAccessStream(ms);
 await bitmapImage.SetSourceAsync(a1);
 imageBox1.Source = bitmapImage;

Optimizing Selectors in JQuery.

jQuery uses a selector engine called Sizzle.Sizzle has various ways of selecting elements. Selecting elements is one of the fundamental part of jQuery, hence it’s important we learn how to optimize our selectors. jQuery selector Engine runs from right to left. Being specific on the left hand side has a lot less value than being specific on the right hand side.

$(“.parent .child”)//This is how the selector engine works.

A common misconception is that being accurate makes the selector works faster as it knows where to find the DOM element. But that is not the case. jQuery has a very different way in which it handles selecting by id or selecting by class.

<ul class=”listing”>

<li class=”bullet”>

<h3 class=”mainelement”> This is a test<h3>




$(‘ul.listing li.bullet h3.mainelement’) //though is the most specific is not the fastest.

The fastest selector is simply the class name by itself.

$(.parent child)//Fastest

Anything else is telling jQuery to do more work than necessary. Starting from the right that is all that we need to get the set of elements.

<ul class=”listing”>

<li id=”bullet”>

<h3 class=”mainelement”> This is a test<h3>



Now since we have an id. We can further bring down the time required by selecting with ID.

$(‘#bullet .mainelement’)//Sizzle operates differently when the first selector is ID

But to really speed things up, we can use

$(‘#bullet’).children(‘.mainelement’) or $(‘#bullet’).find(‘.mainelement’)

The latter being the fastest. To understand the discrepancy we must look into the jQuery Source. When the only part of the selector is an ID jQuery uses document.getElementById(id) which drastically reduces the time taken.

$(‘p#randomid’) //jQuery will use getElementsByTagName(), then iterate though the array of elements for the above selector.

var div = $(‘#randomId’);ßjQuery will use getElementById() for the above selector

From the source code we can see, the fastest selector is

$(‘ ‘)//Returns an empty jQuery object.

$(‘body’)//Next in line, jQuery converts this to document.body

$(‘#id’)//Third fastest, jQuery converts this to document.getElementById(‘id’)


Now to distinguish between children() and find(), Children only looks at the immediate children of the node, while find traverses the entire DOM below the node. But in general cases find is faster. children () internally makes calls to sibling(), filter(), and goes through a few more regexes than find() does. find () and children() fulfill different needs, but in the cases where find() and children() would output the same result, it’s better to use find().

Jquery Mobile Page events demystified.

Why Not $(document).ready ?

Typically, one of the first things that we learn in JQuery. This function is invoked after Jquery Loads the DOM and finishes any initialization work that needs to be done. This is the preferred choice since the normal Javascript Window .onLoad() waits for all the images to be loaded and that can make our web page unresponsive. Whereas the DOM ready event fires when all the DOM content is parsed and placed into the document.

But in case of JQuery Mobile, a single HTML file can have multiple “pages”. Technically in JQuery Mobile any container with a data-role=”page” is considered an independent page.

Hence Jquery Mobile has a different life cycle of events. If at all we use $(document).ready , we will see it will fire when the entire html is loaded once only. During successive “page” traversal it wouldn’t fire since the DOM is loaded once.

Even if the “pages” are kept in different HTML, JQueryMobile ignores everything that is not within the data-role page. It takes the page elements and puts it inside the current DOM instead of loading the DOM of the page as page transitions are done using AJAX.

Jquery Mobile provides us with various Page events

pagebeforecreate Triggered when the page is just created and the Jquery widgets are yet to be initialized.Basically it is used bt developers to change or edit the markup before Jquery does it.
pagecreate Triggered when page is created but before widget enhancement is done.
This event is most useful for user’s wishing to create their own custom widgets for child markup enhancement as the jquery mobile widgets do.
pageinit The usual Documentready event that we use for JQuery.It runs after the page is created and the enhancements are done.
pageshow This runs after pageinit. Runs everytime a page is shown.

A key difference is between “pageinit” and “page show” is that “pageinit” runs once when the “page” is displayed first. But somehow if we return to the particular page in our app, the pageinit event wont fire, but the “pageshow” event fires every time the page is displayed.Hence code that needs to be run only when the page is initialized first needs to be associated with the “pageinit” event. While the code that needs refreshing every time the user returns to the page should be associated to “pageshow” event.

Windows 8 Launch

Some of the key topics presented today are:

Microsoft will be launching 3 items today

1. Windows 8 Launch

2. Windows Store

3. Windows RT launch, windows 8 experience optimized for PC with arm processor

Session kicks off by talking about the development experience of Windows 8 , how they had collaborated with OEMS, customers various stake holders. The result is Windows 8 which has a Battery life improvement of 13 % less .Cold start time under 10 seconds, Memory usage optimized by 20%

Win 8 Preview had been beta tested for almost 1.24 billion hours of across the world, making it the most heavily tested OS ever. Starting 12 :00 Windows 8 and Windows 8 upgrades will be available .Upgrades starting as low 39$ 99 cents in US. Over 1000 certified Windows 8 PCs are slated to be launched .Every windows 8 runs Windows Store apps that will be open to 231 markets in 109 languages across the world.

Windows RT includes office 2013 which is said to be touch and stylus optimized , supports more than 400,000 devices and peripherals through it USB. This basically means that device that would be ready to plug and play through Bluetooth, Wi-Fi, USB will also remain the same for win RT. Power efficient and touch optimized office apps. Windows RT does not run programs for windows 7.Windows RT can only run apps from Windows store. Windows RT can run the same peripherals that we are used to windows 7.All day battery and SkyDrive and Live services are built in.

Windows 7 PCs that have been upgraded to windows 8 have been demoed. A windows 7 PC when upgraded uses 33% less boot time and 43% less memory. Lenovo ThinkPad tablet 2 is being shown running windows 8 PRO, full featured enterprise level. Reacts to both stylus and touch.10 fingers touch supported.

Dell PC shown which flips out from pc to tablets.

One click install from windows store. Search functionality is embedded, searching across various apps through charms bar. Wikipedia app is demoed. How an user can search across both Wikipedia and apps from the same place without unnecessary clicks.

Dell XPS 10, Samsung ATIV tab advertised with 12 hours battery life.

Asus vivo tab runs windows RT comes with a detachable keyboard with doubles the battery to 18 hours. The key board actually has a battery pack which doubles the battery time. Pretty neat I must say!

Steve Balmer comes on stage .He speaks about how windows had been completely reimagined from the ground up.

Devices ranging from affordable to high end. Unified pen,stylus and keyboard and mouse all within a single OS. Talks about office optimized for touch and stylus. Bing apps built right in.Talks about the new ‘Always on Skype app’. XBOX music, XBOX Videos and XBOX games services built in.

He talks about entertainment features of Windows 8.Windows tablet serves as a second screen while watching movies through Xbox.It will be displaying relevant information pertaining to the movie.

Enterprise apps will be redesigned for windows 8.

Finishes off by saying the commercial opportunity of the windows Store as 670,000,000 Windows 7 pcs ready to be upgraded.400 million pcs forecasted to be sold annually.

PageInit binding anamoly in JqueryMobile

The reason:

In JqueryMobile, while traversing in pages within the webapp, JQueryMobile fetches the page and puts it in the current DOM. While this is true for all situations. This might result in a large DOM that eats up lot of memory. JqueryMobile has a way of overcoming this barrier. The JqueryMobile documentation states that

“JQuery Mobile therefore has a simple mechanism to keep the DOM tidy. Whenever it loads a page via Ajax, jQuery Mobile flags the page to be removed from the DOM when you navigate away from it later”.

This can lead to browser specific strange behavior of our web apps. As the amount of cache varies and how the pages are cached also varies. Hence often it leads to multiple ‘pageinit‘.

It’s of common practice to bind the code that needs to be run to the pageinit event. As a result each time pageinit is fired, our function is also called. Now if the function is fired multiple times for the same page, it leads to performance issues. Sometimes due to the nature of code we might not be able to see visualize that the function binded pageinit had been fired twice or thrice. JqueryMobile being a fairly new technology has a dearth of materials across the web. While making the app, we found that the debugger showing multiple service calls instead of just one. While there was absolutely no noticeable changes in the UI, the debugger console showed results as if the page was repeatedly refreshed. While this error has been faced by many developers, there are no articles explaining it.

The Problem:

On careful perusal, I have able to reproduce this problem consistently in Chrome v22.0.

There are 3 html files each having a JqueryMobile “page“.Please refer to the above diagram

Page1 has a link to Page2.Page 1 also has some code that tracks how many time ‘page-init’ event is fired.

Page2 has a link to both Page1 and Page3.

Page3 has a link to page 1.

We start from page 2.

  1. Step 1: We start from page 2.Navigate to Page 1.
    1. Result: page1 fires pageinit event and we get an alert with c=1;
  2. Step 2: We navigate to page2 through the link.
  3. Step 3: We navigate to page3 from page2 through the link.
  4. Step 4: We navigate to page1 again through the link in page3.
    1. Result:pageinit fires twice.c=1,c=2
  5. For each successive iteration through Step 2-step 3-step 4,the number of times page-init fires increases by 1 each time.

This by no way means that pageinit is fired 4-5 times !!. Pageinit is fired only once for each page. This anomaly is because pageinit is binded to the same handler/callback more than once that causes the unpredictable results

The Solution:

To fix the problem we need to call die to unbind the event before binding it to ensure that it will only trigger once. Here is the fix.

Before we attach the function to pageinit event. We write $(“#FirstPage”).die(‘pageinit’);This tells Jquerymobile to unbind all functions from this event. The fix above ensures that only one handler is binded to pageinit event of the page. Hence the problem of repeated binding is gone. While the solution is pretty easy, the problem itself is very subtle but has serious consequences. Pageinit event binding is the best way to initialize the page like loading the data or initializing states. The only problem with pageinit
is that we need manage it in such way that it will not trigger more than once.