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.

Scot ALT.NET: An Evening of O/RM

O/RMs help us bridge the gap between the database and the code base we love to write. On the night we will be looking at two O/RMs, NHibernate the most mature O/RM in the Alt.Net space and Microsoft’s recently released Enitiy Framework, the young pretender to the O/RM thrown.

ScottLogic, a leading financial software and consultancy company based in Edinburgh, have been kind enough to offer the use of their premises for an evening of O/RM knowlege sharing and dicussion.  The event will take place on 2nd of July at 7pm, 17 Gayfield Square Edinburgh EH1 3NX.  All are welcome!

The agenda

19:00 – 19:30 Paul Cowan – An Introuction to NHibernate
19:30 – 20:00 Chris Canal – FluentNHibernate in 15 minutes
20:00 – 20:10 Break
20:10 – 20:40 Colin Gemmell – NHibernate vs Entity Framework – which is best?

After the meeting we will retire for a beer and some heated discussion.  If you are planning to attend, please let us know by registering at the Scot Alt.Net Edinburgh EventBrite page (http://altdotnetedinburgh.eventbrite.com/).

About the speakers

Paul Cowan has recently started his own business Cutting-Edge Solutions.  He is a keen advocate of iterative development, test driven development, continuous integration and modern techniques.  Paul is a regular committer to the horn open source project.  He recently gave a presentation on horn at the Dsl DevCon at Microsoft in Seattle.  You can follow his blog here.

Chris Canal has worked at a Web Developer for the past 7 years. Starting with procedural languages like ASP and PHP, he quickly moved onto the .NET Platform when first released. A great believer is continual–improvement, Chris is constantly looking for new technologies, tools and methodologies that will help in creating robust and maintainable software applications. Having felt the pain of using Microsoft “Demoware”, Chris has become an active member of the Scottish Alt.Net Community to share his findings and ideas with like-minded developers.

Colin Gemmel is a Web/Application Developer working in the Medical Faculty of Glasgow University for the past 3 years. An avid follower of agile principles and practices he is always happy to pass on his views of software development to anyone that will listen. Colin is also a regular participant of the Scottish Alt.Net Community

http://scotalt.net/blog/2009/06/11/an-evening-of-orm/
http://www.scottlogic.co.uk/contact_info
http://altdotnetedinburgh.eventbrite.com/
http://groups.google.com/group/scotaltnet

Things I've retweeted

I just had this fantastic idea. I share things I like on twitter by “retweeting” it. But I thought I’d spread the link love a bit more by blogging an aggregate of these retweets from time-to-time. The retweets here have been modified slightly so that links are more “normal”

 

 

* Actually, this was one of my comments that was retweeted by a few other folk.

Granny's Shortbread

By request from Betsy Weber, I’m revealing my granny’s shortbread recipe (with permission).

Ingredients

  • 200g plain flour
  • 100g Butter
  • 50g Castor Sugar (called superfine sugar in the US)

Method

  • Mix the flour and sugar together
  • Cut the butter in to pieces.
  • Using fingertips rub it into the mixture until evenly distributed (almost like bread crumbs)
  • Knead the mixture together into a soft but not sticky dough.
  • Divide the mixture and shape into rounds (about 1cm thick).
  • Place rounds on greased baking tray(s)
  • Bake at gas mark 3 / 325°F / 160°C for about 45 minutes until the shortbread is a pale golden colour.
  • Cool before storing in an air-tight container

Variations

Instead of rounds, the mix can be spread out over a rectangular tray and cut in to fingers after baking, but before cooling.

I should also note that following the recipe above will not give the same results as the 8 decades worth of expertise in lovingly baking shortbread that my granny has. As a child the first thing I asked for when visiting was always: Did you make any shortbread?

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

Upcoming events

In June Scottish Developers have two evening events with Kathleen Dollard. Kathleen is the Chief Technologist for AppVenture (www.appventure.com) where she leads the application generation efforts. She has been a Microsoft MVP for 11 years and is a member of the INETA Speaker’s Bureau. Kathleen has worked extensively with application code generation and is the author of Code Generation in Microsoft .NET (from Apress). She has published numerous articles on a range of .NET technologies and writes the monthly column “Ask Kathleen” in Visual Studio Magazine (www.visualstudiomagazine.com). Kathleen is also active in the Northern Colorado .NET SIG, Denver Visual Studio User Group, Northern Colorado Architect’s Group, and IASA Denver.

Rethinking Object Orientation

Monday 22nd June, 2009 at the offices of Baillie Gifford & Co.

Decades after object orientation design altered programming, it’s still evolving, and we’re still learning to use it better. Many changes in the tools we use and how we write applications affect the approach we take to OOD. Some of these changes relate to architecture where new approaches like SOA and the layering revolution behind Silverlight alter the place of traditional OOD within the bigger picture of architecture. Other changes are language improvements that alter the very meaning of the phrase “object” from a design point of view. While touching on architecture, this talk focuses primarily on the effect of language features like generics, extension methods, delegates/lambda expressions, partial classes/methods, reflection, anonymous types, and declarative programming. I’ll the growing role of interfaces as a contractual base in block based development and show a roll your own example of dependency injection so you understand this basic technique more often accessed through a tool. You’ll come away ready to leverage new features while retaining solid overall design.

Sign up for Rethinking Object Orientation!

Your Application in Pieces – MEF and MAF

Tuesday 23rd June, 2009 at Glasgow Caledonian University

Decoupling portions of your application has tremendous payback during both development and maintenance. Your application becomes more testable and flexible and can more easily evolve to meet changing demands. Decoupling your application also allows a new level of partnership with external groups because you can safely incorporate their code in your application without recompiling or releasing source code. Microsoft has exposed different provider models in many areas of the framework and libraries, and this year has moved toward consolidating its efforts at decoupling with the Managed Extensibility Framework, or MEF. This tool differs from an IoC container because its focused directly at simplifying the extension of applications and focuses at extensibility, discover, and composition. The underlying engine can support Microsoft efforts like Visual Studio and your own applications. MEF comes up short when you encounter isolation and versioning issues, such as wanting that external code to run in its own AppDomain. The Managed Add-In Framework, or MAF, focuses on these problems and the significant complexity they bring with System.AddIn namespace of .NET 3.5. You’ll learn more about architecting applications in pieces and the sweet spot of using MEF and MEF together. You’ll leave ready to evaluate the role of MEF and MAF in your applications.

Sign up for Your Application in Pieces – MEF and MAF!

What not to develop

I was recently looking to book a hotel in Southwark in London. I thought I’d found the perfect hotel, it was inexpensive (by London standards) and close to where I would be visiting. They also had availability on an offer for £75 per night, so long as you checked in and out on specific days, which I happened to be doing. It looked perfect.

But then things started to go wrong.

I selected the rate from the availability page and clicked the “Book” button. The next page popped up (it opened a new window) and the details were pre-populated. However, it had changed the number of nights from 2 to 3. I didn’t want 3 nights, so I changed it back to 2 and I got a rather terse message saying “Minimum Stay: 3”. I’m happy to accept that style of message from a compiler, but not from a public facing website.

I went back and repeated the process wondering if I’d somehow clicked on the wrong rate. I double checked everything this time. Date is correct (but in an American format on a .co.uk website), number of people (1), number of nights (2), number of rooms (1), the room description explicitly gives the rules for the stay conditions for the rate. I meet all the conditions that are presented to me. I press “Book” again…

And it has pre-populated everything again and added an extra night on. I don’t want an extra night! Why even present me with a rate that I can’t have because it doesn’t meet my needs.

By this point I’m more than a wee bit frustrated. So I take off to the website’s contact us page. Instead of providing an email address there is a form to fill in. So, I write a description of the issues I was seeing on their site at which point the site fails again. It failed spectacularly badly. If it had taken me to an error page I would have just shrugged my shoulders and gone off elsewhere. But no, it decided to throw up its internals at me. It vomited details of the SQL Statement that failed, stack traces and so on.

It even had the audacity to tell me that “The following information is meant for the website developer for debugging purposes.” It might have well have said “The following information is meant for an attacker so they can destroy our server.”

So, back to my title, what not to develop. There were many failings on this website that I could see. The user experience was poor to start with and it then descended in to abject failure when it vomited its guts up at me.

1. Don’t use pop-up windows; browsers may block them; they cause confusion for some users. Absolutely do not have a pop-up out of a pop-up; it clutters my screen with needless windows.

2. Don’t have a disconnect between the display locale on the site and the TLD. If you have a geographic TLD then display information in a way that consistent with the culture of that location. e.g. Do not display dates in Month/Day/Year format when you are serving pages on a .co.uk domain. If you have customers from overseas and want to localise content for them then offer that ability, but default to your own locale if you don’t know their preference. Some websites try to be clever and will detect based on the IP of the user but even this isn’t 100% accurate. I’m located in Glasgow, but if you use a IP geo location service it shows me in Greater Manchester.

3. If a user has told you their needs do not present rates that do not meet those needs. If you do want to show near alternatives then make it clear that the details entered do not match the rate displayed, but some minor changes will get the user the rate. Put this information at the bottom or in a different colour. Anything that makes it easily distinguishable.

4. Don’t allow a business rule to mismatch the user friendly description. Make sure that the description of the rate actually matches the business rules that will be used to enforce the rate. If you have a rate that is described to the user as from X to Y don’t have the underlying business rules enforce a stay from X to Z. That will just irritate people.

5. Don’t give users terse error messages; it is unpleasant and unfriendly. If a user has made a mistake then gently point it out.

6. Don’t just send data to the database without validating it first. If a user has typed something that is too long for the column in the database for which it is destined then the software controlling the website should never have attempted to send it to the database in the first place.

7. Don’t display information that could be useful to an attacker. Don’t display stack traces, SQL Statements, system generated error messages, code snippets, etc.

Rant of the day: Learn to frickin' count!

I was in a shop recently and I bought 6 items at £5 each. A total price of £30, even I can manage that mental arithmetic without resorting to a calculator. However, the till decided that the total price was £30.01. For a penny I really can’t be bothered to argue, but it got me thinking about code quality and wondering about what awfulness must be sitting in that system to create such a simple basic mistake.

My colleagues are probably all aware of my views on code quality. I rant daily whenever I see examples on ineptitude by people that are paid money to write code. I read and respond on forums in order to help others learn their craft, or just get unstuck when they accidentally dig themselves in a hole. However, I see on an almost daily basis these days people posting their homework questions with no apparent attempt to at least try to work it out from themselves.

Take this example I found on Code Project a while ago:

I need to know how to do some simple things with arrays please help with any!
1.Find largest or smallest value
2.Count how many times a given value is in the array
3.Count the number of even or odd integers in the array
4.Add up the sum and compute the mean
5.Create another array of the same size containing the same values in reverse order
Thanks!

This is very obviously an exercise from an introductory course on the language they were studying. They just want someone to give them an answer that they can copy and paste. If this is what they are like now, imagine what they will be like years down the road writing commercial software.

I’ve seen lots of evidence over the years of people writing software by copy and pasting examples from the internet without thought of what is actually going on. This results in slow, bloated, inefficient code that is integrated very badly with the rest of the system, hard to read, hard to debug, and is just generally a complete mess.

If you are tempted to copy and paste some code snippet from the internet for your application then stop and think first. Do you actually understand the code? If not, then don’t copy and paste it. If you don’t understand it, how will you debug it?

I would say that if you are tempted to copy and paste from the internet that you create a very small test application first, paste it in to that and learn how it works. Once you understand how it all fits together and how it works you can then write a version that will integrate in to your application.

While you are at it, write some unit tests to go with it. Make sure you test for edge cases, make sure you test for some normal cases too. If you ever get a bug, then add a test that replicates the bug. So if someone suddenly discovers your software things that 5 times 6 equals 30.01 you can add a test for it, fix the bug and redeploy the system. Hopefully, this would have been caught before the public get a chance to see the glaring error and write blog posts about it.

Rant of the Day: I hate low fares airlines.

And that is me being diplomatic! There is no point in me naming the airline because, quite frankly, they are all at it. They are all as bad as each other as far as I can see.

Why do they insist on displaying the fare sans taxes and charges. If they are not optional then they need to be included in the fare. I can’t NOT pay taxes. I can’t NOT pay the airport charge.

If it is an optional element then allow that to be added, if the item must be paid in order for me to simply board the plane and get to my destination then roll it into the flight price. If they want to show how “unfair” the tax or airport charges are then split it up on the final confirmation page. I do not, repeat NOT, like being told £30 for the fare and discover another £28 of hidden mandatory extra charges later on.

I hate them all!