Random Walks For Windows Phone 7

WinP7MiniTutorialLogoFramed_thumb

It makes me a little crazy that every time the markets go up or down the newspapers cannot resist attributing a reason (though they’re not so good at predicting!).  Today’s NY TimMarket Predictores: “Markets down 2% on concerns about slowing economy.”  Oh Yeah? How do they know that’s the reason?  Maybe it is the cost of oil, the situation in the middle east, unemployment, gamma waves…   So I decided to try an experiment: let’s predict up or down randomly, and give reasons, and we’ll see how well we do.

Now, I believe in modeling that ADHD and other such things are nothing to be ashamed of. Simple brain chemistry; doesn’t make you a bad person.  But what many folks don’t realize is that ADHD involves hyper-focus as much as inattention, and so setting off to build a simple random number generator… well the truth is I already have one. But what a great opportunity to build a Win Phone Application. So, I got this working in 20 minutes. And then tinkered for a few hours.

[Click on image to see full size]

The application itself is pretty simple, just a single page that displays a scrollable  list of 30 days worth of randomly generated predictions.

Let’s take a quick look at the code.

Here’s the markup for the Content Grid in MainPage,

<StackPanel x:Name="TitlePanel"
            Grid.Row="0"
            Margin="24,24,0,12">

   <TextBlock x:Name="ApplicationTitle"
              Text="Market Predictor"
              Style="{StaticResource PhoneTextNormalStyle}" />
   <TextBlock x:Name="PageTitle"
              Text="Next 30 Days"
              Margin="-3,-8,0,0"
              Style="{StaticResource PhoneTextTitle1Style}" />

</StackPanel>

<Grid x:Name="ContentGrid"
      Grid.Row="1">

   <ListBox x:Name="MainListBox"
            ItemsSource="{Binding}">
      <ListBox.ItemTemplate>
         <DataTemplate>

            <TextBlock x:Name="ItemText"
                       Text="{Binding DateAndPrediction}"
                       Style="{StaticResource PhoneTextNormalStyle}"
                       FontSize="18"/>

         </DataTemplate>
      </ListBox.ItemTemplate>
   </ListBox>

</Grid>

Note that the ListBox’s ItemsSource is set to Binding with no binding path. This causes it to bind to the page, and we’ll set the data context dynamically. Also note that I wanted finer control over the font size, and so modified the standard style with a fontsize attribute in the DataTemplate

For this quick and dirty application I did not use MVVM (sometimes you just don’t!), and all the code is in MainPage.xaml.cs.

Predictions

The list box will be populated with predictions, and so I’ve created a small class to manage that information.  Each instance has three properties:

  1. The date for the prediction
  2. Whether the market will be up or down
  3. One of half a dozen standard “reasons.”
public class Prediction
{
    private Dictionary<int, String> Reasons =
            new Dictionary<int, string>();

    public Prediction ()
    {
        Reasons.Add( 0, "Jobs predictions" );
        Reasons.Add( 1, "Economic forecasts" );
        Reasons.Add( 2, "the Cost of Oil" );
        Reasons.Add( 3, "Congressional action" );
        Reasons.Add( 4, "President Obama's statement" );
        Reasons.Add( 5, "the OMB");
        Reasons.Add( 6, "economic trends");
    }

    public string PredictionDate { private get; set; }
    public bool PredictionBool { private get; set; }
    public int PredictionReason { private get; set; }

    public string DateAndPrediction
    {
        get
        {
            string reason = PredictionReason > 0 &&
                            PredictionReason < Reasons.Count
                                ? Reasons[ PredictionReason ]
                                : Reasons[4];
            return PredictionDate + ": " +
                   (PredictionBool
                        ? "Up"
                        : "Down") + " on news of " + reason;
        }
    }
}

The public property DateAndPrediction returns a string that will be displayed in the list box, and it is to this property that the TextBlock in the DataTemplate binds.

OnNavigatedTo

When the page is navigated to the OnNavigatedTo event handler is called. In this method we do three things:

  1. Call the base class
  2. Call a private helper method SetData() to set up the predictions
  3. Set the data context to the collection of predictions defined as a member variable of the class.
protected override void OnNavigatedTo( NavigationEventArgs e )
{
    base.OnNavigatedTo( e );

    SetData();
    if ( DataContext == null )
        DataContext = Predictions;
}

SetData

All the fun happens in SetData.  We’ll create an array to compute the number of days in each month and a Dictionary for the month names.  With those ready, we can compute the current date and then create predictions for the next ten days.

private void SetData()
{

    int month = DateTime.Now.Month;
    int date = DateTime.Now.Day + 6;
    int[] daysInMonth = {
                          31, 28, 31, 30, 31, 30, 31,
                          31, 30, 31, 31, 31
                      };
    var monthNames = new Dictionary<int, string>
                         {
                             {1, "Jan"},
                             {2, "Feb"},
                             {3, "Mar"},
                             {4, "Apr"},
                             {5, "May"},
                             {6, "June"},
                             {7, "Jul"},
                             {8, "Aug"},
                             {9, "Sept"},
                             {10, "Oct"},
                             {11, "Nov"},
                             {12, "Dec"}

                         };

    var r = new Random();

    for ( int i = 0; i < 30; i++ )
    {
        var prediction = new Prediction();
        if ( ++date > daysInMonth[ month - 1 ] )
        {
            ++month;
            if ( month > 12 )
            {
                month = 1;
            }
            date = 1;
        }
        string newDate = monthNames[ month ] + " " +
                         date;
        prediction.PredictionDate = newDate;
        int randomNumber = r.Next( 0, 100 );
        prediction.PredictionBool = randomNumber %2 == 0;
        prediction.PredictionReason = r.Next(0, 6);
        Predictions.Add( prediction );
    }
}
Share

About Jesse Liberty

Jesse Liberty is a Master Consultant for Falafel Software, and has three decades of experience writing and delivering software projects. He is the author of 2 dozen books and multiple Pluralsight courses, and has been a Technical Evangelist for Telerik and for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS.
This entry was posted in Mini-Tutorial, News, WindowsPhone and tagged , . Bookmark the permalink.

5 Responses to Random Walks For Windows Phone 7

  1. Pingback: Windows Phone 7 资源汇总 | DanceCoder

  2. Pingback: YOUR-TITLE

  3. Pingback: DotNetShoutout

  4. @Steve Ruben
    You just made my whole day, week and month. As for ADHD, the best title for a book I’ve ever seen was “You mean I’m not lazy, crazy or stupid.”

    But as a society there is a gap between what we say about mental illness and what we really feel. My boss talks about his diabetes. I doubt he takes much of a career risk doing so. Talking about my ADHD is different, and raises all those familiar questions “why do you need to talk about this; isn’t it private?” yadda yadda. That’s all code for, there’s nothing *wrong* with it, we don’t really think it is a moral failing, but it isn’t quite okay either. Too broad a statement, but true for an awful lot of folks i meet.

  5. Steve Ruben says:

    Your tutorials are really great, love the focus on silverlight. With your help my company and I where able to deliver our medical systems built with Silverlight 3/4 with ease. Also I think it’s great that you understand ADHD there are so many people in this world that only think of it as a disability but fail to see the enabling side. When I hyper focus I can work for long stretches 3 – 5 producing both quality and volume that non ADHD brains often have a hard time keeping up with. Having ADHD also makes you a wiz in whiteboard / brainstorm sessions.

    Thanks again for all your great tutorials and code samples it’s people like you that make working in the Microsoft community of developers so fun.

    - Steve.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>