Tuesday, December 15, 2009

PLINQO adds 'wow' to LINQ 'cool'

Ok, I am the first to admit that I am firmly entrenched in the "Not Built Here" camp. Not only for controls but tools as well. The only tool I've let into Visual Studio for the longest time is Resharper.

I love the power of LINQ but the LINQ to SQL ORM tools have never really thrilled me.

Well, I have changed that rule and I've added PLINQO. I've looked at other tools for ORM, even LINQ to SQL and EF. Thus far I've never liked how the code that these tools generated, but the code that PLINQO generates is the BOMB! PLINQO is like LINQ on steroids, without the roid rage!

Individual files for each table, Generated code does not overwrite custom changes, custom names .... the list just goes on and on.

I could go on and on, but there is a fantastic 70 minute video tutorial here and I guaranty that within the first 10 minutes you will want to pause the video and download PLINQO!

Monday, November 30, 2009

How to create your own Silverlight Cube Control similar to Telerik's Cube

Well, as part of our lastest project, I needed to figure a way how to spin a widget.

So, how do you rotate widgets in an Asp.Net application? Well that question is fairly simple to answer - Silverlight!

The next question is much harder: Buy or Build?

After some searches I found two controls for sale: The Telerik Cube control and the ComponentOne C1Cube control.

So, first stop, download each and put them through the paces. I found a deal breaker for each control.

We need to be able to minimize our widgets but both controls had problems with that:
- The Telerik control would resize but would apply a transform to 'Squash' the widget and according to the Telerik website FAQ, this behaviour can not be overridden.
- The Component one control 'Must' be in the shape of a cube. Ok, I know that sounds like a 'duh' point, but like I said, we need to minimize our widgets. But when I altered the height of the control to just the height of the header, the cubes' width was also adjusted.

So, that left build - but there did not seem to be any examples of how to rotate a cube from side to side, on demand. I did find an example of a continuously spinning cube. With this example to decompose, I slowly taught myself the parameters and transformations that were needed to create the appearance of a cube spinning from one face to another.

So, here is my demo of a rotating six sided cube. If you do not need to rotate to the top and the bottom, you can have sides of any height, as long as all the sides are of the same height. Plus, my example is not limited to four or six sides. This example allows for an unlimited number of sides!

Now, there a couple of things that the professional controls do that my demo cannot. My code cannot free rotate and it also does not twist as it rotates to properly show a side. If you need these properties, you may want to go with the professional controls.

Here is the Visual Studio 2008/Silverlight 3 project.

Thursday, November 12, 2009

Personal Site Launched!

Well, it has taken awhile but I've finally rolled out a personal website. LeeSaunders.net is a place that I can post about all things that interest me ... except dot net programming, of course!

There is not much content as of yet, but the reason I am posting about it here is that I've used the asp.net web template that I created in a previous post. So if you want to see a live site, not just a live example, then head out to LeeSaunders.net!

Thursday, October 22, 2009

My first free ASP.Net CSS web template

Note: I've added a label: "Free Template" for all my posts relating to converting free CSS XHML web templates to Asp.Net web projects.

While watching TV for a couple evenings, I converted a simple CSS XHTML web template into a Asp.Net 2.0 project.

The template I converted I found on ThemeBot.com. I like ThemeBot.com because most of the web templates are covered by the Creative Commons license. The license gives you two explicit rights: you are free to share the template and you are free to adapt the template. The license(s) have either one condition: you must attribute the template, in the manner as specified by the author or two: attibute and Share Alike, where if you share your creation, you must also use this license (Or a similar one).

The template I altered was this one: sparkBB014. It is a simple template for a blog. Here is the link to the sparkBB014 Demo.

Now with all the prelimaries out of the way, here is what I did:

I wanted to achive a couple of things:

1 - Use a MasterPage
2 - Wrap the reusable/optional elements in UserControls
3 - Move all the data to the code behind so that users can easily be made dynamic.

So, I created a web project and added a master page to the project. Next I copied all the markup from between the body tags and copied it into the master page.

Then I pulled out each block of data and the surrounding markup out and replaced it with a ContentPlaceHolder. Then inside the Default.aspx for each ContentPlaceHolder I placed a corresponding Content tag and filled it with the data/markup I had just removed from the Master Page.

Once that was done, I started IDing and runat=servering html elements so that I could touch them programatically.

Seeing that the entire blog design scheme was repeated for each entry, I pulled the entire structure out into into own ascx UserControl.

And since I would not want the search area on every page I moved it as well to its own ascx UserControl.

Last but not least, I removed the actual data from the markup and coded the codebehind c# to dynamically load the data into the markup. So, here is the zip file containing the project and here is a link to the asp.net site hosted at 1&1. Please, tell me what you think!

Monday, October 19, 2009

One Year of "Old School Dot Net"

Well, it has been one year. I've posted about complex computer science problems and I've created and wrote about silverlight 2 games. And, I've blogged about everything in between.

When I started this blog I set some goals for myself. I wanted to blog an average of once a week, or a total of 52 posts as of this week. I only made it to 40. 41 would have be 80% of my goal, or a B, but at 40 I only grade myself at a c+.

I also wanted to write 12 articles for codeproject.com. I completed 0. And, last but not least, I wanted to present at a conference this year. I ... well ... I think I'll join TechMasters and try to work on my presentation skills.

For next year I will keep the same goals and hope to get an aggregate passing score.

Wednesday, October 14, 2009

free asp.net web templates

Note: I've added a label: "Free Template" for all my posts relating to converting free CSS XHML web templates to Asp.Net web projects.

Ok, Why are there no websites offering free asp.net web templates? Is there no market?

There are tons of websites offering free xhtml/css website templates. Nearly all of them have licenses that allow compete freedom to alter it as long as you give credit to the creator. So, nobody can say that there is no material.

So, is it because there is no need? The way I see an asp.net web template offering is an asp.net web project with a master page with ContentPlaceHolder's sprinkled throughout so that a user of the template could get an asp.net website up and running quickly.

I'm not talking about anything as detailed as the starter kits from Microsoft, just simple templates, like the ones all over the net, but configured for asp.net.

So, tell me, would a site like ... say ... freeaspnettemplates.com be a site that anyone would use? Tell me your opinion, you just may start me on a new hobby!

Wednesday, August 19, 2009

The easiest way to convert vector graphics to XAML

Wow, this is sooooo simple. I've been converting WMF, EMF, CDX, CDR, AI, EPS, PDF and SVG to XAML all day. This is actually fun!

First get a vector graphic and a program that can open it. I've used Adobe Illustrator, CorelDraw, Inkscape and even Windows Picture and Fax Viewer.

Next get a vector graphic that your program can open.

Finally get the Microsoft XPS printer driver if it is not already installed.

Now open the file in your program of choice and print it to the XPS printer driver.

Now rename the resultant XPS file to ZIP.

Open the ZIP file and inside the Documents/1/Pages folder is a file named 1.fpage.

Extract the file and rename it to .XAML.

Now you have a XAML file that will open in Internet Explorer, but if you want to have a XAML file that will open kaxaml or for use in a WPF or a Silverlight application, open the file in notepad and replace the FixedPage tag with the Canvas tag.

Here is a XAML graphic I converted from my Corel Gallery. (Either open link in IE7/IE8 or download the XAML file and open it in your XAML viewer of choice)

Older posts from other blogs tell you to use Inkscape and print to PDF and then open the PDF in Adobe PDF Viewer. Fron the Adobe PDF Viewer you can then print to the XPS printer driver. The reason was that Inkscape converted the file to a raster image. Then and only then could you retrieve the 1.fpage file. This was because Inkscape sent the graphic to the printer as a raster image, not a vector image.

Well, since those blog posts were written, there have been updates to Inkscape, and now Inkscape prints a vector image as a vector, so there is now no need for converting it to an intermediate format (PDF).

Tuesday, July 28, 2009

A Checkers Rules Engine in C#

One of the things I've always wanted to program is a game using a Genetic Algorithm to generate the AI. Well at work I was talking about AI coding and my aforementioned desire came up and as we talked about it, the idea of using game of Checkers as the game I could use with a GA surfaced.

When I got home that evening and was relaxing after diner, I booted up the laptop and started cruising around the web. I was started looking around for a rules engine for checkers - hopefully in C#. You see my thought was, if I could find a rules engine that, from a given game board configuration and who's move it was, it would output all valid moves.

Well, no matter how I arranged the words in Google, I could not find a rules engine for checkers. I found a few complete C# checkers games but the rules were too integrated into the rest of the game for me to filter out.

So, I decided to write one.

I started with an enum to define the two players:
public enum PlayerColors { Black, Red }

Then I wrote a class to hold each checker piece:

CheckerPiece has a single constructor:
CheckerPiece(PlayerColors MyPlayerColor, int MyPieceLocation, bool MyIsKing)

Four properties:
public int PieceLocation { get; set; }
public bool IsKing { get; set; }
public PlayerColors PlayerColor { get; set; }
public List PossibleMoveLocations { get; set; }

and Three methods:
public char GetPlayCharacter()
public void FindAllMoves(char[] GameboardArray)
public void FindAllJumps(char[] GameboardArray)

The constructor sets the PlayerColor, PieceLocation, and IsKing.

PlayerColor defines which side the piece belongs to.
PieceLocation is an int from 0 to 63 defining each square of the game board.
IsKing is a bool that determines if the piece is a king or not.

GetPlayCharacter returns a lowercase r for a red piece, a lowercase b for a black piece, an uppercase R for a red king piece and an uppercase B for a black king piece.

a game board array is a char[64] array that can hold on of these chars 'r', 'R', 'b', 'B' or ' ' (a space).

FindAllMoves and FindAlJumps take in a GameboardArray and sets the PossibleMoveLocations list with all the possible Moves or Jumps.

Now with that built, I created the CheckersRulesEngine class.

CheckersRulesEngine has a single constructor:
public CheckersRulesEngine(char[] gameboardarray)

A static char array that holds a starting game board configuration for convenience:
static public readonly char[] StartingGameboardArray =
" b b b bb b b b b b b b r r r r r r r rr r r r ".ToCharArray();

Three properties:
public List MovablePieces { get; set; }
public List Pieces { get; set; }
public char[] GameboardArray { get; set; }

And Three Methods:
public void GetPiecesWithMoves(PlayerColors CurrentPlayer)
public void GetPiecesWithJumps(PlayerColors CurrentPlayer)
public string OutputAsciiBoard()

The constructor the GameboardArray and creates a CheckerPiece entry into Pieces for each piece defined in the GameboardArray.

GetPiecesWithMoves and GetPiecesWithJumps works its way through the Pieces collection and loads MovablePieces with the pieces that qualify.

OutputAsciiBoard is a helper function that outputs an ascii board showing the location of all the pieces.

You can get the c# code for the CheckersRulesEngine here! Or, you can download a Visual Studio 2008 solution that also includes a console program that plays a game of checkers against itself using random moves! The solution can be downloaded Here!

Tuesday, July 21, 2009

Widgets: Drag, drop and reorder. Simply done with JQUERY.

The heart of the Dropthings project, IGoogle or Pageflakes is the client side moving of the widgets. Be it dragging and dropping the widgets in other columns or reordering the widgets in a single column, this client side behaviour it the flashy part of the widget system.

In the Dropthings project the Author originally used the microsoft AJAX client side library along with quite a bit of his own code. No critisim here, he coded a complex cross-browser system that WORKED! I would not even have tried.

But, in the latest addition it says that the code was converted over to JQUERY. Well I looked at that code and while he may have converted to use JQUERY, he is not really USING JQUERY. Most of his system is still in place. No problem with that, unless you are not the Author and want to modify or enhance it.

I went another route: pure JQUERY. With just a few lines of code and a bit of AJAX to update the server I got all that functionality without all the complexity. Here it is:

        $(document).ready(function() {
opacity: 0.5,
smooth: true,
helper: "clone",
handle: ".WidgetHeader",
connectWith: ".DropZone",
placeholder: "WidgetSortPlaceholderHighlight",
forcePlaceholderSize: true,
stop: function(event, ui) {

Thats it. You now have multi column drag and drop support. Just have your div's associated with the DropZone class and the Header of the WidgetContainer associated with the WidgetHeader class. My OnStop call to callMyService() walks through all the .DropZone controls and gets the ID of the Widget, the ID of the DropZone and the index (the order of the widgets) and calls the Webservice to update the database.

Here is a link to a working minimum example.

Thursday, July 16, 2009

A c# class to convert between bases

Ever needed to work with numbers in base 17, or base 3? I have always wanted to write a Genetic algorithm that used base 3 numbers to represent the board - 0 empty, 1 my piece, 2 opponent piece. Recently at work, we needed to work with base 36 numbers. While doing some searching I also learned that some people needed numbers that were alpha-int (Where the letters preceded the numbers) instead of the standard int-alpha.

Here is a class that I think Microsoft left out. We work different systems and different numbers every day, so why didn't Microsoft include a base converter class? It probably was just too low on their list of priorities.

Well, here is my interpretation. It is a static class that exposes three overloaded functions:
Encode(long Value, sbyte Base)
Encode(long Value, sbyte Base, bool NumeralsFirst)
Decode(string Input, sbyte Base)
Decode(string Input, sbyte Base, bool NumeralsFirst)
BetweenBases(string Value, sbyte FromBase, sbyte ToBase)
BetweenBases(string Value, sbyte FromBase, sbyte ToBase, bool NumeralsFirst)

By using the BetweenBases function, you can convert directly from one base to another without decoding to a long in between.

The complete code for the class can be downloaded here.

Saturday, July 11, 2009

Risk Map in Silverlight 2

As I mentioned in a previous post, I have reworked the USA map project to represent the map in the game of Risk.

The above image shows how the XAML is defined. The XAML is based on the SVG file found here. Once the project is ran, each country (both its inner and outer polygons) are entered into a data graph, similar to the one I used for the USA Map, with just a few improvements.

This demo, when ran, assigns each country to a player and assumes that you are the Green player. If you click on a country that is bordered with bright green, its border will turn black and all enemy held countries' borders will turn white. This shows what nations are available to attack.

If a programmer had a risk game play engine, this silverlight front-end will work quite well for you. The complete project can be downloaded here.

Tuesday, July 7, 2009

Dropthings - The good ideas and the bad

In a previous post I talked about my first impressions of the Dropthings project. Here I will talk about some of the ideas that I really liked in the Dropthings project, what ideas I will take away for my own project and the ideas that I thought were great but did not fit with my exact needs. And, at the very end I may add a few comments on another bad idea contained in the Dropthings project.

First I like the idea of not directly loading the widgets onto the page but instead having a common container where you load the widget, then the common container [lets call it the WidgetContainer :-)], is loaded on to the page. Here is a mockup of my version of the WidgetContainer user control:

The Dropthings project and my project save the widget information in two tables, the Widget table where all the default information about the widget is stored and the WidgetInstance table where the user specific widget information is stored. Since my requirements are that no controls are loaded until the user logs in, the entire generic user system in Dropthings, though cool, is not needed in my application.

So, after login, the process of loading the page is as simple as looping through the returned records and creating an instance of each widget inside its host container.

Lastly I would like to talk about the use of LINQ in the Dropthings project. Now I am not a huge advocate of LINQ, but there are times when it is the only tool that can solve the problem at hand, and I love it for that. What I do not like is that it:
A: Is database specific. Try running LINQ on Oracle or DB2 without purchasing third party plug-in. Sorry, cannot be done.
B: Unless it is watched very closely, the implementers of LINQ cross the data/rules boundary. In Dropthings you find LINQ commands everywhere. If you wanted to roll the Dropthings project out with an Oracle or DB2 back end, you would have a monumental time replacing all the Data access.

So, if the Dropthings project were not so tightly coupled with the data layer and workflow, I think (just my opinion) that the entire system would have benefited.

Thursday, July 2, 2009

Which UpdatePanel caused the Post?

Now that is a question! And the answer tool me nearly a day to discover. (OK, all of you that know the answer, stop snickering. I'm just learning the ASP.NET AJAX model)

After many dead ends, here is the key to finding what UpdatePanel caused the Post:

This returns the actual element ID that forced the Post. How does this help? Well, any post that originated in a UpdatePanel would be from a child control. So, if you walk up the control tree and find a UpdatePanel, you will have the UpdatePanel that caused the Post.

private UpdatePanel GetUpdatePanelThatCausedPostback()
var c = Page.FindControl(ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID);

while (c != null && !(c is UpdatePanel)) { c = c.Parent; }

if (c != null) return (c as UpdatePanel);
else return null;

Here we get the control that actually fired the Post and then we walk up the control tree, one by one, until we are either past the top (null) or we have found an UpdatePanel.

Then we simply either return the newly found UpdatePaenl or we return null.

Monday, June 22, 2009

Creating a Widget framework in ASP.Net

Note: I've added a label: "widget" for all my posts relating to implementing a Widget framework in Asp.Net.

A recent request at my workplace sent me off looking for a Widget framework for ASP.Net similar to IGoogle and PageFlakes. All I found was Dropthings.

Just like everyone else, after downloading the source code, I loaded the project in Visual Studio and tried to run the solution. After messing with the SQL Express DB for a few minutes, the Dropthings solution fired up with no problems. Well, after playing with the example site for a few minutes I shut the site down and started it back up again, this time walking through the code, one line at a time.

After manually stepping through about a gazillion lines of code, the site finally fired up. Wow, was it really that complex to dynamically load a few widgets on a web page? OK, maybe I was so focused on the trees that I could not understand the forest. So, I tried to step through the click event of the minimize button and ... well, lets just say that there is complex and there is COMPLEX.

Before we go any farther, lets start with a few definitions:

1 - Widget: A self contained application that runs in a subsection of the web page. Widgets usually have header area similar to a windows program and just like a windows program usually have minimize and maximize buttons. Other buttons, such as refresh and edit buttons may also be available.

2 - Widget Container: One or more areas, usually columns, where widgets are displayed on the web page and with drag and drop functionality, between which widgets can be moved and re-ordered.

3 - Widget Based Site: A web site with one or more pages that dynamically display widgets that the user can personalize by adding removing and rearranging widgets.

Now, does such a framework have to be soooooo complex as dropthings? After a deep and long look at the source code, there are quite a few things to commend the author for. There is also a ton of things he needs to be castigated for.

As I endeavor to create a widget based site from scratch, I will blog my successes and failures as well as the elements I found in dropthings that I decided to recreate in my site.

Tuesday, June 16, 2009

Ramblings + some upcoming posts

Wow! Vacation, A move from my laptop to my desktop (The laptop is my primary computer in the winter and my desktop is my primary computer in the summer - It's cold in the basement in the winter!) and Lots of work on the "Farm" seems to have made eight weeks disappear like smoke.

Well, I'm finally back to my blog.

What I'd like to post in the near future:

The missing conversion class: Why didn't Microsoft include a class to convert numbers from any base to any base from 2 to 36? Well, I've got one.

A Silverlight Risk Map: I built on the USA Map to create a risk map that shows the colors of the "owning" player.

Thanks to a start from another blog (I'll give the credit in the post) a generic full singly linked list based on class references instead of an array.

Now, long before I started this blog I was deeply involved in the Campaign Cartographer 2/3 (CC2/CC3) community. After I received my pre-ordered copy of CC2, way back when it was first released, I started to expand its capabilities.

I found out how to write XP's (plugins) for CC2 and wrote the fractal commands that are in the product today. CC2's core is written in assembly and the XP's are written in either assembly or C/C++. I wrote a random name generator that combined C++ with VB6. After .net arrived I rewrote my random name generator in C#. I even wrote five tutorials (You can read the tutorials here.) on using Microsoft's IJW (believe it or not, IJW stands for "It just works) to interconnect C++ with C# using CC2/CC3 as the example application.

Well, I've recently been contacted by an individual trying to work my tutorials and they are having issues, so I will be revisiting them - and posting about it here.

I've also got an application 75% done that is a "stand alone WIKI" for CC3. The idea here is to be able to link RTF data and map links. I'll also be posting about this as I dig back into this project.

I've not forgotten my efforts at board game programming, I just have to clean some of these other projects before I can get back to game programming.

Well, that's all my thoughts for now. If anyone has a preference on what I post first, feel free to add a comment. I DO read all comments!

Sunday, April 12, 2009

How to get AJAX to work at 1and1 (Sort of)

Normally you cannot run Microsoft's asp.net AJAX on the 1and1 servers because they have not installed it, and you cannot get it to run in a partially trusted environment.

But do not despair, older versions of Microsoft's asp.net AJAX, code named ATLAS, an still be downloaded from Microsoft.com and ATLAS does not need to be installed on the server. You only need to copy the Microsoft.Web.Atlas.dll to your bin directory.

There were two releases of ATLAS, the April CTP (community technology preview) and the June CTP. You need to download the April CTP here since it seems the June CTP needs installation.

Here is my example page on 1and1. My example uses the UpdatePanel control.

Monday, April 6, 2009

The "Weekly" Newsgroup post #2

This is my second "Weekly" (Oh, that's a laugh) Newsgroup post.

In this post, we have what seems like a simple question: How to ensure that at most there is one occurrence of each character from a list of characters.

Or, to be more specific, Byron gave this example:

For example, a string [starting with a capital 'D' and a dash - ed] can have up to 4 unique digits between 1 and 4.

The following strings should pass:

The following should fail:
D- (no digit)
D-0 (out of range)
D-5 (out of range)
D-11 (repeated digit)
D-1 2 (embedded space)
D-12345 (out of range and too long)

The first reply was by Peter Duniho, who instead of trying to answer the question suggested that Bryon try using C# instead. Many other replies sought to answer the question with brute force, the same way that C# would have to.

Now, I did not select this post because I contributed to it, but I did suggest using lookaheads and a true RegEx guru came up with the an amazingly elegant solution.

Which Peter immediately to exception to. Now, I would be the first to say that Peter is an amazing C# programmer and he leaves me in the dust, but it is BECAUSE he is such a great C# programmer that he seems to look at everything through C# goggles.

His argument boils down to Regular Expressions are hard and some people do not understand them, so do not use them.

Well, I agree that if you do not understand Regular Expressions, you should not use them, but the same holds true to C#, if you do not understand a language you should not be programming in it.

But, Peter points out, look how long it took this group to find an elegant solution. That definitely shows how hard Regular Expressions are. Well, this is a C# group not a Regular Expression group so it makes sense that it could take us awhile. I bet if we asked a non-trivial question on a Regular Expression group it would take quite a few iterations till they came up with an elegant C# solution.

Why did I not point this out to Peter in the post? I've found that you never really win an argument with him ... it is just best to smile, nod your head slowly and back out of the discussion.

So, with Peter's straw man firmly destroyed, lets take a look at this "elegant" Regular Expression by Jesse Houwing:


The beginning is fairly straight forward, the string must start with a "D-"

Then we see, at the innermost set of parenthesis is ([1234]). This is a capture group that simply means, the next character I find must be in the set of 1 through 4 and then save it as a capture. Since the capture is not named, it can be referred to by its number. Since it is the first capture, it is #1, or \1, in RegEx speak.

Next we see another set of parenthesis, but the opening paren is immediately followed by "?!". This turns the RegEx code inside the parenthesis into what is called a Negative Lookahead. What it does is, it scans the rest of the string and if a match is found for the lookahead, the entire Regular Expression fails.

The RegEx code for the Lookahead is: .*\1

This simply says can I find a match to the character I found in the capture with any number of characters before it? Or, i.e. does the character ever appear again?

All of this is surrounded by a set of parens with the opening paren immediately followed by "?:". This says that we do not want to capture, i.e. remember the strings that RegEx would normally keep as a sub-group.

last but not least, "{1,4}$" informs the RegEx engine that the string must end with 1 to 4 matches from the parens that we said we did not want to keep track of for later.

This amazing little bit of code will fulfill all the requirements the original requester asked for and teach a bit as well!

Thursday, April 2, 2009

How to get a Silverlight Application to work at 1and1

Just a quick little post to tell everyone what they need to get a Silverlight Application up and running at 1and1.

You only need to make two quick changes.
1- Rename the XAP file to ZIP
2- Change the call in the TestPage.html file to reference the ZIP file instead of the XAP file.

Saturday, March 28, 2009

How to make Asymmetrical Board Game maps in Silverlight

Or, how I spent my evenings at MIX09 in Las Vegas.

Last year, I began looking into writing board games with an asymmetrical map boards. I started with Awful Green Things from Outer Space (AGTFOS), a classic beer and pretzels game by Tom Wham. I started with an alternate game board graphic I downloaded from boardgamegeeks.com.

But, since the map is asymmetrical, there is no simple math function that, given an X,Y coordinate, would tell me what room in the spaceship I clicked on.

After a lot of googling, I found that boardgame programmers use a 2D array where every every element in the array corresponds to a pixel in the map image. Then set al the array elements to values that equal what room that pixel is in. This worked great, but it has a problem - No scaling. I could not scale the graphic and still know what room I was in.

WPF and Silverlight to the rescue!

So, as a proof of concept, I took a states map of the USA in SVG from Wikipedia and used ZamlTune to convert the SVG to XAML. Since all the elements in WPF are scalable and clickable, I was able to, with just a few lines of code, make the map aware of what element I was clicking and change its fill color.

That solved half of the problem of a asymmetrical board game map. The other issue is for movement and conflict. We need to know what states directly border the selected state. For this we need to go back to Comp Sci 350 - Data Structures. We need a graph.

Graphs have Vertexes and Edges. A vertex can be thought of as a location and the Edges as the roads to and from these locations. So, if we had a Graph with a vertex for each State and an edge to each bordering State, we could easily find out what States border each other.

Unlike previous silverlight examples I've posted, this one cannot be embeded since it needs to resize, so you need to open the link to run my example USA map. If we wanted to play Risk on a USA map, this would be a large positive step towards that goal.

As, you can see in the image the selected State is in Blue and the bordering States are in Light Blue. (Click on Image to Open The Silverlight Application)

Unfortunately the Graph object I wrote for this proof of concept is not nearly as full featured a Graph object as per my previous post.

And here is a zip file containing the entire Visual Studio 2008 Project.

Saturday, March 21, 2009

Why MIX09 was a success!

After a shaky start with their pre-conference workshops, the actual conference was fantastic.

All four of the Keynotes were fantastic - and quite motivating.

Unlike other conferences I've attended where the entire content is based on future, unusable at work, new products. Or, they all seem to be doing nothing but promoting their book. Well, MIX09 was, of course, a little of both of those, but it was also so much more.

There was a lot of "soft" information for the designer on the UX or User Experience. Since I am mostly a backend developer, I gained a lot of insite on the design side. There was also quite a bit of information on silverlight - including animation.

So, all in all, for me MIX09 was an unqualified success.

Tuesday, March 17, 2009

First impressions from MIX09

Well, I'll been here in Las Vegas for 36 hours and I'd just like to say that I've never stayed at a hotel where the employees are as helpful and pleasant as here at the Venetian.

The first session of the pre-conference was fantastic: Semantic HTML and Unobtrusive JavaScript presented by Nate Koechley

The second session, on the other hand, Cascading Stylesheets presented by Molly Holzschlag was atrocious. After the first two hours, we had covered what anyone can learn about CSS from a book in the first ten pages. Quite a few attendees, including my team, left the presentation early. (Hint Molly, you do not need to repeat war stories more than six or seven times)

So, with the main conference starting tomorrow, MIX09 is batting 50%.

Monday, March 9, 2009

The "Weekly" Newsgroup post #1

When I decided to become more active in the dot net community, I did a number of things:

I started this blog,
I started to attend the monthly meetings of our local users group ( omahamtg.com )
I started writing articles for codeproject.com (None of which I've finished yet - Bad Lee)

And, I started to hang out in the C# and ASP.net newsgroups as well as the forums at asp.net and silverlight.net in the hope that with my feeble knowledge I could help someone that the more experienced and knowledgeable would pass over as not worth their time.

Well, first thing I learned was that all the "Experts" on these newsgroups/forums are so helpful that I was only able to help a few people, and only then because their questions dovetailed exactly into my knowledge base.

But the big thing I learned was home much I could learn by reading the posted questions and answers. People are out there trying to do things with Dot Net that I never even thought of trying and reading in the replies how achieve those things has expanded my knowledge of all things Dot Net.

I used to think (and still do) that reading others source code was a great way to learn. When I found a link to Scott Hanselman's Weekly Source Code blog entries, I was forever indebted to Scott for searching the web and finding those few source code gems in the vast sea that is the Web.

I the same vein as Scott's Weekly Source Code posts, I'd like to start a "Weekly" posting of one or more Newsgroup/Forum questions that really deserve more focus than they received.

And Now: Question of the Week #1
is there shorter way to code this

In this series of questions and answers, rodchar asks how he can get to two properties (Id and Text) of three different controls. His example shows the brute force way of taking an Object and through a series of IF statements determining if the Object "IS" of a certain type, then casting it to that type so as to access its ID and Text properties.

On reading the answers the Experts gave, it is obviously a perfect problem to be solved by an Interface. I chose this question because in my dealings with other programmers, Interfaces are the hardest part of OOP for them to grasp. Here in this one simple question, we have nearly the perfect example of how and where to use an interface.

Since there is now common parent that exposes the Text property, rodchar cannot just cast the Object to the parent. But, since they all already implement a Text property and an Id property, we can define an Interface that declares these two properties.

Here is the Interface suggested by DabblerNL

public interface ITextAndID 
string Text {get;set;}
string ID{get;set;}

Now, All that is needed is to have the Objects implement the interface. Since they technically have already done so, they only need to be declared.

public class InterfacedTextBox: TextBox, ITextAndID {} 
public class InterfacedCheckBox: CheckBox, ITextAndID {}

And viola! Just replace your old TextBox and CheckBox with the new versions and then all you need to do is cast the new controls "AS" your new interface: ITextAndID as so!

var TheId = (ITextAndID)TheObject).ID;
var TheText = (ITextAndID)TheObject).Text;

Being able to access these properties through the interface, and being able to implement the interface with no actual code other than the declarations makes this a pure example of interfaces!

Sunday, March 1, 2009

Sudoku in Silverlight

You know how it is, you learn a skill (Programming in my case) because you see the results of others. Looking at the fruits of their labors, you say, "wow! I want to be able to do that." So you start learning, take some classes, read some books, maybe like me you enroll in the Computer Science program. If you get good, you may even get a job using your new found skill. But, did the learning of this skill lead you to the place you wanted to be, all those long years ago?

When I first started programming, it was to automate the games I was already playing. Then I moved into trying to replicate the types of games that I had played before on the computer. But as it usually happens, the real world got in the way. Instead of learning how to animate sprites, I had to learn how to connect to a database. Instead of graphics, I had to learn about algorithms.

Now, I'm not knocking my job and the work I do. I rarely go to "Work" since I get to indulge in my passion for programming every day. But, I feel this need to give more than lip service to the original reason that I got into the "Biz" in the first place.

Believe me, in 25 years the landscape of game programming has changed so much that I hardly recognize it! And, I've tried to keep my feet wet in the technology the entire time. The time when the ability to draw a digital stick figure and write a great game around it (Lode Runner) is long gone. When I first made up my mind to bite the bullet and truly try to learn game programming, in depth, the technology seemed so complicated that I almost quit.

But Rome was not built in a day and neither were any of my favorite games. Like I tell all of my junior programmers, "Start at the beginning, then just program each little piece until it is done”, I decided to start with the smallest bite I could “chew” and then just keep going. The first "Game" I wrote was a Sudoku generator with a Javascript back end. I Wrapped a website around it and launched it a couple of years ago.

Well, here is the thing about games, the are not all created equal. Sure Sudoku is a "Game" per se, but not really related to my true love, boardgames. So http://www.freedailygames.net languished for a few years without any upkeep. I even thought of just shutting it down, but according to Google analytics, I have a few very loyal customers. And, now with the new technology of Silverlight, I thought that updating my site with a Silverlight implementation of Sudoku would help me build my skills and give freedailygames.net a tech boost.

Well, here is my take on Sudoku in Silverlight.

And here is a zip file containing the entire Visual Studio 2008 Project.

Thursday, February 26, 2009

So finish something already!

Now most of the better programmers love to code. Most Professional programmers love a challenge. So, to play to these twin desires, a lot of us have hard drives littered with the five-to-fifteen minute test bed projects that we create as we tackle a programming challenge.

This post is not about those projects.

This post is about the three quarters written Pente game that has been languishing on your hard drive for three years or the redesign to your website that you can never seem to quite finish or cool little app that just needs that last bit of spit and polish before you can release it to the world. These are the projects this post is about.

And why are they not done? The challenge to create them in the first place was exciting! Why is the bloom gone from the rose?

I think that this is a critical flaw in the personality of most programmers (Myself included). We love the challenge at the start. The puzzle that needs solving. We may spend hours or days working out how to do a single coding trick that we needed at the time. We sweat blood trying to breath a form of life into our creations.

Then when we get to the equivalent of getting our creations through Junior High, we look down on our creations and say we'll finish it later. We've got this other idea that we want to work on right now. And, so the cycle repeats itself, over and over again.

But, why do we abandon our nearly completed creations? Some say that it is because the creation process is done and now we need to polish and primp our creation so that it is truly finished and this is not nearly as fun as the process of creation. That may be true, but are we just big adolescents then, chasing after a series of "Oh shinny!" objects, that once we catch them are not nearly as fulfilling as we thought? Or are we intellectually lazy and when we get to the parts we do not find as fun we wander off in search of new challenges?

Could it be how we are trained to code in the first place?

From the moment we start we are bombarded with code snippets on how to do this or that. Homework assignments are fragments that do this or that function, never a complete application. If we are ever given an assignment to write a complete application, it is a class long project and is given such grading weight that we are almost forced to understand that "A complete application is so hard, we need to make it a very substantial part of your grade".

I do not know the answer to my question for myself, let alone everyone else. But, I can tell you that the last little bit of getting finished software out the door is about as fun to me as doing the dishes after a fine meal. but, just like those dishes, if you do you work and finish what you start then it gets easier the next time. After a few iterations, you will find yourself cranking our completed projects like copies out a Xerox machine. And if you think the high from solving a problem is great, then you will love the feeling of having your software being used the world over.

So, have you finished something today?

Friday, February 20, 2009

When will I ever learn ....

I think that if the song Blowin' in The Wind was written today, it would have included in the lyrics:

How many times must man loose his code
Before he uses source control?

The answer, my friend, is blowin' in the wind
The answer is blowin' in the wind

Now I am a true fanatic when it comes to source control at work, but the moment I walk through the door at home, it all seems to leave me and I "just want to get it done" and not worry about source control.

Well, once again that laissez–faire attitude towards source control has bitten me again. No, nothing catistrophic, just that somehow I've lost 75% of the AI code I was writing for Switcheroo.


Maybe now I'll start using source control at home? A thousand times burned, forever shy?

Do not count on it, I just want to get it done.

Sunday, February 8, 2009

Fancy fonts in XAML (Silverlight and WPF)

Outline, Shadow, Embossed and Engraved text in XAML.

Here are a few quick and easy ways to spice of your text in XAML.

To use these tricks, you need to have the ability to exactly place the text. For that you need to use a Canvas Layout control.

<UserControl x:Class="SilverlightApplication2.Page"
Width="320" Height="200">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.ColumnDefinitions >
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<Button Margin="3">
<Canvas Width="800" Height="60">
<TextBlock FontSize="36"
Canvas.Top="2" Canvas.Left="10">Outline</TextBlock>
<TextBlock FontSize="36"
Canvas.Top="2" Canvas.Left="12">Outline</TextBlock>
<TextBlock FontSize="36"
Canvas.Top="4" Canvas.Left="10">Outline</TextBlock>
<TextBlock FontSize="36"
Canvas.Top="4" Canvas.Left="12">Outline</TextBlock>
<TextBlock FontSize="36"
Canvas.Top="3" Canvas.Left="11"
<Button Grid.Column="0" Grid.Row="1" Margin="3">
<Canvas Width="800" Height="60">
<TextBlock FontSize="36"
Canvas.Top="5" Canvas.Left="4"
<TextBlock FontSize="36"
Canvas.Top="3" Canvas.Left="2"
<Button Grid.Column="1" Grid.Row="0" Margin="3">
<Canvas Width="800" Height="60">
<TextBlock FontSize="36"
Canvas.Top="3" Canvas.Left="0"
<TextBlock FontSize="36"
Canvas.Top="5" Canvas.Left="2"
<TextBlock FontSize="36"
Canvas.Top="4" Canvas.Left="1"
<Button Grid.Column="1" Grid.Row="1" Margin="3">
<Canvas Width="800" Height="60">
<TextBlock FontSize="36"
Canvas.Top="5" Canvas.Left="3"
<TextBlock FontSize="36"
Canvas.Top="2" Canvas.Left="2"
<TextBlock FontSize="36"
Canvas.Top="4" Canvas.Left="4"

Sunday, February 1, 2009

My Five Minutes of Fame

Well, I've had my five minutes of fame. I submitted my Silverlight Tic Tac Toe project to the silverlight.net site. They posted it to their site on Tuesday.

Since then, the statistics on my blog have went crazy. I was seeing a net traffic load of about 15 hits per day (Yes, I know that is a pathetically low number, but since I've only been blogging for a few months, I thought that was a good start). But, since Tuesday I've averaged 150 hits per day.

The one thing that had disappointed me was the lack of comments from my visitors. Well, with over 800 hits on my Tic Tac Toe post, I only got two comments. Sigh. I guess I was just expecting too much.

The one thing the stats told me before I posted my Silverlight Tic Tac Toe game, was what people were interested enough in to seek me out. I learned that Counts in a substring, shuffling and Latin squares are by far the most popular things I'd blogged about. Now all my stats point to Silverlight.net.

Who knows what tomorrow may bring. I may finish that old magazine game, Switcheroo (The endgame AI is giving me fits!) or I may post some more "Old style" coding articles. What would you rather see more of?

*** And maybe a blatant call for comments will work :-) ***

Wednesday, January 21, 2009

Tic Tac Toe in Silverlight

When I first started looking Silverlight, I looked around for tutorials that focused on topics I find interesting. I have found that I typically learn better if I'm applying learning to topics for which I have a passion.

I love games and one of the simplest is Tic Tac Toe. I thought if I could find a tutorial on implementing Tic Tac Toe in Silverlight, it would not only teach the basics of Silverlight development but would also teach how to interact with graphics. Unfortunately I could not find such a tutorial.

I eventually waded my way through much less entertaining tutorials and got my programming feet wet with Silverlight. As a test of my learning I wrote a two player Tic Tac Toe game.

After finishing my first AI post on Rock/Paper/Scissors I started looking for my next AI project. Well I had that two player Silverlight game laying around, how about I write an AI opponent for it?

What could be easier?

Well a lot of things could be easier, like "Hello World", but once I get my teeth into a project I see it to the end. Well, first things first, how have others designed AI opponents for Tic Tac Toe? A quick google search proved that I was definitely not blazing an new trails here. I found tons of examples for just about every type of AI for Tic Tac Toe.

But this webpage gives a simple set of patterns for matching. Best of all, they could be implemented using Regular Expressions!

So, here is my Silverlight AI Tic Tac Toe game where the pattern matching AI is implemented using Regular Expressions.

And here is a zip file containing the entire Visual Studio 2008 Project.

Monday, January 19, 2009

Programmers must continue to stand on the shoulders of giants

Many of the greatest thinkers credit their accomplishments to those that came before them by stating the old saying that even a dwarf can see farther than a giant when the dwarf stands on the shoulder of the giant. Or, in other words, they came to their breakthroughs by understanding the research and works created by notable thinkers of the past.

How can that help modern programmers? Simple, when was the last time you read a computer book or magazine? It does not matter what the subject was, just the fact you read it added a little bit to your knowledge and experience. It is amazing what great little tidbits you can find to enhance your abilities.

For me, that two that come to mind the fastest are from Programming Pearls by Jon Bentley, first published in 1986 and Expert C Programming: Deep C Secrets by Peter Van Der Linden first published in 1994.

From Programming Pearls, I learned the lesson that a senior developer should never answer the question that he was asked, but instead answer the base need that spawned the question. In Programming Pearls, the programmer asked how to do a disk-based merge sort. Now, yes I know that coding things like that went out of style a looooong time ago, but the underlying process that the author used to help the programmer has stayed with me ever since. This is because the author did not show the programmer how to implement the disk-based merge sort, but instead learned what the base problem the sort was supposed to fix and with his greater programming and analyst experience came up with a much faster and more elegant solution. No, I’m not going to tell you want the solution was, go read the book!

From Expert C Programming: Deep C Secrets, I learned a very simple programming principle: look at a problem from both directions. Where from one direction, a problem may include complex tracking code, worked the other way, the problem may be quite simple to code.

What does that exactly mean? Let us look at an example:

Say you need to build a comma delimited list of numbers from some input. You could say “I need a comma after every number except the last”. This is the normal view and leads to either adding a comma after every entry and then removing the last one once you have exited the loop, or checking in every iteration if its time it is the last element so that you do not add the comma.

But if you look at it from the other end and say “I need a comma before every number except the first”. Once stated this way, the problem is simple. It’s much easier to code a beginning edge case than an ending edge case.

The point of this post was not just to share these two fun little facts, but to show that we, as senior level developers, and those that wish to become senior level developers need to continue reading and learning. As long as we do that, the giants that we stand on will keep getting taller.

Wednesday, January 14, 2009

The simplest AI in C#

Creating board games on the computer is easy, creating an opponent to play the game against is hard.

A lot of us programmers out there are also board game enthusiasts. We would like nothing better than to sit down in front of the computer and spend a few hours out maneuvering some truly diabolical AI opponents. Whether it’s crushing the Axis in Axis and Allies, dominating Europe in Diplomacy or simply enjoying a quick game of world conquest in Risk, we get to enjoy our favorite board games without the need to coordinate a date and time with up to five or six of your friends. Even when you can take on each other online, sometimes getting everyone together is harder than winning the games you wish to play.

Well with a good AI, all your games become playable by yourself and with a great AI, they become obsessive as you try to, at first barley hold your own and later to finally dominate these awesome challengers. Yet, how are these opponents created? Other than creating a completely random opponent, writing an AI to play a board game at a high level is one of the hardest things in programming you could do.

Which brings me to my point: I’m not going to show you how to create a diabolical AI opponent. I’m not even going to say if I even know how to. What I want to show you though, is how to take that first step in writing AI’s, by creating what could possibly be the simplest AI opponent ever … for the game of “Rock, paper and scissors”.

There are many types of AI opponents, but in “Rock, paper and scissors” the only type of opponent is one that tries to predict his opponent’s next move. So let’s create a predictive AI.

What is the one piece of data that a predictive AI needs to calculate a decision? His opponents’ prior moves. So, as play of “Rock, paper and scissors” continues, we will need to accumulate the human player’s prior moves. The easiest way to do that is to hold them in a string, each character (‘R’, ‘P’ or ‘S’) representing a move.

To keep it simple, my AI will look for three move patterns. It will take the last two moves off the end of the string and add each of the three possible moves, in turn, on the end and do a string search to find how many times the human opponent played the same three move pattern previously. The IA will assume that the pattern with the highest count will be the one the human plays and will choose the move to beat it. If there was a tie (Even if that it is a tie of zero count for all three possible patterns) a move is picked randomly among the tied choices. Just to through a bit of confusion in, 10% of the time, the AI’s move will be completely random.

Now, this AI is by no means unbeatable, but playing against it in a race for the first to win 100 games, it is a very tough opponent, just like AI opponents should be.

The complete code for a console application implementing the “Rock, paper and scissors” AI can be downloaded here.

Monday, January 5, 2009

C# Yields a better Fibonacci Sequence

In the title of this blog entry I've done a bit of punning. This quick blog entry is about an alternate usage of the Yield command and how, for example, it can help build a better FibonacciSequence() function.

With the addition of the Yield command, we can now create looping functions that return a value for each iteration. Ever need to walk through a sequence and perform some fuction for each element? Now it is as easy as pie!

private IEnumerable FibonacciSequence(int MaxIterations)
decimal i = 0;
decimal j = 1;

yield return j;

if (MaxIterations==0) yield break;

var temp = (ulong) j;
j = temp+i;
i = temp;

private IEnumerable FibonacciSequence()
return FibonacciSequence(49);

Thursday, January 1, 2009

C# - Counting the number of occurrences of a substring - Take two

In my last post, I stated that I knew of only one way to find a count of all the substrings within a string without looping through the string. Well, a co-worker pointed out to me the other day that I had shown a non-looping way to count all the substrings within a string when I gave a class on Regular Expressions.

That is true. A very simple Regular expression:

new Regex(mySubString).Matches(myString).Count

But, that simple line of code is not the reason for this post. I've found an even deeper issue, and it all comes down to how you define the problem (doesn't it always).

Lets say that my string is "BOBOBOB"

How many instances of the substring "BOB" is in "BOBOBOB"? 2 or 3?

My way in the previous post and the regular expression both agree, the number is 2.

But, say you are writing a game and you are using a string to store previous moves. Each move can have only two choices: a 0 or a 1. So after a number of moves, the storage string could look like this "0111110010100111110110111101".

Now, how many times did the player choose to play a 1 after playing a 1 the prior two moves, i.e. a "111"? If you did a substring search, you would get a 3. But if you count the number of times "111" appear including overlap, the number is much higher: 8.

So, an AI routine that was based on prior moves would need to find all combinations of "111" even if one set is partially contained within another.

So, here is my LOOP that counts the number of substrings within a string, even if the substring is partially contained within another substring.

for (var i = 0; i <= myString.Length - mySubString.Length; i++)
if (myString.Substring(i, mySubString.Length) == mySubString)