Brendan Enrick

Daily Software Development

Introduction to Partial Classes

I've recently written a beginner's article explaining what partial classes are and how to use them. My Partial Classes Tutorial walks you through how how partial classes work, how to create partial classes, when one would use partial classes, and a few other bits of useful information. If you don't know much about partial classes I recommend you read the article it has some useful information in it. If you have any partial class question either ask me here or comment on the article. I will be happy to answer questions.

As always, thank you very much for reading.

Creating a Simple Hello World Application Using MVC

So I am finally sitting down to play with the ASP.NET MVC Framework. I've installed Visual Studio 2008 on my machine. You can obtain a 90 day free trial of Visual Studio 2008 from Microsoft if you don't own a copy. There are also Express Editions of Visual Studio 2008.

After installing Visual Studio 2008 I installed the ASP.NET 3.5 Extensions Preview. It contains the required components to use the new MVC Framework. Now that you have it installed open up Visual Studio and create a new project. Choose the web section and select ASP.NET MVC Web Application. I named my project "HelloMvc".

 NewProjectHelloMvc

Here you can see the files currently in this empty project. Notice there are a bunch of files that it comes with including a Controller and a couple of Views.

 HelloMvcEmptySolution

So now run the application by pressing ctrl + F5. You'll see this page once you run the application.

HelloMvcStartingPage

Fairly simple for now, but hey it works. Now we should try to figure out how to create a simple static page. We'll make it look kind of like that about view that is already in there. We want it to be hello. OK, so click on the About Us link in the application. You'll be at a URL similar to this one http://localhost:64701/Home/About. So as a nice test try changing "About" to Hello in the address bar. You'll receive this nice error message which tells us the first step in creating our Hello World page.

 HelloMvcActionNotFound

Ok so we need to define an action in our controller. The Home part of our URL is saying we want to use the HomeController, so open up that file in the Controllers folder and add the following code into that file.

[ControllerAction]
public void Hello()
{
    RenderView("Hello");
}

Notice that all we needed to do here is to use the ControllerAction attribute for a method we define. We'll defined the method named Hello by added a line calling the RenderView method. Congratulations you've defined your first Controller Action. So we now refresh the page where we previously received an error message, and we're greeted with a new one. So we are on the right track.

 HelloMvcViewNotFound

Now we need to create the view that we are trying to call in our Controller Action. So we'll right click on the Home folder inside of the View folder and select Add then New Item. Here is where Microsoft has tried to trick you. They've now changed how you attach to MasterPages. Instead of picking a Web Form and checking a box you now have a new choice Web Content Form. Make sure you pick that or you'll not get a MasterPage added for you. It will look like this.

 HelloMvcAddNewView

So now that we have that empty view we can quickly add a nice message into it. So go ahead and type in some html like the following.

<h2>Hello World! MVC is here!</h2>

Now you need to go into the code of this view and place in the following.

using System;
using System.Web;
using System.Web.Mvc;

namespace HelloMvc.Views.Home
{
    public partial class Hello : ViewPage
    {
    }
}

Notice here that we need to inherit from the ViewPage class instead of the System.Web.UI.Page class. We are instead using the System.Web.Mvc.ViewPage class. This will allow our .aspx page to work as a view. Make sure to build the application and then open up the view again in the browser. Woohoo you've successfully created an MVC Controller Action and a View. And as some icing on the cake we will now add a link to our view on the MasterPage so that we can easily access this Hello View whenever we want to.

Open up the Site.Master file. It is located in the \Views\Shared. You will see an unordered list in the html. There are currently two list items in the list; Home and About Us. You will want to add a new one using the following code.

<li><%= Html.ActionLink("Say Hello", "Hello", "Home") %></li>

Now refresh the page. From anywhere on this site you can now get to the Hello World View. The method we used here took 3 arguments. The first is the text which appears for the link, the second is the name of the view, and the third is the name of the controller. The following is our final product. We have the Hello World page as well as a nice link to it.

HelloMvcHelloView

Enjoy creating simple MVC Views!

Blogging Code Snippets Using Windows Live Writer

So obviously anyone wanting to write technical blog posts will eventually require code snippets on the posts. Posting code is not very difficult. The basic part is just that you want the browser to know that your text is code and it should not apply standard html formatting to it; wrapping lines, etc. The key ingredient to this is the html tag pre. It tells the browser that the following is special. It really just means that the inner text of the tag is preformatted, and that the browser should do nothing but display the text. Very useful for displaying code snippets. Especially if the snippets are html snippets. Wouldn't it be bad if the browser rendered the code you were trying to show people.

So great we have preformatted text, but it still doesn't look nice at all. Well I could sit there and color the snippets and spend time formatting it nicely, but I use Windows Live Writer. Great tool. I blogged about why I like Windows Live Writer in the past, and the add-ins I am about to mention simply add to my admiration of this tool. There are a few great code snippet inserting tools. Which let you choose a language and it will format the code nicely including some coloring for you. Some will give you containers and fancy alternating lines. I've settled on no container without lines. It seems to work well enough for my purposes. Not too fancy, but still readable enough to allow the code to be useful to others.

I hope that is useful to people out there. I highly recommend these code snippet inserting tools. Also I recommend Windows Live Writer and the plug-ins for it. There are a lot of useful tools for this application. (Yes, I am using Windows Live Writer for this message.)

Happy blogging!

Silverlight Expired The Pain of Reinstalling

So I have been ignoring these messages I've been receiving for a while about Silverlight. Now I might not have ignored it, but it said my version of Silverlight expired. Ok so big deal. You might say, "Why not just go get a new version?" Well it says to go to a certain URL. You can't click on the URL, and you can't copy and paste the text. Typing URLs by hand is so mid 90's.

SilverlightExpiredMessage

So the really annoying part of all of this. I just now navigated to that site by typing in all of that junk. And it takes me to the Silverlight page on the Microsoft site. http://www.microsoft.com/SILVERLIGHT/default_ns.aspx

I am also annoyed that the older versions of Silverlight don't still work. So I click the download link, and when the download completes I run the install, and this pops up on my screen.

SilverlightInstallFailed

What the hell shouldn't the link that the error message sent me take me to a page where the download will just work? Since it is the URL from the error message it should send me to instructions at least. So now that my install has failed at least I have a link to click on. It takes me to this nice page where I get some Silverlight help. It has links to actually go to the pages. The kind where I don't have to type in a URL by hand.

SilverlightHelp

So it says I need to uninstall. Why wasn't I told this before I was sent to go download the Silverlight install at first? So just for kicks because I thought it was kind of funny to have it there. I clicked on the Silverlight Uninstall Instructions. The best thing ever happened. Going to that page gave me the error message again. So they actually try to have Silverlight content on the page with the instructions to uninstall Silverlight...... Now this is truly amazing. They actually have videos explaining how to uninstall Silverlight on this page, but they couldn't give me a link in the error message. They could have just said, "You will need to uninstall your current version of Silverlight. You can download a new version here." That would just be way too easy though.

SilverlightUninstall

Just thought I would share that nice bit of fun with you.

The moral of the story is probably something about not expecting error messages to give good information. Perhaps also that some install files aren't smart enough to handle an upgrade of any kind.

XNA Game Studio 2.0 Released

So I've dropped the ball on XNA. I've been meaning to read and learn about XNA for a while now. Microsoft has done something truly revolutionary here. They're taking efforts to encourage the little guy to write games for their console. As far as I know, they're the first console to do this. Please correct me if I am wrong about that. I'll get to the point now. Microsoft released a new version of XNA Game Studio which is the development environment for working with XNA games. I'm a version behind...

XNA Game Studio Express works along side Visual Studio 2005. In previous version I don't think you were able to use anything except for the C# Express Edition. According to the XNA web site, the new version supports the following versions of Visual Studio.

  • Visual C# 2005 Express Edition
  • Visual Studio 2005 Standard Edition
  • Visual Studio 2005 Professional Edition
  • Visual Studio 2005 Tools for the Microsoft Office System
  • Visual Studio 2005 Team Edition for Software Architects
  • Visual Studio 2005 Team Edition for Software Developers
  • Visual Studio 2005 Team Edition for Software Testers
  • Visual Studio 2005 Team Edition for Database Professionals
  • Visual Studio 2005 Team Suite

They also have some nifty cool starter kits for those of you who hate beginning projects from scratch. They should also be very helpful while learning to develop games using XNA. There are also tutorials and articles on the site which should help us along while learning XNA.

For those of you who somehow missed XNA completely, it is a game development framework. It helps you develop games for Windows as well as Xbox 360.

Now that I've got an Xbox 360 I think I'll finally hop on board if I get the chance. I am only one major version behind on this one.

Static Methods and Interfaces in C#

Someone just commented on my C# interfaces article on ASP Alliance asking an interesting question, and I figure I will respond to it here since I can give a better response here. I don't want to clutter the article comments. Also I can add nifty cool pictures, format all of my text nicely, and write a heck of a lot more here.

This is the excellent question I was asked.

All my classes implementing my interface should have a static funtion.
Why can't I have a static function in an interface???

-Jan

This is how I responded in the article.

One important thing to understand about static methods is that they don't really need to be tied to classes. Static methods basically just exist for convenience.
An interface is as the name says an interface to something. Think of it like an automobile interface. There are defined ways of working with the car. They have a steering wheel a gas pedal and brakes. An interface defines that and all automobiles will have those, but an interface doesn't define anything about "cars in general" (static) it defines what will be the interface for individual cars (instances).

As I was saying interfaces are used for defining interfaces for code. I like my car analogy, but I think I'll use a sail boat analogy this time.

Think of writing an interface in C# called ISailable. This objects implementing this interface will be sailboats. So what does every sailboat need to be able to function. For simplicity I'll say that we just need to have sails and a wheel. All sailboats will also need to be able to sail. So now we've defined how our ISailable objects work. We can now create sailboats using this nice interface. Notice we haven't defined how large the sails are or what style of sails. We just said we need sails. We also did not define the wheel. Is it metal or wood? How large is it? We don't care in the interface the classes implementing the interface will each define those differently. Notice that different boats have very different types of sails.

We might define out ISailable interface in the following way. Keep in mind I am using a lot of simplicity here.

namespace Enrick.Interfaces
{
    public interface ISailable
    {
        void Sail(string destination);
        void Steer(string direction);
        void RaiseSails();
        void LowerSails();
    }
}

Then once we have that defined we are able to implement the interface and create our first sailable object which will of course be a sailboat.

namespace Enrick.Boats
{
    public class SailBoat : Enrick.Interfaces.ISailable
    {
        #region ISailable Members

        public void Sail(string destination)
        {
            // Write sailing logic here. It should be specific to this type of boat.
        }

        public void Steer(string direction)
        {
            // Write steering logic here for this exact type of boat.
        }

        public void RaiseSails()
        {
            // Write logic to raise these specific sails here.
        }

        public void LowerSails()
        {
            // Write logic to lower these specific sails here.
        }

        #endregion
    }
}

Static interfaces do not really apply to what we've defined though. We've just been talking about how to interface with individual sail boats. We haven't gotten to static methods really. This is because static methods aren't really necessary. Many languages have them, but they could just as easily be outside of the class and have the same functionality. Static methods are by definition methods which aren't specific to individual instances of classes. This means we could define these methods anywhere and achieve equivalent functionality. They also don't really apply with interfaces and the C# language specification doesn't allow static methods on interfaces because they don't really make sense with interfaces.

There are circumstances where someone might want to have a static method on an interface. Perhaps the static method was going to be a way of performing an action on an entire collection of the instances of the objects. Perhaps you have a fleet of ISailable ships that you will want to sail together. This would make sense to have a static method which would be associated with the class, but it isn't necessary. Instead we will create a static method elsewhere. It will not be tied to our interface. We can have it take a list of ISailable objects and then it can perform the sailing operation of our fleet.

public void SailFleet(List<ISailable> fleet, string direction)
{
    foreach (ISailable boat in fleet)
    {
        boat.Sail(direction);
    }
}

Notice here that I've defined a method which might have been static before on each of the boats and each one would have take a List of their instances, but that would be silly. This solution allows us to have methods which work with ISailable objects but they need not be defined as requiring an interface. Sadly there is not a way of having static methods on interfaces in C#.

I hope that answers some questions. As always, thanks for reading!

w00t! The Word of the Year is Awesome

Yes, you read that correctly, because Merriam-Webster's Word of the Year is w00t. Most of you have probably heard this interjection often exclaimed by geeks winning some sort of competition usually a multiplayer game. I know not where the word originated. I would assume an online computer game. Perhaps counter strike. I am quite impressed that Merriam-Webster would allow w00t into the contest. I would venture a guess that it is the only word in the competition which uses numbers and letters. Perhaps this is the beginning of a deluge of changes in the English language. The Internet has spawned changes faster than could probably have been imagined in the past. It takes writing over time for a written language to change, but the vast amount of writing which occurs every day on the Internet is an extreme. I expect we'll be seeing far more changes to the language we love in the next few years. What word will be next on the list. I can only wait and hope for 1337. Perhaps it will be next year's word of the year. It lacks letters completely, and overcoming that hindrance will surely pave the way for future Internet-based words.

w00t Merriam-Webster !5 1337!!!!1!

Great Conditional Logic

It is amazing some of the relics that can be found while code reviewing old code. Sometimes developers do things without thinking and make some great code. I am of course referring to some really funny code such as what I found a few minutes ago. I am always annoyed when boolean values are checked explicitly in conditional statements like the following code.

if (IsValid == true)

This bothers me because the true is completely useless. I would read this code as "If is valid is true", and that is kind of silly when I could say "If is valid".

if (IsValid)

This is just part of the annoyance in the code. Now I've cleaned it up a bit here, because it didn't really have a variable named IsValid. It was actually a variable named edit. We were not sure if edit meant that someone was allowed to edit or if it was in edit mode or what.

This was just slightly annoying. The really amazing part was in the else of this if statement. It had a great bit of else if logic. The code looked overall like this.

if (edit == true)
    // Lines of code here
else if (edit == false)
    // Lines of code here

I now wonder what possible other condition is there? In the else is there another state for edit? It is not a reference type, it is a value type so it can never be null. Just got to be careful of boolean operators there are so many other values for them other than true and false.

I hope everyone enjoyed this fun little code snippet.

Little Bobby Tables

One web comic I commonly read is xkcd. It is a great comic that has a lot of good computer as well as just nerdy jokes. It has a great comic about SQL injection attacks and why you need to sanitize your database inputs. This is a lesson in what to not name your child.

I hope that everyone who reads this gets this joke. Quite amazing. This comic is full of great stuff like this. Try to not waste your day reading this grade A material.