This may just be the shortest post, with the most amount of work going into it :)

So, if you are passionate about Windows Phone development, a little something on the .NET web stack should interest you. It is called SignalR — An async signaling library for persistent connections between server & client. The real fun begins when you consider Windows Phone applications as client, with a SignalR powered server backend .. you get real-time connectivity on Windows Phone!! And tons of possibilities, like Chat, Maps, Game Scores, Stock Tickers, Object Exchange etc.

I was quite excited by the opportunities and took a stab at writing a Helper library with a demo Windows Phone application & a SignalR backend server. Since SignalR is open-source, along with most knowledge around it, why not this? So, all of my work is on CodePlex, ready to view/download/extend. A lot more work needs to go in to improve the libraries & may be make NuGets sometime. Please give it a shot .. download & hit F5. Would appreciate any feedback!

Windows Phone SignalR Helper
On CodePlex: http://wp7signalrhelper.codeplex.com/
Demo Video: Added to my WebCasts

Thank you & Adios!

Let us begin by … oh heck; we are trying to cut the fluff & fine-tune our Windows Phone applications, right? :)

So, here goes:

  • Images:
  • This should be common knowledge .. Windows Phone handles JPGs much quicker than PNGs. So, unless we need transparency, let’s stay away from unnecessary PNGs. Next comes the Resource vs Content dilemma. Resources adds bulk to DLL and Content adds files to the XAP. Larger DLL will add to App startup time; but render images quicker than first-time file access for Contents. There is no easy thumbrule here; depends on what fits your app. I personally see better performance with a Resource if app startup time isn’t being hindered much, and if using an image many times as panorama/page backgrounds. Much more details HERE.

  • DataContext/Binding:
  • If the XAML page has data binding (specially in case of panoramas), I find it odd to provide context to XAML on Page_Loaded event. Why not on Constructor, if possible? Not that Constructors need to be bloated; but why wait for the Loaded event if you can data bind right away and allow rendering? Even if I am firing off heavy operations on background thread, I prefer data binding (with cached data) before anything else. Data binding on Loaded/NavigatedTo should be reserved for times when on back navigations, you truly want updated data source or two-way binding.

  • App Startup:
  • Let us do everything possible to not hinder the rendering of the first frame page. Shoot for minimal code in App Constructor/Launching; similarly in MainPage with simple XAML layout. Progress indicators are great after first page renders; consider if the SplashScreen is really needed. If data binding needs dynamic data, consider overlaying the page contents with some progress indicators until ready. If binding to static data but fetching fresh data in background, I think it’s ok to load page and warn the user that he is looking as stale data. Great article HERE.

  • Threading:
  • Let’s make sure we understand the subtleties of threading and never ever block the king, the UI thread. Composition threads handle animations and off-load work to GPU; so not suitable for us to do any more heavy-lifting. Let’s make friends with the Background thread/worker (HERE‘s how) and push off anything we can to this guy. Until Async-Await become more mainstream, let us be diligent about marshaling stuff back to the UI thread through shared variables or Dispatcher.BeginInvoke().

  • Network Calls:
  • 4 thumbrules I try to follow: Through Background thread/HTTPWebRequest. Grab more in one call, instead of making many API calls. Cache anything possible. Check for connectivity & degrade gracefully.

  • Isolated Storage:
  • If not close to 90MB memory restriction, I try to minimize hits to Isolated Storage for disk access. It’s ok to have a giant object & serialize/deserialize in one go. And remember, encryption/decryption is expensive; so reserve for the super-sensitive stuff.

  • Performance Tools:
  • Let’s use what’s at our disposal – the Windows Phone Performance Analysis Tool (HERE) for detailed performance walkthrough and the Frame Rate Counters to figure out the bottlenecks. I try to watch out for huge memory footprints, like a high resolution image loaded in memory, but displayed as a small picture.

  • Controls:
  • Yes, we would love our Apps to be flashy; but complex & nested XAML comes at a price .. so let’s try to keep our layouts simple. Panoramas render all panels with data binding at once, which can take a toll on memory. Deferred panel loading and background bitmap as Resource are things I try doing when using Panoramas, or considers Pivots when possible. Things like toolkit HubTile controls also add a little bulk; make sure to stop animations on non-visible areas. Maps & WebBrowsers are expensive too; consider if the corresponding Tasks fit what you are trying to do.

  • Low-Cost Device Optimization:
  • Taking the marketing fight downstream was needed; hence comes the so-called lower devices with 256MB RAM. For the most part, we should be fine if following performance best practices for regular Windows Phone devices. Just a few additional things for us to keep in mind: Let’s not use Background Agents (can’t depend on them anyways since they can be disabled by user or overuse); watch the 90MB memory footprint; no looping backstack navigation; use the 256MB emulator for lowest common factor and let’s do all the things above to make our apps performant in low-memory devices. Best possible checklist HERE.

  • Common Sense:
  • The cliched term is true and lack of common sense on our part can have expensive performance repercussions. Or may be, this is just me :) . Late night coding sessions are great for ego & getting stuff done; but let’s sleep on it & review our work the next day for sanity checks. I have done stupid things like setting a background image on a panorama/grid & then the same one on every panel; result – double the brush memory gets loaded & counted against the app footprint. A responsive UI wins the battle any day over a complex layout. No unnecessary namespaces, proper use of threading & resources and general common sense = wonderfully performant Windows Phone apps. And a proud you, right?

Would really appreciate any feedback. Tell me what I missed. What techniques do you use?

Adios!

This will be a short post on a little roadblock that was overcome.

To-Do:

An internal Windows Phone application that we are building for Sogeti needed to pull down a chunk of data from a server for caching & displaying on the phone.

Meh .. So, what’s the Challenge?

Well, two little issues:

  • The content was sitting behind a Basic Auth protection with Windows credentials.
  • The downloadable piece is a Zipped file with hierarchical content, that had to be unwrapped.

Problems with the usual suspects

  • For some reason, WebClient refuses to honor Header information attached, which contains the user’s credentials to clear the basic authentication. Yet to figure out why .. may be Fiddler would help.
  • The Zipped file was a red flag. Although pulled down as HTTPResponse, how do we unpack & parse content files?

The Solution

Turns out, the solution was quite simple & included right in the toolset itself. As we know, WebClient is an abstraction over HttpWebRequest and big brother does do a few things better, including honoring HTTP Header information correctly. And after looking around for 3rd party libraries to unzip the content, good ol’ .NET seemed sufficient to reach inside the zipped content to parse exactly what’s needed. Here’s some sample code:

                      
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("https://someURI/File.zip"));

 byte[] credentialBuffer = new UTF8Encoding().GetBytes("UserID" + ":" + "Password");
 request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(credentialBuffer);

 request.BeginGetResponse(r =>
 {
    var httpRequest = (HttpWebRequest)r.AsyncState;
    var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);

    using (var reader = new StreamReader(httpResponse.GetResponseStream()))
    {
        StreamResourceInfo info = new StreamResourceInfo(httpResponse.GetResponseStream(), string.Empty);
        StreamResourceInfo fileStreamInfo = App.GetResourceStream(info, new Uri("SomeFolder/SomeFile.txt", UriKind.Relative));

        StreamReader fileReader = new StreamReader(fileStreamInfo.Stream);
        string rawText = fileReader.ReadToEnd();

        Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
        {
           // Update UI with rawText.
        }));
     }
 }, request);

As you could see, we reached inside the hierarchical folder structure within the Zipped file & were able to pull out file content. And since this is read in as a byte stream, the content could be any type of file that could be read from the Windows Phone client. Voila!

Now, this technique has one weakness – you need to know the folder structure inside the Zipped file to pull out exactly the content you want. If your goal is to explore the unknown inside a Zipped file, this would obviously not work. Two solutions I came across for such scenarios are Silverlight SharpZipLib and SharpGIS Unzipper.

Hope this was helpful.

Adios!

I guest-blogged for SilverlightShow recently:

Windows Phone + SignalR combo in action!

Real-time communication. Many software applications on variety of platforms & form factors have a genuine need for it. But persistent networks, real-time connectivity & asynchrony continue to challenge us developers in building such applications. Is there a silver lining? Could we have near-real-time communication in our mobile apps? Imagine the possibilities.

SignalR is an async persistent connection library for client-server communication that aids in building real-time, multi-user connected applications across multiple platforms. In this article, we take a quick deep dive into SignalR usage and how to leverage this technology from a Windows Phone application. Real-time communication with a backend server on a personal device like the Windows Phone has potentially tons of ways to apply SignalR in Apps.

Full article with screenshots, code samples & downloadable source code can be found HERE.

All the other great SilverlightShow content on Silverlight, WPF, Windows Phone, Windows 8 & other related technologies can be found at http://silverlightshow.net. Cheers!

Adios

null This is the Day #7 & last post in the article series “7 Deadly Sins for Windows Phone Developers!“.

What is Lust ?

From http://deadlysins.com:

Lust is an inordinate craving for the pleasures of the body.

Why: Oh, please.

How does Lust relate to Windows Phone development ?

– excessive desires ..

Upfront, we’re not going try to map Lust in the true sexual sense, since that would be difficult & a slippery slope :) . Let’s see how we Windows Phone developers can be wary against being over-zealous. Zest is good; craving without taking any appropriate action – not so much:

  • Bandwidth: Coming from a strong web background, we developers might end up blatantly using the user’s bandwidth. While rich content is good, we need to be aware that the phone is a mobile wireless device & not everyone is on an unlimited data plan. So, think twice when making data requests from the phone & have a solid caching strategy when possible. Use the DeviceNetworkInformation API to figure out state of network connections; may be we can do some heavy-lifting when appropriate (like data sync through ResourceIntensiveTasks while on WiFi).
  • Start-Up: While a dynamic flashy panorama/pivot home screen on your App may be a lucrative proposition, be aware of the cost. You only have a few seconds on the Splash page (if using one) before loading up the Home screen/MainPage. And while you can dummy up a Splash-screen-like pop-up on Home screen (like here), users usually do not want to wait too long. Consider using cached data from prior run of the App & indicate visually that you are fetching fresh data. And any time you are working with pop-up or login pages that you do not want to leave in page Backstack, make sure to clear them up.
  • Live Tiles: You desire your App to be like ones built by the cool kids. Don’t worry, we all do. One of the best favors you can do for your App is to support Live Tiles. This is one of the unique selling points of the platform, epitomizes Glance & Go and keeps inviting the user back into your App. Application Live Tiles or Secondary Live Tiles with backend support would be great; at the very least, you should consider presenting a slice of your App data as a local Secondary Live Tile.
  • Emulator Skins: We grew up knowing it’s not polite to stare, right? Yet when it comes to fancy new gadgets like smartphones, we openly drool .. and you know what, it’s ok :) . Sadly, we live in a society of perpetual buyer’s remorse where newer electronics tickle our wallets every day. Now, fancy new Windows Phones will come up every now & then, which you may not be able to jump to given your contract cage. However, instead of drooling, you can go one step closer while you develop Apps for Windows Phone. Check out the cool Windows Phone Emulator Skin Switcher — choose between any one of 25 different Windows Phone skins. Or make one yourself. If you’re doing Windows Phone Dev on spare time, might as well make it a little fun!
  • Marketplace Woes: In the zest to get our dream App live in the Marketplace, we can all get trigger-happy in Marketplace submissions; but beware of these potential ingestion hiccups. Also, some newer Markets may have additional Certification obligations to meet local regulations .. check all details with the Application Certification Requirements. If you go with worldwide distribution, your certification time would be longer and your App will be subject to extra scrutiny. If you see failures, resubmit after fixing the issues or you could deselect the troubled Markets to get your App live in the Marketplace quicker.

Today is the last article in this series of “7 Deadly Sins for Windows Phone Developers!“. Apologies if the tone of anything I said sounded awkward .. by things “you” need to do, I really meant me. I simply wanted to document all the resources I want to keep in mind during my next Windows Phone app. Hope the articles were somewhat fun .. thank you very much for reading. Lot of good times ahead for us Windows Phone developers .. cheers to that.

Adios!

null This is the Day #6 post in the article series “7 Deadly Sins for Windows Phone Developers!“.

What is Gluttony ?

From http://deadlysins.com:

Gluttony is an inordinate desire to consume more than that which one requires.

Why: Because you were weaned improperly as an infant.

How does Gluttony relate to Windows Phone development ?

– over-indulgence/over-consumption ..

Gadgets. They just keep coming .. new & improved, faster & better, smarter & more personal. Tablets & computers of today easily match the computing & storage capabilities of super machines from a few years back. All this, in my opinion, is making us developers a little lazy. We are having to pay less attention to performance as the available horsepower simply swallows potential issues.

Mobile development is a great leveler in that regard. Just the constraints of the smartphone form factor give it limited resources and this brings our code closer to the metal & demands restraint. We need to worry about performance optimization, since lack of it leads to crappy user experience. Let’s take a look at how we Windows Phone developers can avoid Gluttony while developing for the Windows Phone ecosystem:

  • Resources: Overconsumption of phone’s resources is bad. The Windows Phone team has worked very hard to make the core OS very very lean .. our resource hungry app will stick out even more in this context. Make sure your memory footprint is small; this ensures that your app runs efficiently when loaded in device RAM and stays longer in memory as Mango does Multitasking/Fast Application Switching(FAS). Managed code helps; but make sure you do not have extra Using statements or referencing any library that you do not need. Beware of using multiple 3rd party toolkits, specially if there is overlapping functionality. Also, animations are nice & an integral part of Metro; but too much of it is not good. I have personally seen performance degrade when swapping out the default PhoneApplicationFrame (one that houses your XAML pages) with 3rd party tooling for custom animations; but that could be just me. Anyways, point is, know exactly what you need & don’t go over. This is an awesome checklist for performance tuning.
  • Threading: Surely no one needs to be told that locking up the UI thread is just not an option on tablet/smartphone applications. You may be counting national population/debt; but your App UI needs to be responsive. Most Silverlight programming forces us to do heavy-lifting asynchronously, by intelligent use of Background threads for processing, Composite threads for animations & auto-merging with UI thread. You may use an explicit Background worker, if needed. Hang tight as life is gonna get better when the now-supported Async CTP is finalized .. no more gobblygowk Dispatcher.BeginInvoke() or DownloadCompleted() APM/EAP patterns (details here) .. you should just be able to do async-await to achieve asynchrony.
  • Caching: Cache anything possible to prevent making the same web HTTP call twice. This specially applies to images/flat data. Check out the following resources to cache artifacts in Isolated Storage here, here & here.
  • Execution Model: Now that you know Windows Phone Mango supports FAS through a in-memory application backstack, did you stop caring to handle Tombstoning? We cannot just write a resource-heavy App and expect it to be held in memory for long. Coming out clean from Tombstoning is a must .. this article on Execution Model could be a good place to start :) .
  • Alarms/Reminders: The new APIs to create Alarms/Reminders are great; but please do not over-indulge in reaching anywhere close to the limit of 50 or create them without user intervention.
  • API Exploitation: The new Calendar & Contacts APIs are super handy, aren’t they? But again, with power comes responsibility. Do not exploit them to do things without user intervention. Uninstallation & bad reviews will follow.

That’s it for today. Crux of this post: Just because you can, doesn’t mean you should! Hopefully, you come back tomorrow for the Day #7 article in this series of “7 Deadly Sins for Windows Phone Developers!“.

Adios!