Thursday, 17 February 2011

Making a Hybrid Web Application Project Type

Like so many of my blog entries, I've been meaning to write this one for weeks. Ever since Scott Hanselman wrote Integrating ASP.NET MVC 3 into existing upgraded ASP.NET 4 Web Forms applications, in fact. Scott just wrote an updated post on using NuGet to bring the MVC bits into a WebForms application, which is a muc easier way to do it. But to me, Scott's still missing the final piece of the puzzle which is: do this once, create it a project type from it, and forget about it.



So, creating a hybrid project type. First of all, go do Scott's NuGet stuff and create your hybrid application. Oh, and add any of your other favourite references - NHibernate, CastleWindsor, whatever. It's OK, I'll wait.
 
Done that. Good.
 
Now click File|Export Template... and open the Export Template Wizard. Check the 'Project Template' radio button so we export the hybrid project as a template. Click Next.
 
On the second screen, enter a suitable name for the project type and description, and choose an icon if you want.

Click Finish and you're done!

Sunday, 30 January 2011

What's A DDD9?

Some of my (non-geek) colleagues who follow me on Twitter have asked me recently: what's a DDD9? The answer: for the UK .net community, it's the major event of the year. Held annually at Microsoft's offices in Reading, it is a free one-day conference run totally by the community. The DDD stands for Developer Developer Developer, from Steve Ballmer's chant of several years ago (http://www.youtube.com/watch?v=8To-6VIJZRE) *. Microsoft employees are welcome to attend, but they aren't allowed to speak. It is only advertised through word-of-mouth and Twitter: this year it sold out 350 spaces in 12 minutes, the waiting list for spaces was full after another 30 minutes. You may find this slightly more notable as DDD is held on a Saturday, which ensures that the people who are there are the kind of passionate people who are prepared to give up a large part (or in many cases the entirety) of their weekend to attend. The programme is completely voted for by the attendees, this year there was again a great mix of technical and technique sessions. The sessions I saw this year were:

.net Collections Deep Dive - Gary Short
Actually I wanted to see all four talks in the first session, but I picked Gary's as I don't think I've ever seen him talk before. This was a session going through many of the Collection classes available in .net, how they work internally and in what circumstances each one offers better performance. It included such gems as the fact that in the multithreaded collections if you call the Count property it is not guaranteed to be accurate unless you can be sure all threads have exited. In which case it wouldn't be, y'know, multithreaded. The top tip I took away was that if you know how many elements you are going to put in a collection, to set the Capacity in the initialiser:
List myListOfTenElements = new List(10);

CQRS, Fad or Future - Ian Cooper
OK, so I, um, didn't actually see this session, I got chattinjg to people in the speakers lounge. The presence of chocolate and raspberry cheesecake brownies (made by me) was a total coincidence. This was still quite useful as I was able to talk to Dave Sussman about a CSS issue I'd been having and get some advice. However I look forward to seeing Ian's slides and maybe catching this talk at a user group sometime.

A Primer on RavenDB - Rob Ashton
One of the sessions I really wanted to see as I'm interested in playing with RavenDB and I can see cases in WSP where it could be a very good technical fit. Rob is quite opinionated, especially on how MongoDB and RavenDB differ. Rob recommends getting the unstable version of RavenDB to play with so you can see the features, although I think at least initially I'll be using the stable build until I've found my feet with it. One of the things I'm most impressed with is the fact that for unit testing purposes, you can run RavenDB completely in memory with no impact to disk.

Is Your Code SOLID - Nathan Gloyn
This talk walked through the SOLID principles of software engineering.Nathan began with a pretty ropey bit of code, and then talked through each principle before demonstrating how the code changed after the application of the principle. A really interesting session for me, SOLID is something I need to think about more as I write software.

CSS Is Code - Helen Emerson
Helen's theme was that CSS code is as important as application source code, but that the rules and principles we apply to source code aren't often applied to CSS. Probably not the right session for me given that I'm a total numpty where CSS is concerned, although it was useful to see that in Helen's demos there were things that chimed with some of the CSS we used on the Intranet last year.

A Beginner's Guide to Continuous Integration - Paul Stack
A great session to round off the day from Paul Stack, talking about how to use CI to reduce the time it takes to release your software. Like RavenDB, CI is something I definitely want to look into, in fact in that respect it was a shame it was a Saturday as I was fired up enough that I wanted to go straight into the office and set up a CI server. The only real negative in this session for me was that there was little discussion of how to set up CI with TFS, although Paul tells me this is straightforward.

The Social Network
There's much more to DDD than just a technical conference - for many if not all of the delegates it is as much a social event as a learning opportunity. It's a chance to catch up with old friends, make new ones, or just an opportunity to put faces to Twitter handles - I've been chatting with Nathan and Paul on Twitter for months but Saturday was the first time I'd met them. And the socialising continues into the evening - there is a Geek Dinner after the conference, at which 40 of us take over most of Pizza Express to eat, drink and chat.
We had an interesting conversation at our end of the table about the nature of developers and DDD and why it seems to work for us but no-one else. There simply doesn't seem to be any other profession that does events like this - even inside IT, there's no equivalent event for IT Pros.

* I did discover through the power of Google an alternative DDD9 conference - Death, Dying and Disposal. Which doesn't sound anything like as much fun.

Thursday, 23 December 2010

switch vs Select Case

I knew if I looked long enough, I'd find something you can do in VB.NET that you can't do in C#. And I think I just found it.


Consider this bit of markup:
Why is it not possible to use an existing approved supplier?
<asp:radiobutton id="ClientNominatedRadioButton" runat="server" text="Nominated/named by client" GroupName="NewSupplierReasonRadioButtonGroup" />
<asp:radiobutton id="AlreadyOnSiteRadioButton" runat="server" text="Already on site" GroupName="NewSupplierReasonRadioButtonGroup" />
<asp:radiobutton id="NewLocationRadioButton" text="New location and no existing supplier" runat="server" GroupName="NewSupplierReasonRadioButtonGroup" />
<asp:radiobutton id="OtherRadiobutton" runat="server" text="Other (please state)" GroupName="NewSupplierReasonRadioButtonGroup" runat="server" />

At some point, I'll want to examine this set of radio buttons to deduce which one is selected. In VB.NET, I would normally do this with a Select Case construct, viz.
Select Case True

    Case ClientNominatedRadioButton.Checked

    Case AlreadyOnSiteRadioButton.Checked

    Case NewLocationRadioButton.Checked

    Case OtherRadiobutton.Checked

End Select
which I always think is a more elegant construct than a thousand 'if...then...else if...then..else if' blocks.

But it seems this construct is not available in C# - here's a screenshot from Visual Studio:


 
 
 
 
 
 
 
 
 
The tooltip for the red squiggly reads 'Code is unreachable. A constant value is expected'.
 
All of which leaves me slightly confused. If they compile down to the same bytecode then why does this approach work in only one language? And is there a more elegant way to determine the selected radiobutton than the aforementioned 'if...then' block?

Wednesday, 25 August 2010

DateTime.DaysInMonth

I stumbled upon this yesterday and thought it was worth publicising a bit.


I'm writing a tidgy little app that will take a load of data about our press releases out of one of our databases and turn into flat HTML files. It needs to write separate files for years and months - years are easy as it's just a for loop, and months are also a for loop, but I need to know the end date for each month so I can create the appropriate SQL query. I'd written a switch block to calculate the last day of the month:


for (int i = 1; i < 13; i++)
{
    DateTime startDate = new DateTime(int.Parse(year), i, 1, 0, 0, 0);
    DateTime endDate;


    switch (i)
    {
        case 9, 4, 6, 11:
            endDate = new DateTime(int.Parse(year), i, 30, 23, 59, 59);
            break;
        case 2:

            endDate = new DateTime(int.Parse(year), i, 28, 23, 59, 59);
            // TODO: Leap years
            break;
        default:
            endDate = new DateTime(int.Parse(year), i, 31, 23, 59, 59);
            break;

     }
}

But further down in my code, I was doing something else with the DateTime class and I spotted it has a DaysInMonth function. You give it a year and a month (both ints), and it calculates the number of days in the month for you, and deals with the leap years that I hadn't got round to doing. Which means I can collapse my for down to:


for (int i = 1; i < 13; i++)
{
    DateTime startDate = new DateTime(int.Parse(year), i, 1, 0, 0, 0);
    DateTime endDate = new DateTime(int.Parse(year), DateTime.DaysInMonth(int.Parse(year), i), 30, 23, 59, 59);
}

Smaller code for the win!


EDIT: I just looked DaysInMonth up on MSDN and I'm surprised to discover it's been in the Framework since .NET 1.0!

Saturday, 14 August 2010

A Good Day

Yesterday had an inauspicious start when the alarm went at 6am. I woke my wife up (again) when getting dressed. And when I got to the station I didn't have time to go to the shop and get a paper to read on the train.

But then...

The ticket inspector had an unexpected sense of humour.
A totally hot woman sat next to me on the train.
I wrote a StackOverflow answer on the hateful editor on my phone. 
And it was accepted.
Getting off the train I bumped into an ex-colleague I haven't seen for four or five years.
I got to spend the whole day getting my geek on watching ScottGu present on VS2010, ASP.NET 4, EF4 and MVC...

Amusingly, as I was waiting outside the cinema an American girl walked past and I heard her say 'must be a premiere' - I wonder how she'd have reacted if I'd told her we were all waiting to see a man from Microsoft...

VS2010 and ASP.NET 4
The first session was on what's in VS2010 and ASP.NET 4. As I've been using VS2010 since April I wasn't sure just how much I'd get from this session - the answer was, obviously, loads. 
I've already been using the HTML snippets, but now I know that there's a setting where I can turn off the requirement for an angle bracket before VS offers to complete the tag for me. What I didn't know is that there's a set of snippets for JavaScript as well. And a set for jQuery
We all learned that Scott doesn't like regions round his privates - cue much sniggering, I'm not sure it means quite the same thing in the States. But the learning point was that if you like regions done one way and your team mate prefers another, you can have regions that are private to you and won't show up when your colleague opens the file in VS. Ctrl + M, Ctrl + K is the keystroke to create one of these. 
Someone asked if there's a way to label these regions, to which the answer is no, however someone else pointed out that if you put a comment at the top of the region, it can work as a label when you hover over the collapsed region.
I picked up a bundle of new shortcut keys.
Collapse all regions - Ctrl + M, Ctrl + O
Incremental Search - Ctrl + I
Navigate files - Ctrl + Alt + Down Arrow
Navigate to - Ctrl + ,
View Call Hierarchy - Ctrl + K, Ctrl + T

Scott demoed some of the debugging features in VS2010, including pinning of watched variables, conditional breakpoints where the debugger only stops on a certain Boolean condition. And trace points, which allow you to write debugging messages to a TraceListener - optionally you can also continue executing your code, which neatly handles debugging a multi-threaded situation where breaking into the debugger hides the bug you're actually trying to find (the Heisenberg uncertainty principle in action!).
Scott showed how to use the ASP.NET Routing module in WebForms (the same one as used in ASP.NET MVC), and also showed off some of the deployment features, especially the Transforms which allow you to generate custom web.config files for different environments. Scott also told us that in the next couple of weeks there will be a new hosting gallery appearing on http://asp.net, which will allow you to search for a web host based on features they support.

MVC2 & EF4
I've seen a number of sessions in the last year on MVC and Entity Framework, but this was the first time I actually felt I was starting to 'get' it. I should have Scott sat next to me at work, think how much more productive I'd be!
Due to popular demand (and some well-publicised issues with the registration system for the day), Scott built a system based around developer events. For this session Scott started with a database, and built an entity model from it, then showed some of the features in MVC for displaying and editing data from the model. Highlights for me were the ease of allowing client-side validation - <% HTML.EnableClientValidation %>. That's it, one line of code!I was also very impressed with the scaffolding feature that allows you to build an editor page really quickly for a model. Whereas previously, you'd have written something like <% Html.TextBoxFor(fieldname) %> and the page will output a text-type INPUT tag (where field name is a string value), you can use the scaffolding to say <% Html.EditorFor(fieldname) %>, and the page will output a field appropriate to the data type of the field - a textbox for a string field, a checkbox for a Boolean field etc. And you can take this a level further - if you write <% Html.EditorFor(model) %>, ASP.NET iterates over the class and outputs the set of controls necessary to display and edit all the fields in the class - seriously cool.
In a large application, the number of controllers and views can grow so large as to make it difficult to pick a particular one out of the clutter, so Scott demonstrated how you can split an application up into Areas which allow you to group sets of controllers and views together to make it more manageable. Finally in this session Scott showed off some of the unit testing features. This included the gems that the 'Do you want to create unit tests' dialog when you create a new project is referred to as the 'Guilt' dialog, and the 'No I don't want to create unit tests' radio button is known as the 'I suck' button.

Windows Phone 7
After lunch, Scott took a (well-deserved) break and handed over to Mike Ormond to talk about Windows Phone 7. There are two programming models available for WP7, one in Silverlight and one in XNA. The Silverlight model should be used for event-driven type applications, the XNA one is more suited for time-driven apps e.g. game. However both types of apps can use features from the other if necessary. Mike also talked about how applications are distributed to a device, however what wasn't completely clear to me was how, as a corporate developer, if I write an app to be used internally to the company, I distribute the app and whether or not I have to release it to the marketplace. I was, mostly, quite intrigued about the platform as a whole - maybe later in the year I'll look more closely into developing for it.

Web Futures
The final session saw Scott back and talking about a number of the things that should be released by Microsoft later in the year, including IIS Express, MVC3, code-first Entity Framework and Razor. Of these, the ones that interested me most are IIS Express, and code-first EF. IIS Express I'm looking forward to as it will allow us to locally test our SSL pages (it comes with a local certificate). Code-first EF was interesting, although having not done any EF work I don't really know how much difference it would make. Similarly with Razor, I haven't done any MVC so I couldn't really appreciate the differences. Finally Scott showed off some TDD and in ten minutes explained Dependency Injection. I've been reading odd bits around DI over the last year, but I can honestly say I picked up more in that ten minutes than I did over the preceding 12 months!

And then we went to the pub with Scott to interrogate him, in which:
I learned that Dependency Injection and Inversion of Control are (more or less) the same thing. 
We were all amazed at how much of Microsoft ScottGu runs.
I learned the year the HTML 4 spec was ratified, though Dave Sussman says I can't tell anyone this.

It was A Good Day.

Thursday, 12 August 2010

Data does not exist in the namespace Microsoft.Practices.EnterpriseLibrary

I started to build a new application this afternoon. It's nothing complicated, it just needs to read all the data for the forum on our Intranet and write it into flat files so we can archive it somewhere on our new improved Intranet. I fired up Visual Studio and knocked up a UI - basically it has a Start button and a number of progress bars. Switching to the code, I added a reference to the Enterprise Library 4.1 Data Access Application Block and wrote some code to read the data. Having got to the first point where I wanted to check that things were going more or less as I wanted them, I hit F5 to build and run the application.
The type or namespace name 'Data' does not exist in the namespace 'Microsoft.Practices.EnterpriseLibrary' (are you missing an assembly reference?)
Er, huh? I hit Rebuild with the same result. 
I checked that I'd added the block - yep, there it was in my project References. 
Rebuild. No joy. 
In the immortal words of Kenneth Williams, "stop messing about". I actually fired up Explorer and browsed to the DLL under my Program Files folder to ensure it was there.
Still no joy...

And then I had a flash of inspiration. The default .NET Framework version for the application was set to '.NET Framework 4.0 Client Profile' - what if that was causing a problem? That's caught me out before when I've been playing with MEF stuff. I changed it to the .NET Framework 4.0 full profile, hit Rebuild again and - success!

I solved my problem, but I'm sure I can't be the only one who's run into this one. It's trivial for me to solve because this application will only ever run on my laptop, but for someone who wants to use the Enterprise Library but also needs a minimal footprint when their app is installed, the two things become mutually incompatible. I can't help feeling that when you add a reference by browsing to a DLL, as I did, that Visual Studio should do a bit of inspection on the DLL and warn you if it's incompatible with the framework version you're currently using.