In my last article I discussed multiple shapes in ASP.NET MVC, in this article I’ll discuss to get around some of the problems that I’ve faced.
Problem 1: There’s no constructor – solved!
'System.Data.Linq.DataContext' not contain a constructor that takes '0' arguments
The first issue was to do with the error shown above which was received upon trying to build the project.
Today I returned to my development environment with a clean conscience and a load of caffeine. Quite often you’ll find that ignoring the issue altogether and coming back to it helps, as well as spending the weekend reading some C. S. Lewis novel. Again I tried to build the project where I was yet again greeted with the same frustrating message. I had discussed the issue on Stack Overflow but the answers I was receiving didn’t fully tie in with the issue at hand. I considered the partial class to inherit the same class as any other share partial class, which is indeed true, but there were some factors that I hadn’t previously noticed. If, when you create a dbml file, you right-click and hit “View Code” it will create a partial class for the name of the dbml file which is expected. The only issue with this newly created partial class (for placing custom code where you may return multiple shapes from stored procedures which LINQ can’t do for you) is that it places the partial class in the root namespace. I’ve reproduced this problem with other dbml files so I think it’s a bug. If someone could confirm I would be most grateful. So, the solution? Append the rest of the namespace! Make sure your <filename>.designer.cs for your dbml file has a namespace that matches that of the filename.cs partial class. Do not modify the <filename>.designer.cs file, Visual Studio will delete it and you will lose everything.
Problem 2: Passing a type failed to build project – solved!
Inherits=”System.Web.Mvc.ViewPage<MyType>
The second issue was with the above statement telling the user upon compile that MyType doesn’t exist.
Unfortunately I’ve left the exact details on another system but I used this blog post to aid me in my quest. You simply have to add certain sections into your web.config in order to get it to work. The MVC project setup is quite strange. For me there are two web.config files, one of them has the things that are missing in them, the other does not. Perhaps I have my environment set up wrong. Simply put, I copied the missing contents from one web.config into the other web.config and hey presto, everything worked fine.
Conclusion
These things take getting used to, especially when you’re not used to working with a web environment which is really quite different from any other you’ve worked with. Problem 1 seemed to me to be a bug with Visual Studio, what’s the point in having a partial class that doesn’t belong to the same namespace? It won’t compile as the same class surely? Problem 2 also seemed silly because without those settings multiple shapes won’t work in your project, these details should’ve been in the web.config beforehand.
Either way, it’s not well documented and it takes forever to solve the problem. The good news is that I actually managed to get some data output to screen, despite not being very enthusiastic.
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.
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.
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.
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.
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.
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.
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.
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.