Silverlight Posts By a Dev Theologian

The WP7/Windows Metro/RT Opportunity! 

Wednesday, January 25, 2012 11:56:27 AM

I think we’ve all seen the commercial where the kids are playing with their dad who is grocery shopping. The kids update the grocery list with all kinds of sweets. Eventually the dad realizes what is happening and he changes the list to “Do your homework!!” Microsoft is famous for showing stuff like this, and about 2 to 3 versions of VS later it gets available to the masses. In other words, it’s a feature they keep to themselves for a bit and then they give it to the developers. Oftentimes we have already moved on or have built our own solutions to the problem that we are now stuck with (until we refactor our code).

This is why I am amazed at what has been announced surrounding SkyDrive, Windows Phone (aka WP7, WP7.5, etc), and the next version of Windows. We are actually getting the ability to make apps like this! Very, very cool!

Theme Park Pro – A Scenario
I was recently at an Amusement Park and used my buddy’s NeurelNet’s Theme Park Pro App. If you are not familiar with the app, it let’s you scope out a bunch of Amusement parks (like Walt Disney World, Busch Gardens in Tampa, and Universal Studios Parks in Florida – just to name a couple). They actually offer badges as you walk around the park letting you check in at the Roller Coasters and other rides. As I was using the app that day I started thinking about a few changes I was going to suggest to the guys.

As the went on I realized that there were a couple things bugging me. I’m getting older (but still in my early 40s), so there are few roller coasters I ‘m not really interested in riding (mainly because I am not the daredevil I once was). I started realizing that what I wish I could have done was customized my trip to show those things that I wanted to do on my trip. Of course I really didn’t want to do this on my phone.. I wanted to do this on something like my tablet or my laptop.. I wanted to be able to customize my experience in Theme Park Pro and have it reflected when I grabbed my phone.

The Opportunity!
As I was thinking how to send this idea to my NeurelNet buddies I realized what an opportunity we all have (those of us who develop for Windows Phone –or other Mobile Platforms, really). We can make Phone Apps that absolutely rock and that combine the experiences of the PC and the Phone. I watched the demos at BUILD, but the reality is hitting me now.. I think there is a huge financial opportunity for us all again!

WinRT Quick Tip #1: Get the Constructor for a Type 

Thursday, January 19, 2012 11:57:52 AM

I ran into this on the Win8 Developer’s Preview. I am porting over some Windows Phone Code. This code has a MEF/IOC-Like mechanism that let’s me do discovery on the project. The project itself is a simple App Framework; it has a bunch of content controls, but with the way it is configured you may decide that you don’t want to deploy all these controls, SO I needed to be able to discover controls and create them dynamically (the latter is what this tip is all about).

My original code looked like this:

        public UserControl GetAndInitControlFor(string targetType, SectionInfo data) 
        {
            UserControl result = null;
            var typ = (from item in Catalog 
                              where item.Key.Equals(targetType, 
                                                  StringComparison.InvariantCultureIgnoreCase) 
                              select item).FirstOrDefault();

            if (!typ.Equals(null))
            {
                var ctor = typ.Value.GetConstructor(new Type[0]);
                result = ctor.Invoke(new object[0]) as UserControl;
                if (result != null )
                {
                    ((ISUAFContentControl)result).SetData(data);
                }
            }
            return result;
        }

 

This particular function looks up a control by it’s content type (a string) in the Dictionary that I have already built. If it finds a match then it takes the type instantiates it via the type’s constructor (essentially doing a “new” on the class). The only problem is that WinRT’s type doesn’t have a way to get the constructor. Instead there is a different mechanism you have to use.

Enter TypeInfo

I did some BINGing and I found the answer. There is a mechanism called TypeInfo. It’s apart of System.Reflection, so you will have to add a “Using System.Reflectiomn;” to the top of your file. Now you can get TypeInfo for you class. Here’s the rewritten function for WinRT:

        public UserControl GetAndInitControlFor(string targetType, SectionInfo data) 
        {
            UserControl result = null;
            var typ = (from item in Catalog 
                             where item.Key.Equals(targetType, 
                                           StringComparison.OrdinalIgnoreCase)
                             select item).FirstOrDefault();

            if (!typ.Equals(null))
            {
                TypeInfo typeInfo = typ.Value.GetTypeInfo();
                var ctor = typeInfo.DeclaredConstructors
                                    .Where(c=>c.GetParameters().Count() == 0)
                                    .Select(c=>c).FirstOrDefault();
                result = ctor.Invoke(new object[0]) as UserControl;
                if (result != null )
                {
                    ((ISUAFContentControl)result).SetData(data);
                }
            }
            return result;
        }

It’s very similar, but about midway down you can see where I create a TypeInfo for the type, and then using that type I have to write a Linq query to pull out the paramerless constructor that I am going to use to new up an instance.

I didn’t like having to change things, but I do like the new mechanism a lot better. These things should have been properties all along.

Mobile Apps and Legal issues 

Friday, January 13, 2012 10:57:27 AM

One of the guys on the local Florida Windows Phone List asked a question about his app which is a medical app. He was becoming worried that he might have legal issues with his app. This resulted into a really nice thread on legal issues and your app (and your business).

I decided to go ahead and make a quick write up (for me as well as for anyone else).

Rule # 1 cover yourself at all times!
Think about the lady who got burnt by McDonald’s coffee who sued because they didn’t say it was hot! You might think the lawsuit was frivolous, but it illustrates the problem. Someone using your app ends up setting their device (and house) on fire, you could get blamed (Ok, that’s extreme, but you get the idea). You can never be too careful!

This advice sounds scary, but there are solutions here.. Don’t give up just yet! Lawyers exist for this very reason.

[Keith Kabza had the best bit of info on this -- I have to credit the source as the info is good, and much of the post from here comes from Keith’s knowledge] To the specifics of medical related apps, you need to make sure you aren’t violating any laws related HIPAA (In my personal experience you need to find someone that knows those laws and walk them through what you are doing – if you don’t know someone, come to a local user group and ask if anyone there knows anything about HIPAA). You also need to avoid exposing data their data without using encryption and basic security principals. The good news is there is limited risk in selling mobile apps.

Next operate as an LLC! This protects you to a point. Form there get at least limited liability insurance. It will cost you about $800 a year, but it will cover you for $1 million. [these next 3 nuggets from from Henry Lee] Additionally you may want to get Errors and Omission insurance which really covers the scenario where someone burns down their house while using their app (that’s extreme, but has happened). Also, getting umbrella insurance to cover anything not covered by the previous two insurances. The short is that you want to cover yourself on all legal aspects because you don’t want your spare time building an app to cause you to lose your house.

You want an attorney when you are crafting your licensing agreements. You want it to be written to protect you from frivolous lawsuits.This is something that gets overlooked by many of us! The lawyer Keith recommended (who specializes in this stuff) charges about $3000.

Resources

A few additional resources came up in the thread, and here they are:

www.techinsurance.com – they are an insurance company who simply finds the best rate for you. (via Henry Lee)
legalzoom.com – offers a whole suite of legal solutions and you can get liability coverage for about $450 a year. (via Greg Leonardo)

Mango Live Tile Helper 

Friday, October 21, 2011 3:39:18 AM

I’m in the process of unveiling a new app on the marketplace (it’s actually ready to publish right now, but I’m waiting to publish a blog post on it later). During the process of creating this app (really it’s a framework), I needed/wanted to enable a Live Tile. While the whole Live Tile thing is not all that complex, I decided to make it even simpler with a single class.

I had been told Live Tiles can be created in 6 lines of code; with my helper I have reduced that number by 66% (so 2 lines of code). I also used this code to produce a new version of my comic reader that let’s you pin a single comic to the desktop (and of course it shows a portion of the cover/first page in the Live Tile).

The Code

I created a class that is called LiveTileTempate. It’s all you need in your projects. All you need to do is create a LiveTileTemplate Instance with the proper values set and then call the UpdateApplicationTile, or CreateSecondaryTile methods. So here’s some example code for updating the application’s pinned/Live Tile:

     LiveTileTemplate tileCreate = new LiveTileTemplate
     {
          FrontSideTileTitle = "Live Tile Demo",
          FrontSideTileCountContent = (new Random()).Next(100),
          BackSideTileTitle = "Back Side",
          BackSideTileContent = "My Content on back of tile"
     };
     tileCreate.UpdateApplicationTile();

So let me explain all this, we create a LiveTileTemplate and then simply call the instance’s UpdateApplicationTile method. Most of this is pretty self-explanatory. We set both the front and back titles that appear under the tile, we set a number which appears on the front, and we set the back to have a message on the tile (we go through all the properties further down this post).

This same code could be used to produce a Secondary tile with 2 changes:

  1. We have to set the NavigationUri property of the LiveTileTemplate instance
  2. The last line would need to call CreateSecondaryTile instead of UpdateApplicationTitle

Let’s see an example of a Secondary Tile:

     LiveTileTemplate tileCreate = new LiveTileTemplate
     {
          FrontSideTileTitle = "2nd Live Tile",
          FrontSideTileCountContent = (new Random()).Next(100),
          FrontSideBackgroundImage = "/Koala.jpg", // this would never fly in the Marketplace process (icon needs to reflect app)
          BackSideTileTitle = "2nd Back Side",
          BackSideTileContent = "This is the backside of the second tile",
          NavigationUri = "/Page2.xaml?value1=content+in+uri&randomNumber=" + randomNumber.ToString()
     };
     tileCreate.CreateSecondaryTile();

So this example has a few more elements in it. We are now setting the NavigationUri to a relative path to a xaml page in our app and can include a querystring. We also set the Front’s image using content inside the XAP. This can also be a URI pointing to an image on the Internet (and can even come from IsolatedStorage, but more on that in a later blog post).

Finally we call CreateSecondaryLiveTile(). The naming of that method is not 100% accurate. It actually will detect changes and apply an update to your tile instead. The big thing is that when updating a secondary tile you have to provide all the information (not just changes), because we aren’t given the ability to reload the content that was previously entered, so we don’t really know, for instance, what was originally the Content of the back of the tile. We can only really detect that there was a tile there before pointing at a specific URI in our XAP.

Additional Functions/Methods

Speaking of existing tiles there are a couple additional static methods that are exposed. You can call LiveTileTemplate.GetExists(“/path/to/aPage.xaml?querystring=somevalue&qs2=someValue&etc”) and it will return to you whether a SecondaryTile already exists for that Uri. This is useful because when you create a secondary tile the OS automatically takes the user to the start screen. If the Tile already exists then they stay in the app. You want to be able to let the user know that the tile was updated instead of created in this second instance and now you can know what is going to happen next before proceeding with the action. My comic reader throws up mock toast notifications in the case where the tile has been updated instead of created.

Finally there is one more static method that you might be interested in. LiveTileTemplate.DeleteSecondaryTile(“/path/to/aPage.xaml?querystring=somevalue&qs2=someValue&etc”) deletes a previously created tile using the Navigation Uri.

There are also one more additional method and a constant that are pertinent to using an image from IsolatedStorage, but that will wait for another post.

LiveTileTemplate Properties

Here’s the properties (and their meaning and additional info) that you can set in the LiveTileTemplate Class:

  • FrontSideTileTitle – The title that appears on the front side of a tile (If this value is null then class will try to infer the name of your app from the Assembly’s name)
  • FrontSideBackgroundImage – Set’s the image for the front side of the tile (the default is to use the Background.png file that is part of your XAP. Also, I’m not sure if you are allowed to radically change this and get accepted into the marketplace, so change this with caution would be my advice)
  • FrontSideUriType – sets whether FrontSideUri is a relative or an absolute Uri. (We default to relative, but if we detect an isolated storage Uri we switch to an absolute Uri).
  • FrontSideTileCountContent – (optionally) sets the number that will appear on the front side of the tile. (We default to null which means no number)
  • BackSideTileTitle - The title that appears on the back side of a tile (If this value is null then we grab the title of the front side of the tile or if that is null we use the name of the Assembly)
  • BackSideTileContent – This is the text that will appear on the back side of your tile.
  • BackSideBackgroundImage – Set’s the image for the back side of the tile (leaving this blank will use the user’s accent color)
  • BackSideUriType – sets whether BackSideUri is a relative or an absolute Uri. (We default to relative, but if we detect an isolated storage Uri we switch to an absolute Uri).
  • NavigationUri – sets the Navigation Uri that is used when the user clicks the live tile. (this should be a deep link into your app and may even be a link that in a place in your app that is inaccessible in other ways; it’s pretty cool that you can do this)

Download

You can get the class and a sample project from my source code repo for this. I have a couple more things I will be doing with this (and another article.. hopefully soon).


Download Queue code… 

Saturday, October 01, 2011 1:13:02 PM

Here’s code/slides to my recent talks (I thought I already posted this)


Repo for the Source code

Intradynamics, LLC: Open For Business (again)!! 

Saturday, October 01, 2011 1:02:29 PM

I just wanted to throw out a quick post letting the world know that I went independent again. Today is the first day in my business’ new start! I’m totally psyched! I’m going to be doing a variety of things: Silverlight (of course), Mobile, ASP.NET, and Javascript (aka HTML5 aka Ajax/Web2.0 aka DHTML… etc.). (and this is just my plan for the first week <grin/>).

One word of warning, I will be interspersing some content in here that isn’t purely Silverlight (and yes, this blog is about to be back in full motion again.. well, I hope so). I will try to keep the content pertinent to Silverlight though (but some of this stuff might be just off the corner.. for instance I have an upcoming Orchard CMS post coming very soon).

Silverlight/WP7 tip: Detecting when in VS Design Mode 

Saturday, October 01, 2011 1:01:31 PM

I have struggled with dealing with this for sometime, and ultimately gave up. Today, I happened across something interesting. I’m doing some intense Isolated Storage stuff with WP7, and I’m using ViewModel. I analyzed one of the errors I was getting in the VS XAML designer, and discovered what in my ViewModel VS didn’t like. So here’s what I discovered.

The Technique

You can detect Visual Studio Design Mode by checking isolated storage. It throws an error when you try to access it from within Visual Studio. This is immensely useful when working with ViewModels that you are instantiating in either XAML or CodeBehind or even some kind of locator class. I wrote a little class in the vein of some of the code in MVVM Light (hopefully I can get Laurent to add this to the next version).

using System;
using System.IO.IsolatedStorage;
 
namespace AmazingPocketComicsViewer.Model
{
    public class VSDesignDetector
    {
        static bool? isInDesignModeStatic = null;
        public static bool IsInDesignModeStatic // Convenient method that can be accessed out of an inherited class
        {
            get
            {
                if (isInDesignModeStatic.HasValue)
                {
                    // only do the check once and use the last value forever
                    return isInDesignModeStatic.Value;
                }
                try
                {
                    var isoStor = IsolatedStorageSettings.ApplicationSettings.Contains("asasdasd");
                    isInDesignModeStatic = false;
                    return isInDesignModeStatic.Value;
                }
                catch (Exception ex)
                {
                    // Toss out any errors we get
                }
                // If we get here that means we got an error
                isInDesignModeStatic = true;
                return isInDesignModeStatic.Value;
            }
        }
 
        protected bool IsInDesignMode
        {
            get
            {
                return IsInDesignModeStatic;
            }
        }
    }
}

And that is it! Enjoy!

Solving the Storage Problem in WP7 (for CF Developers) 

Saturday, October 01, 2011 1:01:04 PM

There are a couple apps I would like to write for Windows Phone 7 that don’t currently exist right now. One of which is a Z-Machine emulator (that would be the same engine used in the Infocom text adventure games like the Zork Trilogy). The problem is getting files onto the device. You can’t sync them from the Zune software. You could create a browser to a site and then download the files that way (but sites tend to change).

If only there was a way to take advantage of some kind of custom user storage, but the average user really isn’t technical enough to manage a web server, etc. I have been searching a solution to this problem and I now have a solution to the problem.

I decided that I needed to go ahead and release a test version of my DropBox Client. You can get a compiled version here - http://sharpdropbox.codeplex.com/

I have tried a few others (WP7 Drop Box Clients) and none really were far enough along for me to use. Mine really needs some good testing, but it is far enough along that you can probably use it for browsing a user's DropBox folders/files and can download/open files from there (and they end up on the device in Isolated Storage).

It uses Isolated Storage for a file cache and it also caches the calls in a SterlingDB instance (also living in Isolated Storage). The only thing I haven’t fixed/tested yet is it needs to detect that there is no network and it then needs to use the SterlingDB for everything (skipping network calls).

I am at the point where I was last trying to implement Delete and Upload (upload keeps failing, so I have given up on that for the moment).

I'm may end up implementing a couple of these types of services and creating some kind of loose wrapper/interface around them so you could let the user choose his/her preferred repo. I really wish SkyDrive was accessible through an official SDK in WP7.

Service-Related APIs and Synchronous/Asynchronous Calls 

Saturday, October 01, 2011 1:00:43 PM

I have a small rant today. It relates to APIs that consume some service like Facebook or Dropbox (the latter being the one on my radar).

Some Service Call Guidance

When calling a service directly, you want to use asynchronous methods in all but one case and that one case is during the processing in a web process or a Service (so within an MVC Actrion or Web Form page process, or during processing within your own service). In all other cases that I can think of you want to use Asynchronous calls; these include JavaScript running in browser, Silverlight in or out of browser, Windows Forms app, WPF app, and WP7 application. This is because you keep the app responsive. You can even go so far as to provide a way for the user to cancel a call, but regardless the user can continue using the app while data is being retrieved.

Now the Rant

If you have created a set of APIs that work synchronously retrieves data or makes a service call, this will work with a number of the scenarios I outlined above where I suggested asynchronous was the preferred way (for instance WinForms, WPF, JavaScript all have mechanisms to do Synchronous). But don’t do this. First of all when you go to support Silverlight you will quickly discover that Synchronous calls don’t exist. There are some hacks you can use, but from my experience they make the app unresponsive (and buggy) while calls are happening (so DON’T DO IT!). In fact when I see those hacks it makes me think that you don’t understand Async (and I don’t want to feel that way).

In some places I have seen where someone has turned the callbacks into events (so you call the api, and get events to fire). This isn’t terrible, but it assumes that I will always want to do the same thing every time a call comes back. You are better off not doing this.

I thought I would show you how to turn a synchronous call into an asynchronous one with minimal effort on your part. Well, you still will need to wrap your head around something like HttpWebRequest, BUT my advice here will help you make it a snap to add Asynchronous callback methods.

My Preferred Signature

First off, I want to show you what I personally like to see (and will give you a couple examples):

public interface iCallbackExamples
{
   // Standard mechnaism that MS APIs typically give you
   ServiceResultObject CallSomeServiceSync(
         int param1 // Insert your service paramters here
    );
 
   // Standard mechnaism that MS APIs typically give you
   void CallSomeServiceAsyncMSWay(
         int param1, // Insert your service paramters here
         Action<ServiceResultObject, object> callback, // success callback
         Action<Exception, object> errorCallback, // error callback
         object state // this is some variable that help you keep track of the call
                      // state is the "object" parameters in the Action callbacks
     );
 
    // DevTho's preferred variation (with state) of an Async call
    void CallSomeServiceAsyncWithState(
           int param1,   // Insert your service paramters here
           object state, // this is some variable that help you keep track of the call
                         // state is the "object" parameters in the Action callbacks
      Action<ServiceResultObject, object, Exception> callback // callback
     );
    // DevTho's preferred variation of an Async call
    void CallSomeServiceWithoutStateAsync(
        int param1,   // Insert your service paramters here
        Action<ServiceResultObject, Exception> callback // callback
     );
     
    // variation that I can live with
    void CallSomeServiceAsyncAlternateWithState(
         int param1,   // Insert your service paramters here
         Action<ServiceResultObject, object, Exception> callback, // callback
         object state, // this is some variable that help you keep track of the call
                       // state is the "object" parameters in the Action callbacks
     );
}

BTW, this is all just to give you an idea of what I think is an acceptable signature. I often don’t use any kind of state object because I typically use an inline anonymous functions (aka Closures), so when I get a callback my local values are all intact and any class level changes have also taken place. (this let’s me return from a call, check the class’ state to see if the data is still valid or not). That callback action will vary depending upon what else I might need back. I have for instance returned the calling parameters in the callback and I will use those as a state check.

Here’s what a call of mine might look like using the “CallSomeServiceWithoutStateAsync” method:

void needsData(int param1) // Sorry Stan Schultes only a C# example.. someday I will create an auto convertor for my blog..
{
    this.currentParam = param1;  // class level field value that we'll use to make sure that the request 
                                 // that is returning matches what is currently being requested (Async calls might return out of order)
    var someLocalValue = true;
    MyServiceHandler.CallSomeServiceAsyncWithoutState(param1, (result, error) =>{
         // See we are handling the request inline (so this is a closure, it holds the original value of the someLocalValue and can
         // see the class level variable
         if(error == null)
         {
            // we have data but is it the data we want
            if(this.currentParam == param1)
            {
                // there might be 2 requests going on because one was taking too long
                // during that time the user might have clicked on something else, so now 
                // we need something else. 
                
                // Put the data some place or process it, etc. In Silverlight/WP7 you would
                // Typically be putting this data into a class-level property that is data bound
                // to the XAML. In that case you would need to use the Dispatcher (aka the UI thread) 
                // to do this.
            }
         } 
         else
         {
            // Do something with the error here
         }
      });
}


 

I wll do a part 2 to his post (shortly to show you how to easily implement Asynchronous from your synchronous calls). Stay Tuned.

The Perf Tweak to my WP7 App that turned it from “ho hum” to “Wow!” (it works in Silverlight3+ OOB too) 

Thursday, April 07, 2011 8:00:00 AM

[If you are in a hurry then the answer is CacheMode=BitmapCache. If you want to read the story/know more then read on]

I have been working on a Windows Phone 7 comic book reader over the last couple months. It’s actually done and has seen a few revisions. During the testing of my original release, my friend (and fellow member of the Florida WP7 developer’s club) Brian Kassay suggested that I should use a different library for my image gestures.

You see when you are viewing a comic book page with my reader you are actually looking at a single image which you can move around on the screen as well as can zoom into/out of, and change pages. The page/image viewer was really sluggish on the device. Brian thought it was the gesture library I was using, but nope. after wiring up a different library (the same one Brian uses), the performance was absolutely identical. No change whatsoever.

After listening to a bunch of performance podcasts and finally got my head wrapped around the problem. I turned on redraw regions (which is another tip I can give you), and saw that my image was re-rendering everytime I touched it with my finger (panned it around the screen)

Back in the Silverlight3 timeframe Microsoft added the ability to create an out of browser app that takes advantage of GPU Acceleration.. One of the things that surrounded this feature was a little property that I had totally ignored: CacheMode. I kind of thought the whole GPU acceleration thing was more about building games and ignored the topic. BUT, GPU Acceleration is on by default in WP7 (and I don’t think there is a way to turn it off). It’s on because guys at Microsoft knew we would need to take advantage of the GPU in WP7 apps more often then in standard Silverlight apps (because we are dealing with a CPU-limited phones). So, I switched this property from the default to “BitmapCache” on my image which was rendering constantly. Instantly I went from slow to fast when panning/zooming the image.

You may be wondering “should I turn this on for everything thjen?" Just cache the entire LayoutRoot?” Well, MSDN suggests to “Set the CacheMode property when you need to increase performance for content that is time consuming to render.” CacheMode=BitmapCache simply causes the element it is applied to to render a single time. The resulting Bitmap is cached and re-used for later render cycles (this is probably taking up some memory somewhere). This is great to use on elements that to don’t animate. I would suggest that you look at your WP7 UI and turn on redraw regions. Watch your app you will see what is rendering excessively. Try setting the CacheMode on these elements and see if your performance increases.

Page 1 of 3 1 2 3 > >> 
Site Map | Printable View | © 2008 - 2012 Intradynamics | Powered by mojoPortal | HTML 5 | CSS | design by dcarter