18
Jun 09

Multiple Shapes In ASP.NET MVC

Let’s admit it, whilst Microsoft focussed on getting some “oohs” and “aahs” from the developer community by releasing technologies to make the developers life easier, they certainly ignored the more important areas, especially MVC technologies in web systems.  The problem with this is that the majority of ASP.NET developers that I know today have absolutely no idea what the MVC architecture is, why it benefits any application, and why it’s more prefered over traditional “web forms”.  The real problem out of all of this is convincing developers who’ve been using form-based technologies for 10 years to start using MVC as a method for developing their web applications.  The benefits aren’t clear, and to receive those benefits appears to take a lot of effort and is definitely a big learning curve – this much is understandable.

This week I’ve worked heavily on developing a technical presentation for a big system to show how it can benefit us in the long run.  The funny thing about this is that I never got it to work despite knowing and understanding how to use what is available.  If only it was user error, then the problem would at least be revealed to me.  I re-created the project multiple times to confirm that it wasn’t just my project settings causing conflicts that would ultimately lead to it not working.  Okay, so I’ll go through all the steps.

Step 1: Create the MVC project

Visual Studio has a template project which provides all of the necessary components to get started straight away with an MVC project.  This is okay, but it’s not what I wanted because I need something called areas which Phil Haack kindly provided. This allows us to group controllers into “areas”.  This is useful if your application is actually composed of multiple sub-applications.  So I would set up the default project then implement the areas functionality and make sure at least one view and one controller worked.  This worked fine without any hitches.

Step 2: Hook up your stored procedure

Quite commonly we extract relational data from a database, for example users belonging to groups.  You would output all of the groups, and all of the users with the associations also output.  A user would have a GroupID for example and we can hook them up in the view.  Now, here’s where the problems really start.  Microsoft provide the ability to create stored procedures in LINQ that return the interface ISingleResult, but it won’t work for IMultipleResults by default, that part is custom.  Now your LINQ file has a designer.cs file associated with it (if you remove the connection settings Visual Studio will delete the designer.cs file, which isn’t good).  There’s two methods to developing the necessary function to get the output you require.  Firstly you can create a partial class and completely define this function yourself.  To do this, right click on the LINQ dbml file and hit “View Code” and it will generate the partial class for you.  The other option is to drag and drop the stored procedure onto the diagram and it will auto-generate an incorrect version of the stored procedure in the designer.cs file.  But why? Well, if you find out, please tell me ;) .  The below code is an example only, this isn’t real code before you attack me.  Let’s assume for a second that if you pass in a GroupID it instead retrieves all users for that particular group.  By default the function instead have ISingleResult as opposed to IMultipleResults.  The function body won’t contain the same code either, but this is what you do with it.

[Function(Name="UserGroups")]
[ResultType(typeof(Users))]
[ResultType(typeof(Groups))]
public IMultipleResults UsersGroups(
    [Parameter(Name = "GroupID", DbType = "Int")] string groupID)
{
    IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), groupID);
    return (IMultipleResults)result.ReturnValue;
}

This won’t do much yet because we haven’t set up the rest of the data.

Step 3: The View Model

We need a model to represent the multiple result sets we are returning.  They’re also referred to as multiple shapes in case you ever see that.  This model allows us to contain all of the data we need to display in the view.  There’s various examples out there but I’ll stick with the quick an easy one using some of C#’s features.

namespace MyProject.Areas.Users.ViewModels
{
  using Intranet.Areas.Users.Models;
  using System.Collections.Generic;

  public class UsersViewData
  {
    public IEnumerable<Users> Users { get; set; }
    public IEnumerable<Groups> Groups { get; set; }
  }
}

This is quite straight-forward, it’s a class to contain data only.  Personally I placed this in a separate folder called ViewModels (at the same level as the Models directory, the namespace reveals all).  So now we have this we can start using it, right?  Not quite, there’s a few fiddly bits yet.

Step 4: Namespaces

The page doesn’t understand this yet despite being a part of the project so you can import the namespace in your web.config file like the following:

<namespaces><add namespace="MyProject.Areas.Users.ViewModels"/>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
    <add namespace="System.Linq" />
    <add namespace="System.Collections.Generic" />
</namespaces>

There’s a couple of ways of doing this, you can set it as a property at the top of your view, but it’s better to do it here in my opinion as you can use it everywhere then.  Talking of namespaces now being available in your project you have to do the following line in your inherits statement

Inherits="System.Web.Mvc.ViewPage<UsersViewData>"

This allows you to access all the properties in the ViewData.Models.* property in your page.

Step 5: Getting the data

Using the controllers functions, or actions as they’re called we do all of the hard work to get it to the view.  Let’s pretend that a null value means that we want all data.  Here’s how we can do it.

public ActionResult DataContracts()
{
    IEnumerable<Contract> users;
    using(UsersDataContext db = new UsersDataContext())
    {
        IMultipleResults results = db.UsersGroups(null);
        users = results.GetResult<Users>();
    }

    return View(new UsersViewData {
            Users = users,
            Groups = groups
          });
}

Then in your view you should be able to access all of the properties strongly-typed, which is excellent.  Unfortunately this doesn’t work for me, so now I’m going to go over the problems I’ve faced.

Problem 1: Where’s the constructor? (solved here)

Here’s an error I receive if I place the function in the dbml file into the partial class

'System.Data.Linq.DataContext' not contain a constructor that takes '0' arguments

I get this every single time, no matter what project I do it in for a C# project (the VB one worked).  I’m not sure if this is a bug, but I’d love to see it be reproduced.  I don’t want to put it on MS Connect until I can verify it happens for other people.  The way I got around this was to instead modify the automatically created function for the stored procedure in the .designer.cs file.  Once I do this, the project builds successfully, great! Or is it?

Problem 2: Generics (solved here)

Using the type in the inherits statement of your view causes the ViewData property to vanish from intellisense, and the project will no longer build.  That’s all I know, I can’t get around the problem therefore I can’t get a working project.  I’ve tried on multiple projects, again, it worked under the non-areas VB version of the MVC project.

Conclusion

Basically returning multiple result sets from LINQ in an MVC project is terrible.  It takes a lot of time, patience and work to get a small set of results, but the real problem is that it’s difficult to get around this.  Bringing back multiple result sets isn’t easy simply because returned shapes don’t have to comply with schemas.  Quite commonly in our business environment our stored procedures bring back a whole lot of custom data.  Personally I created my own classes in the dbml file which are used to represent the data output.

Whilst I think the Microsoft team have come a long way with these problems in mind it actually makes it impossible for me to proceed in making MVC the choice architecture in our application.  Furthermore I really don’t think the Microsoft team have addressed the issue of returning multiple result sets in enough detail yet, it appears to be a set of sporadic blog posts from various Microsoft team members.  In fact, I don’t even think the ASP.NET MVC tutorials have anything on this from what I remember.

Note: If you take a look at the next article you’ll find the solutions to problem 1 & 2.


15
Jun 09

Another Charger Dead

I made a post on Facebook about my MacBook Pro charger which decided to end its own life last night.  Unfortunately everyone reads into it way too much.  This is the third laptop charger to die in the space of six years, so one every two years on average.  After reading the reviews of the MBP chargers it seemed that their average life span is very short, and people had complained theirs lasted only a year before they died.  That doesn’t really surprise me to be honest.  I guess it depends on how much you use it, I’m not entirely sure.

Anyway, I got completely flamed for saying it’s not uncommon for laptop chargers to die, which in my experience is true.  Whilst I was at university pretty much all students had laptops, and many of which whom were friends of mine had a charger die on them.  Contrary to this however, some people had their laptops for more than five years using the same charger.  Environmental factors probably play a great deal in their life span.  Our house is usually extremely warm (my wife suffers from ‘coldaphobia’) so that could attribute towards its death.

Anyway, I’ve got all the details I need and I’m going to see if I can get a free replacement under warranty.  Oh also, it’s not the fuse, unless I’m unfortunate enough to have a spare plug-head with a brand new dead fuse.


6
May 09

Reformsoft Relaunch

Whilst we haven’t completely finished yet (we’ve still got plenty on our to do list!) the reformsoft website has been re-launched this evening.  We came up with the design in the end.  Well, Jase co-ordinated it and I developed it.  It’s far from complete anyway.  We haven’t got much time as we’re working on many projects at the moment.  Enjoy.


6
May 09

Taking It To Another Level

Before I planned to get married my original plan was to graduate from university and then move straight onto my masters degree.  Simply put, priorities change.  I don’t regret not going to my masters degree straight away, and in fact things have worked out much better.  In the last few months myself and Amanda have been discussing the possibility of me studying my masters degree part-time as it only requires six hours study per week.  I say “only” in the lightest sense though, six hours when you’re married, working, and spending large amounts of time on personal projects is actually quite a lot of time.  We don’t have kids therefore it’s viable.

So, the news is that I will be starting my masters degree starting this November and the only way I was able to afford this was sponsorship from my company which I’m extremely thankful for.  There’s a lot of inner-educational talks about how much masters really help you so I decided to make sure I carefully studied the topics covered.  For the masters degree in Software Development many of the courses actually relate directly back to my job so it’s beneficial not only for me, but for those whom I work for.

The study works on a modular basis, I will study one module every six months requiring roughly three tutor marked assessments and one exam.  The six hours study is gained back by changing my weekly timetable and stopping certain commitments I have on weekends which will free up enough time for study.  It looks like I’m actually starting with a database development course which is handy as that’s what I tend to work with most days (and nights!).

Anyway, I’m back in Guernsey now after being in Jersey today and I’m having the final, conclusive meeting tomorrow.  Oh also, I’m studying it with the Open University as I have previous experience with them and it works well for overseas support.


1
May 09

Working With ASP.NET MVC

Since the release of ASP.NET MVC I think the whole world has suddenly realised that the Microsoft team are actually doing something good, despite taking years to catch up with other MVC frameworks such as the Zend Framework. The good thing is that I’ve been keeping a close eye on what the team have been doing, and despite my knowledge not being great in the area I’ve noticed that throughout Scott Gutherie’s blog the decisions made do seem to be very good.

When I first started with ASP.NET I thought it was a nightmare, the fact that you had “web controls” which required forms on the page with runat=”server” attributed on all HTML elements.  I hated this.  I started off in the company I currently work for wondering what on earth we were using, but the fact was that ASP.NET had evolved into “web forms”.  There are many reasons I don’t like it especially with the ViewState property being enabled by default on all controls meaning if you check the response from the server when a web page is generated you’ll notice a load of encoded data sat near the header.  On some of the pages we worked on the ViewState drowned out the actual HTML  completely.

ASP.NET MVC gets rid of all of this.  No more ViewState, less use of forms et cetera.  As lovely as it is though the majority of guides, articles or tutorials simply don’t cover large-scale applications.  Our applications are gigantic, some of them I’ve never had to deal with and simply wouldn’t be able to by myself because they’re so large.  Applications as large as this need testing which is one of the major points of MVC.  So, here’s some problems with ASP.NET MVC that I have.

Nested Controllers, Views and Models

So imagine your application is simply so large that you have roughly one hundred folders and some of which go to about five to six levels deep.  This is done to separate out area of the application.  The application is one major application made up of many smaller applications essentially.  Should you create separate projects for each which are somehow controlled from a single web application, or combine the lot?  Is we combine all of them, how do we deal with nested folders?  ASP.NET MVC deals with controllers, views and models on a folder by folder basis.  So our mapped routes looks like {controller}/{action}/{id} but if we have folder structures such as myapp/mysubapp/adeeperfolder/thepageaction/theid then things start to get tricky, especially if this happens time and time again.  Haacked covers areas in MVC, but again, this may not cover all cases especially for those of a gigantic application.  There are custom routes available to work with, but how many would we need? Quite a lot to be honest.

So what’s the solution? Well, if we had a URL such as app/myapp/mysubapp/myaction/param then could we not take everything before myaction/param and map it automatically as the path to the controller?  I believe this actually breaks the separation of MVC, but for us it seems the most logical approach.  I do ponder on this.

No More Controls!

Okay, whilst beforehand I would’ve cursed at controls they do aid in speedy development.  So what now?  We have to manually create reports in the view.  I’m not saying I have a problem with this, but as my boss said, this moves back to the “Active Server Pages” days.  We’re so used to saying “yes we can provide this report, and it’ll only take us two minutes to do”.  It may not be the right way, but it produces a result which someone may need right now.

The idea is that every view represents just that, a different view of something.  If you’re editing results returned into a table then the “edit” button would take you to a different view.  Are you supposed to be able to edit within the table i.e. turn the row into a row filled with textboxes that you can edit, then have an update button the same row?  I’m guessing now.  But this does mean that the amount of views and associated controllers increases substantially.  If you have thousands upon thousands of pages already, surely they will multiply?

No Going Back

The other major concern is that it’s simply such a big step that it’s a case of “out with the old and in with the new”.  You can’t mix and match, and you couldn’t move back again.  It’s just too big of a job, and required too many man hours.  The amount of time already that I’ve spent in investigating, gathering requirements, and solving problems is already too great to be throwing the idea out altogether.

XSLT?

Seeing as though we no longer have controls what happens with things that we commonly use such as XSLT for generating complex pages?  Has that died a horrible death altogether?  Again, I’d love to know.

Data Access

The major issue I’m really having is accessing data correctly.  Seeing as though I have no prior experience I’ve realised it’s extremely important to have a data access layer, but there are many tools available such as LINQ.  LINQ won’t do what we want because it’s slower than other technologies and we’d simply only use it for stored procedures.  Simply, strongly-typed stored procedures are required.  Also the ability to insert/update/delete based on exposed functions through objects.  Again, with such a complex schema this isn’t a simple task.

I’m not sure what everyone else’s opinion is on the use of ASP.NET MVC but those are just a few of the issues I’ve run into so far.


29
Apr 09

Hex Colour Picking In Pixelmator

I actually bought some software for once, that being Pixelmator. To be perfectly honest with you, it’s an absolute steal for the actual cost. At the moment it’s roughly £42 GBP, compare that to Photoshop’s cost and then take into account the chances are you won’t use a great deal of Photoshop’s features. I’m not saying Photoshop isn’t a bad product, it’s extremely good, but from the extensive use I had of it, it appeared many of the tools weren’t suited for the work I did with it.

Now that I’m working on my Mac instead of using Windows I wanted something other than GIMP. I’ve never got on with GIMP at all, I find it difficult to use and not very user friendly. Some people are really quite amazing using it, but for me personally it just doesn’t cut it.

Anyway, moving swiftly on to my point. Pixelmator uses Apple’s built-in colour picker which I think is a great idea, but Apple’s built-in colour picker doesn’t have a hexadecimal picker, and for the large amounts of work I do with the web that just doesn’t really help me much. Well, that’s extremely simple to solve seeing as though someone’s provided one. Just drag and drop it into Library/ColorPickers and make sure you restart Pixelmator if its already open. This time a new tab will be available with a gigantic hex value.


7
Apr 09

Cross-Platform Team Development Setup

Fortunately for me I started out software development in the times where Java-based IDE’s were available meaning I’d use the same one in Linux and Windows. Now that I primarily develop in Mac OS X I need to make sure that I can work alongside team mates whom work under Linux or Windows. Fortunately we can all have the same Subversion client, the same IDE, and generally the same plug-ins whilst working on the same project but under different environments.

The very first thing you’ll want to do is get the subversion binaries and install them in the dmg format provided if you’re on Mac. It took minutes to get this part setup and is generally very straightforward.

As we’re working on a PHP project we first headed over to the Eclipse PDT page and got the all-in-one package as this means we don’t have to do any setting up of any kind. I’ve found getting a base install of Eclipse and then figuring out how to add the PDT plug-in later on generally causes more problems for me. The only downside to getting the all-in-one package is that it won’t be the latest build of Eclipse, if you’re okay with that.

The second step was to install the Subclipse plugin. To do this you simply open Eclipse, hit “Help” then “Software Updates”, click on the “Available Software” tab, then click on “Add Site” and enter http://subclipse.tigris.org/update_1.6.x into the input box (make sure you always use the latest version however). Once you click okay Eclipse should install Subclipse in the background. You must ensure you have an installation of the subversion binary for this to work, otherwise you can get some random errors that confuse you.

Once this was set up myself and my team mate went on to unfuddle, an extremely good project management and subversion base and set up our repository and project. We then right-clicked on our repository pane in Eclipse and hit the “Create Repository” button and entered the relative details. From here, as long as you understand subversion basics, I’m sure you’ll get along with it just fine. The very first thing we tend to do is to create folders “branches”, “tags”, and “trunk” which is just a standard set up. Following this, as it’s a web project, we create the folders “admin”, “include” and “content” within the trunk folder.


13
Mar 09

Facebook Just Turned Into Twitter

The mad phenomenon that is Twitter has been a serious influence on the latest version of Facebook, so it seems. I think the very first thing I said when I logged onto Facebook today was “Facebook is trying to be like twitter”, low and behold many other of my friends were sporadically “status changing” with the exact same thing. Well that’s just a darn shame. I think the Internet has gone into an adverse state of pointlessness.


5
Mar 09

IHttpModule Over Global.asax

I had the job of re-writing some old code that existed in Global.asax which is used to respond to certain initialisation and tear-down events. A significant event of ours is the Session_Start event as this is where we assign session variables used for the lifetime of the transactions carried out by the user. It’s quite common practise as I have seen and is extremely handy in the context of our application.

The re-write was basically to move some code to a more secure location within a compiled stored procedure on our SQL server (later versions of SQL provide some handy features). I first researched any improvements upon Global.asax as it has been around for so long and had been superseded by its predecessor, Global.asa. IHttpModule was a major hit and seemed to be specifically designed for the purposes of improving upon Global.asax. VB.NET isn’t quite as savvy as registering event listeners in comparison to other popular languages such as C#.NET or Java so that was the first major hurdle I had to get over (which took quite some time, MSDN isn’t the best search tool ;) ). Unfortunately upon further coding I came to realise that the Session_Start event which was freely available – and worked perfectly in Global.asax – firstly didn’t even exist, and secondly required some hacks to ensure that the relative code was called at that specific point in the initialisation of the web session. The solutions I saw just weren’t worth it to be honest.

If you’re looking to ensure that certain code is called on Session_Start then I’d highly advise just sticking with Global.asax. If you don’t require Session_Start and Session_End then it’s definitely worth looking at implementing the IHttpModule interface. Registering the class in your Web.Config allows it to respond to the relative events that are setup to respond to within the implementation. It’s basically a modularised solution to Global.asax. Anyway, I thought this may be a handy bit of knowledge to save you a few hours of tedious work :)


28
Feb 09

Hectic Fortnight

A couple of weeks ago I headed off to the UK for a number of reasons, here’s the low-down of what went on.

Training

My company sent me on a SQL developer training course, although it didn’t go as well as I was expecting it to. In fact, on the first day of the course I quite bluntly confirmed that I would be failing it. The course outline in no way reflected the actual content of the course and has since – I believe – been revised. We were under the impression that I would be learning more-so about real development using MS SQL Server but alas it covered things I had never even heard of and more worrying was the fact that I hadn’t done the pre-requisite so when it came to one of the day’s where we’d talking about subject y, you’d have to have first learnt about subject x in the pre-req course leaving me quite abandoned for a whole day. 90% of the time I was there I think I was in another world just trying to understand what was being spoken about let alone learning about the subject matter. I kept up with the reading but was swamped with chapters on subjects I’d never even heard of when in relation to SQL server. Questions such as “Would you use the Service Broker to do this?” were quickly responded to with another question such as “What is the Service Broker?” – I was then told that it couldn’t be taught in this course and was something that we should know already.

Sufficed to say my work mates were extremely supportive amongst my incoherent stressful ranting and instead I managed to approach the content with a more constructive approach by taking as much out of it as I can (which I believe I did). Ultimately I failed both of the exams, but there was only a 30% pass rate out of our class so I didn’t feel so bad after I had learnt that others on the course who had ten times the amount of experience and knowledge in SQL server and had actually done the pre-req and failed this course. I feel terrible for saying so, and I’d never want to feel happy out of someone’s failure, but I felt more comforted to know that even those whom had experience and knowledge in the correct areas found it quite difficult. I’m sure they won’t have a problem passing the course when they re-take the exams.

Unfortunately the company we dealt with have a few lines of service, the first being customer support, those whom only have to know what the course consists of and work on a “we pay you by customer” basis just allowed me to go on the course fully well knowing I didn’t have enough knowledge or experience which is a big let down for the company and now we know that our internal discussions about the course should not be persuaded by training company employee opinions.

I actually didn’t fail by much, the course works on a pass/fail basis where you have to get 70% or over, I think I got something like 59% which isn’t bad considering that I knew absolutely nothing about any of the course content and it was a six day course. Due to an NDA I signed I’m unable to speak about much of the course content or anything about the exam whatsoever.

London

My wife joined me a few days after I finished the course where we stayed in Oxford – she hadn’t been to London before so we decided to do a few tourist things such as London Dungeon and The Tower of London which were okay. My wife knows a scary amount about history so she gave me all of the realistic details. We got to check out the crown jewels which were probably the most impressive part of The Tower. It was absolutely packed considering it was a gloomy February day.

The London Dungeon was an absolute nightmare considering the local schools decided to send in all of their children in a few buses worth. The queue lasted about 30 minutes before a friendly staff member noticed that real tourists had come and were receiving some incredibly bad service and decided to bump us up the queue and push us to the front. The Dungeon was more of a visual thing rather than a factual thing, and there’s an incredibly crap water ride inside. Fortunately we got in on the two-for-one offer that’s all over London.

We went to Oxford Street shortly after just so I could show my wife the real central London. We went in a few shops but we’ve not got much money after all of this so decided not to go shopping.

Hospital

The real purpose of the second week of my trip to the UK was to go into hospital for a prolonged EEG which lasts a few days. Basically they hook you up to a machine where twenty-two probes are super glued to your scalp and a heart monitor is attached then you’re sent off on your way to monitor brain activity and heart rate. It was quite uncomfortable and I felt like quite the idiot walking around even with my hoody up. We went out on the Thursday night for dinner with some friends in Oxford where we were staying. We had an amazing night just catching up really and I ended up taking my hood off as it got so hot. I think the entire restaurant just stared at me the entire time trying to figure out what was going on. My friend whom I won’t name thought it’d be funny to tell the staff “he’s terminal” so they’d stop staring (and try and get a free meal) – whilst hilarious as it was I quickly stopped him ;)

We got a chance to actually watch my brain waves live which was quite weird. It looked much like any regular line graph with four different sections which all looked like a flat-line heart monitor. When the graph suddenly changed and all the monitors dipped rapidly I got quite worried until the neuro guy said to me “that’s what happens when you blink”. Your brain waves go through a radical change when you blink, otherwise they look quite regular so it was really interesting to see this live.

Safely Returned

Sufficed to say, I couldn’t wait to get back. Going to the UK wasn’t the best time for me as I’ve been just so busy and loads of things have been going on. I’m actually looking forward to going back to work which isn’t that surprising as I really enjoy my job and feel I’m a bit more equipped for dealing with our large-scale databases which grow an extraordinary amount each day. I’ve realised that the difference between SQL 2000 and SQL 2008 are so big that if you were a professional SQL 2000 developer it’s absolutely vital that you train for SQL 2005+ because Microsoft have actually pulled their finger out and done a really good job by providing some exceptional tools. Although I’d just like to point out here is that the only real Microsoft software I like are their developer tools (i.e. VS and SSMS).

Also, tomorrow my brother is leaving the island for at least a few years so we went out for dinner with him tonight as a send off. In the last couple of years he’s had pneumonia, cancer and loads of other illnesses so I’m hoping that in places like India and China where he’s headed don’t destroy his immune system more than it already has been but I think it’ll be really good for him.