Monthly Archives: March 2010

Techfriday: Looping Panorama for Windows Phone 7 Series

Just a quick note:  I’m sure MS will be providing controls to this interface in the future so we don’t have to spend too much time building these controls ourselves Smile This post, as with the previous one, was meant more as an Expression Blend Exercise for myself to be explore the features of Silverlight / Windows Phone 7 and Expression Blend to see how much can be done with what we have today.

This is more of an Expression Blend exercise to simulate a looping panoramic interface on Windows Phone 7

There’s one annoying thing that I can’t figure out though: on the first scroll, you’ll notice from the video that the screen flickers. There’s probably something I’m doing wrong here but I just can’t figure it out yet Sad

So I had set out to accomplish two things: Simulate the looping background and sections in the panoramic interface on windows phone and instead of flicking, let the user touch and drag the controls from left to right before switching. I was able to accomplish the two, but like I mentioned, there’s an annoying thing that happens on the first transition from state one to state two. Another thing that’s wrong with this sample is that, I shouldn’t be switching states right away on a drag to left or drag to right. You should be able to pan a bit and the screen holds to that position till you pan to a certain threshold before the interface snaps to the next section. But yeah, maybe next time.

The first challenge was implementing the drag to next state instead of the flick. I couldn’t really isolate this into either a trigger or an action as it’s actually a combination of both, therefore a behavior. Basically, depending on the sum of the left and right value of the users drag motion, I trigger either GoToNextState() or GoToPreviousState(). Code for these two were modified from http://gallery.expression.microsoft.com/en-us/MIXBehaviorPack.

image

So I built a PanoramicPanningBehavior that has a few properties I can set.

First there are  the BackgroundElement, SectionsElement, TitleElement. I want them to be grouped so when it’s time for me to handle the drags, they don’t necessarily have to move at the same pace. That’s when the BackgroundMovementFactor and TitleMovementFactor come to play. Intstead of translating the background and title according to the value of the drag, I multiply it by the specified factor first. I’ve also let myself specify the StateGroup that has the states of our sections as described in my previous post, just in case you have other stategroups in the scene (though I haven’t tested this yet ^_^)

Now that I have the essential parts of my UI identified, I can now define what I want to do with them in my behavior when I start handling the events ManipulationDelta and ManipulationCompleted.

 

 

First for ManipulationDelta, I first check to see whether the parts are not null, and then based on the input factors, I apply them to the Translation.X property of the DeltaManipulation, or basically the change in the touch points and assign the value to the TranslateX properties of the CompositeTransform of the elements that have been identified through the properties. I think it’s better to read the code Smile 

void RootVisual_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
     {
         if (!e.IsInertial)
         {
             if (BackgroundElement != null) {
                 var BG = getElement(BackgroundElement).RenderTransform as CompositeTransform;
                 BG.TranslateX += e.DeltaManipulation.Translation.X * BackgroundMovementFactor;
             
             }
             if (SectionsElement != null) {
                 var SE = getElement(SectionsElement).RenderTransform as CompositeTransform;
                 SE.TranslateX += e.DeltaManipulation.Translation.X;
             
             }
             if (TitleElement != null) { 
                 var TE = getElement(TitleElement).RenderTransform as CompositeTransform;
                 TE.TranslateX += e.DeltaManipulation.Translation.X* TitleMovementFactor;  
             }
                               
         };
     }

 

If I wanted to run the project at this point, I’ll have to create a stateGroup and the section states in order for this not to go haywire. When I recreated the project, I actually added the panning behavior last. Next we’ll see the reason why I say this is meant more as an exercise for myself (and maybe for building demo apps) than production code. I think from this screenshot you can more or less figure out what I did.

image

Okay, so seeing as how you’re able to, from the leftmost part of your UI, be able to pan even more to the left to peek and even transit into the rightmost section, there had to be something there. And since I didn’t want to duplicate all the controls, I wanted to use WPF’s VisualBrush. Sadly, this isn’t available for Silverlight, however, I did find this: http://dotneteers.net/blogs/vbandi/archive/2009/03/26/discovering-silverlight-3-poor-man-s-visualbrush-behavior.aspx When I tested it out, it wasn’t as performant as WPF’s visual brush, but since I only needed to draw the UI once, I thought this would do.If we had the PathListBox in WP7, that would have been a better option too.

If you look at my visual tree, I basically created a brush for the background image(image), the TitleGrid and the ContentGrid (which you won’t see since I collapsed it because there were more stuff inside. Next, you’ll notice that these elements are inside a stack and before and after each of them is a Rectangle. Basically, I created identically sized rectangles that use as brushes the PoorMansVisualBrush.

imageTo do this, after adding a reference to the PoorMansVisualBrush (which I’ve made a WP version of ), I select the Rectangle and temporarily choose, TileBrush, click on Advanced Options in the Fill property and select Convert to New Resource… This will prompt me with a dialog to create a new brush resource and I’ll name it accordingly. In this Case, I have BackgroundBrush.

image

Next, with the behavior selected, I set the properties accordingly. Most important to note is to set the UpdateIntervalDuration to 00:00:00 so that the behavior doesn’t waste resources by repainting the brush. Next, you’ll want to go to each of the rectangles and assign their fill properties to the BrushResources you created. Also remember to set the Stroke to No brush especially if you have background images that are supposed to seamlessly merge the leftmost and rightmost portions. Now the tedious part is doing this for all the rectangles. Smile 

image


The last, and yet another tricky part is setting up the states. What you’re seeing here is pretty much the same as the last post where I have 3 states, to show my 3 sections. Note that when you position the states, you’ll want to position the actual to the middle/actual objects. It’ll probably be too difficult to set up using the rectangles with the brushes anyway since they don’t render at design time ^_^. Here, you’ll notice I’ve added custom transitions for when Section1State goes to Section3State and vice versa.

image

To do this, I’ll click on add transition button and select Section1State –> Section3State

image

In order to see what I’m doing better, I’ll switch to the Animation Workspace by pressing the function key [F6]. I’ve also minimized the stacks back so it’s easier to manage. With the transition to Section3State selected I’ll record a keyframe at the start, and end of the .5s transition.

image

When I record a key frame at the end, it’ll actually default to moving to the right most part of the actual controls which I changed to the one below. I’ve highlighted the outlines of the rectangles that mimic the actual controls.

image

Do the same for transitioning Section3State->Section1State. What will happen here is the application will play this custom transition animation to showing the visual brushes and when the transition is done, it’ll switch to the destination state where the real controls are visible.

Run the app to test and that’s it!

Again, not an ideal solution for production but at least I got to learn a few more useful things in Blend that might be useful in the future.

I’ve uploaded the code here so if you want to test it out, download the zip file, rightclick –> properties –> Unblock to avoid getting those dll not found / inaccessible errors.image

 

Panoramic Navigation on Windows Phone 7 with No Code!

I was reading through the UI Design and Interaction Guide for Windows Phone 7 Series and found out that there is currently no panoramic application template or control provided as part of the standard application platform. Nothing stops us from creating our own though.

image

To make things easier, I’ve made a behavior library for everyone to use that will handle flick gestures. I’ve also included a “GoToNextState” behavior which I based on http://gallery.expression.microsoft.com/en-us/MIXBehaviorPack. If you want to follow along, you’ll need to download my behavior library. Also, if you don’t know where to get the Blend bits, check out this post: http://electricbeach.org/?p=460

So, let’s start by creating a new Windows Phone Application project in Blend 4.

image

You’ll be presented with a default layout. Obviously, your panoramic screen design will go outside the bounds of the “phone”. Layout your screen accordingly. This is what I did with mine.

image

image

Now that I have all my elements on screen, I’ll create 3 visual states, one for each active session. Let’s go into our States tab and add a state group called Sections. To do that, click on the icon with a green plus sign.

image

In the Sections state group, let’s add the 3 states and name them accordingly. For each state, let’s also move the Grid along the  x-axis.

image

image

image

We can also set the default transition to some built in easing functions to smooth out the user experience.

image

In my case, I used the back easing function but you can play around with the different functions to see what suits you. You can preview what the transitions look like by clicking on the Turn on transition preview button.

image

Okay, now we’re all set. The only thing left to do is enable state changing when a user flicks the screen either to the left or to the right. This is where we will be making use of the my WPBehaviorsLibrary. We’ll go into our asset library –> behaviors tab and you’ll find a behavior called GoToNextState and GoToPreviousState:

image

Drag and drop these two behaviors one by one to the LayoutRoot so that it looks like this:

image

With one of the behaviors selected, go into the property inspector. You have a few options you can set (Loop & UseTransitions) which are pretty self explanatory.

image

. You’ll notice there is also a trigger property. The default trigger type is an event trigger. Let’s go ahead and click New to select the FlickGestureTrigger.

image

When you click ok, you’ll find that the Gesture has a Direction property that you can set. Basically, we’re saying that the GoToPreviousState action gets fired when the user triggers a flick to the Right. Do the same for the GoToNextState behavior but with a flick to the Left.

image

And that’s it! Press f5 and select Windows Phone 7 Emulator, unless you’re lucky enough to have a Windows Phone 7 Device. Smile

image

You’ll get something like this:

 

After reading some more on the UI Guidelines, they’ve mentioned a few things about the title like moving at a different speed from the sections, etc. so I’ve tweaked the animations a bit,and now I have the title outside the overall grid, animating it separately. I also have different easing functions on the first and last page from the middle one. The result is this:

You can get the code for this project as well as the library here. Also, although I’ve only managed to port  (i.e. copy paste) the States behavior from the Mix Behavior Pack to a Windows Phone behavior,  I’ve recompiled the pack to work with Silverlight 4. It’s in this folder as well.

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

Fixed Red Light & Low Audio Quality problems in Win7 on my MBP

I started out with two problems, the insanely low audio quality + this strange red light emitted from my headphone jack, and not being able to update to Bootcamp 3.1. I’ve been wrestling the internets to find out how to fix both these problems and it turns out, the former can be solved if you get the latter.  I then found the thread on http://discussions.apple.com/thread.jspa?threadID=2326188&tstart=0 that says the Bootcamp Update has issues when you have remote viewing software. The advice was to remove any additional graphics adapters apart from your actual graphics adapter.

You can do this by going to the start menu, right-clicking on Computer -> Manage.

image

grr.. so print screen button in MBP is Fn+Shift+F11 (thanks F 🙂

You can right click on the extra display adapter and uninstall for now. You’ll probably need to reinstall your remote viewing software after the update.

After you uninstall, you should be able to install the Bootcamp 3.1 update with the Apple Software Update. I’m not sure whether that alone did the trick to fix the red light problem and the poor audio quality, but I had previously downloaded and installed the latest Realtek drivers for Windows 7 from their site cause I saw folks mentioning this solved their problem though this didn’t fix it for me before the 3.1 update.

Now I can get back to coding with some good background music. Yey Sunday!