Brendan Enrick

Daily Software Development

Differences Between Structures and Classes in C#

Earlier today I was looking for a good reference outlining the differences between structs and classes in C#. I wanted a refresher on the subject, because I've been doing a reasonable amount of teaching lately. At Lake Quincy Media we have hired a couple of developers currently in school. In bringing them up to speed, I've been explaining a lot about programming languages, paradigms, etc. and it is nice to have good references to make sure that I am not passing along misinformation. In my quest to make sure that I'm remembering things correctly I found a great resource showing the differences between C# structs and classes. It is a very nice reference. I has links to different sections and code examples showing the differences it lists. I'll definitely be recommending that these guys take a look at this resource.

Note: In my opinion the best one thing to remember when thinking about structs and classes is that structs behave like value types and classes like reference types. If you know how to interact with each of those then you'll understand a lot of the differences right away.

Happy Programming Everyone!

Fake Binary Clocks

I recently downloaded a Vista clock gadget. It is kind of nice, but as with most things claiming to a binary clock, it really is not one. I am bothered by ThinkGeek's binary clocks as well as pretty much all of others I've seen. Don't mistake me here I love the nerdniness factor. They are quite amazing devices to marvel your friends with. The problem is that true nerds have recognized and been bothered since the beginning by these bearers of false names. They are in fact binary-coded decimal clocks not binary clocks.

Here is an example of this type of clock.

Notice that it keeps a column for each digit of the time. This is because they are using 1 binary number for each decimal digit. This is not true binary. If it were binary there would be 3 columns: hours, minutes, and seconds. I now sit and wait for ThinkGeek to begin selling a real binary clock which is not a binary-coded decimal clock.

I should form a group called Coalition Against Binary-Coded Decimal Clocks Being Advertised as Binary Clocks (CABCDCBABC).

Yes, I like the name and the acronym is catchy and easy to remember. CABCDCBABC members unite!

Handling Keyboard Input in Silverlight

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.

Creating a Game Loop Using Silverlight

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.

Programming Information Titled Security

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?

Enabling Mixed Mode Authentication in SQL Server

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.

SQLServerConnectWindow

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.

SQLServerContextMenu

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

SQLServerMixedModeAuth

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

SQLServerConfigMessage

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.

SQLServerRestartContext

Congratulations you're done.

Change SQL Server Instance for Visual Studio Database Project

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.

SetValidationDatabase-Step1

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.

SetValidationDatabase-Step2

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.....

Creating a Recursive FindControl Extension Method

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!

Linking to the "I'm Feeling Lucky" Google Search

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

Google-FrenchMilitary

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 current version of the Google results page, but it is still pretty nice. I could also link to this site, and send people through Google to get there.

Orcs Goblins and .NET

Have a great day, and don't use this for anything nefarious!

Watch TV Shows on Hulu

Not sure if everyone new about this. I would argue it is not off topic since it is an interesting thing on the web. Hulu is a great new service for watching television shows online anytime. Commercials are short and quick. It is an amazing service I expect plenty of people to start using. I've watched a few shows on there already.

Hulu-Home

I've found the interface quite easy to use and understand. Nothing seems weird or difficult. So when you go to watch a show you might get a message like this before the show starts.

Hulu-AdsQuestion

OK, cool. I can either watch one movie trailer at the beginning or I can have some commercial breaks. Not too shabby. If the movie trailer sounds interesting I will watch it, and if not I'll take the commercials. Trust me the commercials are not bad at all. There are not too many of them, and they are quite short compared to standard television commercial breaks.

Hulu-Commercials

This example I have here is a 1:26 runtime, so that is not too many commercial breaks. Plus, you can see when they are coming . This is a two hour long episode on television, so as you can imagine there are normally more and longer breaks. I've been very impressed with how quickly I can skip to any point in the show and watch. I've never had it lag on me, and it has never given me any loading screens or pinwheels that I often receive from other sites. Not sure how they got everything to stream so quickly and nicely, but you can be sure I will be watching on here a lot now.

If you have not looked at Hulu yet, you really need to. It is an amazing service, and it is free.