How to get a value from a text box into the database

This question was asked on a forum and I took some time to construct a reasonably lengthy reply so I’m copying it to my blog for a bit of permanence.

I suspect that many of my regular readers will be dismayed at the lack of proper architecture (e.g. layering) but we all had to start somewhere and I suspect that your first programs were not properly layered or structured either. I know mine certainly weren’t. My aim with this was to show how a simple goal can be achieved, what basic things are needed and how to fit it all together by doing the simplest thing that would work (a mantra from the agile world).

Here’s the post (slightly edited to put back some of the original context):

Okay – Let’s step back and show the whole thing from text box to database. NOTE: that this example shows everything in one place. This is generally considered poor practice, but as you are only just starting I’ll not burden you with the principles of layered architecture and the single responsibility principle and so on. (Just be aware they exist and one day you’ll have to learn about them)

So, let’s say you have a form with two text boxes, one for a name, and one for an age. Lets call them NameTB and AgeTB. The user can enter information in these text boxes and press a button that adds them to the database.

First, we need to get the data from the text boxes into a form we can use.

string name = NameTB.Text;
int age = Convert.ToInt32(AgeTB.Text);

Since text boxes only deal with strings we have to convert the string into a number (an Int32 – a 32bit integer) for the age value.

Now, we need to set up the database connection and command in order to insert this. I’ll assume you already have a connections string to your database, I’ve called it myConnectionString for this example.

SqlConnection myConnection = new SqlConnection(myConnectionString);
SqlCommand myCommand = new SqlCommand("INSERT Person(NameField, AgeField) "+
    "VALUES (@nameParam, @ageParam)", myConnection);

I’ve now set up the SQL Command with an insert statement. I’ve assumed there is a table called Person and it has two columns called NameField and AgeField. I’m also going to insert the values via parameters, which I’ve indicated with @nameParam and @ageParam. SQL Server requires that all parameter names start with an @ symbol. Other databases may vary.

myCommand.Parameters.AddWithValue("@nameParam", name);
myCommand.Parameters.AddWithValue("@ageParam", age);

We’ve now added the parameters into the SQL command and we’ve given each parameter the value we got earlier. Finally:

myConnection.Open();
myComment.ExecuteNonQuery();
myConnection.Close();

This opens the connection, runs the INSERT statement and closes the connection again. We’re using ExecuteNonQuery because we don’t expect any results back from SQL Server. If we were expecting data back (e.g. because we were using a SELECT statement) we could use ExecuteReader (for many rows/columns) or ExecuteScalar (for a single value).

This is a very basic example. I’ve not shown any error checking or exception handling. There is also the implicit assumption that all this code resides inside a button click event, which is considered poor practice for anything but a small or throw away application.

Dynamic Objects in C# 4.0

It seems only very recently that I was posting about this wonderful new feature in C# 3.0 called LINQ and its associated language features such as anonymous types, object initialisers and lambda expressions. Soon C#4.0 will be released and it has a host of new goodies to look forward to.

So far I’ve just been dabbling with dynamic types and the dynamic keyword.

C# has been up until this point a purely statically bound language. That meant that if the compiler couldn’t find the method to bind to then it wasn’t going to compile the application. Other languages, such as Ruby, IronPython, Magik and IronSmalltalk are all dynamically (or late) bound where the decision about where a method call ends up is taken at runtime.

Now if you declare an object as being dynamic the compiler will hold off, just as it would do naturally in a dynamic language. The method need not exist until runtime. The binding happens at runtime. SnagIt CaptureIf, like me, you rely heavily on intellisense to figure out if you are doing the right thing then you are going to have to get used to not having it. Since the call will be bound at runtime the compiler (and of course intellisense) won’t know whether a binding is valid or not. So, instead of regular intellisense you get a message simply saying “(dyanmic expression) This operation will be resolved at runtime.”

So, how do you get started with dynamic objects? I suppose the simplest example would be an object graph that is built at runtime that would normally have a fairly dynamic structure, say a nice XML file.

In this example, I’m going to take an XElement object (introduced in .NET 3.5) and wrap it in a new object type I’m creating called DynamicElement. This will inherit from DynamicObject (in the System.Dynamic namespace) which provides various bits of functionality that allows late binding.

using System.Dynamic;
using System.Linq;
using System.Xml.Linq;

namespace ColinAngusMackay.DynamicXml
{
    public class DynamicElement : DynamicObject
    {
        private XElement actualElement;

        public DynamicElement(XElement actualElement)
        {
            this.actualElement = actualElement;
        }

        public override bool TryGetMember(GetMemberBinder binder,
            out object result)
        {
            string name = binder.Name;

            var elements = actualElement.Elements(name);

            int numElements = elements.Count();
            if (numElements == 0)
                return base.TryGetMember(binder, out result);
            if (numElements == 1)
            {
                result = new DynamicElement(elements.First());
                return true;
            }

            result = from e in elements select new DynamicElement(e);
            return true;
        }

        public override string ToString()
        {
            return actualElement.Value;
        }
    }
}

The key method in this class is the override of the TryGetMember method. Everytime the runtime needs to resolve a method call it will call this method to work out what it needs to do.

In this example, all that happens is that if the name matches the name of a child element in the XML then that child element is returned. If there are multiple child elements with the same name then an enumerable collection of child elements is returned.

SnagIt CaptureIn the event that there is no match the method defers to the base class. If the binding fails then a RuntimeBinderException is thrown.

However, if the binding works you can make complex or ugly calls look much easier. For example. This program using the DynamicElement class to read the contents of an RSS feed:

using System;
using System.Xml.Linq;
using ColinAngusMackay.DynamicXml;

namespace ConsoleRunner
{
    class Program
    {
        static void Main(string[] args)
        {
            XElement xel = XElement.Parse(SampleXml.RssFeed);
            dynamic del = new DynamicElement(xel);

            Console.WriteLine(del.channel.title);
            Console.WriteLine(del.channel.description);

            foreach (dynamic item in del.channel.item)
                Console.WriteLine(item.title);

            Console.ReadLine();
        }
    }
}

The program starts off by reading in some XML into a regular XElement object. It it then wrapped up into the DynamicElement object, del.

The variable del is declared as a dynamic which lets compiler know that calls to its members will be resolved at runtime.

The program then uses the dynamic object to very easily navigate the XML. In this example, I’ve used the XML of the RSS feed for my blog.

The output of the program is:

SnagIt Capture

 

The barrier to entry for creating and using dynamic objects is quite low. It will be quite interesting to see how this new feature plays out.

Many people like the additional comfort that static binding at compile time provides as it means less things to go wrong at compile time. Advocates of dynamic binding often argue that if you are doing TDD then the tests will ensure that the application is running correctly.

Of course, dynamic binding, like any other language features, is open to abuse. I fully expect to see on forums examples of people who are using it quite wrongly and getting themselves into a terrible pickle as a result. This does not mean that dynamic objects are bad, it just means programmers need to learn how to use the tools they have correctly.

Caveat Programmator: This blog post is based on early preliminary information using Visual Studio 2010 / .NET Framework 4.0 Beta 1

Rant of the day: IDisposable

My colleagues are probably used to the fact that I rant about code quality frequently. I take code quality very seriously. Not because I’m especially expert in it, but because features of basic code quality make it easier for other people to read and maintain the code.

Today’s irritation comes from some code (replicated in a number of classes I might add) that implements IDisposable. It is a fine interface and by implementing it you are telling the rest of the world that you have some stuff that can’t just be left to the garbage collector to clean up. These are things like file streams, database connections, etc. Any type of scarce resource that you want to hand back as soon as you are finished with it rather than leave it up to the garbage collector.

However, I came across this “gem” in some code today where the class, basically a utility class, contained no fields (so it wasn’t holding on to anything at all, let alone anything that might be a scarce resource). Yet, for some reason it implemented IDisposable. What was it going to dispose? What could it dispose?

The answer was in the code:

public void Dispose()
{
    // Nothing to dispose of.
}

Quite!

The StackOverflowException

Take a look at the following code:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            RecurseForever();
        }
        catch (StackOverflowException)
        {
            Console.WriteLine("Caught Stack Overflow Exception");
        }
        catch (Exception)
        {
            Console.WriteLine("Caught general Exception");
        }

        Console.ReadLine();
    }

    static void RecurseForever()
    {
        RecurseForever();
    }
}

What do you think the output of the program will be?

If you had asked me a few days ago I’d have said the output would be “Caught Stack Overflow Exception”, however that isn’t the case. If you run the code in the debugger this is what you actually get:

StackOverflowException

The exception simply isn’t caught.

If the application isn’t being debugged it will simply end at this point. It goes directly to jail. It does not pass GO. It does not collect £200.

ConsoleApplication2 has stopped working

Formatting dates the hard way

I was doing a bit of a code review and I spotted this in the code base.

string[] splitOptions = new string[1] { dayEarlier.Date.Year.ToString() };
string[] earlyDates = dayEarlier.Date.GetDateTimeFormats();
string[] earlySplit = earlyDates[67].Split(splitOptions,
    StringSplitOptions.RemoveEmptyEntries);
earlySplit[0] = earlySplit[0].Replace(",", string.Empty);

Essentially the code gets the date in a specific format. However, it does it in the oddest most convoluted way I’ve ever seen.  Just to explain, here is the code again but this time I’ve added some comments:

// dayEarlier is a business object with a property called Date that returns a DateTime.
// splitOptions will contain the year in an 1-element string array.
string[] splitOptions = new string[1] { dayEarlier.Date.Year.ToString() };

// earlyDates will contain the dayEarlier Date in umpteen different formats.
string[] earlyDates = dayEarlier.Date.GetDateTimeFormats();

// earlySplit will contain the 68th (!) formatted date (out of 89 that get generated).
// Element 0 in this array will contain the bit upto the year, element 1 will contain
// the bit after the year. The year itself is discarded.
string[] earlySplit = earlyDates[67].Split(splitOptions,
    StringSplitOptions.RemoveEmptyEntries);

// The first element (element 0) of earlySplit is then modified to remove the comma.
earlySplit[0] = earlySplit[0].Replace(",", string.Empty);

In short, what is actually being looked for is the day name, day of the month and the month. That’s it. And that, apparently, isn’t even in the 89 permutations of the date that .NET generated in the second line of code. To add to the potential problems with this, I’ve not seen any documentation that states that the permutations given by this method will stay the same.

All this code could easily be re-written simply as:

dayEarlier.Date.ToString("ddd dd MMM");

And the bonus here is that we are not generating 88 completely useless permutations, nor are we generating the permutation that is simply the closest match that we still have to futz around with. We are generating the date in exactly the format that we want. (Current culture permitting)

Errors like these drive me insane

Today I was trying to fix up a website for one of our clients. I got the site out of source control but somehow or other it wouldn’t compile. I’m not going to talk about the fact it didn’t compile out of the box – We all know that is not a good situation and the person who allows source to get into a state like that needs to be slapped repeatedly with a wet fish.

What I’m going to talk about is what the eventual error turned out to be because it is not something I’ve ever seen before and it was such a bizarre thing that I can only hope it isn’t common. But if you are afflicted by it you will be pleased to know that the solution is easy, even if the discovery of what the problem actually was wasted several hours.

If you are reading this then I suspect you will probably be suffering from this problem in which case you are probably now yelling “STOP BABBLING MAN AND TELL ME WHAT TO DO”.

First, a description of the problem:

There is an ASP.NET web site project (probably does the same thing on a web application… And let’s not get in to why this is a web site project, it’s an old project and the standard now is web applications) with a number of web forms in it.

The ASPX for the default page currently looks something like this:

<%@ Page Language="C#" AutoEventWireup="true"
      CodeFile="Default.aspx.cs" Inherits="Default" %>
<html>
<head><title></title></head>
<body>
    <form id="form1" runat="server">
        Stuff that's on my page
        <asp:Label ID="MyLabel" runat="server"></asp:Label>
    </form>
</body>
</html>

Nothing too odd about that, you might say… And you’d be right. There is nothing at all wrong with this page. However, when you go to compile your website you get this error:

Infuriation 2
The name ‘MyLabel’ does not exist in the current context

But… but… but… You can see that MyLabel exists on the ASPX page and if you type in the C# or VB source file you’ll see that intellisense finds the object perfectly well. So what is going on?

Well, it is interesting to note that Page1 and Page2 are very similar to Default. In fact, so similar that when they were created the person that did this just copied Default.aspx and Default.aspx.cs (or Default.aspx.vb if that’s your poison). What they didn’t do when they made the copies was to change the page directive at the top that has the Inherits attribute that points to Default. So, Page1 and Page2 are inheriting the behaviour in Default.

When this first happened that wasn’t a problem. Page1 and Page2 had just minor cosmetic differences, the behaviour was the same and no one noticed.

At some point later someone came along and added MyLabel to Default.aspx… This still didn’t make a difference. Everything worked as normal.

Then someone came along and realised that MyLabel needed to change on some condition and added some code into the Default.aspx.cs file that modified MyLabel. At this point all hell broke loose!

Suddenly, MyLabel can’t be found and no one can figure out why. It is there on the ASPX page, intellisense picks it up, the stupid compiler can’t see it.

The Solution

Eventually, after spending a couple of hours on the problem and batting it around some collegues and doing bit of brainstorming someone (let’s call him Craig Muirhead because he figured it out in the end and deserves the credit) comes up with the idea that perhaps other pages are inheriting the wrong class. A quick find in files on the name of the class and we found it was referenced by 4 other pages. It takes a matter of moments to fix all those files to point to their respective code behind files/classes rather than the one on our hapless page. And all of a sudden everything compiles.

Technorati Tags: ,,,,

Crazy Extension Methods Redux (with Oxygene)

Back in April I blogged about a crazy thing you can do with extension methods in C#3.0. At the time I was adamant that it was a bad idea. I still think it is a bad idea, however, my thoughts have evolved a little since then and I have, possibly a solution to my hesitance to use said crazy feature.

So, if you can’t be bothered to click the link, here is a quick recap. You can create an extension method and call it on a null reference and it will NOT throw a NullReferenceException like a real method call would. At the time I was saying it was not best practice because it breaks the semantics of the dot operator which is used for member access.

Last night, I attended an excellent talk by Barry Carr on Oxygene, an Object Pascal based language that targets the .NET Framework. Oxygene has a very interesting feature, it has a special operator for dealing with calls on a reference that might be null. If that language can do it, what’s so wrong with the functionality that Extension methods potentially give? Semantics. Notice that I said that Oxygene has “a special operator”. It doesn’t use the dot operator. The dot operator still breaks if the reference is null. It has a colon operator. In this case if the reference is null (or nil as it is called in Oxygene) then the call to the method doesn’t happen. No exception is thrown.

For example. Here is the code with the regular dot operator:

class method ConsoleApp.Main;
var
  myString: String := nil;
begin
  Console.WriteLine('The string length is {0}', myString.Length);
  Console.ReadLine();
end;

And the result is that the NullReferenceException is thrown:

NullReferenceException

Here is the code with the colon operator:

class method ConsoleApp.Main;
var
  myString: String := nil;
begin
  Console.WriteLine('The string length is {0}', myString:Length);
  Console.ReadLine();
end;

And the result is that the program works, it just didn’t call the property Length as there was nothing to call it on:

Result

At this point I really would like to show you what this looks like in Reflector to show you what is going on under the hood, however, I get a message that says “This item is obfuscated and can not be translated” and the code afterwards isn’t quite right. However, the crux of it is like this in C#:

int? length;

if (myString != null)

length = myString.Length;

Console.WriteLine(“The string length is {0}”, length);

Now, back to these extension methods. After seeing this I was thinking that perhaps my total unacceptablity of allowing a null reference to be used with an extension method was perhaps incorrect. In a normal situation with an accidental null reference exception being used the NullReferenceException wouldn’t be thrown at the point of the method call (after all, the null reference is actually being passed in as the first parameter in an extension method), but somewhere in the method itself. Normal good practice would place a guard block at the start of the method so that it would be caught immediately.

However, what if you wanted to create similar functionality to the colon operator in Oxygene and have it ignore the null reference and do nothing? Well, my advice would be to create a naming convention for your extension methods to show that null references will be ignored. That way you can get the functionality with a slight semantic fudge of the dot operator. Of course, you still have to do the work and set up guard blocks to handle the null situation yourself in the extension method.

Here’s an example:

class Program
{
    static void Main(string[] args)
    {
        string myString = null;
        Console.WriteLine("The string length is {0}", myString.NullableLength());
        Console.ReadLine();
    }
}

public static class MyExtensions
{
    public static int? NullableLength(this string target)
    {
        if (target == null)
            return null;
        return target.Length;
    }
}

Tip of the Day #8 (string performance)

Concatenating strings in .NET can be very easy. There is the overloaded + operator that makes stringA + stringB + stringC statements very easy to write. But, it isn’t very performant. The reason is that strings are immutable, and concatenating strings in this way causes lots of short-lived objects to be created and thrown away, which in turn causes the garbage collector to run frequently.

There are two better ways in .NET to concatenate strings. One is to use the string.Concat() method. The other is to use the StringBuilder class. They both perform better than adding strings together, but you still have to know when to use each.

According to this article on “Performance considerations for strings in C#string.Concat() is good up to 600 strings. But, only if you have 600 strings to concatenate in a single statement. StringBuilder is better if you have more than 600 strings to concatenate, but you can do so over multiple statements. In reality, I think the benefits of appending strings over multiple statements with StringBuilder will work out better even with much less than 600 strings because to get the performance out of string.Concat() you’ll have to perform some form of setup operation to line all those strings up – and that will take time.

So, today’s tip is don’t use the plus operator to combine strings except in quick / throw-away applications. Use string.Concat() or StringBuilder instead.

Monitoring change in XML data (LINQ to XML series – Part 5)

This is the 5th part in a series on LINQ to XML. In this instalment we will look at monitoring changes in XML data in the XML classes added to .NET 3.5.

The XObject class (from which XElement and XAttribute, among others) contains two events that are of interest to anyone wanting to know about changes to the XML data: Changing and Changed

The Changing event is triggered prior to a change being applied to the XML data. The Changed event is triggered after the change has been applied.

An example of adding the event handler would be something like this:

XElement root = new XElement("root");
root.Changed += new EventHandler<XObjectChangeEventArgs>(root_Changed);

The above example will trigger for any change that happens in the node the event handler is applied to and any node downstream of it. As the example is applied to the root node this means the event will trigger for any change in the XML data.

The event handler is supplied an XObjectChangeEventArgs object which contains an ObjectChange property. This is an XObjectChange enum and it lets the code know what type of change happened.

The sender contains the actual object in the XML data that has changed.

Adding an element

Take the following example where an element is added to the XML data.

XElement child = new XElement("ChildElement", "Original Value");
root.Add(child);

In this case the ObjectChanged is Add and the sender is the XElement: <ChildElement>Original Value</ChildElement>

A similar scenario happens when adding an attribute. However, instead of the sender being an XElement it will be an XAttribute.

child.Add(new XAttribute("TheAttribute", "Some Value"));

Changing an element value

If the value of the element is changed (the bit that currently says “Original Value”) then we don’t get one event fired. We get two events fired. For example:

child.Value = "New Value";

The first event with ObjectChanged set to Remove and the sender set to “Orginal Value” (which is actually an XText object) and the second event with the ObjectChanged set to Add and the sender set to “New Value” (again, this is actually an XText object).

Changing an element name

If the name of the element is changed then the ObjectChanged property will be set to Name and the sender will be the XElement that has changed.

child.Name = "JustTheChild";

Changing an attribute name

Unlike changing an element value, when the value of an attribute changes the ObjectChanged property will be Value and the sender will be the XAttribute.

child.Attribute("TheAttribute").Value = "New Attribute Value";

Technorati Tags: ,,,

Tip of the Day #4 (Connection Strings in Config files)

From .NET 2.0 onwards a new and improved configuration management system has been put in place. You can now add a <connectionString> element to the config file and use it to place the connection strings to the database and then retrieve then in a consistent way in your application. It supports multiple connection strings too if you need to access multiple databases.

The config file looks like this:

<configuration>
...
   <connectionStrings>
    <add name="Default" connectionString="Server=(local);database=MyDatabase"/>
  </connectionStrings>
...
<configuration>

From the .NET application you can access the connection string like this:

connectionString =
    ConfigurationManager.ConnectionStrings["Default"].ConnectionString;

Just remember to add a reference to System.Configuration in your project and ensure that the code file is using the System.Configuration namespace as well.