Mutually Exclusive: Agile and Windows Phone Development

May 17th, 2012

"Agile" software development often has developers, testers, writers, etc., all working for a short period of time to 100% finish one small part of the product before moving on to another part of the product. This time period might be as short as a week. At the end of that time, the product is reviewed and changes are made based on how things are turning out. It is a very interactive development cycle.

Microsoft Phone app testing can be done by the developer on the one device that they have registered for their testing. All other testing is done using a "Beta" test program through Microsoft. For a manager, an external client, and a few other people to test the app during development, they must get it from the Windows Phone Marketplace.

Here’s the rub. Microsoft takes upwards of a week to make a submitted app available in the marketplace. Anyone who would test the app are not only a week behind but they might be testing a feature that has been redefined, redesigned, or abandoned.

I am considering having my boss and other interested parties install developer tools and register their phones as development devices so that they can test my code in a timely fashion. We might have to shell out $100.00 per year for each person but the week wait to get an app onto the marketplace is totally unacceptable in an Agile programming environment.

A Scheme for Passing Data in a WP7 App

May 11th, 2012

Silverlight applications on a Windows Phone use a web-style mechanism for page navigation. Most applications will have at least a few levels of child pages in a hierarchy where a child page represents some sort of activity started by an action on a parent page. In a weather application, clicking on a button to see a specific day of a ten day forecast would show a new page with the day-specific information. Clicking on an hour of that day might show a new page with the forecast for that hour. There would then be three pages in the hierarchy.

A more interesting application might let the user do something on one of those child pages that changes the data shown on one of the parent pages. How does the data get back to the parent in a Silverlight application.

Many people that post about this on the internet mention passing data to a child page using the URI for the page and text parameters. This is fine for text or data that can be easily converted to text. In most cases it is enough. When it comes to passing data back to a parent, global variables are suggested. This might work for a simple app but it’s not a robust solution for anything complicated.

Tombstoning

Tombstoning is where an application is deactivated with the expectation that it might be reactivated later. The application needs to act as if it never went away.

This is very interesting because the binary data for the application does go away. All of the pages are gone. The only things that will exist when the application is reactivated is the app object itself and the page that was active when the deactivation occurred. The active page needs to recreate any binary data that is is using from serialized data that it stored when it was last active.

A page doesn’t know that it is being deactivated, just that navigation is leaving the page. When the page doesn’t get a deactivation event makes no sense although it might be the case that the app gets a deactivation event notification at a time when it can set a global variable that the page can then use to know what is happening. The whole tombstone process seems a bit half-assed in many ways, including in this way. It is also hard, but not quite so hard, for the page to know to restore it’s own state when reactivated. It still requires one piece of code saving a bit of state information for another piece of code to use but the state information is kept within the page object and is not global.

Solution

My first solution to page navigation was to create an object for each child page activity and store this object on a stack. Code uses the activity on the top of the stack to get parameters and data that is needed on the current page. The code also stored result data in the activity object on the top of the stack as a way of returning data to the parent page.

But what if the parent page can have numerous different child pages? Each different child page is represented by a different type of activity. When an activity object is created for a child page, a callback function delegate is stored in the activity object to be called when the child page is finished. The parent page simply calls the callback function for the current activity when the child is done and things work great. The callback function handles the results of the activity as needed.

But what about tombstoning? I didn’t realize the implications of tombstoning when I designed the activity scheme.

The New Solution

The new solution is the same as the previous solution except for the delegate functions. I could actually get the name of the delegate function as a string and save that for later. C# let’s me find functions by name and call them that way but it’s not really safe in my mind. Still, the callback function concept keeps me from having a bunch of if() tests in the code to examine the activity object type. And isn’t testing the type of an object also a bad coding practice?

Either way, I will test the object type of the activity or call the delegate by name. One of those two things will work fine and remove the need to keep track of binary data like the reference to the callback function.

I will also need to remove code that keep track of the current page for the sake of knowing that an activity is the one for a child. I will need to just make sure that there is an activity for every single possible child page even if the activity is not holding any useful information. Some pages just don’t return data and I was not creating activities for them.

Finally

I don’t know if this is a good solution but so far, there does not seem to be a good way to handle this otherwise. I would use global variables but there are too many pages in my app that have too many various results to make global variables a clean solution.

Tombstoned

May 9th, 2012

… or “How my app dies and comes back to life to read its own tombstone”

I’m working on code related to tombstoning my Windows Phone app. I’m slowly discovering that the Microsoft designers were not thinking much about app developers when they designed their tombstoning feature.

When not dealing with tombstoned app code, a page (using Silverlight) has a certain flow through the code based on the activity:

  • Navigating forward to a page: Constructor is called for the page followed by a call to OnNavigatedTo().
  • Navigating backward to a page: A call to is made to OnNavigatedTo().
  • A page being shown after tombstoning: A call is made to OnNavigatedTo().

What we see is that the code for a page doesn’t get a call that it is being restored from the tombstone state. If we look closer at the data when OnNavigatedTo() is called, we will see that the navigation mode is “Back” when navigating back from a child page and is “Back” when coming back from the tombstone state.

It is absurd for the mode to be “Back” when being reactivated because, for this app, it is not coming back from anything it went to. It was just dead and the page is now new. “New” happens to be the navigation mode when the page is navigated to from an earlier page.

The trick is to then detect that a page is technically new but that the navigation mode is “wrong” when it says the code is coming “back” to it. This is simply a matter of detecting that the constructor for the page object was called before the OnNavigatedTo() function which indicates that the page content is being generated from scratch. Checking the navigation mode for “Back” will then indicate that the previous state needs to be restored.

Microsoft could have just set the navigation mode to “Reactivate” or something similar to avoid every single programming writing the exact same code to determine this.

I’m also trying to deal with the OnNavigatedFrom() function. How to handle this is not so obvious. The navigation mode will be “New” when navigating to another page and will be “Back” when going back and theoretically abandoning this page. The mode is also “New” when going to a page in another app or the home screen. In all of the “new” cases, the state should be saved because we might come back here after reactivation and also from a child page after hitting the back button. Maybe the state should always be saved when this page is “new” in case we ever come “back” here after reactivation. There is no way to anticipate reactivation.

Another Interesting Issue

I find it annoying that a Dictionary can have this added to it and can have things changed in it but that there is no single function to do whichever is appropriate without throwing an exception at me. If I want to add something to a dictionary but also overwrite it if it is already there, I need four lines of code:

if( DictionaryThing.ContainsKey( "thekey" ) )
	DictionaryThing["thekey"] = newvalue;
else
	DictionaryThing.Add( "thekey", value );

I’m fairly new to C# so maybe every single programmer is not writing this same code every time they are in this situation. The whole point of a library is to provide programmers with code so that they don’t have to all write the same thing over and over.

I’ll have to look closer at the Dictionary class.

Windows Phone Project

April 20th, 2012

Since I am writing a Windows Phone app for a private company during my free time, I don’t have any other news to report. I can’t describe much about the phone project because it is all proprietary. I’ll try to have more cool posts some day.

Dave

Time Zones

March 27th, 2012

Time Zone handling in programs is interesting. Beyond the incredible inconvenience of Daylight savings time, programs tend to use the local time and let other programs deal with that information.

I suggest that all code in the world be changed to send and receive data using GMT, UTC, Zulu Time! This would certainly simply things for me.

Java describes time zones using Olson time zone descriptions. These look like “America/Los_Angeles”. This is interesting but countries and cities don’t change much. Still, using “UTC-8″ would be much better. Some code still needs to figure out if UTC-8 is really UTC-7 because of day,might saving time although it seems like a client device should be doing that. In the end, it’s all a bit crappy.

It is made even worse because Windows Phone OS and C#.net don’t use Olsen time strings. They use their own proprietary strings to describe time zones. I’ve even found information that says that Windows XP uses different strings from Windows 7 when the exact same function is called. It makes time zone handling a bit trickier.

Now if a client device like my phone were to submit some records to a server and use GMT, the server could display those values in a web page and just translate then based on the client time zone of the client browser. Then it would be a matter of a few browsers on a few operating systems agreeing on how to handle time zones instead of every app writer and every server code writer deciding how to transmit data.

I am tempted to get a GMT/UTC time on the client and set the time zone to something GMT so that I never had to change time zones for phones in different areas of the world. All of them would use GMT and transmit GMT.

Change the target of a delegate in C#

March 19th, 2012

I had this problem that I wrote about this morning where I needed to save a pointer to a member function in one object then call it in another object of the same type as the first. The code would work fine in C++ because it is possible to have a pointer to a non-static member function.

In C#, there are delegates. These are objects that include an object and a function pointer of sorts. When a delegate object is created and used, the programmer does not set the object and function pointer. The programmer sets the delegate to a method and the compiler handles keeping track of the object and function pointer. There is no easy way around this and there is no alternative that can be written in one line of code.

While doing some research today, I discovered reflection. I don’t know the ultimate purpose of reflection but I was able to write code that did what I wanted. What I wanted was to call the proper function in the context of a new and different object. My code will fail in some interesting and yet unknown way of I don’t use the same objects when creating the delegate and then calling it but my initial test worked properly. Here is the code that I threw together using Silverlight and C#.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Reflection;

namespace SilverlightApplication1
{
   public class PersistentInfo
   {
      public PersistentInfo() {}

      /*
       * A delegate type must be defined before an actual delegate variable
       * is declared. This is done here since it is not needed anywhere else
       * in the code.
       */

      public delegate int TheDelegateType( int NewValue );

      /*
       * The delegate variable.
       */

      public TheDelegateType TheDelegate = null;

      /*
       * CallbackInContext will call the delegate in the context of the specified
       * object. The Context object MUST be of the same type as was used when the
       * delegate was set or at least one exception will be thrown. This sample
       * code has no error checking.
       */

      public void CallbackInContext( object Context, int Value)
      {
         Type ContextType = Context.GetType();

         MethodInfo TheMethodInfo =
             ContextType.GetMethod( this.TheDelegate.Method.Name,
                                    BindingFlags.Public | BindingFlags.Instance );

         Delegate TheDelegateVariable =
             Delegate.CreateDelegate( typeof( PersistentInfo.TheDelegateType ),
                                      Context, TheMethodInfo );

         PersistentInfo.TheDelegateType TheDelegate =
             (PersistentInfo.TheDelegateType)TheDelegateVariable;

         int Result = TheDelegate( Value );
      }
   }

   static public class Global
   {
      static public PersistentInfo Info = new PersistentInfo();
   }

   public class ContextClass
   {
      public ContextClass( int NewValue )
      {
         Value = NewValue;
      }

      public int Value;

      public int TweakValue( int NewValue )
      {
         Value = NewValue;
         return Value;
      }

      public void SaveState()
      {
         Global.Info.TheDelegate = TweakValue;
      }

      public void CallDelegateWithValue( int NewValue )
      {
         Global.Info.CallbackInContext( this, NewValue );
      }
   }

   public partial class MainPage : UserControl
   {
      public MainPage()
      {
         InitializeComponent();

         /*
           * The test code happens inside of the MainPage constructor.
          * Create an object and call a function to set the global
          * delegate to "point" to a function in that object.
          * Then create a second object and call the delegate from the
          * first in the context of the second. This works because they
          * are the same type.
          */

         ContextClass FirstObject = new ContextClass( 11 );
         FirstObject.SaveState();
         // FirstObject.Value == 11

         ContextClass SecondObject = new ContextClass( 22 );
         SecondObject.CallDelegateWithValue( 34 );
         /*
          * SecondObject.Value == 34
          * Without the special delegate target object change, the value
          * would be 22 and the FirstObject.Value would have been set
          * to 34 in the previous line of code.
          */
      }
   }
}

This is hard to describe because I copied this from some other place on the web and modified it to work in my situation. All of the work is done in the PersistenInfo class. The other classes are just used for the test. I set some integer values so that I can see the code working properly without having to do a lot of debugging.

All of the real work is done in PersistentInfo.CallbackInContext(). This function accepts an object that represents the new context for the call. This is the object that will be used to call the delegate. I save the typeof() that object and use it to find the method that has the same name as the saved delegate. there will probably be an exception thrown if this doesn’t’ match and I will add error checking later. Leaving the unhandled exception might be best since this cannot be allowed to fail in a final product.

A new delegate is created of the same type as the original delegate but using the Context object and the method info for the now found member method. This is the crux of the code. The delegate variable is turned into a delegate method and called. The new delegate is associated with the right object and things work as expected.

This is slow and dirty because it finds the method by name. This is not at all appropriate for code that must run quickly but it works.

Function Pointers in C#

March 19th, 2012

There are no such thing as function pointers in C#. There are no pointers. There are no function pointers in Java, JavaScript, and many other languages.

So how does one handle saving a function and then calling it later from where it is saved? “Delegates” is what they are called in C# and they are essentially function pointers. The problem is that they may be more than that and there is no way to know.

So far, all of my debugging in from within the Windows Phone emulator. I have not tried to find more information on the problem but here is that happened to me that prompted this post:

  1. From inside of a member function in a class, save a delegate function that “points” to a member function of the class.
  2. Navigate to a different page of the user interface thus destroying the object that held the code from step 1 above.
  3. Navigate to the page that was active in step 1 thus creating a new object of the same class as was used in step 1.
  4. Call the delegate that had been saved. The code fails to function as expected.

What I think is happening is the delegate function has knowledge of the object related to the function that I save. When the delegate function is called, the function is called in the context of the original object, not the new object.

This makes some sense but also makes no sense at all. I want to save a pointer to a function in a class so that I can call that function when I return to the page the second time. I don’t want to get back or operate on the object for the page that is gone.

I did not try to find more information about the delegate function. I don’t know if the failure was as I described and it is possible that I screwed up the code. On the other hand, this is fairly simple code. There is no reason for it to fail to operate properly but to also not crash.

More Detail

The class is a PhoneApplicationPage and it has a function that handles a button press. When the button is pressed, I set the delegate function to “point” to the function that I need to execute when this page is displayed again later. I use the NavigationServices.Navigate() function to navigate to a different page and the object for the page is destroyed at some point. Or maybe not. Upon successful navigation back to the original page, I call the delegate and all changes to the user interface DO NOT HAPPEN. The code runs fine so it is not a matter of there being no page or no user interface controls. The changes just don’t show up.

My only explanation is that the delegate is operating on the original page object. Since this is C#, objects persist longer than I think I need them and any reference to an object should keep it around in memory and usable.

Managed code that has no pointers protects me from making mistakes but it also hides mistakes by letting my code run when I would rather have it crash. I need to figure out how to fix this but I have a project that has a deadline so I worked around this by not saving a delegate. I decide what function to call based on other information upon successful return to the original page.

UPDATE

And after one minute of searching today, I find the answer. No amount of searching yesterday yielded useful results. Here is what Microsoft says:

http://msdn.microsoft.com/en-us/library/aa664602(v=vs.71).aspx

Unlike C++ function pointers, however, delegates are fully object oriented, and unlike C++ pointers to member functions, delegates encapsulate both an object instance and a method.”

What then is the way to solve this? The immediate solution seems to be to create a static member function and have it accept an argument that is the object to use for a call to the non-static function I need. Saving a delegate for a static function means it will not have any object information in it.

I see no other solution which makes me thing that someone really missed the mark when designing delegates in C#. On the other hand, there is then no way to accidentally call the wrong function in the wrong place in C#. Still, I prefer the flexibility of C++ even if the risks are higher. I can write less code in C++ to do what is tricky in C#.

Microsoft Visual Studio Epic Fail

March 14th, 2012

Microsoft Visual Studio is a great tool. The integrated development environment let’s me manage large projects with multiple components. I can manage the files, edit the sources, build the entire product tree, and debug code line by line, all using this one software package.

So why is it an epic fail?

When using source control, Visual Studio manages all of access to the source control database. I can check out files, edit them, and check them in. Someone else on another machine can then get those new sources from the source control database and be on their way. This is great until the network connection to the source control database is not working. This is where Visual Studio fails badly.

  1. Visual Studio asks me if I want to connect to a different database. No.
  2. Visual Studio asks me if I want to use an HTTP plugin to access the database instead of the mechanism I had been using. The network is not working so no, that won’t work either.
  3. Visual Studio asks me if I want to work offline, disconnect permanently, or a few other things. YES! I want to work offline. Ignore the source control database please.
  4. Visual Studio then decides that my project files all need to change because of this and it presents me with these options once for each of 80 projects that are part of my project source tree:

    image
  5. I hit the escape key to cancel these changes because I don’t want to change anything!
  6. As soon as I try to change a file and build part of the tree, I am asked again because the project files are all in memory and all need to be saved.

Why the hell is there a Check Out button when I have specifically asked to not use source control? Okay, I get it. I asked to disable source control temporarily and I still need to mark files as checked out so that they can be updated when I have source control access.

I could discard the changes to the files but there are three dialog boxes to go through for each of the 80 projects in the tree if I try to discard the changes.

Some of this may be the fault of Microsoft Visual Source Safe. It’s hard to tell since I cannot change source control providers to find out.

What irks me the most is that Visual Studio feels the need to change project files because of source control being temporarily disabled. This is temporary so I really don’t a record of it saved in any files. I just want things to work exactly as they work when I do have source control.

Another great thing is that I can’t build any part of the product until all of the changed files in memory have been saved to disk. Yay. I’m stuck saving 80 changed files using three dialog boxes each just so that I can work without source control while my network connection is broke.

I can’t get any work done.

Dave

Blog is Stale

March 9th, 2012

I had to write something just because my blog is getting stale. Maybe stagnant is a better word for it.

I am still working on the Windows Phone project but I’m working on it professionally and I don’t know if I can talk about the project at all. I am past the learning curve and I’m now doing a lot of porting of Java code to C#. The user interface work I did made the customer happy and there is a demo version for them to look at. Now I just need to give the app all of the functionality of it’s Blackberry and Android predecessors.

Windows Phone Development

February 21st, 2012

I’m working on a Windows Phone project. This is a native app for the Windows Phone OS. I have a Nokia 710 for testing and things are going smooth.

So far, the only problems that I have had are related to not knowing the intricacies of the XAML “programming” for Silverlight. Switching to C# from C has been easy.

I’m about to delve into using a relational database for storage of some data. This is new to me since I have not used relational databases in quite a few (15+) years.

I can’t post pictures because this is not a personal project. The App will be available in a few months but until then, it is up to the people paying me as to who sees this and who does not see it.

Dave