Category: Programming

MIX 10: A Brief Overview

For the first time, I attended MIX 10 live in Las Vegas.  The last couple years, I was forced to attend the event from the comfort of my office chair via streaming video.  While this approach works, it lacks the interactive quality of being able to actually converse with the speakers and other attendees.  Most of what I actually learned from the event, came from these interactions.

You can find all the videos from the event here.  I believe each keynote and every session is now available for streaming.  I am currently going through them and watching the ones that I am interested in but couldn’t attend.

The first keynote was interesting.  The primary focus was Silverlight 4 and Windows Phone 7 Series.  The main reason for me being there was together  information on the upcoming release (version 4) of Silverlight so that portion of the keynote was definitely interesting.  I also have to admit that I liked what I saw regarding the phone.  It seems appealing but I am primarily excited about being able to develop apps for it using Silverlight.

The second keynote was not quite as interesting.  I did enjoy Bill Buxton’s talk about NUI(Natural User Interface) but I wasn’t overlly joyed or moved by the unveiling of Internet Explorer 9.  I believe the only thing of interest, to me, regarding IE 9 was the announcement that they are pushing and working hard to ensure that the same HTML and code works in IE 9 just as it does in the other browsers.  Basically, they are actually embracing the standards (especially HTML 5) and even going so far as to work with W3C.

I only wanted this first post to be a brief overview so I am going to stop here.  I have written many notes regarding the sessions that I attended and I am working on conducting additional research and compiling all the notes so I can write several related articles.  I am also working on configuring one of my computers with all the RC and beta products I need.  I do want to make a quick note that if you want to do phone development, you need Vista or Windows 7 (XP is not supported).

Sudoku 2.0 – The Board

I have finally finished enough work that I can start this article series on Sudoku, again. I apologize for starting it so long ago and never finishing it. As I mentioned in my previous introductory post, I have learned a lot since the last time I approached this subject.  I am not going to repeat myself by discussing what Sudoku is and how you play it again.  I did this in my original article.

Ok, I lied.  I will repeat myself briefly because it is important.  The sudoku board is a 9 x 9 grid.  Each cell in this grid holds a value as part of the puzzle.  The cells are further grouped into what is called a Minigrid, of which there are 9.  Each mini grid is a smaller 3 x 3 grid of cells (9 total).

Covering that was important because I used that knowledge to design the board itself.  To keep things straight forward, I used UserControls as their really wasn’t a need to create a custom Control.  The parent control is the Board.  The XAML for the Board UserControl can be found below.

<UserControl
    x:Class="Sudoku.Board"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Sudoku"
    Width="400" Height="400">

    <Grid x:Name="LayoutRoot" Background="White" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Border x:Name="MainBorder" Grid.ColumnSpan="3" Grid.RowSpan="3"  Background="White" BorderBrush="Black" BorderThickness="1" Margin="-1" />

        <!-- Miini Grids -->
        <local:MiniGrid x:Name="C1R1" Grid.Column="0" Grid.Row="0" />
        <local:MiniGrid x:Name="C2R1" Grid.Column="1" Grid.Row="0" />
        <local:MiniGrid x:Name="C3R1" Grid.Column="2" Grid.Row="0" />
        <local:MiniGrid x:Name="C1R2" Grid.Column="0" Grid.Row="1" />
        <local:MiniGrid x:Name="C2R2" Grid.Column="1" Grid.Row="1" />
        <local:MiniGrid x:Name="C3R2" Grid.Column="2" Grid.Row="1" />
        <local:MiniGrid x:Name="C1R3" Grid.Column="0" Grid.Row="2" />
        <local:MiniGrid x:Name="C2R3" Grid.Column="1" Grid.Row="2" />
        <local:MiniGrid x:Name="C3R3" Grid.Column="2" Grid.Row="2" />

        <!-- Highlighters -->
        <Rectangle x:Name="MiniGridHighlighter" Grid.Column="0" Grid.Row="0" Fill="#FF848484" Opacity=".5" IsHitTestVisible="False" Visibility="Collapsed" />
    </Grid>
</UserControl>

The Board itself is pretty simple.  It mainly consists of a Grid control which has 3 columns and 3 rows.  This grid uses a Border to draw a black line around the outside of the board itself.  Each cell in the Grid contains a MiniGrid control.  A MiniGrid is a user control that I created that represents, well, a mini grid on the board.  Each MiniGrid is named after the cell that is in.  For example, the MiniGrid that occupies the first cell on the board (column 1 and row 1) is named “C1R1″.  The Rectangle, named MiniGridHighlighter, is currently a place holder.  The Board doesn’t really use this yet.  I created it because I figured I might need a way to highlight the entire minigrid when I start working on the user interaction and game play.

<UserControl>
    x:Class="Sudoku.MiniGrid"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Sudoku"
    Height="Auto" Width="Auto">

    <Grid x:Name="LayoutRoot">
            <Border Grid.ColumnSpan="3" Grid.RowSpan="3" BorderBrush="Black" BorderThickness="1">
            <!-- Cell Container -->
            <Grid x:Name="CellLayout">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>

                <!-- Cells -->
                <local:Cell x:Name="C1R1" Grid.Column="0" Grid.Row="0" />
                <local:Cell x:Name="C2R1" Grid.Column="1" Grid.Row="0" />
                <local:Cell x:Name="C3R1" Grid.Column="2" Grid.Row="0" />
                <local:Cell x:Name="C1R2" Grid.Column="0" Grid.Row="1" />
                <local:Cell x:Name="C2R2" Grid.Column="1" Grid.Row="1" />
                <local:Cell x:Name="C3R2" Grid.Column="2" Grid.Row="1" />
                <local:Cell x:Name="C1R3" Grid.Column="0" Grid.Row="2" />
                <local:Cell x:Name="C2R3" Grid.Column="1" Grid.Row="2" />
                <local:Cell x:Name="C3R3" Grid.Column="2" Grid.Row="2" />

                <!-- Highlighters -->
                <Rectangle x:Name="ColumnHighlighter" Grid.Column="0" Grid.RowSpan="3" Fill="#FF848484" Opacity=".5" IsHitTestVisible="False" Visibility="Collapsed" />
                <Rectangle x:Name="RowHighlighter" Grid.ColumnSpan="3" Grid.Row="0" Fill="#FF848484" Opacity=".5" IsHitTestVisible="False" Visibility="Collapsed" />
            </Grid>
        </Border>
    </Grid>
</UserControl>

The MinGrid is constructed similar to the Board. Everything is contained within a parent Grid control. This has a Border control and an inner Grid. The inner Grid control, as with the Board control, has 3 columns and 3 rows.  This gives us nine cells total.  Each of these cells contains a Cell control.  Each Cell is named in the same manner as the MiniGrids were (as discussed above).  The MiniGrid also has two highlighter Rectangle controls which we may use later.  One is capable of highlighting a row while the other takes care of the column.

<UserControl>
    x:Class="Sudoku.Cell"
    xmlns">http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="Auto" Width="Auto">

    <Grid x:Name="LayoutRoot">
        <Border BorderBrush="Gray" BorderThickness="1" />
        <TextBlock x:Name="ValueTextBlock" Foreground="Black" VerticalAlignment="Center" HorizontalAlignment="Center" FontWeight="Bold" FontSize="24" />
    </Grid>

</UserControl>

Finally, above, we have the Cell itself.  This control is very simple and is made up of a Grid that contains a Border and a TextBlock.  The TextBlock is where the actually value for the cell will be displayed.

Sudoku Board

The three user controls, mentioned previously, make up the Sudoku puzzle board, which looks like the image shown above.  At this point there is no interaction but we are ready to fill the board with the actual puzzle (which I will cover in the next article).

Sudoku 2.0 – Introduction

First, let me apologize for taking forever to follow up on the Sudoku article I wrote a while back.  I always intended to actually complete the game and I never got back to it.  Finding the time to keep up with a blog is much more difficult than I initially imagined.  I have made a New Years resolution to attempt to do much better this time around.  I figured I would start with the Sudoku articles, which appear to get the most hits.

I am still using Silverlight but the biggest initially change is that I am not going to bother dynamically creating the Grid this time around.  The first artile, which I should have up in a couple days, will cover the board itself.  I am almost finished designing it in Expression Blend 3.  I have the main board and the minigrid control designed.  I just need to finish up the inidivudal cells.  Once this is all done I will move the XAML over to Visual Studio to wire-up with code.

Thanks for your patience, I promise I will have it up and running soon.

Custom Slider Control – The Base Class

This is part 2 of a multi-part article on a custom Slider control.  You can find the other articles here:

The source code is now available on CodePlex

The purpose of this article is to start digging into some of the details behind the updated Slider control.  The best place to start is with the underlying base class.  The standard slider that comes with Silverlight has a base class called RangeBaseand can be found in the System.Windows.Controls.Primitives namespace.  This class defines the standard properties (Minimum, Maximum, LargeChange, SmallChange and Value).  Minimum and Maximum describe the lower and upper range of the slider itself will Value reflects the current value of the slider (where the thumb currently is located).  LargeChange and SmallChange indicate a value that will be used to increment/decrement the value property.  The RangeBase class also defines the ValueChanged event, which is fired when the Value property changes, and ensures all properties are correctly coerced (which I describe in more detail further down).

One of the main requirements for the new Slider was to be able to select a range of values (an upper and lower bound) rather than just a single value.  Since I still wanted to support everything else offered by RangeBase, I created DualRangeBase which inherits from it.  This became the base class for my version of the Slider control.

This new base class provides three additional properties:  LowerRangeValue, UpperRangeValue and  RangeValueLowerRangeValue and UpperRangeValueprovide the lower and upper values of the range (dictated by the position of the lower and upper thumbs repectively) while the RangeValue is the difference between the lower and upper values.  The DualRangeBase also adds three additional events:  LowerRangeValueChanged, UpperRangeValueChanged and RangeChanged.  The first two can be used if you want to handle the events separately while RangeChanged is fired any time either value changes.

The code snippet below shows the definitions of these properties.

// Defines the LowerRangeValue dependency property.
public static readonly DependencyProperty LowerRangeValueProperty = DependencyProperty.Register("LowerRangeValue", typeof(double), typeof(DualRangeBase), new PropertyMetadata(0.2d, OnLowerRangeValuePropertyChanged));

// Gets or sets the LowerRangeValue of the range.
public double LowerRangeValue
{
     get { return (double)GetValue(LowerRangeValueProperty); }
     set { SetValue(LowerRangeValueProperty, value); }
}

// Defines the UpperRangeValue dependency property.
public static readonly DependencyProperty UpperRangeValueProperty = DependencyProperty.Register("UpperRangeValue", typeof(double), typeof(DualRangeBase), new PropertyMetadata(0.8d, OnUpperRangeValuePropertyChanged));

// Gets or sets the UpperRangeValue of the range.
public double UpperRangeValue
{
     get { return (double)GetValue(UpperRangeValueProperty); }
     set { SetValue(UpperRangeValueProperty, value); }
}

///
/// Gets the size of the current range based on the difference
/// between the lower and upper range values.
///
public double RangeValue
{
    get { return UpperRangeValue - LowerRangeValue; }
}

The trickiest part of the base class, for me, was dealing with coercion.  I got the concept of this from the source code of the RangeBase class which uses coercion as well.  The concept of this is to ensure that when the value of any of the main properties (such as Maximum) is set it undergoes a set of validation checks.  If any of these checks fail the value is changed appropriately.  Coercion occurs during the properties PropertyChanged event handler.  For instance, the UpperRangeValue cannot be greater than the Maximum value.  If it is, the value is changed to equal Maximum.  You can imagine the trouble this can cause.  A single change to a value can cause a recursive loop of multiple changes.

This issue is at its worse when property values are being set during Design Time or the values are programmatically set within the code.  Let’s look at the previous example again and say that you want to set UpperRangeValue to 80.  Since we haven’t yet set Maximum to 100 (our target), the default value of 1 is used when the UpperRangeValue is coerced, which causes it to be set to 1 (the current value of Maximum).  Now you can see the difficulty I had ensuring the coercion between all the properties worked correctly to ensure the intended values got used.  I was able to overcome the issue (mentioned in the example) by coding the coercion process in a way that it remembered the intended value and attempts to use it when it can.  This means, in the example, after the Maximum is set to 100, the intended UpperRangeValue of 80 is applied.

In an attempt to understand this better, lets take a close look at the OnUpperRangeValuePropertyChanged method (which is called when the UpperRangeValue dependency property changes.

DualRangeBase dualRangeBase = d as DualRangeBase;

// Validate the provided UpperRangeValue.
if (!IsValidDoubleValue(e.NewValue))
{
    throw new ArgumentException("Invalid double value", UpperRangeValueProperty.ToString());
}

This beginning portion of the method simply creates an instance (since the method is static) of the DualRangeBase that called it and checks to ensure that the NewValue is valid.

// The code that follows is borrowed from the Microsoft code in RangeBase
// that performs the same actions on the Value property.  The trick here
// is to hold calls to the property changed methods until after all
// coercion has completed.
if (dualRangeBase.levelsFromUpperRootCall == 0)
{
    dualRangeBase.requestedUpperRangeValue = (double)e.NewValue;
    dualRangeBase.preCoersionUpperRangeValue = (double)e.NewValue;
    dualRangeBase.initialUpperRangeValue = (double)e.OldValue;
}
dualRangeBase.levelsFromUpperRootCall++;

This portion of the method saves the new value (requestedUpperRangeValue), the new value before it has been coerced (preCoersionUpperRangeValie) and the old value (initialUpperRangeValue).  These values are used later as part of the coercion testing.  If you remember from what I mentioned earlier, coercion can cause the value to be changed multiple times in an almost recursive manner.  levelsFromUpperRootCall is used to determine the current phase of this process.  I must thank Microsoft for this idea as it is how they did it and it works very well.

// Coerce values
dualRangeBase.CoerceUpperValue();

// This portion of the borrowed Microsoft code finally fires
// the change events once all coercion is confirmed complete.
dualRangeBase.levelsFromUpperRootCall--;
if (dualRangeBase.levelsFromUpperRootCall == 0)
{
    double value = dualRangeBase.UpperRangeValue;
    if (dualRangeBase.initialUpperRangeValue != value)
    {
        dualRangeBase.OnUpperRangeValueChanged(dualRangeBase.initialUpperRangeValue, value);
        dualRangeBase.OnRangeChanged(dualRangeBase.initialLowerRangeValue, dualRangeBase.LowerRangeValue, dualRangeBase.initialUpperRangeValue, value);
    }
}

The above code covers the last part of the method. First, the call to the coersion method is made. I talked about this a little bit already but the biggest thing to remember here is that the value being changed may actually be changed again during coersion. Once coersion has been completed, and the process has returned back to the initial call to the method, the OnUpperRangeValueChanged and OnRangeChanged events are fires.

That pretty much concludes the base class.  I know that might seem a bit confusing but you will understand my points if you step through the code once in Debug-mode.  All of the work that was put into the coercion functions allows the control to behave property when the properties are being set in the XAML in either Blend or the Visual Studio designer.  It also ensures only the appropriate values can be set.  I included a set of unit tests specifically for testing this and suggest you examine those in detail for further understanding.

Custom Slider Control – Overview

This is part 1 of a multi-part article on a custom Slider control. You can find the other articles here:

The source code is now available on CodePlex.

As I promised, here is the initial post in a series that I plan on writing that covers the Slider control that I created for Berico Tailored Systems (BTS).  This is the control that I entered into the Silverlight Control Contest and that I blogged about earlier.

 This custom Slider came about because of an application (SnagL) that I have been working on for Berico Tailored Systems (BTS).  Several of the application’s requirements dictated the need for a slider with additional functionality, primary the ability to provide a range of values rather than just a single value.  My initial plan was to simply subclass the existing Microsoft Slider control and make the required changes to include the additional Thumb control.  I also decided to add handles at either end of the slider to make the control more standardizes (as most sliders have these handles for increasing and decreasing the value of the slider).  I quickly found out that I couldn’t do this by inheriting from the existing Slider control.  The root of the problem is in the UpdateTrackLayout method.  The purpose of this method is to appropriately layout the controls along the track as the slider is updated.  Some of the calculations used in this method use ActualWidth and ActualHeight, which refers to the width and height of the control itself and not just the track that the Thumb controls are on.  Adding the handles to the either end of the track changes the overall size of the control which causes the calculations to be off.  Since this method is marked as internal, it cannot be overridden by our class.  I was forced to create the updated Slider control from scratch.

Since I was starting from scratch I figured I would design the control from the ground up and look at what is available to sliders in other applications.  I will say from the start that much of the code that was used for the Microsoft slider was reused for this control, although it was greatly altered.  Here are the main requirements I decided on:

  • Provide functionality to select a range
  • Provide a way to switch from a regular slider to a range slider
  • Provide an increase and decrease handle
  • Provide a way to turn handles on and off
  • Support all the standard slider functionality such as Orientation, IsDirectionReversed and IsEnabled
  • Support styling and custom styles and templates
  • Work with the Visual Studio IDE and Expression Blend
  • Display tooltips over the Thumbs during dragging

Below is a sample Silverlight application that demonstrates this new Slider control.  Obviously, you will need the Silverlight plugin installed to be able to see it.

Install Microsoft Silverlight


The two horizontal sliders have been fully restyled while the two vertical ones are using the default template. Ignoring the details on the styling, the code snippet below shows the XAML used to create all 4 of the sliders.

<Berico:Slider x:Name="TestH1" Style="{StaticResource FancySliderStyle}" IsEnabled="true" Grid.Column="1" Grid.Row="1" IsRangeEnabled="False" Value="5" />
<Berico:Slider x:Name="TestH2" Style="{StaticResource FancySliderStyle}" IsEnabled="true" Grid.Column="1" Grid.Row="2" IsRangeEnabled="True" />
<Berico:Slider x:Name="TestV1" IsEnabled="true" Grid.Column="2" Grid.Row="1" Grid.RowSpan="2" IsRangeEnabled="false" Value="5" Orientation="Vertical" />
<Berico:Slider x:Name="TestV2" IsEnabled="true" Grid.Column="3" Grid.Row="1" Grid.RowSpan="2" IsRangeEnabled="True" LowerRangeValue="2" UpperRangeValue="8" Orientation="Vertical" />

I finally got around to setting up a CodePlex project for the custom controls (including this Slider) that I have been working on. I will update it as often as I can.

Silverlight Control Contest

I have been playing with Silverlight for a while now and recently came across a site that announced a contest for creating a custom Silverlight control.  I have always wanted to submit something  to a contest like this but never really had the time.  In this case, I already had a couple controls (a custom Slider and a GridSplitter) that I could use.  The catch is that I created this controls for Berico Tailored Systems (BTS), a company that I do some work on the side for.

BTS has a product called SnagL that is built on Silverlight 2.  I helped design the look of the application and created most of the controls that make up the user interface.  Marc Schweigert of Microsoft even conducted an interview with us about the product.  I have been very pleased with Silverlight and in how well some of the controls I worked on turned out.  While many of the controls are specific to SnagL, a few other controls are more general and usable by other applications so I broke those off into their own namespace.  This namespace contains the controls that I was curious about entering into the contest.

I decided, on a whim, to discuss the issue with BTS.  They were more then happy to embrace the idea and provided me permission to release these controls  as open source (under the Ms-PL license).  After some discussions and some research I got the official go ahead to release the source code as open source.

This leads me up to last night, when that final approval came through.  I selected the custom Slider control and created a new project to just include it.  I then submitted this control to the Silverlight Contest, which you can find here.  The contest ends on September 19th and I am excited about it.  Not only do I have a chance to win some great prizes but I am more than happy to share my custom Slider with the Silverlight community.

Aside from the contest, I hope to start a CodePlex project to host the custom control library.  I also plan on writing a series of detailed blogs on how I created each control (starting with the Slider).  Look for those soon.

I just wanted to update this article and mention that the winners for the control contest were announced and my Slider control was, unfortunately, not picked. I guess it just wasn’t flashy enough. I do hope  that it is, at the very least, helping someone else out in IT land.  I have started on that series of article that detail the Slider control and I have posted a project for it (and other custom controls) on CodePlex.

Silverlight 2 Controls Source

I have been sick the past week which has kept me from posting anything new. However, while doing some research yesterday I came across the notification that Microsoft was kind enough to release the source code for the release version of Silverlight 2. You can download the source here.

The download is a self-extracting zip file.  Once extracted you will have two folders:  Runtime Controls and  SDKControls.  The solution file is contained in the Runtime Controls folder.  The source code for the following controls can be found here:

  • ButtonBase
  • RangeBase
  • RepeatButton
  • Thumb
  • ToggleButton
  • Button
  • CheckBox
  • HyperlinkButton
  • ProgressBar
  • RadioButton
  • Slider
  • ScrollBar

This solution also contains a sample project that demonstrates the last 7 controls in the above list.

The source code and unit tests fall under the Microsoft Public License (Ms-PL).

Under the SDKControls folder, you will find the Data, Test, and Extended folders.  The Extended folder contains a solution file which has the source code and unit tests for the extended controls, which includes the Calendar, DatePicker, GridSPlitter and TabControl.  The Datafolder contains a solution file which has the source code and unit tests for the DataGrid and related controls.  The Test folder just has the unit test projects that the other solutions use.

Silverlight Sudoku – The Grid

I long time has past since I initially started this article series which I never got around to finishing. I have since restarted this project and have posted a new article in the new series (which I will actually complete).

I am sure many of you have heard of Sudoku (pronounced soe-DOE-koo). Sudoku is a very popular puzzle game.  The name itself is a Japanese word that roughly means number place.  Playing Sudoku is fairly easy, but, since it IS a puzzle game, not always so easy to complete.

The Basic Rules
I use the term basic because there are many different variations of Sudoku.  This article series will focus on the standard game which, as seen in the image below, is played on a 9×9 grid.  This grid is further divided into 9 3×3 sub-grids.

Standard Sudoku Grid

Standard Sudoku Grid

The figure above also shows the valid values for each cell.  To win Sudoku, every cell must be filled with a number ranging from 1 to 9.  Each sub-grid will contain the numbers from 1-9 with no repeats.  Each row and column in the overall 9×9 grid will also contain the numbers 1 – 9 (also, not repeating).  Since it is the key to playing the game, I am going to repeat that each column, row and sub-grid must contain the numbers 1-9 with no repeats.

When you are first given a Sudoku puzzle, the grid will be partially filled out.  As mentioned above, your task is to use logic to determine what numbers should be in each remaining cell.  I am not going to use this space to step you through all aspects of Sudoku.  There are many sites on the Internet dedicated to providing you with this information and I don’t feel the need to repeat it.  From this point on I am going to assume you know how to play the game so we can move on to the task at hand.

Drawing The Grid
The first thing we are going to work on is drawing the grid that Sudoku will be played on.  For the record, I am using Visual Studios 2008 SP1, Silverlight 2 and Microsoft Expression Blend 2 SP1.  I am also assuming that you have some basic understanding of Silverlight.  If you don’t, you can find everything you need here.

Initially I started drawing the playing grid in Expression Blend.  I started using the Grid control to separate each cell since it already understands the concept of columns and rows.  The idea was to place a TextBlock in a Border control in each cell.  As I was doing this I was a little put off by how long and cluttered the XAML was appearing.  Since our grid is 9 x 9 we are dealing with at least 81 controls, which is a lot.  I was going to use styles to make configuring the TextBlock controls a little easier but even a simple change to the grid or any of the sub controls could be very time consuming.  What I decided was that the creation of the playing board (or grid) needed to be dynamic.

Since this is just the starting point of our project I didn’t do anything fancy.  I created a simple Silverlight project in Visual Studio and added a Canvas (named LayoutRoot) and Rectangle (named BoardBackground) to the Page.xaml file, shown below.

It is important to note that the standard Sudoku board is square so the Height and Width of our page (where the board is being drawn) should be the same.

 

public partial class Page : UserControl
{
    int gridSize = 9;

    public Page()
    {
        InitializeComponent();
        DrawBoard();
    }

    ///
    /// Dynamically draw the Sudoku board
    ///
    public void DrawBoard()
    {

        // Create the lines on the board
        for (int i = 0; i < gridSize; i++)
        {
            // Every third line should be highlighted
            bool highlight = (0 == ((i + 1) % 3));

            // Create new lines
            Line verticalLine = new Line();
            Line horizontalLine = new Line();

            // Configure the vertical line.  If it is a highlight line, it will
            // be darker then the other lines.
            verticalLine.Stroke = new SolidColorBrush { Color = (highlight ? Colors.Black : Colors.Gray) };
            verticalLine.StrokeThickness = 2;
            verticalLine.SetValue(Canvas.ZIndexProperty, (highlight ? 1 : 0));
            verticalLine.X1 = Width * ((double)(i + 1) / gridSize);
            verticalLine.Y1 = 0;
            verticalLine.X2 = verticalLine.X1;
            verticalLine.Y2 = Height;

            // Configure the horizontal line.  If it is a highlight line, it will
            // be darker then the other lines.
            horizontalLine.Stroke = new SolidColorBrush { Color = (highlight ? Colors.Black : Colors.Gray) };
            horizontalLine.StrokeThickness = 2;
            horizontalLine.SetValue(Canvas.ZIndexProperty, (highlight ? 1 : 0));
            horizontalLine.X1 = 0;
            horizontalLine.Y1 = Height * ((double)(i + 1) / gridSize);
            horizontalLine.X2 = Width;
            horizontalLine.Y2 = horizontalLine.Y1;

            // Add the lines to the Canvas
            LayoutRoot.Children.Add(verticalLine);
            LayoutRoot.Children.Add(horizontalLine);
        }

        BoardBackground.Width = Width;
        BoardBackground.Height = Height;
    }
}

The code behind file (Page.xaml.cs), shown above, contains all of the code necessary to draw the board dynamically.

The gridSize variable is used to hold the size of the grid. This defaults to 9 but makes it easy for us to change in the future. All of the drawing is handled by the DrawBoard method. Since I am taking the dynamic approach I realized that I don’t have to use border controls or grids. After all, a Sudoku board is simply made up of a series of lines that cross, forming a grid. Therefore I just use Line controls.

I just wanted to add a quick note to apologize that the previous code example does not have all of the appropriate objects highlighted. It seems that the plugin I am using has not been updated to support Silverlight at this time.

All of the drawing takes place within a loop and we loop the number of times equal to the size of our grid, which is 9. The highlight variable is used to determine if the current line being drawn should be a darker line. This is calculated by checking if the current line is divisible by 3 (since every third line should be highlighted) evenly.

The vertical and horizontal lines are evenly spaced based on the overall size of the control and are configured in a similar manner, differing only in what axis (X for horizontal or Y for vertical) is the primary axis. First, the color of the line is set. As I mentioned above, if this is a highlight line, it will be colored Black; otherwise Gray. Next, the ZIndex property of the Canvas is set. This ensures that the highlight lines (the darker ones) are drawn over the regular lines. Finally, we set the X1, Y1, X2 and Y2 properties which determine the starting and ending points for our line.

For a vertical line, X1 is calculated by multiplying the Width of the page by the current loop index divided by the overall size of the grid. Y1 is 0, X2 will be the same as X1 (since our line needs to be straight) and Y2 will be the same as the Height of the page.

For a horizontal line, X1 is 0 and Y1 is calculated by multiplying the Height of the page by the current loop index divided by the overall size of the grid. X2 is the same as the page Height and Y2 is the same as Y1.

Finally, we add the new line controls to the canvas. The only thing left to do, once the loop is done, is to ensure that the background of our grid (the BoardBackground rectangle) is the same size as our page.

When the application executes, you will see our Sudoku board (as shown in the image below).

Sudoku Board

Sudoku Board

That is the end of this article. I know you didn’t get to do too much. In the next article, which I will try to get to shortly, we will add in the logic to generate a Sudoku game (populate the board).

Amazon Web Services – Paging

This article is part of a series of articles I am working on that cover the use of the Amazon Web Services (AWS).  This is the second article in the series.  You should read the first article if you haven’t already.

The previous article covered the general usage of the Amazon Associates Web Service to perform a search using the ItemSearch operation.  I am going to assume that you read my previous article and target this article on paging.

As mentioned in the previous article, the data returned from the web service call is in the form of XML.  Just below the Request element are the TotalResults and TotalPages elements.  These are the elements that we will concentrate on in this article.  Here is a snippet of the XML that shows these elements:


  True
  
    New
    Ship
    Visual Basic Recipes
    Amazon
    Small
    Books
  

7
1

In the example we used, and as the elements above show, our search only resulted in 7 items. Pages are limited to 10 items so the result was only page. For this search, there was no reason to use paging. Let us change the initial request by broadening the search, like this:

http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=YourAccessKey&AssociateTag=YourAssociateTag&Operation=ItemSearch&SearchIndex=Books&Keywords=Visual%20Basic

Now if you take a look at the results the TotalPages element is 406 and TotalResults is 4054. You actually only get 10 items. To get the rest of the items you need to make additional calls to the web service. The documentation isn’t very clear about doing this. I guess it is a common practice with REST services, which I have limited experience with. I was able to figure out how to accomplish what I wanted by a little research.

The trick is to add the ItemPage parameter to each additional call and increment its value. For example, if you want the 100th page, set the value to 100. In that case, the call would look like this:

http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=YourAccessKey&AssociateTag=YourAssociateTag&Operation=ItemSearch&SearchIndex=Books&Keywords=Visual%20Basic&ItemPage=100

You will now get the results for page 100. You can confirm this by taking a closer look at the ItemSearchRequest element. It now contains an ItemPage element whose value is set to 100.

Now that we have covered that I need to warn you about a caveat I discovered. Your ability to page is limited. In the example above you would not be able to ever see all items. If you set the ItemPage parameter to 401, your results would contain an error message stating The value you specified for ItemPage is invalid. Valid values must be between 1 and 400. As the message makes clear, you cannot get more than 400 pages of results. Your only option is to refine your search, this reducing the number of items and pages returned.

Amazon Web Services – General

When I was setting up this blog I decided that I wanted to be able to display links to some Amazon products on my site.  I didn’t want this to become a full interface to Amazon or anything, just enough to display my books and maybe a few other items.  I found the plug-in that I am currently using and it seemed efficient.  I am a bit of a nerd and I decided that I wanted to know exactly how this all worked so I visited the Amazon Web Services (AWS) site and began to read. I quickly learned that Amazon provides a large amount of information, a very detailed program and site and several different services for possible use.

The service that seemed to be of the most interest to me was the Amazon Associates Web Service.  This service, formally known as the Amazon E-Commerce Service, provides access to Amazon’s product data.  The concept behind using this web service is to display Amazon product information on your web site, and allowing you to earn money in the process.  I will admit that I haven’t read too deep into the “money earning” aspect but the way I understand it is that if a person purchases a product by following the link on your web site, then you earn a small commission.

To use the web service you must sign up.  I actually figured out that you need to sign up in two places if you want to earn that money mentioned earlier.  Signing up on the AWS site gives you access to use the web service using a special key that is generated for you (this key will be covered in more detail later on).  From what I can understand, to actually earn money you also need a special tag that is included within your service call.  This tag is provided when you sign up here.  You definitely should read through both sites before moving on but that is as much detail as I will go into for now.

The Amazon Associates Web Service is a standard REST service that consists of a base URI followed by parameters which tell the service what action you want to perform.  The base is http://webservices.amazon.com/onca/xml and the first parameter to supply is Service.  The Serviceparameter is used to specify the web service that you are connecting too, which should be AWSECommerceService in our case.  At this point, the URI would look like this:

http://webservices.amazon.com/onca/xml?Service=AWSECommerceService

You must also provide your associate key via the AWSAccessKeyId parameter.  You were given this when you signed up to use the web service.  Providing this key is mandatory and is used, according to the documentation, to “uniquely identify you to the seller”.  Now the URI should look like this:

http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=YourAccessKey

While it is not mandatory, if you want to earn any money you need to add the AssociateTag parameter and set it’s value to your associate tag.  You were assigned this tag when you signed up through the affiliate web site (mentioned earlier).  With this new parameter the URI is:

http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=YourAccessKey&AssociateTag=YourAssociateTag

Next, you need to provide a value for the Operationparameter.  This parameter tells the service what action, or operation, you want to perform.  Their are over 10 valid values for this parameter, such as ListLookup, ItemLookup, ItemSearch, etc.  You can get the full list from the document.  For this article we will focus on performing a search which means we use the ItemSearch value.  The URI should look like this now:

http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=YourAccessKey&AssociateTag=YourAssociateTag&Operation=ItemSearch

Since we selected ItemSearch, we have a couple other required parameters.  The first of which is the SearchIndex parameter.  Again, their is a long list of possible values here, such as Books, DVD, Toys, VideoGames, etc.  For this article lets go with Books.  We must now select at least one more parameter that will be used to provide the search criteria.  Their is another list of possible choices but for now let’s select KeyWords and assign it a value of Visual Basic Recipes (make sure to encode the spaces).  Our URI is a bit longer now and looks like this:

http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=YourAccessKey&AssociateTag=YourAssociateTag&Operation=ItemSearch&SearchIndex=Books&Keywords=Visual%20Basic%20Recipes

This is all you need to get this working.  If you dropped this into the Address bar of your browser you would see the results in the form of an XML document.  Since it is rather involved, I will save the details on the return data for another article.  For prosperity, the results of the above would look similar to this:


  
    
      
20974e28-a26a-4c30-a3f6-2a7492f6f9d6 0.2950220000000000 True New Ship Visual Basic Recipes Amazon Small Books 7 1 1590599705 http://www.amazon.com/Visual-Basic-2008-Recipes-Problem-Solution/dp/1590599705%3FSubscriptionId%3DYourAssociateKey%26tag%3DYourAssociateTag%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D1590599705 Todd Herman Allen Jones Matthew MacDonald Rakesh Rajan Apress Book Visual Basic 2008 Recipes: A Problem-Solution Approach 1590598520 http://www.amazon.com/Visual-Basic-2005-Recipes-Problem-Solution/dp/1590598520%3FSubscriptionId%3DYourAssociateKey%26tag%3DYourAssociateTag%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D1590598520 Todd Herman Allen Jones Matthew MacDonald Rakesh Rajan Apress Book Visual Basic 2005 Recipes: A Problem-Solution Approach (Expert's Voice in .Net) ...

To put it in a programming perspective, let me give you a short code example.  Since I have recently decided to start playing around with PHP for the first time (in an effort to better support my blog) I will provide the example in that language.

$path = "http://webservices.amazon.com/onca/xml?Service=AWSECommerceService"
           . "&AWSAccessKeyId=YourAssociateKey"
           . "&AssociateTag=YourAssociateTag"
           . "&Operation=ItemSearch"
           . "&SearchIndex=Books"
           . "&Keywords=Visual%20Basic%20Recipes";

$results = file_get_contents($path);
echo $results;

The code above will provide the identical results that you received when you just entered the URI in the Address bar of your browser.  I know the example isn’t very in-depth but I wanted this article to mainly provide an overview of making a call to the Amazon Web Services in general.  The services provided by Amazon are fairly sophisticated and easy to use.  What I didn’t cover here, but will try in a future article, is how you can also provide a parameter to influence the amount and type of information that is returned by the web service call.

WordPress Themes