February20

Minimal Virtualized Data List for WP7

I recently gave a talk about data management on Windows Phone 7 for XapFest and I put in a slide about virtualizing your data for data bound objects.  I didn’t really think it was that big of a topic when I was putting together the talk, but it generated a lot of interest from attendees. 

I am going to demonstrate the minimal virtualized data collection object you can easily create for data binding with a Listbox. 

For this example I am using a simple class named FeedItemDataModel.  This represents a class that holds a single item from an RSS Feed.  In this simple implementation the values are simple and set in the constructor.

image

The sample application shows a UI with a collection of this object databound to the UI and lets you jump to a specific index in the list.  The red text you see is a memory watcher class that shows memory usage within your app.

More...

February17

Create a file from a resource on WP7

I got an email from someone today asking about how to take a resource from their XAP (which is read only), and put it in a location where they can update the file. 

Initial Data Load

I highly recommend this approach for getting an initial data load for your application.  Give the application a base of files to work with rather than requiring an initial round trip to a server for those files.  It is fine to need to update them almost immediately.  Think about the scenario where the user has no network access (a first run of the app this is really vital).  Does the user get an error that no data is available, or do they get a nice default experience?  Even if you just put in data that says “no data here yet”, that is better than a blank screen to the user.

Create File From Resource

I put this in a utilities class as a static method since it doesn’t really need any state.  One thing to ensure you do is put a using() block around the objects that are disposable.  This ensures they are cleaned up and released as quickly as possible.  I think this is a common reason why people think they need to GC.Collect, they are not cleaning up memory.

public class FileUtilities
{
/// <summary>
/// Given a resource name, create a file in the isolated storage.
/// Resources are read only, but copying them to the isolated store means you can edit them.
/// Useful for including a starter file in your XAP, and then copying it out to storage
/// for editing it at runtime.
/// </summary>
/// <param name="resourceName">The name of the resource</param>
/// <param name="fileName">Optional param for the name of the file, 
///
by default uses the same name as the resource</param> public static void CreateFileFromResource(string resourceName, string fileName = null) { // Find the resource and get the stream // Note the using() block to ensure this gets cleaned up when we are done using (var resourceStream = Application.GetResourceStream(
new Uri(resourceName, UriKind.Relative)).Stream) { // Get the location where we can write files using (var userStorage = IsolatedStorageFile.GetUserStoreForApplication()) { // Use the filename (if given) or the resource name using (var newFile = userStorage.CreateFile(fileName ?? resourceName)) { byte[] byteBuffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = resourceStream.Read(
byteBuffer, 0, byteBuffer.Length)) > 0) { newFile.Write(byteBuffer, 0, bytesRead); } } } } }}

Please forgive the formatting above, trying to make it fit on a smaller size screen.

February06

Using a custom attribute to determine type at runtime

On a Windows Phone 7 project I am currently building I had a need to build a factory that instantiates different concrete classes depending upon an object at runtime.   I have a number of information feeds, that all have different classes built to actually go get their data.  One for RSS Feeds, one for Twitter, etc.  Each Feed has a property for the FeedType, this is the information needed to determine what class to instantiate at runtime.

I have written this pattern many times, but I ran across an interesting post on StackOverflow where Steven gave a different approach to solving this without the classic giant switch statement in the Create method.   I thought it was neat enough to use in my application and share here.

There are a couple of steps you have to take, but none of them are difficult.

  • Decorate your objects with a custom attribute
  • Build the object types using reflection
  • Implement your factory method

Custom Attribute

The attribute I added is called FeedTypeAttribute, I then add it to the concrete feed processor classes.

class FeedTypeAttribute : Attribute
{
private int _feedType;

public FeedTypeAttribute(int feedType)
{
_feedType = feedType;
}

public int FeedTypeId
{
get
{
return _feedType;
}
}
}

Adding the attribute to a class looks like the following.
 
[FeedTypeAttribute(1)]
public class StaticFeedProcessor : IFeedProcessor
{
public StaticFeedProcessor()
{

}

public void ProcessFeedModel(FeedModel feedModel)
{
throw new NotImplementedException();
}
}

Note that this class would be a FeedType of 1 in my data, but how do you determine what class that is during runtime?  The answer is reflection (and yes, this does work on Windows Phone 7).
 

Factory Method Using Custom Attributes

public class FeedProcessorFactory : IFeedProcessorFactory
{
private static Dictionary<int, Type> processorList = new Dictionary<int, Type>();

static FeedProcessorFactory()
{
// Get the types in this assembly that implement our custom attribute
var targetTypes = from type in Assembly.GetExecutingAssembly().GetTypes()
where type.CanBeTreatedAsType(typeof(IFeedProcessor))
where !type.IsAbstract && !type.IsInterface
let customAttributes = type.GetCustomAttributes( typeof(FeedTypeAttribute), false)
let attribute = customAttributes[0] as FeedTypeAttribute
select new { type, attribute.FeedTypeId };

processorList = targetTypes.ToDictionary(p => p.FeedTypeId, p => p.type);
}

public IFeedProcessor CreateProcessorByFeedType(int feedId)
{
Type feedType = processorList[feedId];

return Activator.CreateInstance(feedType) as IFeedProcessor;
}
}

The key here is the type.GetCustomAttributes() call.  The linq expression gets all the type of the current assembly where the type can be assigned from the IFeedProcessor class.  We have to ensure the class is not abstract or an interface, and then get the custom attributes. 

The let clause in the linq expression can be thought of like a local temporary variable.  Assigning the attributes to it, and then processing them in the final select.

Consuming the Factory

Consuming the factory is then as simple as instantiating a factory object and calling the CreateProcessorByFeedType function.  A fully allocated processor is returned ready to handle the feed.

// This is in my container object
private static IFeedProcessorFactory _feedProcessorFactory = new FeedProcessorFactory();


// This is in the function to process the feeds
IFeedProcessor processor = _feedProcessorFactory.CreateProcessorByFeedType(feed.FeedType);
processor.ProcessFeedModel(feed);

Less Coupling is Good

This code allows for the addition of new processor classes just by building the class and adding the custom attribute.  Of course you should check if the feedtype is not supported before trying to use the object (I omitted some code used for safety checking).
 
If a newer class is created in the future to replace a current one I only have to change the custom attribute to handle it.  No switch statements, or remembering to update a config somewhere.

February02

Is this .Net Type Assignable from another Type?

I have run into this a few times and always have to go to the MSDN to find the answer.  I have a situation where I needed to determine if a given type can be treated as a base type in an object factory.  I wanted to be able to create my concrete classes without having to do a switch statement for each type.

First I had to determine if the types were assignable to each other, then find the type to implement.  I will cover that in another article.  In this one I just want to cover the assignment test.

Can this type be assigned?

There is a function IsAssignableFrom that you can call on a System.Type. 

if( ParentType is ChildType )

It actually has to be written the other way around.

if( ChildType.IsAssignableFrom(ParentType) )

Quick Extension Method

So instead of having to do that all over my code, I wrote an extension method to allow me to do it following a different ordering.  I actually got this basic idea from one of the comments on the MSDN page.

if( parentType.CanBeTreatedAsType(childType) )

As you can see the extension method lets you write the syntax in a more natural manner.  Your preference may differ, but this makes more sense to me.

Example Code

public static class DataExtensionMethods
{
public static bool CanBeTreatedAsType(this Type CurrentType, Type TypeToCompareWith)
{
if (CurrentType == null || TypeToCompareWith == null)
return false;

return TypeToCompareWith.IsAssignableFrom(CurrentType);
}
}

void Main()
{
System.Type parentType = typeof(ParentClass);
System.Type childType = typeof(ChildClass);

bool ChildToParent = childType.CanBeTreatedAsType(parentType);
Console.WriteLine("Child can be treated as parent: " + ChildToParent );

bool ParentAsChild = parentType.CanBeTreatedAsType(childType);
Console.WriteLine("Parent can be treated as child: " + ParentAsChild );
}

public class ParentClass
{
public ParentClass()
{
}
}

public class ChildClass : ParentClass
{
public ChildClass() : base()
{

}
}

January04

Debug Secondary Tiles

This is another of those posts for my future self, because I know I won’t remember this little tip.

Set startup through app manifest

The WMAppManifest.xml has a property that tells it where to send the default launch of the application.

    <Tasks>
      <DefaultTask Name="_default" NavigationPage="MainPage.xaml" />
    </Tasks>

So the normal launch page is MainPage.xaml. But you can change it to another page, and include your parameters just like from a secondary tile!

    <Tasks>
      <DefaultTask Name="_default" NavigationPage="/TileDetails.xaml?myid=2" />
    </Tasks>

Now you can just press F5 and debug just as if that secondary tile had been clicked.

January03

Coding 4 Fun Phone Toolkit updated

If you have not looked at the toolkit before you seriously owe it to yourself, go get it now!

Coding 4 Fun Phone Toolkit

Windows Phone Geek has also done a great intro post on one of the new controls (the MetroFlow control).  Getting started with MetroFlow Control is a great read, even just to get up to speed with the overall concepts of the toolkit.

December09

Click back twice to exit app?

I have been adding animations to a Windows Phone 7 app that has a panorama control and ran into a problem I have seen others post online.  I figured it out, so I thought I would take a minute to explain how.

Get ready to add transitions

The Silverlight Toolkit is the way you want to go about adding quick and easy animations when a page loads and navigates away from the current page.

If you are not familiar with the basics visit the link above, or read this really good tutorial about wp7 page transitions on Windows Phone Geek.

The basics are that you have to include the toolkit, and you have to modify the root frame of your application to be a transition page instead of a normal phone page.

In a typical application you have the RootFrame declared in your App.xaml.cs like this:

    public partial class App : Application
    {
        /// <summary>
        /// Provides easy access to the root frame of the Phone Application.
        /// </summary>
        /// <returns>The root frame of the Phone Application.</returns>
        public PhoneApplicationFrame RootFrame { get; private set; }
    }

But for transitions to happen you need to change the object to a TransitionFrame when your InitializePhoneApplication is called.

            // REPLACE THE FIRST LINE WITH THE SECOND
            // RootFrame = new PhoneApplicationFrame();
            RootFrame = new TransitionFrame();

This will give you the ability to add transitions to your page.

I prefer to define my transition style at the application level, rather than the page level.  Usually I want all the pages to behave the same, so this gives a nice central point for all of them to reference it.

More...

October14

TouchDevelop makes Windows Phone 7 easy to program

I attended a great XAPFest meeting last night about TouchDevelop.  This is an app you can download today for your Windows Phone 7 from the Web Marketplace.

What is it?

Many of us were introduced to programming because we had computers at home (and usually lots of free time).  Most machines had built in BASIC or some other language, and there were lots of magazines and books with code you could type in to make your machine do what you wanted.

 

Today most machines do not have a built in language, or tutorials on how to use the built in tools like Powershell to write programs.  Even then the tools and learning curve is very steep.  Learning to do something like post an image to Facebook means having to learn a LOT of different technologies.

TouchDevelop is a very easy to use programming tool that lets users write applications directly on the phone.  No need to sync to a PC, or learn C# or even know the SDK.  All of the features of the phone are exposed through built in objects in the tool.  The user doesn’t have to know the difference between a JPG and a PNG.  They just say Image.

More...

August14

Pick A Park Walt Disney World WP7

Pick a Park is an application I wrote for my kids on a different phone platform.  We used it to help us decide what park we wanted to visit while driving to Walt Disney World.  We originally had a Disney pin that we could spin to decide, but it would always be forgotten at home.  Since we lived about an hour away from the parks it was pretty easy for us to go, but there was always the debate about which park to visit.

The application is a very simple way to choose from two or more of the Walt Disney World theme parks and get a random choice of which one you should visit.

Pick A Park is in the Windows Phone MarketplaceMainPageScreenShot

Windows Phone 7

This version is for Windows Phone 7.  Since I work at Microsoft I got a free phone right when they first launched.  This app was my initial way to help learn the programming model.  I wrote this over Thanksgiving weekend 2010,  but I was so embarrassed by the app that I never released it until summer 2011.

The reason I finally released it was a XapFest event I attended where another internal Microsoft employee said that he felt you should always release the app while you are still a little embarrassed, it will keep you humble and motivate you to improve it.

To date there have been hundreds of downloads for what I was pretty embarrassed about at the time.  I get a few hate mail, but I get a lot of people just asking for advice on what park they should visit when they only have 1 days in Orlando after a conference.  Overall it has been a great experience.

Mango Update is interesting

I have been toying with the app more and more as Windows Phone Mango has progressed through beta.  I wanted to initially include two modes, one for picking the park, but another for just exploring which park you might want to visit.  But I couldn’t figure out how to do the data filtration because there was no database on the phone.  Now with Mango there is an embedded database (SQL CE), so I wanted to revisit the problem.  First a little about the current version.

More...