Tag .NET

Consuming data from Nimbus Using LinqToXML (Updated) on iPhone + WP7!

I’ve been starting to explore iPhone development lately. At first I was taking my time at learning at Objective C which went fine for a while but one of the guys on the project was asking if I could help build some apps for Project Nimbus, translation: build stuff fast. We talked about MonoTouch.NET which is basically a framework that will allow you to code apps with .NET. JOY!!

First a quick intro about Project Nimbus: as Chewy would put it, it’s basically a supermarket for data here in Singapore. The team is hard at work at securing data from all sorts of providers. They currently have Hungry Go Where, Land Transport Authority, National Environment Agency, and National Library Board onboard as data providers, and i know they have quite a few more coming. What this means for developers is that if they have a great idea, they don’t have to go out by themselves with these big agencies and possibly spend tons of money on acquiring the data. If you want to find out more, check out http://projectnimbus.org/about/ for more information. They also very keen on getting input from developers as to what types of data they think would be useful, as well as feedback on the project as well. If you’re interested, the about page has a link to contact them :)

So back to my application. Right now, I’m figuring out how to actually get the data from the service. Looking at this entry, they actually provide a link to the data that’s returned when you make a call to the service. Check out the post, and towards the end, you’ll find a few links that shows how the data looks like.

First we create a webrequest to the URL that gives me the dataset we want. In this case, we want to get access to the NowcastSet i.e. current weather. The service actually gets authentication from the headers so we add these two keys & values. We then make the request and read it into a string for parsing later on.

wpid-PastedGraphic6.6QgjwaKOHyeZ.jpg

Next, if we look at the dataset that’s returned, we see that it makes use of a few namespaces. To make things WHOLE lot easier for us, we’ll use one of the cool features of the .NET Framework which I LOVE called LinqToXML. If you want to find out more, check out http://msdn.microsoft.com/en-us/library/bb387098.aspx.

Let’s first add the System.Xml.Linq namespace in order to use it’s classes.

wpid-PastedGraphic1.ItVM3vydQ2bH.jpg

We can now add a our XNamespaces:
wpid-PastedGraphic2.CJ4wKM6qhF3A.jpg

The following stuff is just magic. With just one statement using LinqToXML, we’re able to parse the xml string without having to use xpath or regex, etc. And, if you read the statement, it’s actually pretty descriptive of what it is trying to accomplish.

wpid-PastedGraphic4.SILwDB5lGtqK.jpg

Given the structure of our sample data, we see that we’re essentially getting elements from entry.content.properties.

wpid-PastedGraphic9.u4eWF4QbhRSy.jpg

Note that the following line is just to make things a bit easier to read.
wpid-PastedGraphic10.hKnF61uZzy7F.jpg

You can also just do the following and remove the let line, though I find it a bit more confusing to understand at first glance.
wpid-PastedGraphic11.yB7JdULt8nja.jpg

This is the full code:

    public List<WeatherEntry> GetWeatherFromNimbusNEA(string AccountKey, string UniqueUserID)
    {

        System.Net.WebRequest wr=
          HttpWebRequest.Create(
            "http://api.projectnimbus.org/neaodataservice.svc/NowcastSet");
        wr.Headers.Add("AccountKey",AccountKey);
        wr.Headers.Add("UniqueUserID",UniqueUserID);
        wr.Method = "GET";
        WebResponse res = wr.GetResponse();
        string resStr
         = new System.IO.StreamReader(res.GetResponseStream()).ReadToEnd();

        XNamespace atomNS
          = "http://www.w3.org/2005/Atom";
        XNamespace dNS 
          = "http://schemas.microsoft.com/ado/2007/08/dataservices";
        XNamespace mNS
          = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";

        List<WeatherEntry> results
          = (from item in XElement.Parse(resStr).Descendants(atomNS + "entry")
            let weather = item.Element(atomNS + "content").Element(mNS +"properties")
                select new WeatherEntry() {
                Area = weather.Element(dNS +"Area").Value,
                Condition = weather.Element(dNS +"Condition").Value,
                Lat = weather.Element(dNS + "Latitude").Value,
                Lon = weather.Element(dNS + "Longitude").Value
            }).ToList();

        return results;
    }

}

//Blogging using a trial version of MacJournal. Windows Live Writer is still my favorite blogging software, and it’s not just because it’s free.

// Update @ 3.40 on my Win7 partition.. I missed you Windows Live Writer!

// and the vspaste add-in!!

It’s an hour after the end of the Mix Keynote. I started watching the video on my Mac partition so I couldn’t download the tools straight away. After it was over, I rebooted, uninstalled my pre-RC bits and installed the tools for Windows Phone 7 Series (which you can find here), fired it up and created a new Windows Phone List Application:

image

Since this is mainly a ProjectNimbus post, I won’t dive into how to build the WP7 app but there’s a new training kit up on channel 9 http://channel9.msdn.com/learn/courses/WP7TrainingKit/ if you want to learn more.

I did make a few tweaks in my code since the original code wasn’t doing downloads asynchronously (which it should, to improve your apps performance and not lock the UI). So how does my code look now?

public void  GetWeatherFromNimbusNEA(string AccountKey, string UniqueUserID)
 {

     WebClient wc = new WebClient();
     wc.Headers["AccountKey"] = AccountKey;
     wc.Headers["UniqueUserID"] = UniqueUserID;
     wc.DownloadStringCompleted
      +=new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
     wc.DownloadStringAsync(
      new Uri("http://api.projectnimbus.org/neaodataservice.svc/NowcastSet"));

 }

 void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
 {
     string resStr = e.Result;

     XNamespace atomNS
      = "http://www.w3.org/2005/Atom";
     XNamespace dNS
      = "http://schemas.microsoft.com/ado/2007/08/dataservices";
     XNamespace mNS
      = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";

     var results
     = (from item in XElement.Parse(resStr)
         .Descendants(atomNS + "entry")
          let weather = item.Element(atomNS + "content")
                        .Element(mNS + "properties")
                 select new WeatherEntryViewModel()
                  {
                   Area = weather.Element(dNS + "Area").Value,
                   Condition = weather
                               .Element(dNS + "Condition").Value,
                   Lat = weather.Element(dNS + "Latitude").Value,
                   Lon = weather.Element(dNS + "Longitude").Value
                  });
     foreach (var r in results) {
         Items.Add(r);
     }
 }

It’s practically the same code except I switched to the WebClient which Silverlight developers are already familiar with to download the string asynchronously. Once the results are returned, I add them to an observable collection which I have data-bound my UI Elements to.

Items = new ObservableCollection<WeatherEntryViewModel>();

The result is a basic list like application that displays weather information:

image

I’m excited about the WP7 platform and it’s definitely going to be a focus in my upcoming TechFriday posts! Next thing on my learning list is to share code between my two application platforms, iPhone and WP7. One thing is for sure though, I’m very happy with Project Nimbus as well because it provides a lot of data that I can already start playing around with. Kudos to the team! Smile

TechFriday: Jumping into Jumplists

Everybody’s excited about Windows 7 and there might be a few of you guys out there wanting to take advantage of some of the new features of the OS in your applications. In this post, I’ll show you how you can quickly add Jumplist support to your existing application (Yes, even WinForms applications)

In order to keep things simple, let’s just make the assumption that this existing application of mine has 3 very useful screens: Default, Green Mode and Red Mode ( I’m a developer, I’m not very creative )

image

Because I want to save my user some additional clicks to get into green / red mode, I can take advantage of a new feature of Windows 7 called Jumplists: when a user right-clicks on my app’s icon on the Windows 7 task bar, this menu pops up and gives him access to tasks that we expect him to frequent. There are a lot of tutorials out there that teach how to add Recent/Frequent documents to this list. The samples included in the library we’ll be using will show you how.

image .

For this example, we’ll learn how to use our applications existing custom functions (and icons) with Windows 7 jumplists but first, download the Windows 7 Taskbar Developer Resource

For this example, I have a very simple Hello Windows 7 application. In the application, I have a menu bar that loads up additional screens. In this case, it’s just the same screen and switching the colors, but it could easily be a function that will load up another UserControl with different functions. Productivity is key, so I’d like to allow my user to go straight to these screens on startup.

image

In order to enable this, I’ve made a method that will allow the application to switch between user screens based on command line arguments when launching the application.

private void ProcessArguments()
{
    string[] args = Environment.GetCommandLineArgs();

    if (args.Length > 1)
    {
        if (args[1].Equals("/r"))
        {
            LoadRedScreen();
        }
        else if (args[1].Equals("/g"))
        {
            LoadGreenScreen();
        }

    }
}

In this piece of code, I’m basically checking that IF there are arguments passed when running the application, I’ll be calling a method to load the appropriate UserControl (We’ve already seen that this is the same method invoked by the menu item in our Menubar).

Now we start using the libraries provided for us to make it easier to integrate with the Windows 7 Taskbar. But first let’s import the namespace of the library, plus some additional ones we will be using along the way

using Windows7.DesktopIntegration;
using System.IO;
using System.Reflection;

Next we add the following properties to the form:

string appID = "Hello Windows 7";
JumpListManager jlm;
    

The key thing here is the JumpListManager but if you want more information on the appID and all the goodness it brings, visit http://windowsteamblog.com/blogs/developers/archive/2009/06/18/developing-for-the-windows-7-taskbar-application-id.aspx. The next thing I have to do is override

protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);
}

Before we start jumping into adding jumplists, we want to remember that since this is an existing application meant to be run in existing versions of Windows, we’d like to make sure that we’ll only execute the additional code IF the application is running in Windows 7, otherwise, operate as usual. To do this, we check whether the OS version is 6.1 or greater (RC builds still register Major version as 6) with this code:

OperatingSystem os = Environment.OSVersion;
if ((os.Version.Major == 6 && os.Version.Minor >= 1) || os.Version.Major > 6)
{
    //some code
}

Now for the fun part. The OS message that we want to lookout for is the message that tells us that the taskbar button has been created. Then we can start adding the Jumplist items to the button.

if (m.Msg == Windows7Taskbar.TaskbarButtonCreatedMessage)
{
    try
    {

        jlm = new JumpListManager(appID);
        jlm.UserRemovedItems += delegate { };

        string strAppDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
        string app = Assembly.GetEntryAssembly().GetName().Name + ".exe";

        jlm.AddUserTask(new ShellLink
        {
            Title = "Color it Red!",
            Path = Path.Combine(strAppDir, app),
            Arguments = "/r",
            IconLocation = Path.Combine(strAppDir, @"ico\Red.ico")

        });

        jlm.AddUserTask(new ShellLink
        {
            Title = "Color it Green!",
            Path = Path.Combine(strAppDir, app),
            Arguments = "/g",
            IconLocation = Path.Combine(strAppDir, @"ico\green.ico")
        });
        jlm.Refresh();

        ProcessArguments();
    }
    catch (Exception)
    {

    }

Let’s break this down.

image

We start by creating a new instance of the JumpListManager passing the appID we’ve assigned to our app. Next we register to the UserRemovedItems event as this is required if we want to refresh the JumpList after adding items to it. In this case, we do nothing when any items are removed.

image

Here, we get the directory where the application is running as well as the app name itself, so we can tell the JumpList link what to invoke when it is clicked. Basically it’s emulating running your app from a command prompt and passing the arguments (if any). Now we can proceed to adding our JumpList items.

image

I’ve mentioned we can add a few other things such as Recent Documents & Frequent Documents  but you’ll find lots of resources on this on the net as well as the samples for the library. In this case, we’re adding a new User Task to the jumplist which results in having these links under a “Tasks” header as below:

image

Path, Arguments, and IconLocation are pretty self explanatory.

image

I need to make sure my icons are available to my application so here I’ve placed all my custom icons in one directory and set the property so the IDE knows to copy these files to the output directory.

image

After defining my JumpList links, I can call a Refresh on the JumpListManager so it loads up all my new links. After this, I make a call to my ProcessArguments method. This will make sure it runs the additional code if any arguments were passed when running the application. Of course, if you see that your users may want to run your app from a command line and pass arguments manually, you might want to put this call outside of the if statement or anywhere before your first form completes loading.

It’s that easy! If you got lost on the way, here’s the source to this project. If you manage to get your JumpLists going, feel free post a link to your app! :)

RESOURCES:

Windows 7 RC Training Kit for Developers

Managed APIs in this sample 

Other Managed APIs available:

Using the Facebook Developer Toolkit 2.0 for Canvas Based applications

I missed the release of the latest version of the Facebook Developer Toolkit from clarity consulting so I decided to play around with it after our Mix It Up event.

There have been much changes to the toolkit since the last time I looked into it. It took me a few minutes to try to figure out how to get a simple application out. The documentation posted here is a bit outdated so let me post my own little how-to. They’ve actually made it a lot easier but the new API needs a bit of getting used to I guess. It’s a bit confusing as the APIs for CanvasFBMLBasePage is different from CanvasIFrameBasePage. I hope they standardize soon though. Considering that this is supposedly an RC, it doesn’t seem like they’ve settled on a convention yet.

So again, assumption is:

1. You’re using C# as your language

2. You’re building an app with the CanvasFBMLBasePage (haven’t tried out the Master Page yet.. baby steps my friend)

1. Visit http://www.facebook.com/developers and Setup A New Application. Expand the optional fields and set up your application, making sure you have the following details filled in:

image

image

image

2. Once you have successfully set this up, take note of your API Key and Secret:

image

3. Fire up Visual Studio 2008 and set up a new ASP.NET Web Application

4. Open up Default.aspx and remove everything but the first line (which is the page directive that says tells .NET which is the CodeFile. Your default.aspx should look something like this:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:label ID="Content" runat="server" text="Label"></asp:label>

// For convenience, I added an asp.net label control where I would write out the FBML later on. If you’d rather use Response.Write() you could do that as well. Then you wouldn’t need to have the second line on Default.aspx

5. Before we dig into the CS files, we’ll need to add a reference to the facebook dlls that we can download from codeplex. Simply select to download bin.zip and it should give you the dlls necessary for you to build a Facebook app. Unzip this in a location you can easily find. Go to your Solution Explorer and right-click on your project –> Add Reference

image

Click on the Browse tab and navigate to where you extracted the binaries for the toolkit. You will want to add a reference to both facebook.dll and facebook.web.dll //yes, the non-caps irks me too.. wait till you see the classes *sigh*

image

When you finish adding these two necessaries, it’ll pull some other files along for the ride as well so don’t be surprised about that.

6. Now that’s finished, we can open up our .CS file and start by importing the necessary namespaces namely:

using facebook;
using facebook.web;

and then, make our class inherit from the CanvasFBMLBasePage class that is part of the toolkit. This base class should take care of all the nitty gritties of dealing with Facebook and making sure it knows who you are (or in this case, your application)

public partial class _Default : CanvasFBMLBasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}
 

7. Before we proceed, lets add a snippet to our web.config file to set our APIKEY and secret. The base class will be looking at our web.config file for the values to use to authenticate with Facebook. All you need to do is find this section:

image

and replace it with something like:

<appSettings>
  <add key="APIKey" value ="8e38f5fc72b989b8146dc91ece7e9b6a"/>
  <add key="Secret" value ="d9a5bd957d3aa1c69316839f1543fce0"/>
</appSettings>

of course put in the APIKey and Secret that was provided to you by Facebook. Don’t go using my key, it won’t work with your URL anyway :) Make sure you SAVE!

8. Going back to Default.aspx.cs, we can now proceed to add logic to our application.

protected void Page_Load(object sender, EventArgs e)
{
    base.Page_Init(sender, e); // this is the code that will call the base
                               // methods that deal with authenticating 
                               // with facebook and all that mumbo jumbo
 
if(!IsPostBack)    {
    stringuid = base.API.uid.ToString(); // this is the code to retrieve
                                          // the userid of the logged in user 
                                          //(the person accessing your application
   Content.Text = "<fb:profile-pic uid='" + uid + "'/>";               // You can also do something 
   Content.Text+= "hello, <fb:name uid='"+ uid + "' useyou='false'/>"; // like Response.Write( 
                                                                       // "<fb:profile-pic uid='" +
                                                                       // uid + "'/>"); for this part
   Content.Text += " you have "+ base.API.friends.get().Count + " friends so far "; 
   //anything you need to know about your user, you will find from base.API – all your base are belong to us


}}

9. Once that’s done, we can now go and publish our application by right-clicking on the project in solution explore and selecting publish

 image

Make sure you are publishing to the Callback URL you specified when you applied for the Application Key and Secret.

10. When you’re done publishing and you try to access the application, you should see something like this:

image

and when you click allow, you’ll get:

image

Some issues I noticed though is that when I try to access the application URL when I am logged out, Facebook tells me that the page cannot be found. But when I access it when I’m already logged in, it’ll prompt me to allow the application to access my information if i have not yet added the app. I’m checking with the forum on codeplex to see whether this is a Facebook issue or whether it’s the Tool’kit’s

Congratulations! You have now built your first FBML based Facebook application! Will let you know how far I go with this new framework.

It seems to be cleaner code right now, but I guess I’ll need to fool around with this to find out more.

Hope this helps!

Copyright © Aimee Gurl…
for as long as i can remember, technology has always fascinated me

Built on Notes Blog Core
Powered by WordPress