Channel 9 - Entries tagged with PuzzleMicrosofthttp://mschnlnine.vo.llnwd.net/d1/Dev/App_Themes/C9/images/feedimage.pngChannel 9 - Entries tagged with Puzzlehttp://channel9.msdn.com/Tags/puzzle
Channel 9 keeps you up to date with the latest news and behind the scenes info from Microsoft that developers love to keep up with. From LINQ to SilverLight – Watch videos and hear about all the cool technologies coming and the people behind them.http://channel9.msdn.com/Tags/puzzle
enTue, 03 Mar 2015 20:47:39 GMTTue, 03 Mar 2015 20:47:39 GMTRev910125New from FUSE: Team Crossword BetaThe team from FUSE Labs (the folks behind Outlook Social Connector, Spindex, Kodu, Emporia, Bing Twitter Maps and Docs) have just launched a new project called Team Crossword. This application isn’t a major release like Docs.com, the Facebook-enabled Microsoft Office service, but is rather just a simple but fun social game. At TeamCrossword.com, you and your friends can solve crossword puzzles together online. The site also tracks the fastest time a team took to solve a puzzle, so you can see how you and your friends compare.

There’s a new puzzle available every day via the website. You can get started here by signing in with Facebook and inviting your Facebook friends to join.

]]>http://channel9.msdn.com/Blogs/coolstuff/New-from-FUSE-Team-Crossword-Beta The team from FUSE Labs (the folks behind Outlook Social Connector, Spindex, Kodu, Emporia, Bing Twitter Maps and Docs) have just launched a new project called Team Crossword. This application isn’t a major release like Docs.com, the Facebook-enabled Microsoft Office service, but is rather just a simple but fun social game. At TeamCrossword.com, you and your friends can solve crossword puzzles together online. The site also tracks the fastest time a team took to solve a puzzle, so you can see how you and your friends compare. There’s a new puzzle available every day via the website. You can get started here by signing in with Facebook and inviting your Facebook friends to join. (Thanks Steve Clayton for pointing this out!) http://channel9.msdn.com/Blogs/coolstuff/New-from-FUSE-Team-Crossword-Beta
Tue, 31 Aug 2010 08:40:00 GMThttp://channel9.msdn.com/Blogs/coolstuff/New-from-FUSE-Team-Crossword-BetaSarah PerezSarah Perez0http://channel9.msdn.com/Blogs/coolstuff/New-from-FUSE-Team-Crossword-Beta/RSSFacebookPuzzlefacebook appBuilding Multiplayer Texas Holdem Poker For The ZuneHave
you ever been interested in creating a game that harnesses XNA's powerful network library to create multiplayer experiences for the Zune device?

The Zune firmware version 3.1 brought us a professionally built incarnation of Texas Holdem that supports network play. Understanding how to send and receive data with the Zune can be a little daunting at first, but once you understand the pattern, it's
easy.

To build out the entire game, you probably need about a week, but you can build some simpler examples in far less time.

This is an earlier project from before the release of my
Zune game development book. Accordingly, some of the code samples you see in this article may be inconsistent with what you find in the download. The code in the article is the “correct” way to do things. The code in the download is still a work in progress.

The Workflow

Developing multiplayer games for the Zune is interesting because you have to deploy to each device individually. Once you have a build that works for you, it's helpful to run-deploy (Control+F5) to one device, leave it running there, and then plug in the
other Zune and debug-deploy (F5) to it. This way you have one debuggable instance of the game running. Make sure to set the appropriate Zune device as the default in the XNA Game Studio Device Center (accessible from the Tools menu).

Starting A Network Session

Because the Zunes connect over an ad-hoc, peer-to-peer connection rather than through an access point, you will have to designate one Zune as the host device. The host is usually determined to be the one that creates a new game. Therefore, all Zunes that
join the host's network session are simply peers. The difference between the host and the peers is that the host usually maintains the game state on top of executing the game as well, because the game data has to be centralized somewhere. Keep that in mind,
because if one Zune is doing substantially more processing, it can lag behind and mess up your network session. Also, remember that all Zunes are running the exact same copy of the game, so the game must support both host and peer scenarios.

Create / Join / Lobby Model

Most peer-to-peer connected games allow a user to create or join a game. After doing so, the player is funneled into an area called the Lobby where they can specify their readiness. When all players are ready, the host can start the game. Some of this functionality
is provided directly by the XNA Framework's Net and GamerServices libraries.

I normally create three separate screens based on the
Network Game State Management sample from the Creators Club website. The first is the Create screen, which looks exactly like a lobby. It starts up a network session and waits for players to join and become ready. The code to create a network session looks
like this (note that I have employed some abstraction to make my code a little more cohesive):

All Zune network sessions are of the type SystemLink, much like LAN-networked Xbox consoles. The ‘1' parameter specifies the number of local players – of course, on a Zune, there can only be one.

This line of code sets the Session property to a newly created network session. The Join screen, running on another Zune, will find this session asynchronously as an available network session and attempt to join it. The first step is to enumerate available
network sessions:

This code looks for SystemLink sessions and calls the callback method SessionsFoundCallback when the operation completes (successfully or unsuccessfully). If sessions are found, an event is fired. Other screens can subscribe to this event and transition
to other screens or do other processing with the network session.

When all players are ready and the host presses the middle button, the network session's StartGame() method is called, which will cause all connected peers to receive a GameStarted event. This loads up the playing screen.

That's basically how to connect up two Zunes in a network session. See my
book for a much more detailed explanation.

Dealing With Cards

As Poker is a card game, you might want to develop a testable, standalone library that you can use not only to house your objects, but also to write out all the intense logic required for a game like poker. The task of determining what a player's best hand
is out of seven cards (and whether it beats another player's hand) is more in-depth than you might expect.

An easy way to go about this is to create a Zune game library. I called mine CardLib. CardLib has objects such as these:

Card which has a suit, a value, some comparers and some utility methods)

Deck, which has a collection of cards and methods like Shuffle, ResetDeck, etc.

Dealer, which has a deck, a list of the five community cards, and methods like Shuffle, DealCard, Burn, DealFlop, DealTurn, etc.

HoldemHand, which contains all of the logic for determining what a hand is (always 7 cards)

BestHand, which takes a HoldemHand and determines what the best possible hand is within that hand

There is a ton of similar and even more disgusting logic to peruse in the HoldemHand.cs file in the region entitled “Poker Logic Fun Times.” This logic covers every possible poker hand and could probably be refactored to be way more elegant.

When it comes time to evaluate the winner, each player's best hand is determined and they are evaluated against each other to determine the winner. This code returns a list of WinnerInfo objects, which returns the player info and a list of the cards they
won with.

Drawing Cards On The Screen

Rather than have 52 different sprites that represent each possible card, I just made my own sheet of Zune-sized playing cards. Horizontally, they are ordered by value (1-13) and vertically they are ordered by suit (both alphabetically and corresponding to
the numeric value of the Suit enumeration in the project, 1-4).

When a specific card is requested to be drawn, a formula is used to calculate the source rectangle from this larger image. This is very similar to how fonts worked before spritefonts were introduced into XNA. This allows us to strip out the graphic of a
specific card and draw it onscreen at some other location.

Managing Network Data

One thing that increases the complexity of this game (in no small way) is the management of network data. First of all, the host's actions are a superset of the peer's actions (a host is also a peer, but it also has to manage the game and network state).
For example, when a peer decides to bet, it has to send a message to the host saying “I would like to bet,” and then the host will process that message and relay it to the other peers. The host is also responsible for managing whose turn it is and determining
who the winner is. Theoretically, you could do a lot of this with every peer acting equally but it feels safer to me to have the host responsible for important activities like dealing cards. In fact, the host has to be the only one who can deal cards, because
if each client maintained its own deck, it would be randomized for every peer when the deck is shuffled.

How Data Is Sent And Received

I will usually create a static class called NetworkMessageSender that is responsible for sending various messages. I keep an enumeration of type byte that holds the possible network messages.

I always send the byte indicating the message type first, so that when the peer receives a byte, it knows how to respond. For example, if the peer receives a CardDealt message, it can pop off a string and a card from the incoming packets. If the card is
not intended for the peer, it can simply discard the message.

Data you want to send is written to a packet writer object. When the data is ready to be sent, you call the SendData method of the LocalGamer object. Depending on how important packet receipt is, you can specify the type of transmission. I use ReliableInOrder
during poker because network data is exchanged relatively infrequently. Although there is only one local network gamer, you can use a foreach loop to ensure this code will work on other platforms.

Specific chunks of data are then sent using various static methods. Each piece of information is written sequentially. The card is serialized into a string format before being sent. The following chunk of code is used to send a card to a player.

There is a whole bunch of similar code that underlies how the game executes. When a message needs to be sent, the NetworkMessageSender class is used. To determine what happens when a message is received, we look at that ginormous switch statement that gets
called in the screen update loop.

Remember that the host is also a peer and it will receive the very same messages it sends (unless you specify otherwise). Be careful not to double-process messages if they are sent by the host. In some cases you will need to check that the current device
is or is not the host. In the sample download, this is achieved just by checking a Boolean value that is set early on in the game.

Conclusion

Building Poker for the Zune, from the ground up, is no small feat! Networked Zune games are far simpler when you have a much more limited set of possible data and messages that could be sent. For example, networked Pong, Battleship or Tetris would be pretty
easy compared to poker. Turn-based games on the Zune also provide an interesting challenge in terms of what happens when a Zune drops from the network session.

This is just a small dip into networked Zune game development. For a deep dive, check out my book,
Zune Game Development using XNA 3.0, also available on
Apress.com as an eBook. The final chapter is a sprawling 120 pages covering how to build Crazy Eights for the Zune from the ground up.

About The Author

Dan Waters is an Academic Developer Evangelist at Microsoft, based in Tampa, FL. When he's not out showing the latest and greatest MS technology to students and faculty, he's spending time with his wife and young daughter or rocking out on one of his (far
too numerous) guitars. Follow Dan on
Twitter or check out his blog.

]]>http://channel9.msdn.com/coding4fun/articles/Building-Multiplayer-Texas-Holdem-Poker-For-The-Zune
Have
you ever been interested in creating a game that harnesses XNA's powerful network library to create multiplayer experiences for the Zune device?
The Zune firmware version 3.1 brought us a professionally built incarnation of Texas Holdem that supports network play. Understanding how to send and receive data with the Zune can be a little daunting at first, but once you understand the pattern, it's
easy.
To build out the entire game, you probably need about a week, but you can build some simpler examples in far less time.
This is an earlier project from before the release of my
Zune game development book. Accordingly, some of the code samples you see in this article may be inconsistent with what you find in the download. The code in the article is the “correct” way to do things. The code in the download is still a work in progress.
The Workflow
Developing multiplayer games for the Zune is interesting because you have to deploy to each device individually. Once you have a build that works for you, it's helpful to run-deploy (Control&#43;F5) to one device, leave it running there, and then plug in the
other Zune and debug-deploy (F5) to it. This way you have one debuggable instance of the game running. Make sure to set the appropriate Zune device as the default in the XNA Game Studio Device Center (accessible from the Tools menu).
Starting A Network Session
Because the Zunes connect over an ad-hoc, peer-to-peer connection rather than through an access point, you will have to designate one Zune as the host device. The host is usually determined to be the one that creates a new game. Therefore, all Zunes that
join the host's network session are simply peers. The difference between the host and the peers is that the host usually maintains the game state on top of executing the game as well, because the game data has to be centralized somewhere. Keep that in mind,
because if one Zune is doing substantially more processing, it can lag behind and mess up youhttp://channel9.msdn.com/coding4fun/articles/Building-Multiplayer-Texas-Holdem-Poker-For-The-Zune
Tue, 05 May 2009 16:06:00 GMThttp://channel9.msdn.com/coding4fun/articles/Building-Multiplayer-Texas-Holdem-Poker-For-The-ZuneDan WatersDan Waters2http://channel9.msdn.com/coding4fun/articles/Building-Multiplayer-Texas-Holdem-Poker-For-The-Zune/RSSGamingHardwarePuzzlecard and board gamesSilverlight Dynamic Video PuzzleMy blog title says it all, Monkey see, Monkey Build. I saw Microsoft Surface's video puzzle and I needed to build it. I took this opportunity to play with Microsoft's new technology,
Silverlight and build my own puzzle game. I couldn't find anything out on the Internet regarding dynamic video creation with Silverlight so I took it upon myself to do this. The screen shots in this demo will be in c#,
however, everything should hold true for VB.

Fixed the Silverlight.Js, used the new version that is included with the 1.1 Refresh SDK so the proper installer will prompt now. Downloads are corrected also too.

6/20/2008 - Verified the solution works with Silverlight 2.0beta2.

Spec's, Requirements and headaches

So I had a few mental requirements for the application to "entertain" myself.

Be able to rotate the video blocks

Be able to translate

Be able to increase the difficulty of the puzzle on the fly.

Zero interaction with the keyboard

Simple, right? You want to see a demo too see some awesomeness? No problem,
head over to my site and see it in person.

Microsoft Surface Video Puzzle

Clint's Silverlight Video Puzzle

To the Internet Batman!

To help save time building this, I first when out and attempting to see if anything has been done anything close to this before. I found

Also I need 2 small controls which I found out are in the Silverlight SDK. I needed horizontal slider controls for this app. While I know a text box control would have worked just as well, see requirement 4.

On the Silverlight community site, there is also a very nice demo showing the
photo application in Surface with source code. This is where I learned the majority of what I needed. This application was very close to where I needed to go with mine. However, while it was close, it wasn't perfect. Parts of the photo application code
are pretty much copied. This isn't the best way of doing this, but it is one way of doing it.

Toolbelt: check, Keyboard: check, Band-aids: check

So on to building it. I first started off with a new project and some XAML.

After clicking "OK", I get a very nice blank project.

We'll want to add an additional XAML object for the video blocks. Go to "Project -> Add New Item", select Silverlight Page, name it "VideoBlock.xaml" and click "OK".

So now we have everything we need for the most part, grab any video you have, if you don't have one, go to a site like
TeamXbox and grab one from there. I used Windows Movie Maker and grabbed a snippet from The Office (best show ever).

In addition to all these files, we need to add in a reference to the Silverlight SDK to get a hold of the Slider controls. Go to "Project -> Add Reference", and add in the
Silverlight.Samples.Controls.dll.

While we have a reference in the application, we still need the XAML to know about this also. So we'll add a line to link this in. It is the xmlns line that I bolded, XML name space, real clever, eh? We'll also change the background color to a gray so
we can see it more easy.

Silverlight 101

So in Silverlight, you have brushes which can "painted" onto objects. One of these brushes is called the VideoBrush which I'll talk about later on. For playing videos, one would use the
MediaElement. Lets add this to our canvas.

<MediaElementx:Name="media"Source="theOffice.wmv"/>

Now if we run the application at this point, we'll get the video playing. Lets sit back with some popcorn and enjoy this victory for a second or two. Now that we have this, lets hide it since this isn't what we want. We do that by adding in an XML attribute
Opacity and setting it to 0.

On top of that element, lets add on some TextBlock elements and the sliders.

Video as Paint?

So now that we have that small part done, lets get into more of the nitty gritty with video. As I said earlier, you'll use a
VideoBrush to paint on the video.

We'll use the brush as the Fill for the rectangle we'll be using to show off the clip of the video we want.

Still not moving? Try explosives?

While doing this project, I discovered an interesting thing when using the VideoBrush and dynamically appending items on. Having items in the XAML rather than programmatically creating everything caused it not to work properly. Nothing would appear.

Throwback to how UI's use to be done

The XAML for this is a simplified version of the Surface demo Photo.XAML. You have a 3 Rectangles, 1 for the video, 1 for translation and 1 for rotation. Simple, no? Doing all this by hand gets a bit annoying since you need to nest everything properly.

Here is the more interesting VideoBrush code. You need the name from the
MediaElement along with the how much of an offset you want the video. Since your moving the "camera" in, this value needs to be negative.

There is a mouse on my object!

So now we have our video block element prepped and ready. There are additional events added in, but they are fairly boiler plate. When looking at this code, you see I pass in a delegate, a function pointer if you will. Why do I do this? This is how the
mouse position is calculated. I bet this could be redone better, but this is how I did it. The parent element, the canvas, has the mouse position I need to calculate proper translation and rotation, however, mouse events on the VideoBlock object will give
me the mouse position only on that element. So I may be at point 150, 150 on the screen, on the VideoBlock object, I'm actually at 10,15.

Additionally, this approach allows me to move the VideoBlock to the top of the objects. Once again, this could be done other ways, this is how I chose to do it.

So on all my mouse related all boils down to doing the exact same function. Since events are bubbled, a mouse movement on a VideoBlock is also a mouse movement on the root canvas.

You built a car out of all these parts?

So we move back from VideoBlock.xaml.cs to Page.xaml.cs

We've created our primary object for painting video, lets populate it. First, how do we know how big the media file is? With the
MediaOpened event! And we'll restart the video with the
MediaEnded event.

So now that we have the media loaded, we can use the media.NaturalVideoWidth and media.NaturalVideoHeight properties to find out exactly how big the video is! I have a function that is fired off when the page is first loaded or a slider value has changed.
This is how we chop it up.

Wrapping it up

So as you can see, Silverlight is pretty powerful once you figure out how to tame it. I used example base code and modified it to suit my own needs to dynamically alter a video in real time. There are a few code tweaks that could happen to improve this
code and I'm betting with some additional effort, one could remove the delegate. In addition, you could add in edge detection code and a timer to make this into a true video puzzle game. This was a pet project I worked on while I was at the airport. This
demo can be downgraded to Silverlight 1.0 also. I don't believe anything I did was really Silverlight 1.1 (now 2.0) only.

Clint's Bio:

Clint is an academic developer evangelist for Microsoft. His two primary development languages are C# and JavaScript. He has built a
Disco Dance Floor too! In his off time, he whips up other random weird projects and does twenty something activities with his friends. His next two big projects are an automated bartender and a skateboard segway. Clint's blog is
betterthaneveryone.com and can be emailed at
crutkas@microsoft.com if you have any question.

]]>http://channel9.msdn.com/coding4fun/articles/Silverlight-Dynamic-Video-Puzzle
My blog title says it all, Monkey see, Monkey Build. I saw Microsoft Surface's video puzzle and I needed to build it. I took this opportunity to play with Microsoft's new technology,
Silverlight and build my own puzzle game. I couldn't find anything out on the Internet regarding dynamic video creation with Silverlight so I took it upon myself to do this. The screen shots in this demo will be in c#,
however, everything should hold true for VB.
Clint Rutkas - Academic Developer Evangelist - Microsoft
Monkey see, Monkey Build
Difficulty: Intermediate
Time Required: 6-10 hours
Cost: Free
Software: Visual Studio Express,
Silverlight SDK and Runtime for
1.1 2.0 beta2
Download: Download c# -
Download VB Updated to Silverlight 2.0 Beta -
Download c#
Updates:
Fixed the Silverlight.Js, used the new version that is included with the 1.1 Refresh SDK so the proper installer will prompt now. Downloads are corrected also too.
6/20/2008 - Verified the solution works with Silverlight 2.0beta2.
Spec's, Requirements and headaches
So I had a few mental requirements for the application to &quot;entertain&quot; myself.
Be able to rotate the video blocks Be able to translate Be able to increase the difficulty of the puzzle on the fly. Zero interaction with the keyboard
Simple, right? You want to see a demo too see some awesomeness? No problem,
head over to my site and see it in person.
Microsoft Surface Video Puzzle
Clint's Silverlight Video Puzzle
To the Internet Batman!
To help save time building this, I first when out and attempting to see if anything has been done anything close to this before. I found
Also I need 2 small controls which I found out are in the Silverlight SDK. I needed horizontal slider controls for this app. While I know a text box control would have worked just as well, see requirement 4.
On the Silverlight community site, there is also a very nice demo showing the
photo application in Surface with source code. This is where Ihttp://channel9.msdn.com/coding4fun/articles/Silverlight-Dynamic-Video-Puzzle
Tue, 22 Jan 2008 16:02:00 GMThttp://channel9.msdn.com/coding4fun/articles/Silverlight-Dynamic-Video-PuzzleClint Rutkas Clint Rutkas 5http://channel9.msdn.com/coding4fun/articles/Silverlight-Dynamic-Video-Puzzle/RSSMediaSilverlightWebPuzzleMash Upweb miscellaneousZero Gravity: Silverlight based puzzle gameZero Gravity is different. Zero Gravity isn't flashed based, it runs on Silverlight. I spoke with the guys from Terralever who set out to prove that Silverlight is certainly a worthy platform for this type of game and talked about some of the difficulties and successes involved in the games development. So, how do you play? Well you put your thinking cap on, try to get Lt. Bennett home via his spaceship and watch this clip for the details. ]]>http://channel9.msdn.com/Blogs/LauraFoy/Zero-Gravity-Silverlight-based-puzzle-gameYou've all played these web browser &quot;twitch&quot; games before when you should be actually working- but wait! Well Zero Gravity is different. Zero Gravity isn't flashed based, it runs on Silverlight. I spoke with the guys from Terralever who set out to prove that Silverlight is certainly a worthy platform for this type of game and talked about some of the difficulties and successes involved in the games development. So, how do you play? Well you put your thinking cap on, try to get Lt. Bennett home via his spaceship and watch this clip for the details.552http://channel9.msdn.com/Blogs/LauraFoy/Zero-Gravity-Silverlight-based-puzzle-game
Fri, 06 Jul 2007 16:36:00 GMThttp://channel9.msdn.com/Blogs/LauraFoy/Zero-Gravity-Silverlight-based-puzzle-gameLaura FoyLaura Foy6http://channel9.msdn.com/Blogs/LauraFoy/Zero-Gravity-Silverlight-based-puzzle-game/RSSGamesSilverlightSeattleZero GravityPuzzleCreating an ASP.NET Hangman Control

In this post, Stephen Walther shows you how to create an ASP.NET Hangman control. This control contains embedded images, sounds, XML, and Javascript.

This month, we create an ASP.NET Hangman control. Our control will render all of the necessary images, sounds, and scripts to create a richly interactive hangman game (see Figure 1). Our control will work with the most recent versions of Microsoft Internet
Explorer, Mozilla Firefox, and Opera.

We tackle several advanced features of the ASP.NET 2.0 framework in this article. You learn how to build custom controls that take advantage of Javascript. You also learn how to embed resources such as images, sound, and XML in an assembly. Finally, you
learn how to write cross-browser compatible Javascript.

Using the Hangman Control

If you are anxious to start playing hangman, you can download the ZIP file that accompanies this article. Click the Download link above. The ZIP file contains two projects: the Visual Basic and the C# versions of the Hangman control. If you are interested
in viewing or modifying the source code for the Hangman control, you can open the Visual Basic version with Microsoft Visual Basic 2005 Express Edition and the C# version with Microsoft C# 2005 Express Edition.

Here's how you use the Hangman control. Launch Visual Web Developer 2005 Express Edition and create a new website (select the menu option File, New Web Site). Next, add the control to your Toolbox by right-clicking beneath the General tab on your Toolbox
and selecting the option Choose Items (see Figure 2). You must have a Web Form Page open in order to modify the Toolbox.

Next, under the .NET Framework Components tab, click the Browse button and browse to the Hangman assembly (dll file). There is both a VB.NET and C# version of this file (it doesn't matter which version you use since you can use a control written in C# with
a VB.NET website and a control written in VB.NET with a C# website). The files are located in the following subfolders:

VB\Hangman\bin\Release\Hangman.dll

CS\Hangman\bin\Release\Hangman.dll

Click OK a couple of times to close the dialog boxes and the Hangman control should now appear on your Toolbox.

After you have added to the Hangman control to your Toolbox, you can add the control to any page simply by dragging the control onto a Web Form Page in either Design or Source view. That's all there is to adding this control to a page.

The Hangman control includes a default set of words included in an embedded XML file (these words are intended to be hard). If you prefer, you can associate a custom list of words with the Hangman control by assigning the path of an XML file to the control's
WordsUrl property. The XML file should have the following format:

<words>

<word>baby</word>

<word>easy</word>

</words>

The file can contain as many words as you please.

Creating a Custom Web Control

The Hangman control is implemented as a custom ASP.NET Web Control. In other words, the control is a class that derives from the base System.Web.UI.WebControls.WebControl class. The Hangman class overrides one method of the base class: the OnPreRender()
method.

The Hangman control's OnPreRender() method loads the XML, Javascript, sound, and image files. All of these resources are loaded by using the Page.ClientScript.GetWebResourceUrl() method to retrieve a valid URL for the embedded resource.

Embedding Images, Sounds, XML, and Javascript

The Hangman control includes embedded image, sound, XML, and Javascript files. These resources are embedded in the same assembly (dll) as the control so that the control can be distributed with a single assembly.

There are three steps required for embedding a resource in an assembly:

1) Set the Build Action for the resource to the value Embedded Resource. You set the Build Action for a file by selecting the file, opening the Properties Window, and modifying the Build Action property.

2) Add a WebResource attribute to the AssemblyInfo file for each embedded resource. When working with Microsoft Visual Basic 2005 Express Edition, select the menu option Project, Show All Files and expand the My Project folder in the Solution Explorer Window
to view the AssemblyInfo file. When working with Microsoft C# 2005 Express Edition, expand the Properties folder to view the AssemblyInfo file. You need to add the following attribute to embed an image resource named MyImage.gif:

VB.NET

<Assembly: WebResource("ProjectNamespace.MyImage.gif", "image/gif")>

C#

[Assembly: WebResource("ProjectNamespace.MyImage.gif", "image/gif")]

By default, the ProjectNamespace will be the same as your project name. In the case of the Hangman project, the project namespace is Hangman.

3) Finally, in your code, you can retrieve a URL to an embedded resource by using the Page.ClientScript.GetWebResourceUrl() method. This method accepts two parameters: a type and a parameter name. Typically, you will pass the type of the current class and
the name of the embedded resource. For example, you would use the following line of code to get the URL to an image named MyImage.gif located in the Hangman project:

Be aware that all resource names are case-sensitive -- even in the case of VB.NET. Make sure that you refer to the name of the resource in the same way with the file name, attribute, and GetWebResourceUrl() method.

Cross-Browser Javascript

All of the logic of the Hangman game is implemented in the Hangman.js Javascript file. When the control loads, the Javascript initializeGame() function is called and all of the game elements are created.

When you click a letter, the selectLetter() function is called. If a matching letter is found, the display of matching letters is updated. If a matching letter is not found, the badGuessCount variable is updated and the image of the hangman is updated as
well.

If you win a game, the doWin() function is called and if you lose a game the doLose() function is called. Both functions play a sound and both functions display a link that enables you to restart the game.

All of the Javascript was written in a cross-browser compatible way. The Javascript code works with Microsoft Internet Explorer, Mozilla Firefox, and Opera. Therefore, the Hangman control works with all three browsers.

Conclusion

The biggest hurdle that I encountered while writing this control was getting the embedded resources to work. Once I resolved the namespace issues and got all of the case-sensitivity issues under control, everything worked out. I was very happy that I was
able to get all of the resource (including the XML file with the list of words) embedded into one control.

]]>http://channel9.msdn.com/coding4fun/articles/Creating-an-ASPNET-Hangman-Control
In this post, Stephen Walther shows you how to create an ASP.NET Hangman control. This control contains embedded images, sounds, XML, and Javascript.
Stephen Walther
Steve's Blog
Difficulty: Easy
Time Required:
Less than 1 hour
Cost: Free
Software: Visual Basic or Visual C# Express Editions,Visual Web Developer Express,
Hardware:
Download: Download
This month, we create an ASP.NET Hangman control. Our control will render all of the necessary images, sounds, and scripts to create a richly interactive hangman game (see Figure 1). Our control will work with the most recent versions of Microsoft Internet
Explorer, Mozilla Firefox, and Opera.
We tackle several advanced features of the ASP.NET 2.0 framework in this article. You learn how to build custom controls that take advantage of Javascript. You also learn how to embed resources such as images, sound, and XML in an assembly. Finally, you
learn how to write cross-browser compatible Javascript.
Using the Hangman Control
If you are anxious to start playing hangman, you can download the ZIP file that accompanies this article. Click the Download link above. The ZIP file contains two projects: the Visual Basic and the C# versions of the Hangman control. If you are interested
in viewing or modifying the source code for the Hangman control, you can open the Visual Basic version with Microsoft Visual Basic 2005 Express Edition and the C# version with Microsoft C# 2005 Express Edition.
Here's how you use the Hangman control. Launch Visual Web Developer 2005 Express Edition and create a new website (select the menu option File, New Web Site). Next, add the control to your Toolbox by right-clicking beneath the General tab on your Toolbox
and selecting the option Choose Items (see Figure 2). You must have a Web Form Page open in order to modify the Toolbox.
Next, under the .NET Framework Components tab, click the Browse button and browse to the Hangman assembly (dll file). There is both a VBhttp://channel9.msdn.com/coding4fun/articles/Creating-an-ASPNET-Hangman-Control
Sun, 25 Feb 2007 04:50:59 GMThttp://channel9.msdn.com/coding4fun/articles/Creating-an-ASPNET-Hangman-ControlStephen WaltherStephen Walther18http://channel9.msdn.com/coding4fun/articles/Creating-an-ASPNET-Hangman-Control/RSSWebPuzzleBuilding a WPF Sudoku Game: Part 5 - The AI Battle: Loading and Comparing AI Plug-ins

Building Sudoku using Windows Presentation Foundation and XAML, Microsoft's new declarative programming language. This is the 5th article from a series of 5 articles and focusses on loading and comparing AI Plug-ins.

Note: This article has been updated to work and compile with the RTM version of the Windows SDK.

Welcome to the fifth and final part of my Windows Presentation Foundation tutorial! In this tutorial we'll be wrapping up our Sudoku game by adding support for comparing multiple plug-ins, multiple threads, new notification messages, and a cool databound
graph control. First, let's take a look at the new interface we are trying to build:

On the left, there is a list of all the installed plug-ins, in the middle, our graphing control, and on the right the details for the current plug-in. To get this working we first need a way to enumerate all the plug-ins available to the app. The simplest
way of doing this is to dump all the .dll files into a directory, which I've called “Solvers”. It's pretty simple to get a list of the assemblies in the folder, using the directory class:

We also need some other groundwork code to accept the new plug-in folder. First, we need to define that our application can load assemblies from a folder other than its base (where the .exe is) and the system folders. We do this by defining an app.config.
Select the SudokuFX project, right click and select “Add new item…” then “Application Configuration File”. This file needs to be modified to specify the subdirectory as a valid assembly location:

Finally, a simple datatemplate needs to be added to the listbox to display the Name property of the object, but you should be a pro at that by now. I also added a custom template to give the list items checkboxes, but that's purely cosmetic and isn't strictly
required. Next, we can bind the right panel's datacontext to the selected item in the left listbox, this way as the selection changes the info will update:

Now that that's working, lets start building the graph control. Add a new user control to the project, but this time alter it to derive from ListBox. Wait? That control's just a listbox? Yup, and not only that, you can throw almost any type of object in
it. How does it know the height of the bars then? The height of each bar is relative to the other bars since the height of the control itself is finite. The answer is attached properties. Using attached properties you can dynamically add new properties to
an object at runtime, the only requirement is that the object derives from DependencyObject, which in WPF means almost any object will work. In fact you've already used attached properties, DockPanel.Dock is an example of one. Each control in a DockPanel needs
to remember where it's docked but adding a property to each class would be redundant because being in a dockpanel is a special case. This way, we can use a property of DockPanel, but store a value on each object. Defining an attached property is very similar
to declaring a dependency property:

Now, we need to define the class we're going to store in the list, this simple class just holds a reference to the solver used, how long it took to run, and whether it was successful in solving the sudoku:

Next, we need to add some code to figure out the heights of the bars in the graph, essentially I just find the highest bar and assume that it fills the control vertically, and then set the properties on each item. This only needs to be done when the contents
change so conveniently we can override the event handler:

Here we make containers to hold the bars and set their heights based on our new property. I also added some triggers to ghost out the bar if the solver failed to solve the sudoku grid.

As you can see, it works but yuck, what is this, 16-color Windows 3.1? We've got to make this look a little better. First, let's throw in some kind of color scheme. Ok, but how do the colors map to the bars? Well, if you've read my previous article, you've
probably already guessed: converters. We can link together our index value with our color scheme using a converter:

Now, if we want to get fancy, it's also possible to define this converter so that when you use it from XAML you can defined the color scheme similar to a gradient, but this way works too. After defining an instance of our converter in the resources section
of our control, we can use it like this:

That's better, about a Windows Forms level of look and feel, but this isn't Windows Forms. We need to give the bars a more complex look based on their base color. Using converters we can setup a binding that will do this for us. First, let's define a new converter:

This converter allows us to lighten or darken a databound color as it passes through the binding. It also makes use of the parameter functionality on converters to allow us to specify how much we alter the color from XAML. After we've added the converter
to our resource section can use it. First, we need to move output from out other converter, the base color of the bar into somewhere we can easily access; the Tag property is a great place to store random stuff like this so let's use it:

Here, I've created a gradient and border outline based on the base color by darkening it with our converter. This gradient adds the striped appearance to the graph bars so the MappingMode property is important, since it specifies that our gradient is sized
relative to the screen not the area it is filling. This prevents the stripes from stretching in an ugly way as the bars change height. Once you do this though, the gradient now becomes 1 point long, hence the scale to 20 points. After adding some more glassy
overlays you can see that the final effect is much better, pretty cool for doing everything in databinding eh?

Finally, we can force a special style onto our ListBoxItems, the class that wraps each item in list to turn it into a control:

The works but there is a problem: solving a grid could take more than a few seconds and this method blocks, causing the UI to freeze until it returns. This is a bad thing. Your users will hate you and your more technical users will point and laugh (you don't
believe me, but I've seen it). How can we fix this? The answer is threads! Unfortunately, it's not that easy, there are significant caveats when writing multithreaded code (which are way beyond the scope of this article). Essentially, for our purposes, the
problem lies in that you can't interact with the UI objects from another thread! This makes it difficult to say, re-enable the button or update the graph. Luckily, the .NET Framework comes to the rescue with the BackgroundWorker class, although this doesn't
completely solve our problem it provides an event which is fired when out background task (our other thread) is complete. Since this event handler runs in our UI thread we can easily interact with those objects. To make things a little more user-friendly I've
also added a new hidden panel over the solver information controls that displays a “please wait” message, which we can show while our process is running. The new code looks like this:

If you're confused, the delegate(object dwsender, DoWorkEventArgs dwe){…} syntax defines an anonymous delegate, a new .NET 2.0 feature. Anonymous delegates are single-use nameless methods. This way we can define our event handlers on the fly without cluttering
up our class with extra methods that aren't meant to be called. Also, since anonymous delegates have access to the scope in which they are defined, we can avoid creating lots of temporary variables to hold the objects local to our BenchmarkClick method. On
top of that, the program execution conceptually flows in a linear fashion if you ignore the definitions around the delegates, so anonymous delegates also help the function of the method remain clear. In action, this looks like this, and it allows you keep
playing sudoku as the solver runs: (It does run slow on my machine though, because much CPU time is spent on the absolutely critical pulsating background featureJ)

I've also added similar threading code the board generation routines and the “I give up” button and a little “x” button to the graph that allows you the clear the current results. Finally, as a finishing touch let's update the extremely dated-looking message
box:

I don't know about you, but this dinky non-xp-themed message box doesn't exactly scream “awesome!” at me. To at least partially fix this, I've added a new grid the covers the entire window and is placed in front. By default it's completely invisible, by setting
to opacity to 0, and doesn't block input events, by setting the IsHitTestVisible property to false. Then when it's enabled, it springs into action and fades in, tinting the window black and disabling its controls:

Then, in the grid, I placed one of the custom styled expanders defined in our resources section and filled it with a textblock, button and glassy icon. Also I added another hidden expander, which contains a “please wait” message. After defining some new
methods to make using these controls easy:

We just need to replace MessageBox.Show with ShowMessage to show a fake window:

Hey, as I said before, at least it's more colorful.

At this point, with the work we've done so far and a few extra lines of code you can find in the download, we have a fully functional Sudoku game. I hope you've enjoyed this tutorial series and have some great ideas about a cool WPF app you can build! We've
only covered the basics and this is just the tip of the iceberg when it comes to XAML and WinFX. There's lots of cool stuff left like 3D graphics, video and multimedia, databinding to XML, loading XAML at runtime, and browser-based applications to name a few
and that's just WPF! If you're itching to code more and want to build on the app, some missing things you might want to work on are:

More plug-ins! It supports plug-ins for a reason! Write a better solver that doesn't take forever to run

Better message windows that you can actually move around and the ability to dock and move the UI containers

Separate the styles and logic more cleanly and implement skins or color schemes

]]>http://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-5-The-AI-Battle-Loading-and-Comparing-AI-Plug-ins
Building Sudoku using Windows Presentation Foundation and XAML, Microsoft's new declarative programming language. This is the 5th article from a series of 5 articles and focusses on loading and comparing AI Plug-ins.
Lucas Magder
Difficulty: Easy
Time Required:
1-3 hours
Cost: Free
Software: Visual C# 2005 Express Edition .NET
Framework 3.0 Runtime Components
Windows Vista RTM SDK
Visual Studio Extensions for the .NET Framework 3.0 November 2006 CTP
Hardware:
Download: Download (note: Tasos Valsamidis has an updated version that supports
Expression Blend here)
Note: This article has been updated to work and compile with the RTM version of the Windows SDK.
Welcome to the fifth and final part of my Windows Presentation Foundation tutorial! In this tutorial we'll be wrapping up our Sudoku game by adding support for comparing multiple plug-ins, multiple threads, new notification messages, and a cool databound
graph control. First, let's take a look at the new interface we are trying to build:
On the left, there is a list of all the installed plug-ins, in the middle, our graphing control, and on the right the details for the current plug-in. To get this working we first need a way to enumerate all the plug-ins available to the app. The simplest
way of doing this is to dump all the .dll files into a directory, which I've called “Solvers”. It's pretty simple to get a list of the assemblies in the folder, using the directory class:
string[] plugins = Directory.GetFiles(&quot;Solvers\\&quot;, &quot;*.dll&quot;);foreach (string p in plugins){ LoadSolvers(p);}
I've also added a new field in the Window1 class to hold the list of loaded plug-ins, which eventually ends up as the ItemsSource for the listbox:
ObservableCollection&lt;ISudokuSolver&gt; Solvers = new ObservableCollection&lt;ISudokuSolver&gt;();
We also need some other groundwork code to accept the new plug-in folder. First, we need to define that our application canhttp://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-5-The-AI-Battle-Loading-and-Comparing-AI-Plug-ins
Thu, 30 Nov 2006 11:34:00 GMThttp://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-5-The-AI-Battle-Loading-and-Comparing-AI-Plug-insLucas MagderLucas Magder9http://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-5-The-AI-Battle-Loading-and-Comparing-AI-Plug-ins/RSSGamingPuzzleBuilding a WPF Sudoku Game: Part 4 - Building a Least Privilege Plug-in System and Even More Custom Controls

Building Sudoku using Windows Presentation Foundation and XAML, Microsoft's new declarative programming language. This is the 4th article from a series of 5 articles and focusses on building a least privilege plug-in
system and some more custom controls.

Note: This article has been updated to work and compile with the RTM version of the Windows SDK.

Welcome to the fourth part of my Windows Presentation Foundation tutorial! In this tutorial we'll be building a plug-in system for sudoku-solving algorithms, delving deeper into custom controls, including deriving from exiting controls and implementing custom
properties. Also, we'll complete more of the UI and game logic to start turning this pile of unrelated code into a game! First, let's look at building a plug-in system: There are essentially two ways of providing an extensibility system in a .NET application:

Scripting: We could provide a custom programming language that plug-in authors need to write their code in.

Module Loading: We could dynamically load pre-compiled modules at runtime.

If we take the scripting approach we need to either create our own language, which is a lot of work and honestly, who likes to reinvent the wheel? We could also use the built-in compilation functionality in the .NET Framework to compiler, say C# code as a script,
which takes less work but doesn't allow us to create a “sandbox” language that can only perform certain actions. Plug-in modules suffer from the same issues, but they don't require us to provide a set of tools for plug-in developers since Visual Studio is
all that's needed. With the availability of the free Visual Studio Express editions, there is really no excuse not to use precompiled modules not to mention that it's less work and therefore less chance of creating bugs or security problems…at least that's
what I tell my boss. There's only one flaw in this method: most of the time standard applications like our Sudoku game run as so-called “full trust” applications that means they have the full permissions of the user they are running under, which in most cases,
at least on Windows XP, is the administrator. Obviously this raises a security concern. Most likely, the user trusts the Sudoku game itself, since they knowingly installed it on their system but do they trust each individual plug-in? What if, for example,
the program could automatically download solver plug-ins from a central web repository; does the user trust this plug-in? One way around this is to use .NET code access security (CAS). We can partition our application into a set of “application domains” You
probably don't know it yet, but you've already used domains. When a .NET process starts a default domain is created. You can even access it from any of your “normal” code through the Current static property of the AppDomain class. We could just load more assemblies
into the default domain but they would then run with same permissions as our application code:

This is bad for two reasons: first, the plug-in can do anything the application can. For example, if the application is allowed to write to a certain registry location by the operating system, even if the plug-in can't break out of the Win32 limits it can
still trash our game's settings, which is bad. Second, because there is no clear segregation of code, the CLR errs on the side of caution and doesn't allow us to unload the plug-in module since it's impossible to reasonably determine if any portions of it
are still in use. If we use the second approach:

The plug-in is sandboxed inside another domain. The only real caveat of this approach is that communication between domains requires the use of remoting, or in other words, the objects need to “self-contained” so that they can be serialized as they cross
the boundary, but we'll get back to that later.

At this point you're probably saying “Application domains! .NET remoting! This isn't what I signed on for! I want to make a game!” Don't worry, most of this is automatic but it's important to understand what's going on so you can debug your code and so you
can avoid creating security flaws. So, how do we go about actually getting this to work? First, we need to define a programming interface for plug-ins to use, to keep it simple, let's build an interface that is exported from our SudokuFX.exe assembly that
plug-in authors are required to implement:

This would work well in the single domain approach but unfortunately it's not ideal for our situation. First, passing an instance of Board, while seemingly convenient, actually adds more complexity because of the serialization that occurs as an object crosses
the domain boundary. This is a problem because the object contains links to event handlers and is databound to elements in the UI so it can't be easily written to self-contained stream. Also, it's generally a bad idea to expose unnecessary internal data to
plug-in anyway. If instead of passing a Board, we say pass an ref int?[,], a simple type that exposes no implementation details can easily be serialized. Also, in order to use an object through remoting it must contain some boilerplate code, an easy way of
adding this code is to derive from the MarshalByRef class. Ideally we also want to hide this detail from plug-in authors so it's actually better to make an abstract class like this:

That way, all plug-in classes automatically inherit the code. Wait no! STOP! It's likely I've convinced you that this is the best way of doing it, but it's not! Building something like this requires that you understand the security implications of what you're
writing. There is a subtle flaw in what I've just described, which I fell into the trap of the first time I wrote this code: In order to directly interact with another object through an app domain, the caller must load the other assembly to process its types.
If a hostile plug-in writer embedded malicious code in the constructor of a class that is used in a static member, this code would be run when the assembly is loaded in our main domain! Instead we should build a proxy object that is defined in our main assembly,
which can sit in the un-trusted domain and provide a layer between our objects. This way the un-trusted assembly will not be loaded in our full trust domain:

Now, we can create our container object as our main assembly's “ambassador” to the least-privilege domain, then call the Init method with the type of solver we want to create. This way, calls to the plug-in are still straightforward but since the class from
the plug-in assembly is never accessed directly from our trusted domain, there is no need to load the assembly there.

Next, let's start building a plug-in we can use to test our system:

In Visual Studio, right-click on the SudokuFX solution and add a new class library project called “SampleSolver”. Now, in the new project, right-click on references and select “add”. In the “projects” tab select “SudokuFX”. Also, we need to add a post-build
event to the new project to copy the dll into our folder: copy "$(TargetPath)" "$(SolutionDir)SudokuFx\bin\Debug". Now, if we define a class that inherits from SudokuFX.SudokuSolver we can start building a plug-in:

publicstring Description { get {return"This is a sample algorithm that uses a combination " +"of logic and guess-and-check."; } }

publicstring Author { get {return"Lucas Magder"; } }

publicbool Solve(refint?[,] board) {//Do stuffreturntrue; } }}

Visual Studio will even set up the blank methods for you if you right-click on the “SudokuFX.SudokuSolver” and select “Implement Interface”. This is great if you're still not 100% on how to correctly set things up. I'll get back to how exactly my plug-in
works in just a second but lets jump ahead and write some code to load it.

First, I've added a new field to the Window1 class:

AppDomain PluginDomain = null;

It's important we keep a reference to our new domain because, like any other object, it can get garbage collected and if that happens all the objects in the domain die, and that's bad. Next, I added a method to load a plug-in:

Here, we first create an AppDomainSetup, which contains the parameters for our new domain. Right now, the only field we need to worry about is the ApplicationBase, this makes sure the loader code, which runs in the new domain can locate our executable to
resolve the references our plug-in contains to it. Next, we create a new empty permission set and add only one permission to it: execution. This means the code in that domain can run but do nothing else, which means no file access, no registry, no network
access, etc. Finally, we create the new domain and store a reference to it in our new field. Now, it's time to load our DLL:

First, we read our plug-in from disk it's important to note that were are not “loading” the assembly at this point. No initialization code executes and no processing of the data is done we are merely reading the bytes from disk. We need to do this because
the module loader itself runs in our new domain, which if you recall, doesn't have access to the file system, not even to load its own code. The actual module loading occurs in the new domain from our buffer, so there is no chance of any code “escaping” Finally,
we search the assembly using reflection to find any classes that implement ISudokuSolver:

The Type class is another way of representing the type of an object. Basically, imagine if you replaced all references to a type, say ArrayList, with a string variable, which you set to “ArrayList”, then at run-time you could change the string to, for example,
“HashTable”, now all the code the used ArrayLists now uses HashTables, in a sense, you've made the type of variable, a variable itself. Ok, so if your head hasn't exploded yet, no imagine that instead of string you used an instance of Type. Why? Well first
of all string comparisons are bad form for things like this and second, Type contains a plethora of useful stuff that allows you to do things like loop through the methods of a class or inspect the inheritance tree. How do you get Types you say? Well it's
simple you just use the typeof keyword to extract it from your class. Here we search for a type that implements ISudokuSolver, then when we find one, we create an instance of it and return it. By default, creating an instance across a domain boundary creates
an opaque proxy object that allows other domains to deal with types they don't reference. Because our code does have access to the SudokuSolver base class we can unwrap the proxy to a transparent proxy. Finally, I added a new field to Window1 to contain the
solver, which I then load in the Loaded event handler. Then to make it work, I added a button to the timer pane, labeled “I Give Up”, which executes the solver like this:

Pretty straightforward eh? The proxy object does all the work of crossing the app domain. You can see that this works, if you try to put an offending line of code in the plug-in, execution stops immediately:

I also added a new board generation algorithm. Really, the one I wrote last tutorial is pretty bad. It generates lots of unsolvable grids, which if you're strict, isn't allowed. The real way of generating a Sudoku board is to generate a full valid board
then blank out cells. To accomplish this I've added a new method to the Board class to generate a board based on a solver. Basically, it seeds the solver by filling in a single random cell with a random number.

Then, it runs the solver to fill the rest of the grid, which it then selectively blanks. This takes a little longer (depending on the solver) than the default method so I also added a radio button to choose the algorithm:

Ok, that's all well and good but how did I go about writing a Sudoku solving algorithm? Well my algorithm is a recursive one. First, I build a new board structure of List<int>s that contain the possible number at each square, so for example, on givens, the
list is 1 item long and contains the given number, whereas on blank squares it contains all possible numbers. Then the algorithm looks for all column, row, and box conflicts that eliminate numbers from lists until there are no more items that can be definitely
removed. Then, the solver finds the shortest list with length greater than 1 in the grid and picks and random starting point in its list. Then for each possible “guess” it performs a deep copy of the board and recurses, this way it can backtrack if a certain
guess results in no solution. When all guesses have been tried and no solution is found then the algorithm returns false. Alternatively, if the board is full, e.g. each list is exactly 1 long and there are no conflicts then the board is solved. You can check
the code out in the download but I'll be the first to tell you that this algorithm sucks, at least for solving the boards the program generates. I hereby challenge you to write a better one - That's the great about supporting plug-ins, it allows you to offload
functionality onto the user….err, I mean include extensibility.

Ok, so now that's working, let's start getting the game more playable. First we need to implement a timer, we could do this in two ways: a) create our own threaded or polling timer code or b) use the built-in WPF animation system….guess which one I'm going
to cover (it really is easier, I promise). First, we need to redefine our timer display to more easily accept a bound input source:

We also need define the storyboard that will control our animation, since we don't want the timer to associate with a particular event or control we can define it as “free floating” by putting in our <Window.Resources> tag (we'll write the Completed event
handler later):

There are a couple of important things to notice here: First, how come the durations of the second counter and the and 1/60th of a second time are only one second and one minute respectively? Well, the storyboard expands to fit the longest animation
it contains. With RepeatBehavior="Forever" each animation repeats indefinitely, if we instead specify a duration, like we will in code later, then the animation will repeat within the overal duration, or in other words, if the total timer runs for 10 minutes
then the second number animation will run 10 times since it counts down each second for a single minute. Second, why do the animations target the Tag property intead of Text? We have to do this because, the Text property is of type string, which cant be animated
using an Int32Animation (there is no StringAnimation, in fact, could you even make one?) To make this work we can define the TextBlocks like so:

This way the control automatically displays the contents of its tag, which we initialize to an integer. Next, lets a pause button. Since this a WPF tutorial, a normal button just doesn't cut it so let's build a custom toggle button:

The needle in the stopwatch should animate as the timer advances, so we'll also implement a custom dependency property that allows the needle to be animated and databound. First, add a new user control the project named “Stopwatch.xaml”, now in the .xaml
and .cs files that compose the control replace the UserControl class with the ToggleButton type, this causes our control to inherit from ToggleButton instead of UserControl. Next, let's start by defining our custom property, to do this we need to define a
property description object as a static member of our class:

When calling the DependencyProperty.Register method to create our descriptor we specify the name of our property (“CurrentTime”), the type it will contain ( a double), what type it is attached to (out new Stopwatch type), it's default value (a double set
to 0), and finally any extra flags. In this case we want our control to be redrawn when the property changes so we include the AffectsRender flag. This is all well and good but we still cant access the property from C# code, to make this work we also need
to define a matching instance property:

This property just wraps our WPF property in a more C# friendly package. We don't actually require this in this particular instance, but its good practice to automatically define these properties in pairs since it avoids some cryptic “why doesn't this work?!”
situations down the road if you forget. As for the control itself, its really just a custom template, in fact if you want to get technical, we could have built this entire control as a ToggleButton style, storing the current time in the Tag property, but that's
no fun! To make the control itself work, I've added triggers to alter the top button image displayed (the lit one uses a another bitmap effect called OuterGlowBitmapEffect) and to “clunk” the control when it is clicked:

Because we derive from ToggleButton, we can use the existing control logic and properties. I'll skip over most the actual XAML that defines the look of the control since you can find it in the download and we've covered doing basic shapes and gradients before,
so the only relevant part is the definition of the needle, which is part of a larger drawing:

You can see here that the Angle property of our transform is bound to the custom CurrentTime property we defined. If you've been paying attention so far you'll notice that the convention in WPF is for angles to be specified in degrees (0-360) while, completion
is usually specified as a double ranging from 0-1.0. How can we multiply our CurrentTime value by 360 in the process of binding it? The answer is converters. By defining s custom converter you can perform any operation on the values as they are bound. Since
we just want to multiply by a number we can use the follow converter:

Then, we just instantiate our AngleConverter class in our resources section and reference it from the binding as done above. Converters also support parameters so if we really wanted to be slick we could supply the multiplier as a parameter to a generic
multiplication converter.

Just like the board control, I've placed the stopwatch on the main window, this time under the timer numbering:

I've also hooked up some of standard ToggleButton events to make the button actually do something. This works transparently, again because our control derives from ToggleButton. Also added is a new animation in our timer storyboard to animate the stopwatch
needle:

Since the storyboard supports pausing and resuming it's dead simple! After adding some extra housekeeping code, an implementing a super-basic save game system using the built-in serialization functions in the .NET Framework to write the array representation
of the game board to a file we now have a working Sudoku game! This code is included in the download so if you're still not a .NET pro (hey, it's ok!) you can check it out. Don't forget to come back next time for the 5th and final article in the
series were we finish off the app and sand off all the rough edges. I'll be covering spiffy stuff like:

Implementing a cooler message box than MessageBox

Selecting and loading multiple solvers

Benchmarking solvers and displaying the results in a graphing control.

See you next time!

]]>http://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-4-Building-a-Least-Privilege-Plug-in-System-and-Even-More-Custom-Con
Building Sudoku using Windows Presentation Foundation and XAML, Microsoft's new declarative programming language. This is the 4th article from a series of 5 articles and focusses on building a least privilege plug-in
system and some more custom controls.
Lucas Magder
Difficulty: Easy
Time Required:
1-3 hours
Cost: Free
Software: Visual C# 2005 Express Edition .NET
Framework 3.0 Runtime Components
Windows Vista RTM SDK
Visual Studio Extensions for the .NET Framework 3.0 November 2006 CTP
Hardware:
Download: Download (note: Tasos Valsamidis has an updated version that supports
Expression Blend here)
Note: This article has been updated to work and compile with the RTM version of the Windows SDK.
Welcome to the fourth part of my Windows Presentation Foundation tutorial! In this tutorial we'll be building a plug-in system for sudoku-solving algorithms, delving deeper into custom controls, including deriving from exiting controls and implementing custom
properties. Also, we'll complete more of the UI and game logic to start turning this pile of unrelated code into a game! First, let's look at building a plug-in system: There are essentially two ways of providing an extensibility system in a .NET application:
Scripting: We could provide a custom programming language that plug-in authors need to write their code in.
Module Loading: We could dynamically load pre-compiled modules at runtime.
If we take the scripting approach we need to either create our own language, which is a lot of work and honestly, who likes to reinvent the wheel? We could also use the built-in compilation functionality in the .NET Framework to compiler, say C# code as a script,
which takes less work but doesn't allow us to create a “sandbox” language that can only perform certain actions. Plug-in modules suffer from the same issues, but they don't require us to provide a set of tools for plug-in developers since Visual Studio is
all that's needed. With the availability ofhttp://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-4-Building-a-Least-Privilege-Plug-in-System-and-Even-More-Custom-Con
Thu, 30 Nov 2006 11:19:00 GMThttp://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-4-Building-a-Least-Privilege-Plug-in-System-and-Even-More-Custom-ConLucas MagderLucas Magder3http://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-4-Building-a-Least-Privilege-Plug-in-System-and-Even-More-Custom-Con/RSSGamingPuzzleBuilding a WPF Sudoku Game: Part 3 - Adding Polish and Customizing Controls

Building Sudoku using Windows Presentation Foundation and XAML, Microsoft's new declarative programming language. This is the 3rd article from a series of 5 articles and focusses on adding polish and customizing
controls.

Note: This article has been updated to work and compile with the RTM version of the Windows SDK.

Welcome to the third part of my Windows Presentation Foundation tutorial! In this tutorial we'll be adding some cool UI elements to spice up the application we built last time. First, let's redo the background a little; let's add a cool pulsating gradient,
like the Xbox 360:

(This picture is from a random internet search, I need to find an internal one I can use in the real article)

Ok. So how we do this? If you've scoped out the documentation already you'll know there is a RadialGradientBrush we can use, but how can we layer multiple brushes, and most importantly how can we animate them? To make this work I've replaced the GradientPanel
style with a new one. The new style uses a DrawingBrush to compose a collection of geometry objects into a single image. To create the desired effect I layered a bunch of rectangles painted with radial gradients like this:

The full version of the code included in the source files produces a background like this (I've removed the controls so you can see it better)

Next, we can use a feature of the framework called triggers to create an animation to make the background pulse. Essentially, a trigger definition tells WPF to connect a cause and effect, or in other words, “when A happens do B”. Triggers can fire in response
to events or a certain value of one or more properties. A trigger can then start, stop or pause animations, or set the value of a property. This is great because it means you only really have to write code if you want to do anything exotic, in this case we
just want to start an animation on the “Loaded” event of our panel.

From the code it should be pretty evident what's going on. The properties of the GradientStop objects are being animated in a loop. The Duration property is specified in h:m:s so the animation runs for 4 seconds and the From and To properties specify the
beginning and ending values of the animated property. If you omit one of these, the current value at the beginning of the animation is used. The only other thing here probably needs explanation is the TargetProperty syntax. Since the storyboard is part of
a trigger that is specified in a style, it has to point to the object the style is applied to. Since we need to affect a property a few levels down the hierarchy we can use a relative property path. The concept here is identical to how filenames work; if we
are in the GradientStop object we can just reference the Color property directly. If we move up to the LinearGradientBrush we have to specify that the property we want is a member of Brush property of our current scope. (If you run the application and find
that it runs unbearably slow with the animation code added, this could be due to WPF falling back to software-only mode. Upgrading your video drivers might help, but if all else fails, just comment out the triggers block)

Next, let's make the expander controls we originally styled in article 1 look better and remove the need for the extra border kludge. To do this we need to modify the control's template, the XAML that defines the visual aspects of the control. Because this
XAML is completely separate from the code used to create the control, we can redefine it easily. In fact, all the standard controls are really implemented through default control templates. The C# code behind them merely implements the “concept” of the control,
for example, you can create any control that can be pressed, by creating a new template for the Button control. What's great about this is that we don't have to waste time duplicating the control's logic, events, or properties, and can change only what we
want, the look. The easiest way to start working with control templates is to start with the default template and modify it. The easiest way to do this, since the default template is compiled into the control, is to dump the XAML to disk with a short code
fragment (which you can then remove):

(If you have Expression Interactive Designer, it also has a feature to do this.) The template for the expander is pretty lengthy since it deals with other cases we don't care about like left-to-right expansion, so I won't show the code here, since your eyes
would probably just glaze over and you know where to get it. Essentially, what's important about this code is it tells us the basic structure of the control, there is a DockPanel with a ToggleButton that's made to not look like a button and that contains the
arrow and the header. The content of the expander fills the DockPanel. In the toggle button I've replaced the default circle/arrow thing with glassy looking button:

These two triggers, respond to property changes. When the toggle button isn't checked (the control isn't expanded), the arrow if flipped vertically to indicate this. Also, when the button is pressed, the ellipse shifts down a pixel to look “pressed” and
provide feedback to the user that their click was received.

These triggers animate a mouse-over effect on the glassy button. When the mouse enters and exits the header they start animations that fade the FadeMask ellipse in and out. The animations have no From properties so that if the user moves the mouse away before
the animation completes the fade out animation will smoothly start instead of jumping to full brightness then fading out. Next, I wrapped the ContentPresenter, the control that displays the expander's contents, in an extra border to implement the effect we
want:

The location is important, before we were modifying the ToggleButton that makes up the header, so we edited its template, which is specified in the Expander's template. You'll also notice that I removed unhidden the control and instead included a scale by
0, the effective does the same thing. This is because I'm about to animate the control's expansion and contraction. To do this I've placed this code in the Expander's control template.

This code shrinks and fades out the contents of the expander as it contracts and does the reverse when it expands. For the same reason as above the animations have no From property. Finally, let's modify the style to add a drop shadow (since drop shadows
are cool). To do this you need to set the BitmapEffect property to a DropShadowBitmapEffect like so:

It's that easy...ok well, its easy compared to doing it without WPF. The only caveat I should mention is that, in the current version of WPF, if you apply a bitmap effect to a control it forces that control to render in software mode, that should be fine for
our simple controls, but for more complex controls it's a significant performance hit. (There are some tricks to lessen the impact of this, which I'll cover later though.) With the new expanders the program looks like this:

You can also define more complex animations in XAML. To add a cheesy bounce effect to the Sudoku title text I modified the code like this:

As you can see, adding animations this way is pretty straightforward, and is almost identical to non-key-framed animations. The only new stuff is the use of the BeginTime property that allows you to start the animation after the event occurs, in this case
it is used to allow the expanders to drop down before the title slides in. Also, the AccelerationRatio specifies the fraction of the total time the object spends accelerating to its maximum velocity. A value of 1.0 means a smooth acceleration and a value of
0 means no acceleration at all.

Ok, so after taking a detour defining some styles, it's time to get more of the basic game mechanics working. First let's modify the SudokuBoard class to allow the board to be altered externally. In reality, the GameBoard field contains the same thing as
the data context of the main list, so instead of synchronizing them, we can eliminate this value altogether.

Next, let's add a new method in the Board class to generate a board. The algorithm I use randomly places givens, checks if they are valid and if not removes them and tries again until it has placed enough. This algorithm sucks, but it is fast, we'll add
a better one late through plug-ins. Next, if we modify the size selection drop-down to contain integers instead of ComboBoxItems then it will be easy to make the “New Game” button functional. We can link into the System namespace in the CLR and use the integer
type directly from there, in fact we can link into any namespace and use any type!

The appearance is identical to the user but it allows the behind the UI to easily work without having to hardcode the items in the list into it. The event handler for the “New Game” button is very simple; the data binding does most of the work:

Data triggers perform an action based on the property of a data source, in this case the triggers change the background of the cell depending on whether it's a given cell or not and to mark invalid cell values. The context menu of a read-only cell is also
removed so its value cannot be altered.

Not that cool looking, but it does the job. In the sample application, I've replaced the solid color fills with better looking effects in the sample app but layering up gradients is just more of the same so I'll move on. I've also added a drop shadow to
the board, but I did this slightly differently then before. Because adding a drop shadow to a control causes it to render in software-mode, sometimes it's worth it to cheat, especially for large, square controls. I layered an empty panel behind the board and
gave it a drop shadow. This has the same effect but avoids the need to process the board graphic itself. I also used this trick to in the template for the expander control; I've included the modified version in the download.

Another cool effect you can do with very little code is control reflections. Let's add a reflection to the title text. First, since we want the reflection to follow the title's animation, we need to refactor the animation from the TextBlock to a Grid surrounding
the text. Then we need to add a rectangle to the grid so that it sits over the text.

The rectangle is flipped and transformed vertically to the correct position using a render transform. Using a render transform as opposed to a layout transform is important because render transforms are evaluated after the controls have been arranged. This
way the reflection rectangle does actually take up any extra space below the text in the window layout. Also new here is the use of an opacity mask, which is a brush that is used to mask out areas in the control. For each pixel drawn, the opacity value is
taken from the opacity mask brush, whose other components are ignored. Next, we need to create an event hander for the window's Loaded event in which we hook up the rectangle to the text:

We do this by filling the rectangle with a VisualBrush, which paints an area with a Visual. Since most controls inherit from Visual, this allows you to essentially paint an area with the dynamic image of a control. This can do more than just reflection,
you could build a magnifier control or even paint other controls on a 3D object. This unification of the graphics system is great example of what's cool about WPF!

Well, you can play Sudoku now, but we're still not done! Stay tuned for the next tutorial where I'll be going over:

· Creating more complex custom controls, inheriting from existing controls, and defining custom properties that can be animated or data bound

· Updating the UI to be more functional and to have a real timer

· Building a Sudoku solver as a plug-in

· Running solver plug-ins with least privilege

See you next time!

]]>http://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-3-Adding-Polish-and-Customizing-Controls
Building Sudoku using Windows Presentation Foundation and XAML, Microsoft's new declarative programming language. This is the 3rd article from a series of 5 articles and focusses on adding polish and customizing
controls.
Lucas Magder
Difficulty: Easy
Time Required:
1-3 hours
Cost: Free
Software:
Visual C# 2005 Express Edition .NET Framework 3.0 Runtime Components
Windows Vista RTM SDK
Visual Studio Extensions for the .NET Framework 3.0 November 2006 CTP
Hardware:
Download: Download (note: Tasos Valsamidis has an updated version that supports
Expression Blend here)
Note: This article has been updated to work and compile with the RTM version of the Windows SDK.
Welcome to the third part of my Windows Presentation Foundation tutorial! In this tutorial we'll be adding some cool UI elements to spice up the application we built last time. First, let's redo the background a little; let's add a cool pulsating gradient,
like the Xbox 360:
(This picture is from a random internet search, I need to find an internal one I can use in the real article)
Ok. So how we do this? If you've scoped out the documentation already you'll know there is a RadialGradientBrush we can use, but how can we layer multiple brushes, and most importantly how can we animate them? To make this work I've replaced the GradientPanel
style with a new one. The new style uses a DrawingBrush to compose a collection of geometry objects into a single image. To create the desired effect I layered a bunch of rectangles painted with radial gradients like this:
&lt;DrawingBrush Stretch =&quot;UniformToFill&quot;&gt; &lt;DrawingBrush.Drawing&gt; &lt;DrawingGroup&gt; &lt;GeometryDrawing&gt; &lt;GeometryDrawing.Brush&gt; &lt;SolidColorBrush Color =&quot;White&quot;/&gt; &lt;/GeometryDrawing.Brush&gt; &lt;GeometryDrawing.Geometry&gt; &lt;RectangleGeometry Rect=&quot;0,0,1,1&quot;/&gt; &lt;/GeometryDrawing.Geometry&gt; &lt;http://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-3-Adding-Polish-and-Customizing-Controls
Thu, 30 Nov 2006 11:09:00 GMThttp://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-3-Adding-Polish-and-Customizing-ControlsLucas MagderLucas Magder6http://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-3-Adding-Polish-and-Customizing-Controls/RSSGamingPuzzleBuilding a WPF Sudoku Game, Part 2: The Board UI and Validation

Building Sudoku using Windows Presentation Foundation and XAML, Microsoft's new declarative programming language. This is the 2nd article from a series of 5 articles and focusses on creating the Board UI and validations.

Note: This article has been updated to work and compile with the RTM version of the Windows SDK.

Welcome to the second part of my Windows Presentation Foundation tutorial! If you've missed the first part you probably want to check it out here (link) since we'll be building on what we did last. In this tutorial I'll be covering
creating a custom control for our Sudoku board and databinding it to the game logic.

First, I think it would be a good idea to go over just what databinding in WPF means, since it's used quite differently than in say Windows Forms or MFC. Hopefully this will give more insight in to why the internal classes are designed
the way they are; you can databind anything but you can only easily databind some things. First off all, despite its name, databinding in no way involves databases, complex schemas, or any boring stuff like that. It's really all about tying your UI
to your code. We've all written that WinForms or VB code that synchronizes a control like a listbox or treeview with an internal array, collection, or other data structure and we all remember how painful it is. Why!? Why can't the control just use my object
for data storage instead of its own memory that I have to keep synced? Well, we don't have to worry about that anymore because that's how it works in WPF, in fact, controls only have their own storage if you explicitly request it and you'll find if you write
clean code you'll almost never need it. So where am I going with this? How does it tie in? Well, if we structure our code correctly, we can have our Sudoku board control automatically display our Sudoku board object and easily enter and validate moves. To
do this we are going to use a hierarchy of listboxes. Before you think I've gone off the deep end, it's important to note that in WPF listboxes are controls that list
anything not just strings. So, lets start hammering out the data structures by looking at a typical Sudoku board for a 9x9 game:

5

3

7

6

1

9

5

9

8

6

8

6

3

4

8

3

1

7

2

6

6

2

8

4

1

9

5

8

7

9

Actually it's a 3x3 grid of 3x3 grids. But let's abstract this to any size. Starting at the deepest level we have a cell itself.

It's simple, but gets the job done and maintains which cells are part of the original puzzle.
Unfortunately this won't work so well with databinding. First of all, databinding only works on properties, not fields and how can the control know when a property has changed? To make this work we have to implement the
INotifyPropertyChanged interface and turn the fields into properties like this:

Ok, before you run away screaming, bear with me for a second. First, you only have to do this for properties that will be databound then changed after they are initially read. Second, there are other methods such as dependency properties
that accomplish something similar that I'll discuss later. Dependency properties support animation, metadata, and all sorts other fun stuff but they have more overhead so this way is probably best if you just want the databindings to update. All that's going
on here is firing off the PropertyChanged event when one of the properties changes, pretty simple and a good candidate for a code snippet or good old copy and paste.

Here we initialize the collections in the inner grid cell and populate then with
Cells. What's neat here is that not only can the framework itself use the
INotifyPropertyChanged interface but so can our code. We are adding a handler to the cell's event in order to revalidate ourselves when one of our child cells is altered.

As you can see I've defined the class to store its data in collections of type
ObservableCollection, this is because ObservableCollection already implements
INotifyCollectionChanged and INotifyPropertyChanged and that's great because I'm lazy.
I've essentially defined an array of arrays containing the cells in the inner grid. This works great for databinding but it kind of sucks to access the cells from C# code. To solve this I also added an indexer to the class like so:

The Board class is extremely similar to theInnerGrid except it stores InnerGrids instead of
Cells so I wont list the entire thing here (you can check it out, and the
IsValid implementations if you download the source). I also changed the constructor and the indexer to drill-down through the two levels of containers. If you're not sure on how this would work you should probably check out the source
before you continue just so we're on the same page.

Ok, so now we've written all these class it's time to hit the XAML and make a custom control. So we need to add a new WinFX user control to the project. I've modified some of the properties of the user control, but basically we start
with this:

The basic idea here is that we'll use a series of nested
ItemsControls to display our board. An ItemsControl is a generic panel that contains any number of other items, for example the
ListBox control inherits from ItemsControl and adds support for things like scrolling and selection but we don't need those. We define the outer control that holds the rows on inner squares.

Ok, so this is where the fun starts. Every item that can be databound has a
DataContext property that specifies the object it's bound to. We'll set this later from C# code but it's important to know that it's there because it's the basis for the binding syntax. When specifying a data binding, if no source
is explicitly set the data context is used. In this code ItemsSource, the collection containing the child items is bound to the
GridRows property of the data context, which will eventually be an instance of our
Board class.

Another thing of note is the use of the UniformGrid class. By default the items control lays out items by stacking them from top to bottom. Instead of this behavior we would rather have the items stacked
in a single column and stretched to fill the entire space evenly. The UniformGrid container does this and so I've substituted it for the default using the
ItemsPanel property, but in general you could use any kind of standard or custom panel here, for example to arrange the items in a ring. Also you'll notice
ItemTemplate points to a resource:

A data template describes how each item in the source list is interpreted as an item in the
ItemsControl. The data context is the current item, which is the list of blocks in the row, which we bind to the
ItemsSource of another ItemsControl. Currently, we have a vertical list of horizontal lists. Then, we do this all over again for the cells inside each block. You can also add other controls in the template
and I've added a border to the InnerGridTemplate to show the boundary between cells.

Here, we draw a lighter border around the cell then display the
Value property of the current cell, which is the data context of the template. Finally, we want the entire thing to stay square as it resizes. Normally this would require a few lines of C# code but thanks to the insanely flexible databinding
available in WPF we can do this with no code! All you need to do it to bind the Width property of the UserControl to its
ActualHeight property, which contains the final height of the control after it's been laid out. We can do this with the
RelativeSource property, to bind to object itself instead of the data context. This sounds complicated but it's actually really simple:

Now, we need to put the control onto our main window. First, we need to map out C# namespace, SudokuFX, to an XML namespace that we can reference from XAML. To do this we define a new namespace in the document root using this syntax:

xmlns:clr="clr-namespace:SudokuFX"

Where the xmlns:clr indicates the xml namespace. “clr” is in no way special an I could have called it

xmlns:stuff="clr-namespace:SudokuFX" or whatever I wanted. Once that's done I can use my control just like any other. I've replaced the stand-in canvas with our custom control tag:

Now, it should look more like this (I've added the numbers just to show that it works):

You can see it rebuilds correctly to match the data, when I change from a 9x9 grid to a 16x16 grid:

Ok, so now that we've got that working, to close of this tutorial lets add the ability to change the numbers on the board. I've added a new collection property to the
Cell class called PossibleValues that is populated with all the possible values when the class is created. Let's add a context menu that's bound to this new property so that the cell values can be changed.
To do this the XAML needs to be changed like this:

The key here is the binding of the listbox to our data source. Because the context menu exists in a separate hierarchy the data context isn't automatically inherited. We can work around this by binding the new data context to the
data content of the parent element just outside our sub-hierarchy. To do this we use the
RelativeSource syntax to access our TemplatedParent. Next, we bind the
ItemsSource property to the new property, which populates the listbox, and then we bind the
SelectedItem property to the object's Value property. Because we specify a two-way binding, when the value of Value changes, so will the selected item in the listbox, and, when the use selects a new item through the UI, Value will
updated also. A listbox is needed because a menu doesn't have the capability to retain item selections. To work around this I added the listbox to the menu as a single item, and then altered the
MenuItem Template to remove all padding and selection logic. I haven't covered altering control templates yet, so don't worry about how exactly that part of the code works, we'll revisit it in the next tutorial.

Now, if you run the application, you'll see that you can edit the displayed grid:

This is really cool because, essentially, there is no code that ties the internal data classes to our UI! The UI automatically and dynamically displays and edits an instance of our custom class. How awesome is that?

Don't worry, we're not done yet! Come back for my next article were we take a break from data and spiff up the coolness of the app's look and feel. I'll be covering cool stuff like:

Automatically selecting data templates based on properties of the object

Modifying control templates to completely customize the look, and operation of a control

Adding animations

Automatically starting and stopping animations and altering objects based on UI events or other conditions

Adding reflections and other imagery based on existing controls

See you next time!

]]>http://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-2-The-Board-UI-and-Validation
Building Sudoku using Windows Presentation Foundation and XAML, Microsoft's new declarative programming language. This is the 2nd article from a series of 5 articles and focusses on creating the Board UI and validations.
Lucas Magder
Difficulty: Easy
Time Required:
1-3 hours
Cost: Free
Software:
Visual C# 2005 Express Edition .NET Framework 3.0 Runtime Components
Windows Vista RTM SDK
Visual Studio Extensions for the .NET Framework 3.0 November 2006 CTP
Hardware:
Download: Download (note: Tasos Valsamidis has an updated version that
supports
Expression Blend here)
Note: This article has been updated to work and compile with the RTM version of the Windows SDK.
Welcome to the second part of my Windows Presentation Foundation tutorial! If you've missed the first part you probably want to check it out here (link) since we'll be building on what we did last. In this tutorial I'll be covering
creating a custom control for our Sudoku board and databinding it to the game logic.
First, I think it would be a good idea to go over just what databinding in WPF means, since it's used quite differently than in say Windows Forms or MFC. Hopefully this will give more insight in to why the internal classes are designed
the way they are; you can databind anything but you can only easily databind some things. First off all, despite its name, databinding in no way involves databases, complex schemas, or any boring stuff like that. It's really all about tying your UI
to your code. We've all written that WinForms or VB code that synchronizes a control like a listbox or treeview with an internal array, collection, or other data structure and we all remember how painful it is. Why!? Why can't the control just use my object
for data storage instead of its own memory that I have to keep synced? Well, we don't have to worry about that anymore because that's how it works in WPF, in fact, controls only have their own storage if you explicitly request it and you'http://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-2-The-Board-UI-and-Validation
Mon, 06 Nov 2006 11:46:00 GMThttp://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-2-The-Board-UI-and-ValidationLucas MagderLucas Magder14http://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-2-The-Board-UI-and-Validation/RSSGamingPuzzleBuilding a WPF Sudoku Game, Part 1: Introduction to WPF and XAML

Building Sudoku using Windows Presentation Foundation and XAML, Microsoft's new declarative programming language. This is the 1st article from a series of 5 articles and focusses on introducing WPF and XAML.

Note: This article has been updated to work and compile with the RTM version of the Windows SDK.

Whenever I want to learn something new I find that just working through a tutorial is much easier and less painful then reading the documentation cold and I assume most people feel the same way, because come on, do you actually read the instructions
for something before you try to use it? I sure don't. To this end, I've decided the jump right into the action and walk though building a Windows Presentation Foundation application right away and since this is Coding4Fun and since, let's face it, the world
has enough enterprise-web 2.0-data-portal-dodads, were going to make a game.Unfortunately, I don't think it's realistic to jump right into making Halo 3 here, so I figured a more bite-sized game might be in order, something we might actually finish by the end of these tutorials, like say a Sudoku game.
(Hey, the upside is you might actually get away with playing Sudoku at work). Ok so what do we need to get started? (Install in this order)

You also need to be running Windows XP SP2, Windows Server 2003 SP1, or the Vista February CTP.

Of course, I just happened to have all that installed on my workstation (yeah right). But now that everything is loaded up lets get started. Fire up VC#, create a new project and select “WinFX Windows Application.” (If you can't see
this item you should make sure you've installed the Visual Studio Extensions since this is one of the things they add.). I entered “SudokuFX” as the project name, and that's what you'll see in the screenshots, but it's up to you what you call it. Right now
you should be starring at this:

<Windowx:Class="SudokuFX.Window1"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="SudokuFX"Height="300"Width="300"

>

<Grid>

</Grid>

</Window>

This is XAML, Microsoft's new declarative programming language. Classes in XAML can have both code (C# or VB.NET) and declarative (XAML) components.The x:Class attribute of the Window tag specifies the name of C# component of the class we are defining. The C# part should look like this:

namespace SudokuFX

{

publicpartialclassWindow1 : Window

{

public Window1()

{

InitializeComponent();

}

}

}

When the program is compiled and run the two halves combine together to create a complete
Window1 class, which derives from the System.Windows.Window class provided by WinFX. The only other non-obvious thing you need to know here is that all the objects declared in XAML can be accessed from code
or vice-versa. In fact, you can write a class using the same API with no XAML at all! The nested elements are placed into collection stored as a property on their parent called
Children, or in object that can contain only one other object they are assigned to the
Content property. So in other words this XAML code creates an instance of
Grid and places it in the window's Content property.

So, how do we go about laying out the application? Well basically the goal layout is to have a title at the top, the game menu down the left, similar to the “tasks” pane in Windows explorer, the game timing info on the right, the
move history on the bottom, and the board in the center. Of course this should all be resolution independent and dynamically resize and flow. (If you've used Windows Forms before, the sweat might be already beading on your forehead as your migraine develops,
but don't worry, dynamic resizing and flow is the default.) The best container for the job is the obviously-named
DockPanel. The DockPanel is a container control that arranges it children based which side they are attached to; the last element added is then used to fill the remaining space. For example, replace the
Grid tag with:

<DockPanel>

<TextBlockBackground="Red"DockPanel.Dock ="Top"FontSize
="36">

Sudoku

</TextBlock>

<StackPanelBackground="Green"DockPanel.Dock ="Left">

<Button>A</Button>

</StackPanel>

<StackPanelBackground="Blue"DockPanel.Dock ="Right">

<Button>B</Button>

</StackPanel>

<ListBoxBackground ="Gray"DockPanel.Dock="Bottom"/>

<StackPanelBackground ="Yellow"/>

</DockPanel>

The DockPanel.Dock syntax is used to refer to a per-child but container-specific property. Another example of this is the
Canvas.Left property, which is used with elements inside a
Canvas, a container control that allows you to explicitly position elements. The
StackPanel container arranges its children in vertical or horizontal stack, going either up or down or left or right. Right now I've added some buttons just pad out the panels so they don't shrink away to nothing and some garishly
horrible background colors we'll remove later so it's evident exactly how things are laid out. If you compile and run the program you get this monstrosity:

Ok, now its time to grind out some code to get a basic UI going. First lets layout the left panel: there's going to be the main menu and the new game settings and lets throw them in expander controls just incase anyone who uses our
program runs at 800x600 (It's frightening I know, but I've seen it).

<StackPanelDockPanel.Dock ="Left">

<ExpanderIsExpanded ="True"Header ="Main Menu">

<StackPanel>

<Button>New Game</Button>

<Button>Load Game</Button>

<Button>Save Game</Button>

<Button>Quit</Button>

</StackPanel>

</Expander>

<ExpanderIsExpanded ="True"Header ="New Game Settings">

<StackPanel>

<TextBlock>Board Size:</TextBlock>

<ComboBoxIsEditable ="False">

<ComboBoxItemIsSelected ="True">9x9</ComboBoxItem>

<ComboBoxItem>16x16</ComboBoxItem>

<ComboBoxItem>25x25</ComboBoxItem>

<ComboBoxItem>36x36</ComboBoxItem>

</ComboBox>

</StackPanel>

</Expander>

</StackPanel>

This gives you:

Ok, so maybe that doesn't look too awesome right now, but wait there's more the come! After fleshing out the rest of the UI in similar fashion and adding a dummy image for the board (we'll make the board in a future tutorial) we get
this:

Now, how do we improve the look and feel of this UI? Well, one way would be to tweak all the properties of the controls individually to make them look better; another would be to use some kind of skinning. Unfortunately, these techniques
add clutter to your code and are difficult to maintain, what we can use instead is WPF's notion of styles. WPF makes it quite easy to customize controls across a given scope, for example: the application as a whole, a particular dialog, or a single container,
by defining a new set of default property values. You can do this by adding styles to the
Resources collection of another object. In XAML, if you want to assign a more complex object or collection of objects to a property you can expand the property out from the
Property="Value"
syntax to the

<Object.Property>

<ValueObject/>

</Object.Property>

syntax. For example, this code assigns the color blue as the background color for all buttons in the application, unless it is explicitly set otherwise:

<Application.Resources>

<StyleTargetType ="{x:Type Button}">

<SetterProperty ="Background"Value ="Blue"/>

</Style>

</Application.Resources>

Styles can also be named using the x:Key property. The reason why
x:Key is used instead of x:Name is because
<Application.Resources> is actually a list of key-value pairs. For example we could define:

<Application.Resources>

<Stylex:Key ="BlueButton"TargetType ="{x:Type Button}">

<SetterProperty ="Background"Value ="Blue"/>

</Style>

</Application.Resources>

This creates a style which only applies to certain buttons, buttons that reference it with their
Style property. For example:

<ButtonStyle="{StaticResource BlueButton}"/>

You can also define resources (there are also other types than styles) inside windows, panels, or other objects that have a
Resources property. When code references a resource a search is made outwards up to the application level thus styles or other resources defined in
<Window.Resources>, for example, only apply inside that window.

So far I haven't explained the brace notation I've been using. Essentially, braces are used to declare references to other object but not instantiate them. For example,
{x:Type Button} refers to the Button class, while
{StaticResource BlueButton} searches the resource hierarchy for the item with the key “BlueButton”. The
StaticResource directive indicates that this search is to be carried out when the object is first created, but
DynamicResource can also be used to specify that the value should be continually updated.

Now we can start adding a style to improve the look of the expander. I added this to the
<Application.Resources> section:

This is a pretty straightforward style, although it does nicely demonstrate the two property assignment syntaxes. The background is set to a horizontal gradient between two shades of gray and the rest of the properties are assigned
to sensible defaults the work well with the background. I've also added an extra border around the inside of the control by adding an extra
Border tag inside the expander's content like so:

<ExpanderIsExpanded ="True"Header="Main Menu">

<BorderMargin ="5"Padding ="10"

Background ="#77FFFFFF"BorderBrush ="DimGray"BorderThickness ="1">

<StackPanel>

<Button>New Game</Button>

<Button>Load Game</Button>

<Button>Save Game</Button>

<Button>Quit</Button>

</StackPanel>

</Border>

</Expander>

The Margin property specifies the spacing border on the outside, while the
Padding property specifies the extra spacing on the inside although only container controls can have padding. Both values are specified by either four comma separated values for left, top, right, and bottom, respectively, or a single
number if all four are the same (as they are here).

If you think this is kind of a kludge, you're right. In fact I could have included the extra border inside the control itself using my custom style. To do this you can modify what's called the control's template, but that's a whole
other topic so I'll just do this for now. Don't worry, we'll come back and fix this later. After whipping up some other styles, which you can check out if you download the code, and adding a nice gradient for the window background the application looks a lot
better……ok, well at least it's more colorful.

Finally, to close off this part of the tutorial, let's add some simple event handling to make the “Quit” button work. This is actually very easy. Just define a method that conforms to the
RoutedEventHandler delegate in your Window1 class. For example:

void QuitClicked(object sender,
RoutedEventArgs e)

{

this.Close();

}

Then just set the Clicked property of the button to the name of your handler like this:

<ButtonClick ="QuitClicked">Quit</Button>

Now, if you click the quit button the program will exit. This is essentially all there is to handling simple events!

Ok, well that's all for now, I hope this tutorial has at least given you a feel for how WPF applications work and how to start building an app. We're just scratching the surface of what you can do with this framework and .NET 2.0!
Stay tuned for the next parts of the tutorial that finish the application and cover cool stuff like:

Triggers, have the UI operate itself and control its appearance with no code

Creating a plug-in system, loading plug-ins written in any .NET language into a sandbox

Writing multithreaded code on .NET

Keep coding!

]]>http://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-1-Introduction-to-WPF-and-XAML
Building Sudoku using Windows Presentation Foundation and XAML, Microsoft's new declarative programming language. This is the 1st article from a series of 5 articles and focusses on introducing WPF and XAML.
Lucas Magder
Difficulty: Easy
Time Required:
1-3 hours
Cost: Free
Software: Visual C# 2008 Express Edition
Hardware: None
Download: Download (note: Tasos Valsamidis has an updated version that supports
Expression Blend here)
Note: This article has been updated to work and compile with the RTM version of the Windows SDK.
Whenever I want to learn something new I find that just working through a tutorial is much easier and less painful then reading the documentation cold and I assume most people feel the same way, because come on, do you actually read the instructions
for something before you try to use it? I sure don't. To this end, I've decided the jump right into the action and walk though building a Windows Presentation Foundation application right away and since this is Coding4Fun and since, let's face it, the world
has enough enterprise-web 2.0-data-portal-dodads, were going to make a game.
Unfortunately, I don't think it's realistic to jump right into making Halo 3 here, so I figured a more bite-sized game might be in order, something we might actually finish by the end of these tutorials, like say a Sudoku game.
(Hey, the upside is you might actually get away with playing Sudoku at work). Ok so what do we need to get started? (Install in this order)
Visual C# 2005 Express Edition (Grab it for free at
http://msdn.microsoft.com/vstudio/express/visualcsharp/!) WinFX February 2006 CTP (Grab it at
http://www.microsoft.com/downloads/details.aspx?FamilyId=F51C4D96-9AEA-474F-86D3-172BFA3B828B&amp;displaylang=en)
Windows SDK February 2006 CTP (Grab it at
http://www.microsoft.com/downloads/details.aspx?FamilyId=9BE1FC7F-0542-47F1-88DD-61E3EF88C402&amp;displaylang=en#filelist)
Visual Studio Extensions for WinFX February 2006 CTP (Grab it http://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-1-Introduction-to-WPF-and-XAML
Mon, 06 Nov 2006 11:32:00 GMThttp://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-1-Introduction-to-WPF-and-XAMLLucas MagderLucas Magder13http://channel9.msdn.com/coding4fun/articles/Building-a-WPF-Sudoku-Game-Part-1-Introduction-to-WPF-and-XAML/RSSGamingPuzzle