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.