An Introduction to ASP.NET MVC

[More details and registration]

 

16th October 2008 at 19:00 in Edinburgh

Today, ASP.NET webforms is a well established and highly productive platform for building web applications. Some people though, crave more control. They want to operate that bit closer to the metal, enjoy a clear separation of concerns and ensure that unit testing their application is made as easy as possible.

Enter ASP.NET MVC. ASP.NET MVC enables you to build Model View Controller (MVC) applications with the ASP.NET framework as an alternative to ASP.NET webforms.

In this session we’ll take a look at the drivers behind MVC, the architecture of a typical ASP.NET MVC application, new features in ASP.NET that make it possible and we’ll build a simple ASP.NET MVC application to explore the key concepts.

Speaker Bio

Mike Ormond gained a BSc(Hons) in Information Engineering from the University of Strathclyde before moving south of the border many years ago. After spending some time with the Defence Research Agency, Mike joined Mars Electronics where he worked on automated payment systems. In 1996 he joined Mercury Interactive before heading over to Microsoft in 1997 to work in their developer support organisation.

In 2003 he joined the Developer and Platform Group as a Developer Evangelist. Since then he’s travelled the length and breadth of the land talking about Microsoft’s platform and developer tools. Currently Mike’s interests include ASP.NET, AJAX, Silverlight and developing solutions with Office Open XML.

When he’s not working, Mike likes to potter in his allotment and listen to Radio 4 on the wireless.

You can contact Mike at: http://mikeo.co.uk

 

[More details and registration]

 

 

The Apple Store

For the first time ever, I bought something in the Apple Store today. Yes, that’s right, I got an iPhone recently and I love it! I feel so dirty yet soooo gooooood!!!

Earlier this evening I went along to my local Apple Store to get a car charger for my iPhone. The shopping experience has to have been the most pleasant I’ve ever experienced.

The staff were very helpful for a start. Nothing unusual about that, staff are helpful in lots of shops.

The staff were also very knowledgeable and were happy to recommend alternatives that I could not necessarily buy in the store. That is slightly unusual because normally staff are trained to ensure the customer buys from the company, not someone else’s. I liked the fact that the staff wanted to ensure that I got the product best for my needs. That is a big plus and it means I will trust them more and will seek their advice again, which obviously means more potential sales for Apple.

As it happens, I wasn’t interested in the alternatives so I did make a purchase. Now this is where it got really interesting. (At least for me, but I’m pleased with lots of simple things)

When I said that I was happy with this particular car charger and I looked over to find the cash desks the guy that was helping me simply asked if I would like to pay by cash or card. Still slightly confused by the question at this particular point, he showed me his card-swipey-machine. I caught on fairly quick and offered up my credit card. He handed me the machine like they do in restaurants and I typed my pin and handed it back.

He also asked the strangest question I’ve ever been asked (at least in this context). “Would you like me to email the receipt to <my email address>?”

Since the credit card I use on the Apple Store on-line was the same as the one I used in the physical Apple Store they matched my details and were able to email me the receipt without being hassled for my email address in the store. I like that kind of joined up system. My receipt was waiting for me when I got home. It is safely stored in my email and will not get lost, unlike other receipts.

So, credit where credit is due – Well done Apple.

Developing with SQL Server 2008, deploying on SQL Server 2005

I received the following by email today:

Hi Colin! I found your blog after googling for a bit about SQL Server. I had a question for you… As someone fairly new to .NET development, would it be easier to stick with SQL Server 2005 for now, or just install SQL Server 2008 express? I ask because I don’t yet know enough about the differences between the two to know if there will be any issues when developing small web applications with 2008, but then deploying them to a hosting provider with 2005. Hope that makes sense. 🙂

Cheers,
Sean

I don’t recommend moving to SQL Server 2008 if you will ultimately be deploying on SQL Server 2005.

If you don’t know the difference between SQL Server 2005 and 2008, yet your hosting provider only supports 2005 then you would be better off sticking to working with SQL Server 2005 on your system. The reason for this is that you don’t want to accidentally stumble into features of 2008 that are not supported on 2005.

Also, even if you were intimately aware of the differences between the two versions it is still a good rule of thumb to develop on a system that is as close to the eventual live system as you can. That way you won’t get any unexpected nasty surprises when you do deploy the application and suddenly realise that things are not quite as expected.

If you have already developed the applications then you can set the compatibility level of the database to mimic SQL Server 2005:

ALTER DATABASE [MyDatabaseName] SET COMPATIBILITY_LEVEL = 90

That way you should have a similar (although not necessarily quite the same) experience as if you were developing on a real SQL Server 2005 system. There will still be things that you cannot do. I don’t think backing up your 2008 database and restoring it on a 2005 system will work.

The try-catch-return-false-throw-catch-return-false-throw-fail anti-pattern

I recently came across a wonderful anti-pattern. Well, anti-patterns are not wonderful, but the mind just boggles at the sheer bloody lunacy of this particular anti-pattern. I’m not going to show you the original code, but I’ll show a general representation of what it did:

        private void DoStuff()
        {
            if (!C())
                throw new Exception("The widget failed to process");
        }

        private bool C()
        {
            try
            {
                B();
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        private void B()
        {
            bool worked = A();
            if (!worked)                throw new Exception("The process failed");
        }

        private bool A()
        {
            try
            {
                // Do stuff that might fail.
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

Now I’ve not shown all the code in order to concentrate on the weird stuff. For context DoStuff() was called from the code behind file for an ASPX page, so when it throws an exception the user will be redirected to the error page. The original exception (caught in method A()) is thrown by code from within the .NET Framework itself. It is a valid exception as the situation should only ever occur if the server is misconfigured.

There are many things wrong with this, not least is the number of things thrown. Mostly, what got me was that the wonderful diagnostic information in exceptions is repeatedly thrown away. Nothing is logged anywhere, so no one would be able to ever tell what went wrong. This is utterly hellish from a debugging point of view. In this case it was because of a misconfigured server and took several hours to track down. Had the original exception been allowed to bubble to the top (with appropriate finally blocks in place for clean up) and the exception information logged then the error could have been tracked and fixed in a matter of minutes. Luckily this happened on a dev system. I’m sure a customer would not have been pleased if their revenue generating website was brought down for hours because of a minor, but incorrect, change in a web.config file. In fact, in a production environment the tools for tracking down the error would most unlikely not exist at all. On a dev system at least a debugger and easy access to source code is present.

So, how could this code have been better written?

        private void DoStuff()
        {
            try
            {
                C();
            }
            catch (Exception ex)
            {
                // If you can add information for diagnostic purposes
                // then create a new exception and throw it. Remember to
                // add the existing exception in as the innerException.
                throw new Exception("The widget failed to process", ex);
            }
        }

        private void C()
        {
            try
            {
                B();
            }
            // Do not catch the exception, nothing was was done with it.
            finally
            {
                // Do any cleanup.
            }
        }

        private void B()
        {
            try
            {
                A();
            }
            catch (Exception ex)
            {
                // Put this caught exception into the new exception
                // in order to keep the detail. This new exception
                // adds detail to the error.
                throw new Exception("The process failed", ex);
            }
            finally
            {
                // Do cleanup
            }
        }

        private void A()
        {
            try
            {
                // Do stuff that might fail.
            }
            finally
            {
                // Do cleanup
            }
        }

This is better, if you ignore the fact that I’m catching and throwing general Exception objects – You should always throw and catch the most specific exceptions that you can.

The main benefit here is that the original exception is allowed to bubble up. When it is possible to add value to the exception a new exception is created and it holds the original as the innerException object.

Note that “The process failed” and “The widget failed to process” are stand-ins to represent meaningful and valuable exception messages. In normal circumstances messages like that do not usually add value.

Scottish Developers August Newsletter

Welcome

I hope you’ve all managed to have a great summer as we enter into our Autumn schedule.

The big news in the Microsoft world this month is that SQL Server 2008 was released to manufacturing (RTM) and Visual Studio 2008 SP1 along with .NET Framework 3.5 SP1 was also released.

We are currently trialling a new events systems, so we’d be keen to hear what you think of it. The events pages will now be on Event Brite. You will be able to see all the details about an event there and register for it. There will also be an RSS feed of all Scottish Developer’s upcoming events too.

As always, we are on the look out for new speakers. If you would like the opportunity to do a presentation on a software development topic from 10 minutes to 90 minutes then get in touch with me at colin@scottishdevelopers.com.

Regards,
Colin Mackay, Chairman, Scottish Developers

Events

25-August-2008 @ 18:30 in Glasgow (Glasgow ALT.NET UG)
Monday Night Coding Session
FREE

The Glasgow ALT.NET user group will be meeting in McGinns at 18:30. First timers are welcome, there will be a sign to point you to the group. The topic will be on creating an IOC container.

9-September-2008 @ 18:30 in Glasgow (Scottish Developers)
An Overview of ALT.NET Technologies
FREE – Registration optional

Most of the patterns and practices that come out of Redmond A.K.A Microsoft are purely to get a response from attendees of conferences like MIX. The same old drag and drop demo ware is both untestable and unmaintainable. Examples of such demo-ware are the CAB application block, SCSF (smart client software factory), ObjectBuilder (a very poor IOC container) and the Entity Framework which many believe to be the catalyst for the ALT.NET movement. The recent ASP.NET MVC framework appears to be an acknowledgement from Microsoft that they want to embrace some of the ALT.NET concepts. The discussion will outline some of the following techniques and frameworks by way of a code review. Attendees are encouraged to participate with questions throughout the duration of the discussion. Some of he concepts and frameworks include: * Test Driven Development (TDD) * Nhibernate (Object Relational Mapper) * Castle Windsor (Inversion Of Control or Dependency Injection) * AOP (Aspect Oriented Programming) * ASP.NET MVC Framework * JQuery (a write less JavaScript library from a very talented team).

8-October-2008 @ 19:00 in Edinburgh (BCS)
The Three Ghosts of Microsoft Security
FREE – Registration Required

In this talk Stephen Lamb will take us through the history of Microsoft security, bringing us up to date on where Microsoft is at today and point out the direction of security improvements coming down the pipeline. He will also discuss how Microsoft responds to security incidents and explain the process to release updates and patches to fix vulnerabilities. Come along to hear why Microsoft software is now some of the most secure on the planet.

29-October-2008 @ 19:00 in Dundee (Scottish Developers)
Look! There’s my data! Virtual Earth san Javascript
FREE – Registration Optional

The Windows Live team have recently made available ASP.NET Server side controls for Microsoft Virtual Earth. In this talk Colin Angus Mackay will show you how to use this control to visualise your data, from sticking some simple pins down for store locations, to drawing thematic maps. All this without writing javascript.

Further Afield

September:
SQL Bits III (Hatfield)

October:
Frank Kerrigan talks about SSIS (Glasgow)

November:
VBUG Conference (Reading)
TechEd Developers (Barcelona)
Developer! Developer! Developer! (Reading)
Functional Programming in C#3.0 (Dundee)

December:
Andrew Westgarth on ASP.NET development on IIS7 (Glasgow)

Current Jobs

Blue Dot: Project Engineer, .NET Development Lead / Glasgow / Salary based on Experience. More Info…

Speaker Interview – Paul Cowan

Scottish Developers: Where are you from and how did you get interested in software development?

Paul Cowan: I am from Belfast, Northern Ireland. I was about 11 or 12 when I wrote my first programs in BASIC on a Dragon 32. I wrote my own textual adventure game as there were very few games for the Dragon. I then did not program again until I was about 30 when after years of getting hacked off working for my family business in Belfast, I did an MCSD course covering VB6 and SQL Server 7. That was in 2000.

SD: You are a major proponent of “ALT.NET”. What does that actually mean?

PC: ALT.NET means many things to many different people. To me, it simply means that there are alternatives out there. Not just tools and frameworks but practices like TDD. Microsoft has only recently got on the testing band wagon. This push came from the open source community. It means an alternative voice. People need educated that there are alternatives out there that come from various different sources.

SD: At what point did you get introduced to the concept?

PC: I got introduced to Castle and NHibernate in a place I worked in London. Working with an ORM and IOC just changed my way attitude to development. Obviously I had never heard of an IOC or an ORM on MSDN or whatever Microsoft propaganda I was reading at the time. Ayende wrote a blog about how to achieve generics with NHibernate and I started reading his blog. Sometime after that people started blogging about ALT.NET.

SD: So what is ORM and IOC?

PC: ORMs or Object Relational Mappers have arisen to ease the pain of converting data between relational databases and objects. They essentially take the pain away from having to hydrate and rehydrate your objects from the database. This mapping can be expressed with xml, attributes, fluent interfaces etc.

IOCs or Inversion of Control containers arose from the pain of having to create multiple object factories to create your components. Think of the inversion in this context as passing the control of the creatio
n of your components to a higher process or indeed a container that holds all your dependencies. Side effects of IOC are separation of concerns, interface driven design, greater testability and component oriented programming. If done right the experience is seamless.

SD: Did you hit any stumbling blocks when your first started using ORM or IOC?

PC: My first experiences of the above were with Castle Windsor’s IOC and the NHibernate ORM. Both sent me on a steep learning curve. The thing that eased my transition was being able to refer to working source code of a project I was working on. NHibernate in particular is a vast framework. The forums did and continue to solve the bulk of any grey areas. Most problems I have had are problems that others have had and as such a recorded posting is there to suggest an answer.

SD: In your session you’ll also be talking about AOP, ASP.NET MVC and JQuery. What are those?

PC: AOP is technically being able to add or introduce new modularised pieces of code into a component without changing the source. I currently use custom attributes to specify the methods I want to intercept so I am actually changing the source but I could achieve the same effect by specifying which methods I want to intercept via a configuration file. I achieve the interception on the back of the IOC container.

ASP.NET MVC is unsurprisingly Microsoft’s web implementation to the Model View Controller pattern. This too is a reaction to keep the vocal minority of ALT.NET onside by producing this framework. The concept is not new and facilitates a better separation of concerns and a greater testing story than is currently available with web forms.

JQuery is a JavaScript abstraction library that allows truly great things with very little code. You can select any number of DOM nodes via a CSS selector like syntax and perform actions against your result set. There is an AJAX story and a multitude of plug-ins that can create various visual and technical themes.

SD: Thank you, Paul, for taking the time to talk to us.

Paul Cowan will be talking about ALT.NET Technologies on the 9th September at 18:30 in Room 6 of the Continuing Professional Development Centre at Glasgow Caledonian University. He also runs the Glasgow ALT.NET User Group. If you want to find out more please visit http://tech.groups.yahoo.com/group/glasgow_altdotnet_usersgroup/

Sponsor’s message

SQL Know How are offering top quality SQL Server training courses at excellent value. Not only is the price great, but by entering the site from the links in this newsletter or on the Scottish Developer’s website you’ll get an additional 5% off the price. Their upcoming courses include the following

Best Practices in Performance and Availability for SQL Server 2005/2008
Kimberly L. Tripp and Paul S. Randal 1st – 3rd September 2008 Hatfield, Hertfordshire

Indexing for Performance in SQL Server 2000/2005/2008
Kimberly L. Tripp and Paul S. Randal 8th – 9th September 2008 Edinburgh

Smart Database Design
Paul Nielsen 22nd – 23rd September 2008 Hatfield, Hertfordshire

Smart Database Design
Paul Nielsen 29th – 30th September 2008 Edinburgh

SQL Server Data Storage Formats: Internals, Performance and Best Practices
Kalen Delaney 3rd November 2008 Harpenden, Hertfordshire

SQL Server Concurrency Control: Locking, Blocking and Row Versioning
Kalen Delaney 4th November 2008 Harpenden, Hertfordshire

SQL Server Data Internals and Tuning
Kalen Delaney 5th – 7th November 2008 Harpenden, Hertfordshire

Friday was my last day…

Colin and the Evil MonkeyFriday was my last day at Barbon Insurance Group Ltd. A company named after the guy that invented Fire Insurance, Nicholas Unless-Jesus-Christ-Had-Died-For-Thee-Thou-Hadst-Been-Damned Barbon. I kid you not! (Incidentally, the change of name to BIGL, for short, had nothing to do with me handing in my notice. Although I have to admit, I had an urge to come in on my last day with a set of flying goggles, reminiscent of the famous fictional pilot, Biggles.)

Just after I handed in my notice, I left my desk for a few moments and when I returned I discovered an Evil Monkey sitting on my PC. (see right) Oops! My bad! He left again shortly afterwards. No doubt after realising that I wasn’t Chris Griffin.

My boss, Steve, (strictly speaking my boss’s boss) gave a wonderful farewell speech that talked about the projects I worked on and my accomplishments since I started with Lumley, which was then bought over by Erinaceous, which was put into administration and split up, and ultimately became Barbon. He also said that it would have been nice if the business had actually allowed most of these projects to come to fruition and be put live. I completely concur with that sentiment, perhaps I would have felt more useful if it had. As it happens, only one of my projects went live (and it works very well I’m pleased to say). I have to say that I’ve enjoyed working with everyone in the development team immensely. I’ll miss the camaraderie most.

I Survived...My colleagues in Glasgow had a whip round and signed a card (see below) when I was down in Lincoln training up the developers there in how to use .NET. They raised much more than I expected so when I left they gifted me with an Ubuntu Linux 8.4 64-bit server install DVD, a Granny-Smith apple (the only apple I would accept [for the uninitiated it was a joke on my opinion about Apple Computers]), a T-shirt with “I survived Lumley Erinaceous Barbon” written on it (see left), and a Wii Fit. I felt really appreciated that gift because I know that Duncan had spent a lot of time phoning around and ultimately queuing for ages trying to get one, and his wife was most understanding also.

After work, we went to the pub for a couple of drinks where Frank, my immediate boss, joined us after returning from holiday. We headed off to The Spice Garden, an Indian restaurant just across the Clyde to have an excellent meal. I have to say that the staff there are very pleasant and helpful and the food is great. I have to admit that my experience of Indian restaurants has generally not been good, but this place really makes up for it. The only thing that I would give as a negative is that it is directly under the tracks for Glasgow Central Station so you have trains rumbling overhead every two minutes. The best thing is that they do take-out as well. Did I mention the food was great!

When I returned home I was full, but the Wii Fit was beckoning. I decided that I would watch an episode of House first in order to let my food settle, then I could at least set it up and start using it the next day. When I went to set it up, I discovered that it would only give me measurements in imperial units. I don’t understand those but I could not discover a way to change it. After going on line I discovered that by changing country it could change units. Apparently the United Kingdom is set to imperial. There were many forums of irritated people complaining that to use the units they wanted they had to change the language to Spanish – so they had a choice, a language they could not understand, or a set of units they could not understand. I eventually discovered that by going into the Wii Settings (for the whole console) and changing my country to “Australia” I could get the Wii Fit to display kilos and centimetres. However, that wiped out my settings for the Weather and News “channels” on the Wii. Apparently it was freezing in Sydney last night. Well, it is winter over there…

Leaving card (outside)

 Leaving card (inside-left) Leaving card (inside-right)

Visual Studio 2008 SP1

Visual Studio 2008 SP1 is here and can be downloaded. Details of the downloads are here, and information on what SP1 brings is here. The big items for me are the Entity Framework and the performance improvements in LINQ.

However, before you go rushing off to install SP1 there are some caveats. If you’ve been running the beta Martin Hinshelwood has some advice and has also run in to problems running the Team Foundation Server SP1 install too.

Once you’ve installed the Service Pack you might want to download the Enhancements Training Kit in order to learn what’s new.

Finally, if you have Visual Studio 2008 Standard edition or above (not including trials) you can download the IconWorkshop Lite from Axialsis.

 

Curious calculation

Last weekend I had to replace two tyres on my car as they were wearing down. It cost £85.50 each to replace them. I was told that usually the back wheels wear away at half the rate of the front tyres. Given that the car has done 25,000 miles, it means that for every 50,000 miles I should have bought 6 new tyres. 6 tyres will cost £513. £513 into 50,000 miles is £0.01026.

Put it another way, my tyres wear away at a rate of just over 1 penny per mile driven.

Or, in terms of fuel costs, it would be like adding roughly 9p to a litre of petrol.

Technorati Tags: ,,

Mixins in .NET (again)

A while ago I wrote about Mixins in C# 3.0, at the time I was saying that you can get some of the functionality, but not all, from some of the new language features in C#3.0. The solution is a bit of a fudge because the language doesn’t support the concept. I’ve been looking at Oxygene recently and it has some language features that go a bit further than C# does and will support greater mixin-like functionality which it calls interface delegation.

Interface delegation is again a bit of a fudge, but not quite like C#. In this case the language supports this mixin-like functionality and the fudge happens in the compiler. Let’s take the class hierarchy that I used the last time:

Class-Diagram-2

In Oxygene the Dog class looks like this:

interface

type
  Dog = public class(Mammal, IRun, ISwim)
  private
      runInterfaceDelegate : RunMixin; implements IRun;
      swimInterfaceDelegate : SwimMixin; implements ISwim;
  protected
  public
  end;

implementation

end.

From this we can see that Dog inherits from Mammal and implements IRun and ISwim. The IRun interface has one method (Run), and the ISwim interface has only one method also (Swim). Of course, there could be as many methods and properties as you like.

The C# version of the Dog class, as produced by Reflector, looks like this:

public class Dog : Mammal, IRun, ISwim
{
    // Fields
    private RunMixin runInterfaceDelegate;
    private SwimMixin swimInterfaceDelegate;

    // Methods
    void IRun.Run()
    {
        this.runInterfaceDelegate.Run();
    }

    void ISwim.Swim()
    {
        this.swimInterfaceDelegate.Swim();
    }
}

As you can see, there are two private fields holding a reference to the appropriate mixin, in each of the methods the responsibility for carrying out the action is delegated to the appropriate surrogate mixin object.

What you will also notice is that you still have to instantiate the surrogate mixin objects. Under normal circumstances that would be in the constructor. If it were a real mixin you wouldn’t have the option as the mixin would be created at the same time as the object it is used with. In fact, the mixin would be mixed in as part of the object itself. So, perhaps interface delegates gives you slightly greater power than with a real mixin as you could reuse the surrogate mixin object. Then again, would you want to? I’ve not been able to think of a scenario where I would, but perhaps it could be useful.

I’d like to see interface delegates in C# at some point in the future (sooner rather than later). In fact, I’d like to see proper mixin functionality, but I recon that will require changes to the CLR to support multiple inheritance. In the meantime, I think I’ll have to write some sort of snippet in C# to quickly generate the code that Oxygene gives me in one line. Either that or start writing in Oxygene… Now, there’s a thought!