Keyboard input is one of the most important aspects of truly rich programming environments. I understand that one usually identifies a rich interface as one which can interacted with visually. This interaction feels more natural than keyboard interaction. The mouse allows the user to feel as if he can truly manipulate the environment in which he is working. One cannot, however, ignore the importance of the keyboard in any environment expecting to be able to perform much meaningful work. Again I'll be talking about some code that I wrote many months ago. Sorry for being so late mentioning this stuff. I just need to find more time in the day. I'll find that 25th hour eventually.
Handling keyboard input with Silverlight 2.0 is very easy. In Silverlight 1.1 there wasn't even an enumeration for the keys. Now that it is included one simply has to wire up some handlers for keyboard input. For my purposes I've been using it for gaming, but others could be using this for almost anything. Keep that in mind and use this by adapting it to your needs at the time.
Initializing the key up and key down event handlers is very easy. You just call a couple of lines like these and create a couple of empty methods which we will write later, so we start with this.
this.KeyDown += new KeyEventHandler(Page_KeyDown);
this.KeyUp += new KeyEventHandler(Page_KeyUp);
This will tie these events to the page. If you want to tie them to another element, use its x:Name instead of this. I like to have a more central method for handling keyboard events, so I'll create a method for handling the keys and I will call that method in my event handlers.
private void Page_KeyUp(object sender, KeyEventArgs e)
{
HandleKey(e.Key, false);
}
private void Page_KeyDown(object sender, KeyEventArgs e)
{
HandleKey(e.Key, true);
}
Notice that the KeyEventArgs parameter, e, has data about the event, so if you needed more information from it you could obtain it and pass it to HandleKey also. I prefer this to having too much logic directly in my event handlers. The boolean value I am passing is just letting me know whether the key is being pressed or released.
In a game it is important to know the state of the keyboard at any given time. Since Silverlight currently doesn't tell me if a key is being pressed I use this system to allow me to detect a held key as well as when keys are pressed and released. If you're doing something similar then you will probably use something similar to this.
private void HandleKey(Key key, bool isDown)
{
switch (key)
{
case Key.Escape:
if (isDown) EndGame(Enums.EndGameType.Quit);
break;
case Key.Up:
case Key.W:
_upIsPressed = isDown;
break;
case Key.Down:
case Key.S:
_downIsPressed = isDown;
break;
case Key.Left:
case Key.A:
_leftIsPressed = isDown;
break;
case Key.Right:
case Key.D:
_rightIsPressed = isDown;
break;
default:
break;
}
}
By knowing the state of the keyboard at any given time, I can allow my silverlight game loop to know what keys are currently being pressed and respond to them. This allows the game to play along as the user uses keyboard input to interact with the game. These same ideas and code can be modified easily to work with nearly anything. This is why I make sure that the code snippets I show are quite simple. It makes them more easily adapted to a variety of solutions.
I hope everyone is enjoying Silverlight. Make sure you listen to the Silverlight Song. It is a riot.
I've been playing with silverlight as a gaming platform for a few months now. I've not published or released anything I've done yet, but I expect I will at some point. I am not much of a game developer really, and I've been hacking things together as best I can. I, like many other developers, have always found game development to be quite interesting. So for now I'll talk about how to create a game loop.
What are Game Loops Used For?
In most games you need to have some control over the passing of time. You always need to be constantly able to respond to user input without stopping the game waiting for this user interaction. It allows you an opportunity to have the game move with or without the player. This loop will allow you to have computer-controlled enemies and neutrals decide how to act and to take these actions.
How to Create a Game Loop
I've found two ways I like for creating game loops. I am sure that there are plenty of others. If you wanted to, you could also wrap these up into classes so it abstracts the ugly details of creating a game loop. Perhaps a class which just lets you create a new instance of the game loop class and lets you assign a method for handling the looping.
Since I am just trying to show the simple how to of it, I'll leave out the class and leave that as an exercise for the reader. The two ways I know of for creating game loops are to use a System.Windows.Threading.DispatchTimer or a System.Windows.Media.Animation.Storyboard. I prefer the timer simply because it feels more hacky to use a storyboard. This just feels more like it should be some sort of a timer managing this, so it's what I like to use.
// Initialize the Main Game Loop
_timer = new DispatcherTimer();
_timer.Interval = new TimeSpan(100);
_timer.Tick += new EventHandler(MainGameLoop);
_timer.Start();
What we've done here is just created this DispatchTimer and told it to run fire the MainGameLoop method every time the timer ticks. The timer has an interval set to 10 miliseconds in this example, so our loop should execute 100 times every second.
private void MainGameLoop(object sender, EventArgs e)
{
// ....
// Do Stuff Here For the Game
// ....
}
Again another exercise for the reader is to create a game by filling in that MainGameLoop as well as other portions of the code. I plan on fleshing out some games if I ever get enough free time to work on it. I'll be back to post some more stuff. I expect it will be more complicated that this. I just don't want to post my whole game yet. It will be released eventually. I am not making Duke Nukem Forever, so you can expect my game will actually release at some point.
Disclaimer: This post is not about security.
Is anyone else bothered by Information titled with the word security? Let me explain what it is I am referring to. I will see an article, a blog post, or a section on a web site which claims to be about "security." I will of course be quite interested when I see this, because I think security is very important when programming. One must be careful to not leave easy ways for people to exploit one's code. I think this is an important issue and it tends to be overlooked by many software writers.
The problem is that most of the time the writing I find about "security" is in actuality information about "authentication." I understand that "security" is a word which certainly can be used to describe authentication, roles, permissions, etc. I just dislike it when it is used in such a way when talking to programmers. Since it is the best word to describe the type of security which is preventing people from exploiting the code. Preventing attacks on a system is a very important aspect of programming, and it seems to be overlooked on the Internet.
I wish people would stop titling articles, book chapters, and whatever else as "security" when it is really just "authentication."
Anyone else run into any similar situations?
I recently needed to enable Mixed Mode Authentication on a SQL Server instance, so I will demonstrate how to go about setting this up. It is a pretty easy process, but I figure I'll document it nicely here. Perhaps I will come back to this later to reference this. Who knows?
First you will need to connect to the SQL Server instance using SQL Server Management Studio.

Once you've connected to the SQL Server you will need to get to the properties window for the server. To do this you can right click on the SQL Server in the Object Explorer window and it will bring up a context menu.

Now that you've got the properties window open, select the Security section and choose the SQL Server and Windows Authentication Mode radio button.

After clicking OK, you will receive a message informing you of the need to restart the Server before the changes take affect.

Now just right click on the server in the object explorer again and select restart from the context menu and the services for the server will restart.

Congratulations you're done.
While installing SQL Server 2005 recently I ran into some difficulty. I use database projects from Visual Studio 2005 Team Edition for Database Professionals. I use Visual Studio 2008 with them now, and I recently made a mistake while using one of these projects. When I ran this project my default instance of SQL Server was not listed, so I figured I would connect it to the SQL Express. BIG MISTAKE. After installing SQL Server and getting it working correctly I removed SQL Server Express, and now the real fun begins. The database project no longer loads.
So I try removing and adding the project in my solution figuring it might prompt me for the database instance again. No luck. So I decide to ask around a bit. One forum got me a nice response. It explained how to make the change as well as linking to this MSDN article.
http://msdn2.microsoft.com/en-us/library/aa833159(VS.80).aspx
To make this change you just have to alter some settings in Visual Studio. Start by navigating to the Tools menu and choose Options.

Once you've opened the Options menu, navigate to the Database Tools section and pick Design-time Validation Database. This is the information for the database used by Visual Studio for database projects. Change the SQL Server Instance Name to whatever the name of the local database is.

I made the bad assumption of assuming that the project is what connects to the server instead of Visual Studio. I checked everywhere in settings for the project, but it slipped my mind that Visual Studio would be what would contain that setting.
As one final note I will say Googling sucks when you're looking for information about "Visual Studio 2005 Team Edition for Database Professionals". Ah what a great name guys.....
Earlier today I posted about a Recursive Find Control Extension Method. I was informed recently by Steve Smith that I should check out the generic find control method which Aaron Robson has on his blog. He has some pretty nice methods there, so I just adapted them to be extension methods now. As extension methods the code looks like this.
/// <summary>
/// Similar to Control.FindControl, but recurses through child controls.
/// </summary>
public static T FindControl<T>(this Control startingControl, string id) where T : Control
{
T found = startingControl.FindControl(id) as T;
if (found == null)
{
found = FindChildControl<T>(startingControl, id);
}
return found;
}
/// <summary>
/// Similar to Control.FindControl, but recurses through child controls.
/// Assumes that startingControl is NOT the control you are searching for.
/// </summary>
public static T FindChildControl<T>(this Control startingControl, string id) where T : Control
{
T found = null;
foreach (Control activeControl in startingControl.Controls)
{
found = activeControl as T;
if (found == null || (string.Compare(id, found.ID, true) != 0))
{
found = FindChildControl<T>(activeControl, id);
}
if (found != null)
{
break;
}
}
return found;
}
And this new extension method is called very similarly to how we called the previous code. It is called using the following code.
Label theOtherLabel = LoginView1.FindControl<Label>("OtherControlToFind");
if (theOtherLabel != null)
{
theOtherLabel.Text = "Found this one also!";
}
It is able to find the Label inside of the the following LoginView.
<asp:LoginView ID="LoginView1" runat="server">
<LoggedInTemplate>
<asp:Panel ID="Panel1" runat="server">
<asp:Panel ID="Panel2" runat="server">
<asp:Panel ID="Panel3" runat="server">
<asp:Panel ID="Panel4" runat="server">
<asp:Panel ID="Panel5" runat="server">
<asp:Label ID="ControlToFind" runat="server" Style="color: Red" />
<asp:Label ID="OtherControlToFind" runat="server" Style="color: Blue" />
<asp:Label ID="AlwaysShow" runat="server" Text="This shows no matter what." />
</asp:Panel>
</asp:Panel>
</asp:Panel>
</asp:Panel>
</asp:Panel>
</LoggedInTemplate>
</asp:LoginView>
I've also updated my FindControl method so that is just an overload of the previous method. Since my extension method takes the same parameters and returns the same type as the existing find control method I needed to rename it FindControlR. I've now updated it so it takes an extra parameter, but doesn't have a different name. I've added a boolean "recurse" parameter. If this is set to false it just calls the standard FindControl method and if it is set to true it will recursively call itself finding the desired control.
This is the final product followed by how one would call it.
/// <summary>
/// Searches recursively in this control to find a control with the name specified.
/// </summary>
/// <param name="root">The Control in which to begin searching.</param>
/// <param name="id">The ID of the control to be found.</param>
/// <returns>The control if it is found or null if it is not.</returns>
public static Control FindControl(this Control root, string id, bool recurse)
{
if (!recurse)
{
return root.FindControl(id);
}
System.Web.UI.Control controlFound;
if (root != null)
{
controlFound = root.FindControl(id);
if (controlFound != null)
{
return controlFound;
}
foreach (Control c in root.Controls)
{
controlFound = c.FindControl(id, true);
if (controlFound != null)
{
return controlFound;
}
}
}
return null;
}
Label theLabel = LoginView1.FindControl("ControlToFind", true) as Label;
if (theLabel != null)
{
theLabel.Text = "Found it!";
}
I hope everyone else sees the great value in extension methods.
So one of the most useful methods for ASP.NET development that never seems to be included in ASP.NET is a recursive find control method. This problem results from the standard FindControl method on controls only searching within that control. It only finds child controls not grandchildren or anything farther down the line. This means that anything nested within other controls is a pain to access.
This limitation of the standard FindControl is annoying and has prompted me as well as many other people to use homegrown FindControl methods to solve this problem. This is a big problem when trying to programmatically access controls within templates. So earlier today I read on a list someone having trouble with the built-in find control, and it made me thing that a recursive find control would make a great extension method since it is a method plenty of people want to see on the control class anyway. So I went and wrote this simple little extension method.
For this nifty example I'll use this as my Page class. I've nested some Panels here to make sure that a standard find control would not work.
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server">
<asp:Panel ID="Panel2" runat="server">
<asp:Panel ID="Panel3" runat="server">
<asp:Panel ID="Panel4" runat="server">
<asp:Panel ID="Panel5" runat="server">
<asp:Label ID="ControlToFind" runat="server" />
</asp:Panel>
</asp:Panel>
</asp:Panel>
</asp:Panel>
</asp:Panel>
</div>
</form>
Now you'll see here in the code behind I am calling my recursive find control extension method. Notice that I am checking for null afterwards. This is because if I do not find the control my method returns null, so I should check for this. Also because I am using the as statement if the control is not a label my variable will also be null.
protected void Page_Load(object sender, EventArgs e)
{ Label theLabel = form1.FindControlR("ControlToFind") as Label; if (theLabel != null)
{ theLabel.Text = "Found it!";
}
}
Here is the code which makes this cool extension method possible.
public static class Extensions
{ /// <summary>
/// Searches recursively in this control to find a control with the name specified.
/// </summary>
/// <param name="root">The Control in which to begin searching.</param>
/// <param name="id">The ID of the control to be found.</param>
/// <returns>The control if it is found or null if it is not.</returns>
public static Control FindControlR(this Control root, string id)
{ System.Web.UI.Control controlFound;
if (root != null)
{ controlFound = root.FindControl(id);
if (controlFound != null)
{ return controlFound;
}
foreach (Control c in root.Controls)
{ controlFound = c.FindControlR(id);
if (controlFound != null)
{ return controlFound;
}
}
}
return null;
}
}
To create an extension method all I need to do is create a static method in a static class and pass as a parameter "this Type name" where Type and name are the type we wish to extend and name is a local variable name for the instance with which we wish to interact.
One thing I don't see in many examples of extension methods which I have used here is passing a parameter in the extension method. It really is this simple to pass the extra parameter.
This syntax reminds me a lot of the python language whose non-static class methods accept "this" as a parameter. It defines them as taking the instance as a parameter.
Have a great day!
So one thing I've always loved about Google is the I'm feeling lucky search feature. Most of the time I know that the top result is the one I need. Earlier today, I was googling for how to link directly to the Google results using an "I'm Feeling Lucky" search, and I found one interesting thing. I am not sure how accurate the information is, but it seems that Google loses $110 million per year because of the "I'm feeling lucky" button. Clicking the button means you see no ads from Google, so Google effectively does not get any money from a user who clicks that button.
OK, so by now I would hope that someone is wondering why I would want to create a link which points to an "I'm Feeling Lucky" result. Well it is quite obvious that I want to hide the eventual destination of the link. I am assuming that people will notice that it goes to Google, but will not notice the part of the query string where it really doesn't send them to Google.
So I found out that all you have to add into the querystring is btnI=745. Yes, it is that easy, so Here is a nice example of a link I believe you should all see.
http://www.google.com/search?hl=en&q=french+military+victories&btnI=745

Following the link I have listed above is the same as doing what my screen shot illustrates.
Yes, I think it is a very funny joke. That site has been the top result on Google for that search for a looong time. It is the top result for "french military victories", and is quite a funny result. It could use an update to look like the curren