Brendan Enrick

Daily Software Development

Visual C# 2008 Keyboard Shortcut Reference

As I've said previously, I am working with developers who are just beginning to learn the tools of the trade. They have a long way to go working with plenty of applications. All people always have more they can learn, so I'll pass along a useful reference here. I found this great reference sheet from Microsoft that has a bunch of key-bindings for Visual C# 2008. It is a PDF poster you can use to reference different shortcuts available to you.

http://www.microsoft.com/downloads/details.aspx?familyid=e5f902a8-5bb5-4cc6-907e-472809749973&displaylang=en

Return Within a C# Using Statement

While writing some code earlier today I needed to return from within a using statement. Doing these sorts of things always makes me appreciate the using statement and how wonderful it really is, so I decided to write about it here. As many of you know the using statement in C# is a good tool for managing types which will be accessing unmanaged resources. Some examples of these are SqlConnections, FileReaders, and plenty of other similar types. The key to these is that they all implement the IDisposable interface. This means that they all need to be cleaned up carefully after using them.

The using statement is great because it guarantees that the declared object is disposed no matter how the execution completes. Whether you reach the end curly brace marking the end of the using statement, throw and exception, or return from a function, the using statement will call the dispose method and clean up the object.

This was important in my code because I was able to return directly from within the using statement without worrying about whether or not eh dispose method will fire. Whenever I use an object which accesses unmanaged resources I always always always put it in a using statement.

It is very important to use a using statement, because it will give you this guarantee that the object will be disposed of correctly. The object's scope will be for the extent of the using statement, and during the scope of the object it will be read-only if defined in the using statement. This is also very nice, because it will prevent this important object which manages the unmanaged from being modified or reassigned.

This is safe to do, because of how great the using statement is. No matter which return we hit we know the XmlReader will be disposed of correctly.

using (XmlReader reader = XmlReader.Create(xmlPath))
{
    // ... Do some work...
    if (someCase)
        return 0;
    // ... Do some work...
    if (someOtherCase)
        return 1;
}
return -1;

Happy coding. Enjoy this powerful tool.

Update: I've posted a follow up to this post with a code sample. It shows that you can return from inside of a using statement in C#.

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!