Saturday, January 26, 2013

Lockscreen applications

At the moment I've written the Instagram Lockscreen application for Windows Phone 8 - but there's a lot more on the way.

(this post is initially a placeholder for more content)

There is a port for Windows 8 on the way.

But, there is something else in progress.. something awesome :)

Tuesday, October 16, 2012

Windows Store Apps quick tip: the sneaky selected item in CollectionViewSource

When assigning an ItemsSource there is a fundamental difference in CollectionViewSource vs “standard” collections: Using a CollectionViewSource will mark the first item as selected, using a “standard” collection will not.

Imagine if you will a ListView where you handle SelectionChanged and fetch data from somewhere depending on what item is selected. If you’re using a CollectionViewSource and navigate to the page you’ll fire that call twice – first for the default selected item, then for the passed in parameter that you’re likely using to the set SelectedItem.

That is all.

Windows Store Apps quick tip: getting the app version number

If you need to get the version information of your app from code, the details you want resides in Windows.ApplicationModel.Package.Current.Id.Version.

For example, to get a full version string you could use the below code:

string.Format("{0}.{1}.{2}.{3}", Windows.ApplicationModel.Package.Current.Id.Version.Major, 
                                 Windows.ApplicationModel.Package.Current.Id.Version.Minor, 
                                 Windows.ApplicationModel.Package.Current.Id.Version.Build, 
                                 Windows.ApplicationModel.Package.Current.Id.Version.Revision)

That is all.

Wednesday, October 10, 2012

Windows Store Apps – a generic connectivity-dropped control to take that worry from your brow

(If you can’t be bothered reading the text and just want the code it’s available for download here)

One of the requirements when publishing your Windows Store app is that the app needs to handle connectivity loss. No matter how much you curse at the certification requirements that one is there for a good reason (as many of them are), and it prevents the user experience from going haywire. So, it’s fair game, not much you can say about that. Usually what people do here is add a handler to the Application.UnhandledException event and swallow as many/few of the exceptions they can. Good on you. now your app is fool-proof.. or is it?

What about letting your user know something happened visually? well, you could show a MessageDialog with the details of that error. I suppose that, at least, gives a bit of context.

Back to connectivity. This shouldn’t be a concern. This houldn’t steal time from you that you can spend on implementing all your ideas. This should just be handled.
One way to handle these issues automagically is by creating a generic control that can visually present meaningful (hopefully, but up to you) context to your user while the app has lost connectivity.

Therefore, I give you ConnectivityPopUp.

ConnectivityPopUp is a custom control that pops up an overlay across the entire screen when your app looses connectivity. The guts of the control consists of a PopUp control containing a Grid with a FlipView and FlipViewIndicator (from the awesome Callisto framework), along with some dependency properties and a control template.

Once placed on your page it handles the hassle of connectivity for you – all you have to do is supply it with at least one ConnectivityPopUpPage and place the control on your page(s). Behind the scenes it then attaches to the Windows.Networking.Connectivity.NetworkInformation.NetworkStatusChanged event.

            var connectivityPages = new ObservableCollection<Usoniandream.WindowsStore.Controls.ConnectivityPopUpPage>()
                                        {
                                            new ConnectivityPopUpPage(){Title = "have you tried DiceFeud yet?", 
                                                                        _imagePath = "Assets/MediumGray.png", 
                                                                        Description = "Lorem ipsum … ante"}
                                        };
            this.DefaultViewModel["ConnectivityPages"] = connectivityPages;

Once that event is fired, and handled, it takes care of telling the UI to show the control on the appropriate thread. This is accomplished simply by travelling the action of setting IsOpen=true through Dispatcher.RunAsync().

The default layout of the control is fairly minimalistic and, yes, boring.

        <usoniandream:ConnectivityPopUp
            Pages="{Binding ConnectivityPages}" />

image

 

But it doesn’t have to be boring. You can customize it using BackgroundImagePath and BackgroundImageStretch properties to your liking.

Perhaps you instead want to create a Homer Simpson styled one..?

        <usoniandream:ConnectivityPopUp
            BackgroundImagePath="Assets/ohno.png" 
            BackgroundImageStretch="Uniform" 
            Pages="{Binding ConnectivityPages}" />

image

 

Or maybe HAL resides somewhere in the void of space in your app..?

        <usoniandream:ConnectivityPopUp
            BackgroundImagePath="Assets/space.png" 
            BackgroundImageStretch="UniformToFill" 
            Pages="{Binding ConnectivityPages}" />

image

The control is dependent on Tim Heuer’s Callisto framework since it uses the FlipViewIndicator from that framework.

This is just my take on handling connectivity issues in a generic way.

If it suits your needs – go grab it. Then use it.
If it doesn’t – go grab it anyway. Then turn it inside out. Change it. Invert it.

Monday, October 08, 2012

Windows Store Apps – a Panorama-ish GridView

The idea is simple: Take a GridView, tweak it to see if it’s possible to get a somewhat similar feeling as the Panorama control for Windows Phone.

If you search for panorama and windows store you’ll likely end up in discussions about something called “parallax background” – at least that’s what I did. One article that cought my eye was this one written by John Michael Hauck. He took an interesting approach and created a ParallaxConverter to sort it all out. Cudos to him – that’s the one I’m using in this example.

Also included in this marriage-of-a-lot-of-techniques is the tip from Jerry Nixon on how to use a variablesizedwrapgrid and custom gridview to make it a little prettier found here.

So, quick recap of the recipie for this sweet cake:

  1. Implement “panorama-ish” effect thanks to John Michael Hauck.
  2. Make the item layout a bit nicer thanks to Jerry Nixon.
  3. Bake both together for 20 minutes
  4. Ready to serve hot from the oven

I won’t dig into details of the code in this post, you have the sourcecode available for that if you wish to dive in.

If you observe the images below you’ll see that the background moves much slower than the gridview in the foreground – voila! mission accomplished!

imageimageimageimage

This is an experimental, playful and far from perfect code. It’s just here to show you that it can be done, and that there are techniques out there that can help you a lot.

Feel free to grab the code in this zip archive. Use or modify it as you wish. If you got the balls to give credit where credit is deserved, go thank Jerry Nixon, John Michael Hauck and the other authors in the community for the effort they put into sharing what they know.

Tuesday, September 18, 2012

Windows Store Apps – using a generic service layer

Another perhaps helpful tip when building Windows Store Apps that are connected in some way to the internet: You can easily create a reusable “service layer” for your web requests that make consuming async http urls more of a walk in the park.

With that said, say hello to the GenericServiceLayer for Windows Store Apps.

the idea is simple: extract away as much as possible from the (often) repetitive task of sending web requests in a windows store app.

Usage:

  1. Reference the dll/project
  2. In your viewmodel/datasource/whatever, create a GenericServiceLayer
  3. use it in your code

Setting up a GenericServiceLayer in your code shouldn’t take much more than this:

    public class GenericServiceLayerSample
    {
        private GenericServiceLayer service = null;

        public GenericServiceLayerSample()
        {
            CookieContainer cookieContainer = new CookieContainer();
            HttpMessageHandler handler = new HttpClientHandler() { CookieContainer = cookieContainer, UseCookies = true};
            handler = new InspectorHandler(handler);
            var client = new HttpClient(handler) { BaseAddress = new System.Uri("http://dev.virtualearth.net/REST/v1/Locations/") };

            service = new GenericServiceLayer(client);
        }
    }

Note that the code above also uses the InspectorHandler I wrote about in the previous post.

Now, to use it. It’s really as simple as:

        public async void Sample()
        {
            // get a string response
            var response = await service.GetAsync("Eiffel%20Tower?o=json&key=BingMapsKey");
            // get a Json.NET mapped model
            var responseModel = await service.GetAsync<MyEiffelTowerModel>("Eiffel%20Tower?o=json&key=BingMapsKey");
        }

Passing in parameters/content is done in a structured way using the normal syntax, for example:

            // pass in content via PUT and get a string response
            HttpContent content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("SomeInnerContent", "innercontent")
            });
            var response = service.PutAsync("Eiffel%20Tower?o=json&key=BingMapsKey", content);

The methods (GET, POST, PUT) exposed in the GenericServiceLayer all implement IAsyncOperationWithProgress<Tresult, int> which easily enables you to also report progress on the requests made:

            // get a string response and listen for progress
            var response = service.GetAsync("Eiffel%20Tower?o=json&key=BingMapsKey");
            int reportedProgress = 0;
            response.Progress = (info, progress) =>
            {
                reportedProgress = progress;
            };

The above “reportedProgress” would probably be a property in your viewmodel (or the approach you’re running with that makes use of NotifyPropertyChanged) so that it’d present a visual progress notification in your app when changed.

Perhaps you’ll find this useful, it has proven valuable in the adventures of Windows Store Apps I’m currently embarking on.

Full source code can be downloaded here.

Windows Store Apps – a simple HttpClient request & response debugger

Here’s the deal: Debugging is a pain. Sometimes a huge pain, other times it’s not that big of a deal. Regardless of the case at hand I often find myself digging into the requests and responses of the HttpClient, so therefore I wrote this little helper.
So, with that said, let me introduce you to InspectorHandler for Windows Store apps.
It’s simple really - InspectorHandler is a MessageProcessingHandler that you can add to your HttpClient definition that outputs the request & response from the HttpClient to the debug output window when you’re in debug configuration.
Usage is really straight forward:
  1. Hook up the handler
  2. Create the HttpClient
  3. You’re set.
Continue using the HttpClient just as you normally would with await, ReadAsStringAsync() and all that.
        private async void btnGo_Click_1(object sender, RoutedEventArgs e)
        {
            // declare http handler
            HttpMessageHandler handler = new HttpClientHandler();
            // append the Inspector handler
            handler = new InspectorHandler(handler);
            // allocate a http client on the above handlers
            var client = new HttpClient(handler) { BaseAddress = new System.Uri("http://dev.virtualearth.net/REST/v1/Locations/") };

            // fire request
            var response = await client.GetAsync("Eiffel%20Tower?o=xml&key=BingMapsKey"); // insert a proper bing maps key here otherwise you'll just get the access denied view..
            // output result
            tbContent.Text = await response.Content.ReadAsStringAsync();
        }
      Below is a screenshot of a example app that once the button is pressed fires a GET request to the http://dev.virtualearth.net/REST/v1/Locations/Eiffel%20Tower?o=xml&key=BingMapsKey url and ouputs the result into a textbox.
image  
And some basic interesting details from the request & response objects are now available in the ouput of the debugger:
image  
There you have it. Simple, fairly effective and perhaps useful. Under the hood the InspectorHandler is far from a work of art, but it does the job quite well for being a simple debug tool. Here’s the complete source code:
    public class InspectorHandler : MessageProcessingHandler
    {
        public InspectorHandler(HttpMessageHandler innerHandler)
            : base(innerHandler)
        {
        }

        protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request, CancellationToken cancellationToken)
        {
#if DEBUG
            if (request.Content!=null)
            {
                var content = request.Content.ReadAsStringAsync();
                content.Wait();
                Debug.WriteLine(string.Format("INSPECTOR: {0} REQUEST - {1} - {2}", request.Method, request.RequestUri.ToString(), content.Result));
            }
            else
            {
                Debug.WriteLine(string.Format("INSPECTOR: {0} REQUEST - {1}", request.Method, request.RequestUri.ToString()));
            }
#endif
            return request;
        }

        protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken)
        {
#if DEBUG
            if (response.Content!=null)
            {
                var content = response.Content.ReadAsStringAsync();
                content.Wait();
                Debug.WriteLine(string.Format("INSPECTOR: {0} RESPONSE - {1} - {2}", response.RequestMessage.Method, response.StatusCode, content.Result));
            }
            else
            {
                Debug.WriteLine(string.Format("INSPECTOR: {0} RESPONSE - {1} - {2}", response.RequestMessage.Method, response.StatusCode));
            }
#endif
            return response;
        }
    }
If you want it, you can grab it here as a zip containing the class library project ready to be compiled & referenced.