Windows Mobile Marketplace gets Deep Linking on Device

Windows Mobile Marketplace gets Deep Linking on Device

For quite a while now you have been able to deep link to your application listed on Marketplace using a url of the form https://marketplace.windowsphone.com/details.aspx?appId=LinkID where the LinkID is unique to your application.  If you want to find the LinkID for any application you simply need to find it in the marketplace and then look in the address bar. Depending on how you found your application you will most likely have a url similar to:

http://marketplace.windowsphone.com/details.aspx?appId=89c01d91-48a1-4e09-895e-74db2ced5345&retURL=/search.aspx%3Fkeywords%3Dcricket

As you can see this is essentially a deep link with some additional information on the end of it. Simply strip off all the extra parameters to give you a deep link that you can use.

http://marketplace.windowsphone.com/details.aspx?appId=89c01d91-48a1-4e09-895e-74db2ced5345

Now when it comes to providing a deep link on the device I think the team has completely missed the point. In the post Drive App Downloads with Marketplace Deeplinking they shown how you can invoke the marketplace client application on the device, passing in the LinkID of the application as follows:

System.Diagnostics.Process.Start("\Windows\WMMarketplaceFullClient.exe", "/appid:LinkID");

Now I had to double read this… surely the only way to do something like this would be to have an application already running on the device… and doesn’t that imply that the user already has your application installed on the device… which means they’ve probably already been to marketplace, found, purchased and installed your application… what’s the point in providing this mechanism????

Ok, in answer to that question I can see that if you have multiple Windows Mobile applications in marketplace then you can increase sales by providing cross links between your applications. That way once someone buys one of your applications, they are more likely to buy the others. Alternatively you could provide a free/trial version with a link to the paid version.

Personally I see that there is an obvious gap here – how do I provide a deep link to my application on a mobile web site (or even a standard web site that is accessible via a WM device) that can be resolved on the device via the marketplace client. It wouldn’t be out of the question to have a link such as wmapp://LinkID that would be handled by the marketplace client in order to display the appropriate application. This link could be used when the site detects the page being browsed by a windows mobile client.

Zune Software 4.2 in Windows Update for Windows Phone

Zune Software 4.2 in Windows Update for Windows Phone

I somehow only just realised that Windows Update was blinking at me indicating there were updates available. I’m usually pretty good about installing all the important ones but this time I noticed there was an optional component titled Zune Software 4.2. I had to ask…”why am I getting an update for Zune software when I’ve never installed the Zune software”. Not thinking much about it I proceeded with the download and subsequent install.

image

Now it occurred to me that I’d heard that the Zune software is going to be used by Windows Phone 7 to sync media, which seems logical since all Windows Phone 7 series devices are a Zune device. Having downloaded the developer tools (see http://developer.windowsphone.com if you want them) I figured that it this update must have to do with some component that was part of those tools. Spinning up a couple of my VMs I tested this out – sure enough on the VM that had the dev tools installed, there was the update but on the other VM, without the dev tools, the update was missing.

Unfortunately just because there appears to be a relationship there, doesn’t mean that you can start syncing with the Windows Phone 7 emulator. I tried both with the emulator that ships with the dev tools and the hacked emulator image that’s floating around. I’m sure there’s probably a magic unlock code/flag that you can set to enable syncing but at this stage I’m just waiting for the next official drop from Microsoft where we’ll hopefully see more of what’s going to be available in the platform as part of the emulator.

Detecting Orientation with Windows Phone 7

Detecting Orientation with Windows Phone 7

With the preview developer bits for building Windows Phone 7 applications now publically available I was experimenting with a few things and one of the first things I went looking for is support for handling device orientation. More specifically the event where the orientation of the device changes. Now you can actually do this two ways: you can either attach to the OrientationChanged event on the PhoneApplicationPage, or since your page inherits from this class you can override the OrientationChanged method. Note there is also an OrientationChanging event/method pair that you can also use.

        private void PhoneApplicationPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
        { … }

OR

       protected override void OnOrientationChanged(OrientationChangedEventArgs e)
       {
           base.OnOrientationChanged(e);
           ….
       }

One of the interesting things to note is that if you are actually interested in whether the device is now in portrait or landscape you have to be careful how you test the new orientation. For example the following condition will probably never be true:

if (e.Orientation == PageOrientation.Portrait)

If you take a look at the PageOrientation enumeration you will see that it actually defines values for each orientation:

public enum PageOrientation
    {
        None = 0,
        Portrait = 1,
        Landscape = 2,
        PortraitUp = 5,
        PortraitDown = 9,
        LandscapeLeft = 24,
        LandscapeRight = 52,
    }

So the only way the previous condition would hold true is if the system decided to return an Orientation set to the more general Portrait, rather than the specifics of PortraitUp and PortraitDown.

Fine you say, it must be a flag in which case you have to “AND” it to work out whether it’s in Portrait or Landscape. Well yes, but you need to make sure that you only do that with the Portrait value. You will notice that the values associated with these values are not your typical flag values of 1, 2, 4, 8 etc. This means that when you AND say the Landscape value of 2 (binary 00010) with LandscapeLeft (binary 11000) you will get 0, when you were expecting to get a value of 2. Luckily when you are testing against Portrait you will notice that both PortraitUp (binary 00101) and PortraitDown (binary 01001) you will get the value 1, which is what you’d expect. So the code for doing different actions based on just the Portrait/Landscape orientation would look something like:

private void PhoneApplicationPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
       {
           if ((e.Orientation & PageOrientation.Portrait)>0)
           {…}
           else
           {…}
       }

Perhaps someone out there can let me know why the enumeration has the values it does? Clearly I’m missing the obvious here, or perhaps this is a feature of the current preview bits.

Enabling Windows Phone 7 Themes in Emulator Applications

Enabling Windows Phone 7 Themes in Emulator Applications

I just noticed that Peter has put up a post on how to make a Windows Phone 7 application theme aware. I couldn’t help but recall one of the more obscure side comments in one of the MIX sessions where the presenter commented out a bunch of code in the App.xaml file in order to get theming to work correctly.  Anyhow, if you’re interested the section of xaml to comment out is the following:

        <!– Brush Resources –>
        <!–<SolidColorBrush x_Key="PhoneAccentBrush" Color="{StaticResource PhoneAccentColor}"/>
        <SolidColorBrush x_Key="PhoneBackgroundBrush" Color="{StaticResource PhoneBackgroundColor}"/>
        <SolidColorBrush x_Key="PhoneContrastForegroundBrush" Color="{StaticResource PhoneContrastForegroundColor}"/>
        <SolidColorBrush x_Key="PhoneForegroundBrush" Color="{StaticResource PhoneForegroundColor}"/>
        <SolidColorBrush x_Key="PhoneInactiveBrush" Color="{StaticResource PhoneInactiveColor}"/>
        <SolidColorBrush x_Key="PhoneDisabledBrush" Color="{StaticResource PhoneDisabledColor}"/>
        <SolidColorBrush x_Key="PhoneSubtleBrush" Color="{StaticResource PhoneSubtleColor}"/>
        <SolidColorBrush x_Key="PhoneContrastBackgroundBrush" Color="{StaticResource PhoneContrastBackgroundColor}"/>
        <SolidColorBrush x_Key="PhoneTextBoxBrush" Color="{StaticResource PhoneTextBoxColor}"/>
        <SolidColorBrush x_Key="PhoneBorderBrush" Color="{StaticResource PhoneBorderColor}"/>
        <SolidColorBrush x_Key="PhoneTextSelectionBrush" Color="{StaticResource PhoneTextSelectionColor}"/>
        <SolidColorBrush x_Key="TransparentBrush" Color="Transparent"/>—>

You should be aware that this effectively breaks the current design experience within Visual Studio and can even cause the IDE to crash.  I actually closed all my open documents before making this change and then un-commented the xaml once I was done testing the theme support.

Anyhow, here’s a (poorly designer) test application that shows the Light theme option:

image

Windows Phone 7 series, Silverlight, XNA, Compact Framework, Background Processing and… Symbian S60

Windows Phone 7 series, Silverlight, XNA, Compact Framework, Background Processing and… Symbian S60

So here are a few things I found interesting from the first day of MIX:

– Windows Phone 7 series…. duh, well yes that one was obvious. It seems that nearly everyone is talking about it. In case you’ve been living in a hole somewhere you’ll have noticed that the development story is Silverlight and XNA for this platform

– Compact Framework v3.7. If you inspect System.Environment.OSVersion in the emulator you’ll see that it reports version Microsoft Windows CE 7.0.6077. This is confirmed by this post that talks about the WP7 Programming Model.

– Background Processing – That’s right, if you’re application is a good phone citizen (as defined by Microsoft of course) and you don’t consume too many resources your application will continue to operate in the background. This is demonstrable in the emulator if you create a background thread that increments a counter or prints a debug statement – when your application looses focus it will continue to increment/print.

– Symbian S60 support for Silverlight (in-browser model). The Silverlight model for WP7 is entirely out of browser. In fact your Silverlight application will be deployed via Marketplace and will not have any contact as such with the browser. S60 support, as discussed in the post Silverlight on Nokia S60 platform, is in-browser and is only a very limited subset of Silverlight 2. The obvious questions here are whether WP7 will get SL in-browser support (they’ve already been talking about Flash inclusion but why not SL) and which other platforms will be next to get in-browser support.

I’m sure there will be plenty more bits emerging from MIX over the coming days.

Windows Phone 7 series Developer Preview…. Virtual Machine Fail

Windows Phone 7 series Developer Preview…. Virtual Machine Fail

Having sat through the MIX keynote I was excited to see the announcement of the Windows Phone 7 series development tools.  These can all be downloaded from http://developer.windowsphone.com.  The downloads are only compatible with VS2010 RC and so installing these on my main machine (which I haven’t had a chance to upgrade from the beta) is going to be a major effort.  I thought I’d go an install them on one of my many virtual machines I have running on my Hyper-V server – FAIL… According to the release notes this is not a supported option. I also noticed that round-tripping between VS and Blend is not supported – doesn’t that defeat the whole purpose?

Scenarios Not Supported

  • Opening Windows Phone projects in Expression Blend® is not supported, except for Expression Blend 4 Beta with “MICROSOFT EXPRESSION BLEND ADD-IN PREVIEW FOR WINDOWS PHONE.”
  • Round-trip editing of the Windows Phone projects between Expression Blend and Visual Studio is not supported.
  • Windows XP and Windows Server® are not supported.
  • Virtual PC and Hyper-V™ are not supported.

I’m actually guessing the issue with Virtual PC/Hyper-V is to do with the emulator, rather than the actual developer experience. This is something that we saw with very old versions of the Windows Mobile emulator where they couldn’t be run in a virtual machine – this was fixed when the emulator was moved to true ARM emulation.

Update: I’ve just finished installing the tools on a VM and the emulator, whilst slow to load the first time did in fact load and run my hello world application. Big kudos to Microsoft – the tooling looks great so far.

Also, don’t forget to check out the following discussion documents on the platform and designing for Windows Phone 7 series.

Jamie Oliver live in Centennial Park with food from Sydney Picnics

Jamie Oliver live in Centennial Park with food from Sydney Picnics

We just got back from a fantastic evening watching Jamie Oliver prepare some gourmet delights on the stage in Centennial Park. He’s got such a great stage presence. Between him, the audience and his good mate, Ben O’Donoghue, Jamie brought the full song-and-dance production to Sydney, delivering an evening that will be remembered for a while to come.

 

Normally at these event you’re left drooling as all the best food ends up being created and eaten on stage by those fortunate enough to make themselves noticed at the front of the event. Not to be left feeling hungry we came prepared and had our own picnic courtesy of the Sydney Picnic Co.

After looking around at a number of different picnic providers I settled on the Sydney Picnic Co because they seemed to have the same idea about food as I do – it’s there to be enjoyed rather than to just fill you up. The selection of cold meats, wild onions, risoni and of course the Valrhona chocolate pots made for an amazing feast from which none of us went hungry. In fact we got a picnic sized for 4 and walked away with enough food for lunch tomorrow (and yes, there’s going to be some arguing over who gets what….).

Anyhow, a big thanks to the Sydney Picnic Co for making a great event and unforgettable experience. If you’re looking to do a picnic in the park or at the beach I can’t recommend them enough!

Windows Phone 7 – Will it be everything Microsoft wants it to be?

Windows Phone 7 – Will it be everything Microsoft wants it to be?

Charlie Kindel’s posted about some internal planning that the team did as part of building Windows Phone 7 series. I’m assuming that this isn’t an ordered list but I’m also guessing that this was the order the points were on some list somewhere (perhaps as they were written on a whiteboard during a brainstorming session). If this is the case, it’s concerning that “It’s easy to build beautiful applications users just love" falls at the bottom of the list.

For those that are familiar with Windows Mobile development you’ll have gone through the list and gone yep, yep, yep to most of the points. Most of these points we could achieve on the current Windows Mobile platform (perhaps with the exception of protecting the developers IP and until recently a single marketplace). Where Windows Mobile sucks is the ability to generate awesome applications that users really want to use – it’s not impossible by the way, just hard to do. Actually, it’s hard to do this full stop. I’d almost stake my life on it that despite Microsoft’s attempt at making it easy to build “beautiful” applications, beauty is definitely in the eye of the beholder and we are going to get some hideous creations appearing on the marketplace.

I’m looking forward to MIX next week when we’ll hear just how great we can my Windows Phone 7 series applications.

OpenGL: More on Transforms

OpenGL: More on Transforms

In OpenGL- Rotate, Scale and Translate I took a very simple example of transforming some text but what happens if you want to do something more complex. For example you want to have a pair of strings that you can transform around the screen together (ie not have to worry about transforming individually. To do this we can use a form of layering in our rendering where each layer can contain any number of items that will be rendered together. Each layer can be transformed with the resulting transform being applied to each item in the layer.

We’re going to start off by defining an abstract class called ScreenWidget. I’ve used widget because I couldn’t think of a more “correct” name to call items that are going to be displayed on the screen. If there is a better name, do tell me as I’m keen to stick with a vocabulary that is well understood.

abstract class ScreenWidget
    {
        public Vector3f Position { get; set; }
        public Vector3f Anchor { get; set; }
        public Vector3f Scale { get; set; }
        public float Angle { get; set; }
        public Vector3f RotationAxis { get; set; }

        public ScreenWidget()
        {
            Scale = new Vector3f(1, 1, 1);
            RotationAxis = new Vector3f(0,0,1);
        }

        public unsafe void Draw()
        {

            gl.PushMatrix();
            gl.Translatef(Position.X, Position.Y, Position.Z);
            gl.Scalef(Scale.X, Scale.Y, Scale.Z);
            gl.Rotatef(Angle, RotationAxis.X, RotationAxis.Y, RotationAxis.Z);
            gl.Translatef(-Anchor.X, -Anchor.Y, -Anchor.Z);

            DrawComponents();
            gl.PopMatrix();
        }

        protected abstract void DrawComponents();

        public virtual void Setup() {}

        public virtual void Update(float secondsSinceLastUpdate){}
    }

In the ScreenWidget class we can see that it tracks values for position, anchor, scale, angle and rotation axis. It’s worth noting that the position is actually the position of the anchor point within the containing widget. If the widget isn’t nested within another widget then the position will be the position of the anchor point on the screen.

The Draw method on the ScreenWidget is called in order to render all items contained within the widget to the screen. Before doing so it applies a sequence of transforms to scale, rotate and position the widget correctly with respect to its containing widget (and thus subsequently the screen).

What’s interesting is that all these transforms and the call to DrawComponents (which by the way is what an overriding class has to implement in order to actually render items to the screen) are wrapped in a pair of PushMatrix and PopMatrix method calls.  Essentially this ensures that the OpenGL model matrix (ie the matrix that is used to transform items being rendered) is the same when the method ends as when the method started – failure to do this may lead to unexpected results with items being incorrectly positioned, scaled or rotated further on during rendering. PushMatrix pushes the current matrix onto a temporary stack, whilst PopMatrix pops the top matrix on the stack off and makes it the current matrix.

We’ll start by creating the simplest of widgets, the TextWidget:

class TextWidget:ScreenWidget
{
    OpenGLFont font;
    GlyphRun title;
    public override void Setup()
    {
        font = new OpenGLFont(new Font(FontFamily.GenericSerif, 12, FontStyle.Regular));
        title = new GlyphRun(font, "Hello World!", new Size(int.MaxValue, int.MaxValue), OpenGLTextAlignment.Left, true);
        this.Anchor = new Vector3f(title.Size.Width / 2, title.Size.Height / 2, 0);
    }
    protected override void DrawComponents()
    {
        title.Draw();
    }
}

As you can see the TextWidget simply creates a GlyphRun object that can be draw during the DrawComponents method. Also note that the Anchor property has been set based on the size of the title. This will ensure that if this widget is rotated or scaled it will be done based on the centre of the text, rather than a corner.

Next is a simple container widget, funnily enough called ContainerWidget:

class ContainerWidget : ScreenWidget
    {

        TextWidget text;
        TextWidget text2;
        public override void Setup()
        {
            text = new TextWidget();
            text.Position = new Vector3f(10,10, 0);
            text.Angle = 30;
            text.Setup();

            text2 = new TextWidget();
            text2.Position = new Vector3f(20, 20, 0);
            text2.Angle = 50;
            text2.Setup();
        }
        protected override void DrawComponents()
        {
            text.Draw();
            text2.Draw();
        }

    }

You can see that the two TextWidget instances have been position and rotated by different amounts. Before we can see this we’ll need to go back to our MainForm and create an instance of the ContainerWidget.  The Draw method will then be called on this instance in order to draw the two nested GlyphRuns.

public partial class MainForm : ApplicationForm
{

    public MainForm()
    {
        InitializeComponent(); 
    }

    ContainerWidget widget;
    protected override void SetupScene()
    {
        base.SetupScene();

        widget = new ContainerWidget();
        widget.Position = new Vector3f(0, 0, 0);
        widget.Setup();
    }

    protected override void DrawScene()
    {
        base.DrawScene();

        widget.Draw();

    }

    protected override void UpdateScene(float secondsSinceLastUpdate)
    {
        base.UpdateScene(secondsSinceLastUpdate);

        widget.Update(secondsSinceLastUpdate);
    }
}

As you can see this keeps both the MainForm and the ContainerWidget very clean in terms of the code than needs to be written to display elements.

image

This image isn’t particularly great as the two pieces of text are mostly off screen. So lets modify just the position of the ContainerWidget in the DrawScene method of the MainForm:

gl.PushMatrix();
gl.Translatef(100.0f, 100.0f, 0);
widget.Draw();
gl.PopMatrix();

This gives a much clearer picture of the two pieces of text but note that we only needed to translate the container widget.

image

OpenGL: Rotate, Scale and Translate

OpenGL: Rotate, Scale and Translate

In my previous post, OpenGL ES Wrapper- Your First Application, you would have seen that we were creating a GlyphRun that we then draw. This is actually a wrapper class that handles all the processing required to draw the text on the screen. However, it doesn’t handle the positioning of the text on the screen – by default it is located at the origin ie (0,0,0).

To move this text around the screen we can specify an amount to translate, scale or even rotate the text by using the appropriate OpenGL commands. One thing to note here is that the order in which you do these operations may change the result you see. For example in the following images the original text (first image) is translated by (50,50,0) and then rotate around the z axis by 40 degrees.

image

Now apply translation and rotation – note the order of the gl.Translate and gl.Rotate method calls.

gl.Translatef(50.0f,50.0f,0);
gl.Rotatef(40.0f,0,0,1.0f);
title.Draw();

 image 

Now apply translation and rotation in the other order.

gl.Rotatef(40.0f,0,0,1.0f);
gl.Translatef(50.0f,50.0f,0);
title.Draw();

image

You can see that the order that rotate and translate are applied makes a difference. Interestingly they almost appear in the wrong order. In the second image the original image has been translated by (50,50,0) then rotated to get the text to where it appears, whilst in the previous image the text has been rotated by 40 and then translated. This is a result of the way OpenGL uses matrix multiplication to apply transforms to what you are drawing. Each time you issue a transform the corresponding matrix is multiplied against the current matrix to calculate the position of the items you drawing.

The other thing you’ll notice is that the text appears to be rotating around the top left corner of the text. To get it to rotate around the centre of the text, you need to apply a translate function to position the text with its centre at the origin, prior to rotating it and then translating it back into it’s final position.

image image image

Update – here’s the code for doing this additional translation (again, note the order that they’re done in)

gl.Translatef(50.0f, 50.0f, 0);
gl.Rotatef(40.0f, 0, 0, 1.0f);
gl.Translatef(-title.Size.Width/2, -title.Size.Height/2, 0);
title.Draw();

OpenGL ES Wrapper: Your First Application

OpenGL ES Wrapper: Your First Application

In my previous post on Getting Started with OpenGL on Windows Mobile I talked about taking the existing OpenGL ES wrapper by Koushik Dutta and extending it to make it easier to work with.  In this, and subsequent posts, I’ll show you how you can take this wrapper and start building out an application.

To get started create a new Smart Device project in Visual Studio 2008.

image image

Note that I’ve created this against the Windows Mobile 5 SDK – if you can find a legacy device still running WM5 which supports OpenGL then this application will still run. I only bother building against the later SDKs if I particularly need one of the few features that were added since WM5.

Next, copy the two OpenGL projects from the this link into your solution folder and add them to your solution within Visual Studio. Also, go ahead and add a project reference from your application to both OpenGL projects.

image

You won’t be needing the designer support for your form but you do need some of the initialization values set in the Form1.designer.cs file. It’s up to you whether you move the InitializeComponent method from your Form1.designer.cs file into your Form1.cs, and then delete Form1.designer.cs, or just leave the designer.cs file there and ignore it.

At this stage I’d recommend renaming Form1 to something more descriptive. In this case my application is only going to have a single form so I have used MainForm. In the MainForm.cs file I’ve modified the class to inherit from ApplicationForm, rather than just Form – this gives me all the OpenGL initialization I talked about previously, as well as some virtual methods that can be implemented to setup, draw and update the current scene:

public partial class MainForm : ApplicationForm
    {
        public MainForm()
        {
            InitializeComponent();
        }

        protected override void SetupScene()
        {
            base.SetupScene();
        }

        protected override void DrawScene()
        {
            base.DrawScene();
        }

        protected override void UpdateScene(float secondsSinceLastUpdate)
        {
            base.UpdateScene(secondsSinceLastUpdate);
        }
    }

In this case we’re going to simply implement Hello World by creating a Font and GlyphRun in the SetupScene method:

OpenGLFont font;
GlyphRun title;
protected override void SetupScene()
{
    base.SetupScene();

    font = new OpenGLFont(new Font(FontFamily.GenericSerif, 12, FontStyle.Regular));
    title = new GlyphRun(font, “Hello World!”, new Size(int.MaxValue, int.MaxValue), OpenGLTextAlignment.Left, true);
}

Then to draw the text on the screen, simply update the Draw method:

protected override void DrawScene()
        {
            base.DrawScene();

            title.Draw();
        }

 

 

image

Not the worlds greatest demo, but surprisingly simple for an OpenGL application. In the next post we’ll start to investigate what you can really do with OpenGL that you can’t do easily with traditional Windows Forms application.

Note: In the InitializeOpenGL function within ApplicationForm you need to include the following call otherwise your text will appear as a solid white rectangle:

gl.BlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA);

Getting Started with OpenGL on Windows Mobile

Getting Started with OpenGL on Windows Mobile

There are a number of good posts on working with OpenGL on Windows Mobile via the .NET Compact Framework but one thing I’ve noticed is that they don’t really try to wrap the OpenGL functionality in a way that makes it reusable as an application/game framework. Mostly the logic for rendering was intermingled with windows forms logic, such as OnPaint, which was intermingled with logic for updating the current scene. If you look at say XNA you notice that the model is very simple – essentially they have a single run loop consisting of Update and Draw. I set out to update the OpenGL ES wrapper initially provided by Koushik Dutta and since extended with some great examples across at XDA Developers. Here’s what I came up with to start with.

If you grab the OpenGL ES wrapper you will notice that at its core is essentially a single Windows Form that handles the OnPaint method in order to draw using OpenGL primitives. Nearly all the computation and rendering is done in this method. In the constructor and subsequent initialization methods there are a number of OpenGL ES calls in order to setup the display, surface and context required in order for OpenGL to draw to the screen. In order to create a reusable framework that would be a starting point for any project undertaken in OpenGL all this code would have to be wrapped in a way that it doesn’t need to be duplicated for each project.

I decided to go down the path of creating an abstract form which I called the ApplicationForm. This form has three virtual methods that the overriding form needs to implement:

protected virtual void SetupScene(){}

protected virtual void UpdateScene(float secondsSinceLastUpdate){}

protected virtual void DrawScene(){}

As you can imagine these form the basis of the Draw-Update rendering loop. Of course SetupScene is called prior to the first iteration of this loop to ensure the scene is correctly setup before the first call to Draw. Unlike some implementations which rely on a For/While loop and DoEvents (to allow windows events to be processed) I went with the approach that works in conjunction with the existing windows message pump. When the form needs to be painted the OnPaint method is invoked:

protected override void OnPaint(PaintEventArgs e)
       {
           base.OnPaint(e);

           // Draw the current scene
           RunDrawScene();

           egl.SwapBuffers(_display, _surface);
           gl.Clear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT);

           // Update the current scene
           RunUpdateScene();
       }

As you can see this does a single pass of the rendering loop.  What’s interesting is the implementation of the RunUpdateScene method:

private void RunUpdateScene()
       {
           // Check for running instance – exit if already running
           if (Interlocked.CompareExchange(ref isUpdating, 1, 0) == 1)
           {
               return;
           }

           // Only instance running, so create the thread in which to
           // invoke the UpdateScene method
           ThreadPool.QueueUserWorkItem((async) =>
           {
               try
               {
                   // Calculate the time in seconds since last update
                   var seconds = (float)Environment.TickCount/1000.0f;
                   var diff = 0.0f;
                   if (this.lastUpdate > 0)
                   {
                       diff = seconds – this.lastUpdate;
                   }
                   this.lastUpdate = seconds;

                   // Invoke the virtual UpdateScene method
                   UpdateScene(diff);
               }
               finally
               {
                   // Make sure this method can be re-entered
                   Interlocked.Decrement(ref isUpdating);

                   // Invoke "Invalidate" on the control which will cause
                   // the control to be refreshed (ie OnPaint called) leading
                   // to another iteration of Draw and Update
                   this.BeginInvoke((Action)(() => { Invalidate(); }));
               }
           });
       }

Essentially this method wraps the actual call to UpdateScene for three reasons:

  1. To ensure only one instance of UpdateScene is being invoked at any time
  2. To push the call to UpdateScene onto a separate thread. This prevents the UI from blocking whilst it’s in running.
  3. To invoke Invalidate once UpdateScene has completed. This ensures that OnPaint will be invoked again and that the draw-update loop will be invoked again.

In the next post I’ll show you how to get started with this wrapper by overriding the ApplicationForm.  In the meantime, try it yourself….

Breaking Changes: Windows Phone 7 series Development Story

Breaking Changes: Windows Phone 7 series Development Story

Well the cat’s out of the bag… actually no all that’s happened is that Microsoft has confirmed that one of the cats that was in the bag is now dead: The rumour that legacy applications will run on Windows Phone 7 series is officially dead with Charlie Kindel confirming the lack of backwards compatibility in a post entitled Different Means Better with the new Windows Phone Developer Experience.

What’s interesting is just how well the whole Windows Phone 7 series announcements have been. If you look at other blogs from Microsoft, they all have similar posts talking about the decisions that were made in order to give developers an awesome platform to start building applications on. For example the following blogs all have posts coinciding with Charlie’s post:

Andre Vrignaud: www.ozymandias.com

Break with the Past, Bright New Future: Windows Phone Application Development Platform built on XNA and Silverlight

Christian Schormann: electricbeach.org

Windows Phone 7 Series for Designers and Developers

Shawn Hargreaves: blogs.msdn.com/shawnhar

Backward compatibility

Anand Iyer: www.artificialignorance.net/blog

Windows Phone 7 Series – Developers, Developers, Developers

Michael Klucher: klucher.com

Gaming Development for the Go!

Also confirmed in a twitter Q&A at @WP7dev was support for both Silverlight and XNA development for Windows Phone 7 series. Hopefully this will provide a much more consistent rapid development environment for building phone applications whilst still making them perform.

Currently on Windows Mobile we have a number of technologies to choose from, none of which provide a great experience to both developer and consumer without a lot of cycles invested in making your application look good. The worst part about this is not the cycles spent working out what the application should look like (eg working with a designer to make it look awesome), it’s the wasted cycles having to code it from the ground up each time.

Native C++: Sure you can do nearly anything you want but you take a major productivity hit. Not to mention building a team of top notch c++ developers is becoming very difficult.

WinForms: This just sux for anything other than a mundane LOB application. Sure you can use some of the transparency tools out there to get stylish buttons, or override OnPaint to DIY it to make it look reasonable but you aren’t really going to be doing much in the way of animations, rotating elements etc.

Direct3D: Well this is a technology flop in so far as there is little hardware rendering support out there on a lot of devices. Best to ignore this one….

OpenGL: This is an interesting beast. You can write all your code in C#, yet you have the power of doing nearly any sort of animation, rotation, translation, in fact there is a lot you can do with vectors, triangles and quads. Documentation on getting started and troubleshooting is a little light on but once you get things up and running the results are quite good. You do of course have to think in matrices, projections etc which for those not familiar with these constructs can pose a bit of a learning barrier.

So, if you were going to build a mobile application today, what would you do….. Well contrary to Charlie’s post in which he suggests that developers will continue to build for Windows Mobile, I suspect the reality is that nearly every mobile developer out there will start building Windows Phone 7 series applications as soon as the tooling arrives.

OData SyncClient for MIX

OData SyncClient for MIX

Yesterday Charlie Kindel tweeted about this session planner that can be used for MIX. What’s really interesting about this Silverlight application is that it has the ability to synchronise data and work offline.

image

Having noticed this (which you can hardly miss given the “Sync” icon in the top right corner) I wondered if there was a session on Sync.  Sure enough there is a session called “Building Offline Web Apps Using Microsoft Sync Framework” with the following abstract:

Come learn about offline web applications and how they can provide a better experience to your users.  Windows Azure, Microsoft SQL Azure, and Sync Framework are the core technologies that enable web developers to create offlien applications. See how to use these three technologies to produce great applications.  We also introduce our upcoming support for offline Microsoft Silverlight clients and show you how you will have the flexibility to use any platform for your offline applications, device or desktop.

Coming from “mobile-land” where we take doing synchronisation (whether it be DIY webservices, RDA, Merge, Sync Services) for granted the idea that finally web developers might get the concept of offline applications is quite laughable. But, leaving that aside what interested me is what this “upcoming support for Silverlight” is going to be – well they kind of let the cat out of the bag with the session builder. Whilst there is a pseudo attempt at hiding what’s going on in the sync (I’m guessing more out of privacy concerns rather than hiding the sync technology) this is easily broken using Fiddler (you’ll have to enable https tracing in Fiddler and add the Fiddler certificate to your trusted cert list – see http://www.fiddler2.com/Fiddler/help/httpsdecryption.asp for instructions).

A typical sync session looks like this:

image

Notice that each request to either GetChanges or UploadChanges has the same suffix:

/ODataSync.svc/GetChanges/377d1869-e69a-4b67-9ddd-392169e9b06e?userToken=d39ea0f0e5104c4aad457b897a7b4b62

/ODataSync.svc/UploadChanges/377d1869-e69a-4b67-9ddd-392169e9b06e?userToken=d39ea0f0e5104c4aad457b897a7b4b62

The response to the first GetChanges call (which doesn’t contain any data) looks something like:

image

In this we can see that there is an anchor and then there are a list of entries.  Each entry, under the content node, contains a series of properties.  As you can see sync is using odata to transport entity information.

Each successive GetChanges call sends the anchor back to the server – I’m guessing this anchor value is used to track the synchronization state of the client with the server.

“eyJLbm93bGVkZ2VCbG9iIjoiQUFBQUJRQUFBQUFBQUFBQkFBQUFBQUFBQUFVQUFCQUFBQUFDTjMwWWFlYWFTMmVkM1RraGFlbXdidGxzQU1rZkowNyt1MHNWYXE1YVBDNEFBQUFZQUFBUUFTZ0NBQUFCQUFBQUZRQUFBQUVBQUFBQkFBQUFBQUFBQUJjQUFBQUJBQUFBRmdBQUFBRUFBd0FBQUFBQUFBQUFBQUFBQUJrQkFBQUFBQT09IiwiVGFibGVXYXRlcm1hcmtzIjpbeyJLZXkiOiJTY2hlZHVsZUl0ZW0iLCJWYWx1ZSI6MTcwNTZ9XX0=”

Of course, the session planner must be storing data in Silverlight’s isolated storage.  After a little poking I managed to find some of the data being stored:

{"Anchor":"eyJLbm93bGVkZ2VCbG9iIjoiQUFBQUJRQUFBQUFBQUFBQkFBQUFBQUFBQUFVQUFCQUFBQUFDTjMwWWFlYWFTMmVkM1RraGFlbXdidGxzQU1rZkowNyt1MHNWYXE1YVBDNEFBQUFZQUFBUUFTZ0NBQUFCQUFBQUZRQUFBQUlBQUFBQkFBQUFBQUFBQUFFQUFBQUNBQUFBQUFBQUFBQUFBRWswQUFBQUFRQUFBQUFBQUVrekFBQUFGd0FBQUFFQUFBQVdBQUFBQVFBREFBQUFBQUVBQUFBQUFBQUFHUUVBQUFBQSIsIlRhYmxlV2F0ZXJtYXJrcyI6W119","Data":[{"Key":"speaker","Value":[{"__type":"ItemChangeOfDbSpeakerzgKIiSuC:#Microsoft.Synchronization.Offline","IsCreate":false,"IsDirty":false,"IsTombstone":false,"Item":{"Bio":"Beginning life as an art student, then after a stint in the military joining the world of technology, Adam Kinney feels right at home in that sweet spot between Designer and Developer. Always at least a part-time evangelist, Adam has traveled the trail of UI technologies. First HTML/CSS, then Flash, WPF and now Silverlight, the one client technology to rule them all, he has enjoyed learning, experimenting and teaching them all.rnAdam’s current focus is Expression Blend, the first interactive design tool that’s really made him happy as a designer and developer.","SpeakerDisplayName":"Adam Kinney","SpeakerFirstName":"Adam","SpeakerID":"b5056969-1f9f-4268-8cbd-64a2fcb7080f","SpeakerLastName":"Kinney","SpeakerName":"Adam-Kinney"}},{"__type":"ItemChangeOfDbSpeakerzgKIiSuC:#Microsoft.Synchronization.Offline","IsCreate":false,"IsDirty":false,"IsTombstone":false,"Item":{"Bio":"","SpeakerDisplayName":"Akash Patel","SpeakerFirstName":"Akash","SpeakerID":"cd381f2f-cdca-469a-a937-dae1ad6f72d6","SpeakerLastName":"Patel","SpeakerName":"Akash-Patel"}},

Sure enough as you can see the anchor is being persisted, along with a series of entities. There are typical fields that you’d expect with synchronization such as IsCreate, IsDirty, IsTombstone but very little in the way of date time or versioning stamps. This again points towards the server doing the bulk of the synchronization logic.

Well that’s enough poking around with the session builder for one day – I can’t wait to see this session at MIX and see what the sync team have been working on.