the next door (so called) geek @rakkimk | your next door geek | friend | blogs mostly on technology, and gadgets.

Extending Glimpse for ASP.NET to include custom Timeline messages

23. August 2013 20:15 by the next door (so called) geek in ASP.NET, Glimpse

If you are debugging any ASP.NET MVC or WebForms, and you haven’t used Glimpse yet, you are missing big! This also has nice extensions to other frameworks like EF, nHibernate, etc. This collects the server side data, and presents an overlay in the client side. Information such as the configuration, environment details, request details, server variables, traces, and most importantly the timeline of events. I’ll let you explore more about Glimpse, and it’s features from their website. Here is an example of how the timeline looks for a sample MVC4 application:

image

Adding your own message in the timeline seems to be a feature that’s getting worked upon by the Glimpse team. Until they release an easier way, here is what you can do to get your custom messages in the timeline. Here are the easy steps.

  • You need to create a new Class deriving from Glimpse.Core.Messaging.ITimelineMessage, and implement it’s properties, and add a new constructor which you will call from your code later to initialize a message to be added to the Glimpse timeline for the request.
  • Grab the Glimpse Runtime in the code.
  • Measure the time between your calls.
  • Publish the message via GlimpseRuntime.Configuration.MessageBroker.Publish<T>(message) method.

Here is the sample code for the above steps:

// grab the glimpse runtime
Glimpse.Core.Framework.GlimpseRuntime gr = (Glimpse.Core.Framework.GlimpseRuntime)HttpContext.Application.Get("__GlimpseRuntime");
 
// get hold of the timespan offset
TimeSpan t1 = new TimeSpan((DateTime.Now - gr.Configuration.TimerStrategy().RequestStart).Ticks);
 
// start a stopwatch
Stopwatch sw = new Stopwatch();
sw.Start();
 
// your function that you want to measure the time
System.Threading.Thread.Sleep(1000);
 
// stop the stopwatch, and get the elapsed timespan
sw.Stop();
TimeSpan t2 = sw.Elapsed;
 
// create the message with grouping text as appropriate
MyTimelineMessage msg1 = new MyTimelineMessage("WebService Calls", "first call to fetch x", "something here too", t2, t1, gr.Configuration.TimerStrategy().RequestStart, "red");
// publish the message to appear in the glimpse timeline
gr.Configuration.MessageBroker.Publish<MyTimelineMessage>(msg1);
 

Once this message is published, this will appear like below (depending on when you have called this in the request processing):

image

Here is my sample MyTimelineMessage.cs that you can use:

using Glimpse.Core.Message;
using System;
using System.Collections.Generic;
 
/// <summary>
/// Summary description for MyTimelineMessage
/// </summary>
public class MyTimelineMessage : ITimelineMessage
{
    TimelineCategoryItem _timeLineCategoryItem;
string _eventName, _eventSubText;
    TimeSpan _duration, _offset;
    DateTime _startTime;
    Guid _id;
public MyTimelineMessage(string itemName, string eventName, string eventSubText, TimeSpan duration, TimeSpan offset, DateTime startTime, string color)
    {
        _timeLineCategoryItem = new TimelineCategoryItem(itemName, color, "Yellow");
        _eventName = eventName;
        _eventSubText = eventSubText;
        _duration = duration;
        _offset = offset;
        _startTime = startTime;
        _id = new Guid();
    }
 
public TimelineCategoryItem EventCategory
    {
        get { return _timeLineCategoryItem; }
        set { _timeLineCategoryItem = value; }
    }
 
public string EventName
    {
        get { return _eventName; }
        set { _eventName = value; }
    }
 
public string EventSubText
    {
        get { return _eventSubText;  }
        set { _eventSubText = value; }
    }
 
public TimeSpan Duration
    {
        get { return _duration; }
        set { _duration = value; }
    }
 
public TimeSpan Offset
    {
        get { return _offset; }
        set { _offset = value; }
    }
 
public DateTime StartTime
    {
        get { return _startTime; }
        set { _startTime = value; }
    }
 
public Guid Id
    {
        get { return _id; }
        set { _id = value; }
    }
}

Hope this helps!

Debugging the (client) ASP.NET SignalR application that someone else wrote

Debugging the code that you haven’t written is a art! We always look for some help from the application developer that would perhaps tell you what’s going on in the application when you perform certain actions. With the rich client applications becoming the main stream, it’s very important that the libraries, and client side frameworks provide with additional debug statements emitted to the browser, so that anyone who are trying to debug the application, gets a little help.

ASP.NET SingalR is one popular library for the ASP.NET developers to build rich, real-time web applications. SignalR’s client side library emits useful debug statements in each event that’s occurring, and that’s very helpful if you are trying to debug your application. For example, if you have the logging enabled for your hub, you would see the below events during the connection establishment. I’m using the sample application that’s build in this tutorial for this blog.

image

Yeah, that’s the awesome looking F12 Developer tools on IE11 Preview. Try it out, and read more about it’s new features here. I’ll perhaps talk about that in a different post later. Let’s come back to our issue at hand. If the developer of this application is you, or someone who is kind enough to turn on logging, they would do this. Most of the time when you are trying to debug other’s production application (like me for living), or some out of curiosity, you will try to find options to ease your job. Here in this case, if I can turn on the logging for the hub, I’m golden. Let’s see how to do this.

Logging for the SignalR hub, if you are using the automatic proxy generated, can be enabled by the below code:

$.connection.hub.logging = true;

Again, in our case, we do not have the access to the code. Somehow, you need to enable the logging in the browser for the application instance loaded inside. Yeah, you guessed it right – console. Most Browsers include Developer Tools that include ‘Console’. That’s most of the time used to emit debug information to understand what’s going on, and most of the time, the developers turn the debug statements on/off via switch, same as ASP.NET SignalR client side library. Do the below steps to enable the logging like above, even if the code doesn’t have it enabled:

    1. Browse to your ASP.NET SignalR application.
    2. Open F12 Developer Tools, and go to the ‘Console’
    3. Type the same code as above to enable the logging - $.connection.hub.logging = true; in the console window, and hit return.
    4. You would now start seeing all the debug messages that SignalR framework emits.

image

However, in this case, we enabled the logging after the connection was established, and so on. However, most of the time we would debug issues on the connectivity itself. In those times, start debugging your page with IE11 F12 Developer tools, if you have noticed, in the latest version, you do not need to reload the page! Set a breakpoint in the $.connection.hub.start() method (inside jquery.signalR-1.1.3.js), and refresh the page. Once the page is refreshed, you could execute the same code in the console as above, so that the option to logging is set. Debug statements that the client side library emits is pretty verbose. For example, when I turned off WebSockets in my IE11, I see the below during the connection establishment, and you would see it switching to long polling mode.

image

Hope this helps someone who want to understand what’s going on in someone else’s ASP.NET SignalR at the client side.

Defining Common issues in ASP.NET applications - Crash.

This blog is a continuation to my previous one in this Troubleshooting series that I’m planning to continue writing. If you haven’t read that one, please read before beginning this one. In the last blog, I spoke about a few questions, and my first step of any troubleshooting – isolation, which helps me narrow down my search, and gives me opportunity to do concrete troubleshooting rather than trying out a couple of random things like rebooting. Yeah, that does fixes a lot of problems, but will you understand the reason why the problem really happened after doing a reboot. Possibly not for a lot of instances. If your application is super smart in doing more logging, and the problem that happened can easily identified in the default logs like event logs, IIS logs, httperr logs, you are golden. Otherwise, you might be pushed by your boss to do an RCA, but you do not have sufficient data.

Defining Crash

In this blog, I’m going to talk about one of the few common issues, and what possibly you need to do during these issues. Again, this is not going to be the complete list of things that you can do, but at least will give you a head start. You know what crash means, but will you be able to identify an end user scenario, and right away classify as crash. No. Not all the time. You know that your code needs to run inside a process in Windows. I define it has “crashed” if the process has exited because of unknown reasons, terminated unexpectedly. If you are running your ASP.NET websites on IIS7+ servers, it is the w3wp.exe process that runs your code.

Understanding Crash, and it’s symptoms

What are the possible symptoms that you can notice in your applications to term this as a crash, or what you can possibly see from the existing logs. I’ll also try talking about a few common tools that will help you in troubleshooting the crash.

First of all, let’s talk about a few common errors, issues that is noticed by the end user:

  • Session Loss – This is the most common symptom for people who store the ASP.NET Session InProc. When the ASP.NET Session mode is configured InProc, your session variables (and values) are stored inside the w3wp.exe process corresponding to the Application Pool that’s configured to run your application. One of my colleague has earlier written briefly on a few questions to ask, and possible reasons for this in this article. Please read it, it is such a valuable ‘session loss’ troubleshooting guide. Often people term as ‘Session Loss’ if their application perhaps tells them that they are logged out of the system, and asking them to login again. Few application developers do custom logging, and they store some session variable when your session starts, and checks for that value in a few pages for custom logic, and show you the “logout” message if that variable doesn’t exist, forcing you to login again that will initialize the session variables again.
  • Webpage keeps spinning for a long time, and gives you the result – This is again a most common scenario, but the end user reports this as a slow performance rather. If the process exits, it takes down all the initialization that you have done, be it session variables, or ASP.NET cache, or something that you have initialized. So, most common logic is, to re-initialize them if it is not available, so you spend time in re-initializing it, getting from database, reading from file system, and so forth.
  • imageYou see ‘Service Unavailable’ error in the page – This is also most common, where the process serving the Application Pool has terminated unexpectedly for x number of times in y seconds. Default configuration in IIS is, if your process crashes for 5 times under 5 minutes, the Application Pool is disabled, or stopped. The Administrator has to manually start the Application Pool in order to get the site back again. You can always change this option. I’d say, better leave it as default – so that it at least prompts you to fix this problem. If you disable this option, your crashes will go unnoticed, unless you pay attention to the user experience, and in the event logs. You can configure this under the ‘Advanced Settings’ of an Application Pool, under Rapid-Fail Protection. You can also configure other options like, a custom executable to run in case if this AppPool gets disabled due to this ‘Rapid Fail Protection’ feature of IIS.
  • Other custom error messages which your application might throw in case if the initialized data becomes unavailable from the process memory.

 

Event logs that gets generated for a crash of the Application Pool

Here are a few event descriptions that you would see if a crash occurs:

Log Name:      System
Source:           Microsoft-Windows-WAS
Date:               [time stamp]
Event ID:          5011

Description:
A process serving application pool '[app pool name]' suffered a fatal communication error with the Windows Process Activation Service. The process id was '[PID]'. The data field contains the error number. 

 

Description:

A process serving application pool 'DefaultAppPool' terminated unexpectedly. The process id was '[PID]'. The process exit code was 'exit code'.

 

Application pool '%1' is being automatically disabled due to a series of failures in the process(es) serving that application pool.

 

Event ID : 1000
Raw Event ID : 1000
Record Nr. : 15
Category : None
Source : .NET Runtime 2.0
Error Reporting Type : Error
Message : Faulting application w3wp.exe, version 6.0.3790.1830, stamp 42435be1, faulting module mscorwks.dll, version 2.0.50727.42, …

Now, you have seen how to define a crash, and possible symptoms, and event logs. But what next? You need to find the cause of the problem, right? You first should looks for clues in the event logs to see if there is anything logged from IIS/ASP.NET components during the time of the issue, other than the few of the above ones. You might be even lucky to spot a 3rd party module that’s causing the crash, but not all the time. What possibly can help you is a memory dump of the process, which been captured just before the process dies. There are a few tools that can help you collecting the memory dump of the crashing process, few which can analyze the dumps for you to an extent to show you the crashing stack. For the collection, you also have an inbuilt option that saves these memory dumps called, Windows Error Reporting. You can read the below blogs that shows you the steps to collect the dumps for this scenario.

Using Windows Error Reporting

Using WER: Collecting User-Mode Dumps
http://msdn.microsoft.com/en-us/library/bb787181(VS.85).aspx

 

How To: Collect a Crash dump of an IIS worker process on IIS 7.0 (and above)
http://blogs.msdn.com/b/webtopics/archive/2009/11/25/how-to-collect-a-crash-dump-of-an-iis-worker-process-w3wp-exe-on-iis-7-0-and-above.aspx?wa=wsignin1.0

 

How to use ADPlus to troubleshoot "hangs" and "crashes"

http://support.microsoft.com/kb/286350

 

Using DebugDiag Tool

How to Use the Debug Diagnostic Tool v1.1 (DebugDiag) to Debug User Mode Processes

http://msdn.microsoft.com/en-us/library/ff420662.aspx

 

Other tools that can help you is, ADPlus (that comes with the Debugging Tools for Windows) article, and ProcDump from the Microsoft Technet Sysinternals (-t option). DebugDiag tool comes with a powerful analyzer as well, where you can just double click the dump file that was collected, and it will create a beautiful report that consists of the crashing callstack, and a possible explanation/next steps for the issue. If you are interested to debug the dumps collected, below links could be super helpful! Tess is known for her brief blogs on dump analysis, and a great person to interact!

.NET Debugging Demos Lab 2: Crash

http://blogs.msdn.com/b/tess/archive/2008/02/08/net-debugging-demos-lab-2-crash.aspx

 

Hanselminutes on 9 - Debugging Crash Dumps with Tess Ferrandez and VS2010

http://channel9.msdn.com/Shows/HanselminutesOn9/Hanselminutes-on-9-Debugging-Crash-Dumps-with-Tess-Ferrandez-and-VS2010

 

I’ll follow up with more posts on general troubleshooting.

Windows Store XAML app sample that uses Bing Maps SDK, and shows the current time of the selected city

I was trying to help one of my colleague who was trying to build a different app, where I found using Bing Maps would be appropriate. While helping him, I ended up building this full working app that shows you the current time of the city that you selected from the map. Here is what you would need do to find a time of a different city:

  • Open the app.
  • Zoom into the city, and just long touch, or right click using mouse.
  • See the time of the city displayed right in the app.

Sounds good? Let’s build the sample. First of all, you need to download the Bing Maps SDK, create an account, and get a Bing Maps Key. Here are a few links that would be helping you.

   Getting Started
   http://msdn.microsoft.com/en-us/library/hh846498.aspx

   Getting a Bing Maps Key
   http://msdn.microsoft.com/en-us/library/ff428642.aspx

   Create a Windows Store app (for Windows 8)
   http://msdn.microsoft.com/en-us/library/hh846489.aspx

Once you have followed the steps in the second link, you would now have the Bing Maps Key that you would be using in the app. Now, you can follow the steps mentioned in the third link above, to have something like below in your XAML, of course having your Bing Maps key that you obtained earlier.

<bm:Map Credentials="YOUR_BING_MAPS_KEY" x:Name="myMap"></bm:Map>

So, going with the functionality of the app, you need to write some code that needs to be executed when the user (long) touches, or just do a right click on the map. Let us write some code for the RightTapped event. Here is what we need to do:

  • Fetch the latitude and longitude of the place that we just selected in the map.
  • Find the timezone for the latitude, and longitude selected.

We could use Map.TryPixelToLocation() that accepts the Point that we we just selected in the Map, and an out parameter that will have the Location co-ordinates. If this method returns true, we could then go and add a pushpin to show the user the place he/she just selected in the map, and then go and fetch the timezone information for the latitude, and longitude selected. I found a free, and easy to use service from EarthTools to get this information that we need. Look at this page for more on their APIs. Again, there are other commercially available services available for this, so please try to explore other options as well. You need to pass the latitude, and longitude of the place, and the service returns you the time of the selected place, also it’s timezone offset, day light savings information. I just parse the time from the output, some lazy code there, doing some string parsing. The output is an XML document, so you could use your own XML parsing to fetch the details, but for the sample purpose, I just stuck to the infamous string parsing.

Here is how my code looks like now for the RightTapped event handler:

private async void myMap_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
// when I right click, or long touch, this event gets triggered. 
// I then try to fetch the selected location's geo co-ordinates
// and draw a pushpin there
    Location location = new Location();
bool succeeded = myMap.TryPixelToLocation(e.GetPosition(myMap), out location);
 
if (succeeded)
    {
// add pushpin
        Pushpin pin = new Pushpin();
        myMap.Children.Add(pin);
        MapLayer.SetPosition(pin, location);
 
        textBlock1.Text = "contacting the server for geo information";
// get the timezone information
        WebRequest webReq = WebRequest.Create("http://www.earthtools.org/timezone-1.1/" + location.Latitude.ToString() + "/" + location.Longitude.ToString());
        WebResponse resp = await webReq.GetResponseAsync();
 
        Stream dataStream = resp.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
// Read the content from the server. 
string responseFromServer = reader.ReadToEnd();
 
// example code to just manipulate the string from the xml output. you could do XML parsing if needed.
int startPos = responseFromServer.IndexOf("<localtime>") + 11;
int length = responseFromServer.IndexOf("</localtime>") - startPos;
string time = " Time : " + responseFromServer.Substring(startPos, length);
 
        textBlock1.Text = time;
    } 
}

You could download the sample from here.

This is how my sample looks:

clip_image001

Hope this helps!

New look of my webtechnews app showing you all the latest microsoft /web news

You can download it from here. And, it looks like below now. Good thing is, I fetch the list of the blogs from a WebAPI I’ve hosted in my Windows Azure Website, so I can modify the list whenever needed. I fetch these colors as well from the WebAPI, so I could even change the look and feel of the app without submitting an update to the app in the Windows Store! Do you like it? Let me know if you have more blogs to add. When I find time next, I’ll perhaps update this with sorting the articles by date, so that you could see what’s the latest, instead of a grouping by the blog author. May be, a read/unread status too. Honestly this app is my playground where I’m trying to implement some of my learning. Hopefully I won’t break anything with the updates. If I did, let me know. Your feedback is very important to me.

Screen shot 2

Screen shot 1

It’s much easier to share screenshots from Windows 8.1, I say!

21. July 2013 11:32 by the next door (so called) geek in Windows 8.1

If you aren’t trying Windows 8.1 yet, you are seriously missing a lot. This update to the brighter Windows 8 brings some cool updates, and improvements that help the user in their daily use. Taking a screenshot of your screen, and sharing it with others is perhaps an activity most of us often do. Windows 8.1 helps to do this quickly.

You can easily take screenshots of any Modern app, and share it with others. For example, I wanted to share a screenshot of my NASA Image of the day app with others. I just open the app, and select the share charm. There is a drop down there, which when pressed shows the different options, like the default share from the app, Screenshot, and Link to app in Store. Much easier to share things with others.

image

Select the screenshot option, and that will show you the apps that can share a screenshot. Most common ones that I expect were Twitter, and other social networking apps, and Mail. You have OneNote too, so it’s much easier to insert a screenshot in some notes that you are writing on. Do the same from the ‘Desktop’ mode to share the screenshot of the desktop. If you consider ‘Desktop’ as just another app in Windows 8, you would understand why you cannot take individual program screenshots using this. What more? You could now share the screenshots of your ‘Start’ screen as well.

From your ‘Start’ screen, invoke the share charm, either by bringing the charms, and clicking/touching on the share, or just Windows + H shortcut, you would get two options if you press the dropdown – Start, and Screenshot of Start.

Troubleshooting ASP.NET Applications running in IIS7 and above

If you do not know me, I work as an Escalation Engineer in Microsoft IIS/ASP.NET Support team in Bangalore, primarily debugging ASP.NET applications of our customers. That’s my day job – to debug other’s code, also any Microsoft Component that’s involved. I ‘m planning to write a series of posts on general troubleshooting, and the steps I typically use to diagnose a customer problem. You could use the same, and it is definitely not a rocket science. If I can do this, you can too!

In this first post, I thought I will not talk anything technical, but probably a few things that you might want to do before you start the real troubleshooting. Let’s take a scenario of a ‘slow running’ ASP.NET website at hand, and see how do we approach this problem step by step. If you have already worked with Microsoft Support before, we would generally ask you ‘many’ questions. All of those questions are asked typically to understand the problem better. For example, for this slow request problem, here are the typical questions that you would need to ask yourself when troubleshooting. Few of these questions apply for ‘any’ problem that you troubleshoot.

  • Issue is slowness, but how slow it is? First, you need to understand how much is the delay you are talking about, so that you can think of using a few tools to troubleshoot this quickly.
  • It is slow, but how fast it should be? What is your expected time that page should respond in? If you do not have a benchmark, then you are shooting in the dark. In reality, this number would be a result of your testing. You would know how much the page typically takes, depending on its operation. Of course, if it is running a lengthy database operation, this number itself would be a larger one. It is very essential that you have a comparison.
  • Environment of the server. Next, you would need to know where the problem is occurring. If you have multiple servers, which are those servers this slow performance problem occurs? It is possible that those servers where the problem occurs are really a slow ones, having an old hardware. Understanding the details of the environment is very important.
  • Environment of the client. You own the server, but the problem perhaps is reported by your end users. You should try to know the environment of those end users as well. If it is happening from many users, you might want to understand about all ranging from their OS version, browser versions, to network topology.
  • When did the problem start? Yes, this would be the most interesting question of all, but this is the one which might not get any ‘right’ answers most of the time. One of the many reasons could be, there perhaps were too many changes that were done. This ranges from deploying the application in a new server, installing a new service pack for the OS, or the application upgrade, to adding new users to the applications. Clear understanding of this would help diagnose the problem better.
  • What exactly is slow? This is another tough question to answer most of the time since there might be many pages that are slow, and you may not know all. But, it is very essential that you list the name of the page, and the operations you do on the page that gives you the problem. For example, a button click on the login page is slow to give the response.

 

Again, these are a few important questions to ask, not the only questions. If I get a chance to talk to you while diagnosing your problem, I’ll perhaps ask 100 more questions – definitely related to the problem :) Okay, what next? You get the answers to these questions, what’s perhaps your next step?

My first step in troubleshooting is, always ‘Isolation’. Try narrow down your search. First split your main problem into pieces, to troubleshoot. For example, one button click might do 10 different activities, try isolating what in that 10 has the problem, so that you can try concentrating only on that particular activity that is slow. Isolation step will also include you trying to check if the problem is isolated to only a few users, or all the users. If it is only for say 2 of your users from their workstations, you have already avoided concentrating on the server, perhaps they have a slow network. This is just an example, your problem well could be in the server even in this case of just 2 users facing the problem, like custom code for them, the query that gets generated for them is different, etc.

Once you isolate the problem, the very important next step is to make sure you aren’t troubleshooting something which is already resolved in say, the latest release of your website. Always, do not try reinvent the wheel. Do not waste your CPU cycles (!) to work on an issue that someone has already fixed. Search. Search in support.microsoft.com, search in StackOverFlow, search in Bing, most important, search in your internal database if you have one, for issues that are already fixed. If you are at a critical problem, make sure you do enough search before trying to dig deeper. Again, this step doesn’t apply for some problems that are isolated to just your application, which is the case most of the time, like this slowness that we were talking about. But for issues like, Exceptions, runtime errors, etc.

Only after you have a clear understanding of the problem, and the environment that this is isolated to, and making sure the issue is not a known issue, you may proceed further. I can in fact write more in this post, but I’ll reserve more like this, general troubleshooting techniques for my future posts. If you are curious, here is what I’m planning to write further on. I’m sure I’ll add more to this list, and perhaps will update this post when I do.

  • Defining Common issues in ASP.NET applications – Slow Perf, Hangs, Crashes, High Memory, etc.
  • Built In tools that helps you troubleshoot a few of these issues.
  • How much existing logs like IIS logs, HTTPERR logs, Event logs would tell you?
  • Scenario #1 : Troubleshooting a slow performance problem using various tools.
  • More Scenarios, more tools, whenever I find time to write.

 

Follow along if you are interested.

WinJS – Creating a ListView, and Binding it to a List populated from an RSS feed

In this post, I would like to talk about how easy it is to reading an RSS feed, create a List, and bind it to a ListView. For this, I’m going to take an idea of mine which I already turned into an app, and it is available in the Windows Store. This, ‘NASA Image of the Day IOTD’ app of mine pulls the RSS feed from NASA site, and displays it in the app. This also stores the last 6 images you viewed using this in the application’s roamingStorage. I fetch the image, and add it to a WinJS.Binding.List, and bind the same to WinJS.UI.ListView control in the page. Before going into fetching the RSS feed, and creating the List, let’s spend sometime in understanding the ListView control better.

Here is a simple ListView control markup:

<div id="imagesListView" data-win-control="WinJS.UI.ListView"
                data-win-options="{
                    itemTemplate: imagesListTemplate,
                    selectionMode: 'none'
                    }">
</div>

This can’t get any simpler than this, right? data-win-control defines what type of control this simple <div> needs to be turned as, “WinJS.UI.ListView”. You could pass in various options for the ListView via data-win-options. Of course, you can set these properties via javascript code as well. For a ListView, you need to associate an itemTemplate, this is nothing but defines how each individual items need to be displayed. Each item would have different properties, in our example, we might want to fetch the image’s title, source url, date as different properties of an item. So, our template is the definition of how the item is displayed in the app. Here is a simple definition of my itemTemplate:

<div id="imagesListTemplate" data-win-control="WinJS.Binding.Template">
    <div data-win-bind="innerHTML: title"></div>
    <img data-win-bind="src: source" />
    <div data-win-bind="innerHTML: date" ></div>
</div>

Perfect! Now, we have defined how individual items needs to be displayed. Note the data-win-control there “WinJS.Binding.Template”. It’s up to your CSS designing skills that you can make these items shine. Now, we have created a bare minimum ListView, and a item template for the same, now let’s try to bind some items to the List from javascript code.

When you create a simple app using Visual Studio, you would find the bare minimum code already available for your to start with. Take a moment to read the portion of the code inside app.onactivated() method, and the last line where you see WinJS.UI.processAll(), is the one which turns the normal <div> into the control that you have defined. This processes all the data-win attributes, and make your controls ready for further processing. Let’s create an init() function, and call it once the WinJS.UI.processAll() finishes. WinJS has this nice little wonder called, Promises. You could check this link to read more about them. Here is the little code that would call our init function right after finishing the processing of the all UI elements in the page.

args.setPromise(WinJS.UI.processAll().then(init));

Before reading an external RSS feed, let’s try to create a simple List, and bind it with the ListView. Here is how my simple init() function looks like:

function init() {
    var imagesList = new WinJS.Binding.List([
            { title: "Preparing NASA's Next Solar Satellite for Launch", date: "Sun May 25 2013", source: "
http://www.nasa.gov/images/content/754945main_2013-2624-full_full.jpg"},
            { title: "The Engine Burns Blue", date: "Fri May 24 2013", source: "
http://www.nasa.gov/images/content/751202main_ionengine_full.jpeg"},
            { title: "Pavlof Volcano From Station", date: "Thu May 23 2013", source: "
http://www.nasa.gov/images/content/751060main_alaskan_volcano_full_full.jpg"}
    ]);
}

We have now created a simple List, and need to bind this to the ListView. Again, it is very simple. Another 1 line code:

imagesListView.winControl.itemDataSource = imagesList.dataSource;

Now when you execute your app, you would see the ListView populated, and items been shown. Now, you can use your existing CSS skills to make the items look better. There are a few CSS classes you can override for the ListView, such as win-item, classifying each image. It would be better if you use Expression Blend to open your app, and play with these classes.

You have seen how to create a simple List, and bind it to the ListView control in a HTML/WinJS Windows Store app. Let’s now use WinJS.xhr() function to fetch an RSS feed, and read the list of items to populate our list.

WinJS.xhr({ url: "http://www.nasa.gov/rss/image_of_the_day.rss" }).then(function (rss) {

    // query the list of items in the feed
    var items = rss.responseXML.querySelectorAll("item");
    for (var n = 0; n < items.length; n++) {
        var item = {};
        item.date = new Date(items[n].querySelector("pubDate").textContent).toDateString();
        item.description = items[n].querySelector("description").textContent;
        item.source = items[n].querySelector("enclosure").attributes["url"].value;
        item.title = items[n].querySelector("title").textContent;
        item.link = items[n].querySelector("link").textContent;

        imagesList.push(item);
    }
}, function (err) {
    // handle your error here
});

Now, I can successfully display the image that I fetched from the RSS feed. Again, if you notice this particular feed, it just gives only one image always. It doesn’t give the old entries, and I didn’t see any easy way to read the old images. Instead of worrying too much, I thought, I’ll perhaps store this imagesList List to my roamingStorage, and will read from it when the app starts again. Here is a snippet that allows you to store into the roamingStorage, and retrieving the same. I convert the List into a JSON string, and convert it back to an object later.

// Storing to the roamingSettings:

var roamingSettings = applicationData.roamingSettings;
roamingSettings ["myImagesList "] = JSON.stringify(imagesList.slice(0);


// Reading it from roamingSettings:

if (roamingSettings .values["myImagesList"] != null) {
    var json = JSON.parse(roamingSettings .values["myImagesList"]);
    imagesList = new WinJS.Binding.List(json);
}

Hope someone find this useful!

Nokia Lumia 820 – Apps, and more

When I wrote my first post about Nokia Lumia 820, I didn’t have much time to play with the apps to understand if this phone feels complete as an end user. Firstly, I got to admit that this phone has minimized my usage of wife’s iPad2. Before talking about this phone, let me cover my use cases with iPad2, a few apps that I typically use in iPad for, Twitter – especially to read all the tamil tweets, Facebook – my social world, Flipboard – connected to my twitter, facebook, google reader account – the source for all my technical blog reading stuff, Times of India App – source of all news around India, Dinamalar, Malaimalar – Tamil news sites apps, and Skype – for video chat with my friends, and family.

I can’t think of any other apps that I frequently use in my wife’s iPad. Perhaps Youtube too, but not that much, so I didn’t even bother to list that in the above list. For my use case, I’m trying to compare the Apps that I’m using in my Nokia Lumia 820:

Rowi

Rowi, perhaps is the best twitter client out there for Windows Phone. This also supports multiple accounts. With WP8 supporting Tamil fonts, I pretty much follow my timeline on my mobile. You can get the app here. Apart from the multiple user support, even the free version includes the ability to include the location in the tweet, and also to add #nowplaying that adds the currently playing song from the Music hub. I do many #CommuteTweets, and #CommuteMusic tweets from this app, and I absolutely love it. I should say that, since I’m now able to read Tamil in my WP8, this app has stopped taking iPad to use the Twitter app (which is one great app, by the way!).

wp_ss_20130207_0005 wp_ss_20130207_0006wp_ss_20130207_0008

Facebook

Facebook on iPad is definitely superior, considering my new phone, but that’s mostly due to the large screen. I know it’s a very blind comparison of a tablet with a phone, but I’m trying to compare based on my usage stats. Of course, with my phone’s ‘Me’ tile, I do not miss any notifications, and I’ve also pinned the ‘Facebook’ app for Windows Phone to my start screen, that gives me toast notifications that keeps me always connected to my facebook world.

Flipboard, and other news apps – replaced by NextGen Reader to a larger extent

As I mentioned earlier, Flipboard gives an absolutely fantastic magazine style reading experience in the bigger screen iPad. I’m sure there is no matching Windows Phone app, yet. However, for my use case, I have the NextGen Reader – a google reader app for Windows Phone. This app is one of the superior google reader client, and also has an Windows 8 Store app as well. Other news apps like TimesofIndia, etc has apps even on Windows Phone platform, also on the Windows 8 store.

Here are a few screenshots of this app, you should use it to believe the superior experience I’m talking about. This also has a Live Tile, and can post a detailed status right on the lockscreen, which is awesome! You don’t even need to unlock your phone to see the latest in your subscriptions.

wp_ss_20130207_0001wp_ss_20130207_0010wp_ss_20130207_0011

Great Apps from Nokia

One of the many reasons why I chose Nokia Lumia 820 is for it’s exclusive apps. To name a few that I use it frequently, Nokia Drive (Beta), Nokia City Lens, Nokia Music, and the PhotoBeamer app.

I think the web has many reviews for all these apps already, and I don’t want to repeat how awesome they all are! Nokia Drive has even ‘Tamil’ turn by turn navigation, and that’s just awesome! Also don’t forget to try the ‘Surfer Dude’ for some fun while driving.

Nokia Music is worth mentioning, which offers FREE MP3 downloads to your phone. They have almost all the top albums available, and it’s a bliss that you hit the download button (while connected to WiFi), and start listening to your favorite songs in minutes. This is a must have app for music lovers, and comes exclusively for the Nokia Lumia, and for free. What more you can ask for!

wp_ss_20130207_0003wp_ss_20130207_0004wp_ss_20130207_0013

PhotoBeamer

You see it yourself in the below video by PocketNow. It is a great app to be used to project some photos on any screen. Imagine you are on the stage, and you want to show off some photos from your phone that you recently took. This is an amazing app, and I’m sure other phone owners would be jealous since it’s exclusive to Nokia Lumia phones.

Credits : PocketNow

That’s it for now, but I’ll write more if time permits Smile

NASA Image of the Day App – yet another one, but it’s different

I don’t have an app that would generate a billion dollar in revenue, but perhaps be useful to atleast a few that I know of, including me. Here is one more - NASA Image of the Day IOTD app.

This app fetches the NASA Image of the day from their RSS feed, and shows you just 1 image per day. However, it puts the last 6 images that you viewed using this app to the localstorage. You can share the picture, set as your lockscreen right from the app itself. Give it a try, and let me know what you think.

Download it from here.

image