Wednesday, 18 February 2009

ASP.NET MVC and the VB XML ViewEngine - Interim 1

This is just as an interim update.

Things have been moving a little slow of late and Part 2 of my journey into ASP.NET MVC and the Spark View Engine has had a minor change of direction. Mainly, I stumbled upon a fantastic new view engine for ASP.NET MVC that utilises the new language feature for VB.NET... Xml Literals.

I just <3 Xml Literals!

Just as a quick example from the standard website that is generated for you when creating a new ASP.NET MVC Project.

Here is the original code for the Index.aspx view...

<%@ Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>


   Home Page



<%= Html.Encode(ViewData("Message")) %>

To learn more about ASP.NET MVC visit http://asp.net/mvc.

Here is the same view using the VB Xml ViewEngine...

Namespace Views.Home
Public Class Index
Inherits SiteMaster

Public Overrides Function Render() As System.Xml.Linq.XElement

  Me.ViewData.Add("Title", "Home")

  Return MyBase.Render()

End Function

Public Overrides Function RenderContent() As XElement
  Return 

<%= Xhtml.Encode(ViewData("Message")) %>

To learn more about ASP.NET MVC visit http://asp.net/mvc.

End Function End Class End Namespace

This is just a very simple example, but it can be very powerful too.

For example, now my views are completely contained with my classes as Xml Literals, the rendered page output is checked at compile time instead of runtime.

I will be explaining more about this new development in the next part of this journey. Until then, note that I have decided to drop my plans to use the Spark View Engine in favour of this new VB.NET Xml Literal based View Engine.

Until then, you can check out this View Engine at it's source, Dmitryr's Blog. There is also an informative interview with Dmitryr at Channel 9.

Enjoy!

Saturday, 7 February 2009

Template Updates

I have been mucking around with the template today. No major changes other than widening the page layout and separating the css into its own file. It gives me a little more room to play with.

The other interesting bit is I have added to the right-hand side a feed from my shared notes in GReader. I still need to fix up the style so that is looks part of the theme but I am quite pleased how easy it turned out. Though I'll need to add some checks into it so that it doesn't end up displaying "undefined" for certain fields from the feed :(

Tomorrow I shall finish up the styles for the shared notes and add a twitter feed too.

ASP.NET MVC and the Spark ViewEngine - Part I

I've finally decided it is time to try out ASP.NET MVC and see if it has any advantages for me over traditional ASP.NET WebForms.

I have only ever create websites using PHP (many moons ago) and ASP.NET WebForms 1.1+.

Over the past number of months, I have been intrigued to try out the new-fangled MVC technology. At the same time, I thought I'd also delve a little in the Spark ViewEngine instead of the built in View Engine. As well as trying out for the first time, Unit Testing with the Visual Studio default test suite, as well as TypeMock. For data access, I will using the latest build of SubSonic 2.1 including a few minor tweaks I've added myself.

I will also be using Visual Studio 2008 as my main development environment and GIT for source control. The development machine is running Windows XP Professional x64 with IIS6.0(ish).

At this moment, ASP.NET MVC is at RC1 and the Spark ViewEngine is currently at version 1.0.317.

As a side note, my main development language of "choice" is VB.NET. Mainly because my work environment encourages its use. A short while ago Roy Osherove was looking for developers who use VB.NET to help test and suggest improvements to VB.NET friendly features for TypeMock which had previously been aimed more towards C#.

It has been a while since I was given the special licence to use TypeMock for testing purposes so I thought now is a good time to fulfil my promises.

This will be the first time that I have actively implemented a proper testing framework including using mocking so please forgive me if my first run at this goes completely haywire.

The Project

In order to try out these new technologies, instead of just putting together lame demos that serve no purpose at all, I will be building a real live application based on a very basic booking application I put together for a friend of mine.

The application as it stands today can be seen at http://www.horsearena.co.nz and is built on ASP.NET WebForms with a SqlServer 2005 backend that is accessed via SubSonic 2.0. It originally usedd NHibernate over (Gods forbid) an MS Access database.

Shamefully, this site is very neglected and is in dire need for an Extreme Makeover.

Therefore I thought it would make an ideal candidate for some MVC love.

Where to Start?

To begin with the first step seems to be to install ASP.NET MVC, Spark and TypeMocks. This is the easy bit. What to do next is the hard bit.

This may be my first project to use all these new tools but it doesn't mean I am completely new to the concepts involved. I have been attempting to keep up to date by reading and listening to as much source material, articles, reviews, tutorials and podcasts as I have time for. This is no easy feat and I am humbled by my colleagues and peers who are able to keep abreast of all these technological changes.

I have been following the concepts behind Test Driven Development and Domain Driven Development etc. and it all looks fine and dandy but I am not yet fully convinced on it's merits or best practices. Basically for this project I will be just winging it a little but leaning towards TDD I imagine. At least my goal is to at least develop some sort of test suite.

Adding a New Project

The next step at least is to add to my solution a new ASP.NET MVC project. This at least creates a nice new project for the new MVC application. At the same time, the project wizard asked if I wanted a test project too so I said, "Yes!"

Screenshot

To the left is the basic project structure that was created. Note that I have made one minor addition to the project. I have included jquery 1.3.1 and the corresponding vsdoc for intellisense.

Technically speaking the vsdoc is for jquery version 1.3 but I am hoping it shouldn't matter to much. In Scott Guthries blog he mentions that the release version for ASP.NET MVC, it will come bundled with version 1.3.1.

This is all fine and dandy but does it work?!

Um... Not exactly :(

Now this is not the first time I started a brand new ASP.NET MVC project though it had been in this particular machine instance.

My first problem I had was the 404 error I was getting.

Why the heck was I getting a 404 error on a brand new web application?

After banging my head against my desk for a moment while checking the properties of the website in IIS and making sure the ".mvc" extension was correctly hooked up, I thought I would check the IIS logs.

Note, there are some handy scripts found in <Program Files>\Microsoft ASP.NET\ASP.NET MVC RC\Scripts to register/unregister the ".mvc" extension for pre-IIS7 and IIS7 classic mode.

Step 1.. Find the logs!

This wasn't quite as hard as I expected at first. It would seem the default location is C:\WINDOWS\system32\LogFiles\W3SVC1\. After quickly scanning the log for today I see the culprit...

Rejected-By-UrlScan

WTF! Oh No! I know what I did!

I was playing around with the Web Platform Installer from Microsoft. A very handy tool for setting up your machine for web development. Why hadn't they come out with this to begin with? It makes it easy to install everything you need, and apparently things you do not necessarily need. In my case, I selected UrlScan 3.1 to be installed. I didn't really need UrlScan. I didn't really understand at the time what UrlScan actually was. I know now. Kinda...

For whatever reason, UrlScan was not liking my web application. Apparently I could configure somehow but I couldn't be bothered so I just uninstalled it.

That didn't work.

Despite uninstalling it was still hooked into IIS. The UrlScan dll was gone from it's installation folder. I tried restarting IIS numerous times. But it refused to let go. I gave up trying to work out how to disable UrlScan and decided it was time for a reboot.

One more thing, because I'm using IIS6 I need to alter the routing in the Global.asax.vb file because I need to specifiy an extension to be mapped for ASP.NET MVC since this application will end up on a shared host where I have no control over the configuration of IIS. As such, the extension I'm going to use is ".aspx".

I replaced the original route...

  routes.MapRoute("Default", _
                  "{controller}/{action}/{id}", _
                  New With {.controller = "Home", .action = "Index", .id = ""})
With the following...
  routes.MapRoute("Default", _
                  "{controller}.aspx/{action}/{id}", _
                  New With {.controller = "Home", .action = "Index", .id = ""})

  routes.MapRoute("Root", _
                  String.Empty, _
                  New With {.controller = "Home", .action = "Index", .id = ""})

Phil Haack has a handy guide for this. Note with ASP.NET MVC RC1 you don't seem to need the fix for the Default.aspx page as it already handles the problem with routing the default page.

Yay! The almost-out-of-the-box ASP.NET MVC application works!

Screenshot

In Part II I begin adding jQuery and the Spark View Engine.

Syntax Highlighters Example

Javascript Code Prettifier

class Voila {
public:
 // Voila
 static const string VOILA = "Voila";

 // will not interfere with embedded tags.
}


Syntax Highlighter 2.0
class Voila {
public:
 // Voila
 static const string VOILA = "Voila";

 // will not interfere with embedded tags.
}

Saturday, 24 January 2009

I like StackOverflow.com but...

StackOverflow is a programming Q & A site that's free to directly copy a line from their "About" page.

But it makes me feel... Inadequate.

But asking and answering questions, other users can vote you up or down to earn (or lose) reputation points.

I have my moments of trolling the site looking for questions I can answer to gain a little rep but I find it a struggle.

How do people manage to devote so much time to gaining so much reputation measured in the thousands?

Is there some trick involved?

I do find the site invaluable for finding the answers for problems I have be stuck with but I sometimes it doesn't come through for me.

I had one particularly nasty problem that I'd keep bumping into for some strange reason.

I have an ASP.NET TreeView control on the page, the user selects a node. How can I tell if the user clicks the selected node again? No event was triggered for clicking the selected node, only for when a non-selected node was clicked.

I couldn't get a satisfactory answer so I updated the post to state that I'd look to develop a solution when I had the time.

In the meantime, my question seems to be getting a significant number of views. Nobody seems to be attempting and answers and nobody seems to be voting.

Eventually I did find the time and I thought I'd find a reasonably good solution. I promptly submitted the solution as an anwser to my own question.

The trouble now is how to get my answer at the top of the list? With the number of views my question has had, surely people are interested in the answer? Is there a reason for not voting up my solution? Is my solution really that bad that they couldn't even be bothered to vote my solution down?!

Maybe it's just me.

I just can't help but get concerned that my solution gets no recognition.

Maybe I should start trolling for some simple questions again... Don't I have something even vaguely more interesting to do?

Sigh...


Just as a side note, when looking at my stats for the question I posted, it seems to show "2k" as the number of views.

But when I select the question, it then states the question has been viewed 1,887 times.

I am pretty sure the 2k does not equal 1887 or even approximate it all that closely.

Finally! I'm a Real Developer!

Today, I finally recieved my MCPID and Access Code.
MCP Logo
It took a while in coming but it hadn't been a priority to sort it out.

I had studied for and passed the exam while working for a former employer. One month after passing the exam I left for greener pastures.

I never received my MCPID or Access Code.

This past week my colleague James Hippolite finally convinced me to sort out my MCPID and graciously offered to help.

He find an email for me to contact, to which I wrote a most heart felt letter discribing the heartache and pain I'd endured in the nearly two years of not being able to log into the MCP website.

Of course I could have gone to more courses and sat more exams but I've been of the mind that certification wasn't for me.

But now that I have finally sorted out my MCP log in and associated it to an email, and I guess Passport/Live ID perhaps, that I shall never consciously lose again - perhaps I shall look more seriously at extending my certifications.

In any case, I am happy that I now have a printed document to show that I've at least achievement one credential... Albiet a little long in the tooth...

Saturday, 13 September 2008

Logging (not the tree kind)

Logging is a great tool when it has been implemented and things go wrong in production. ASP.NET applications can be a real bother when there is no logging of any sort.

I am a bit of a late starter when it comes to implementing logging within my applications and the only options I really had was writing either to the Event Log or writing to a database "Audit" table. Both options tend to involve writing a pile of code that I was never really all that happy about.

Then for a long while I kept hearing about a wondrous tool to solve all my logging woes... Log4Net

Log4Net just made logging so easy. I'd wrap Log4Net into my own custom class which would give me the basic methods to call appropriate Debug/Warning/Error/etc. methods and I would be away laughing.

Configuration was reasonably straight-forward. Log4Net gave me the flexibility to log "fatal" errors to the Event Log and/or email them to the appropriate person. All other levels of logging could be switched off and on at will and would log to a daily file.

All as sweet.

Then one day not too long ago I was watching a screen-cast from a certain fellow called Rob Conery. He just happened to brush upon the notion of logging within this particular installment of his MVC Storefront series but he wasn't using Log4Net!

Shock! Gasp!

*** NEWS FLASH ***

I seem to have killed Rob Conery's web site! Saturday 13th at 6:05PM NZ time... It may just be a coincidence. Or maybe it is just playing up for me. All I was doing was clicking on a tag in the tag cloud and it stopped working.

My bad.
*** NEWS FLASH ***

Anyhoo, back to the gasping...

He implemented not Log4Net but a relatively new kid on the blog... NLog

Dramatic riff...

I love it.

Just as simple to use as Log4Net and even easier to configure. More importantly easy to extend! The first thing I did was write my own custom layout renderer.

The documentation is quite straight-forward but I did have one stumbling block when I first tried to view all my wonderful new logging files NLog was now creating. Except it wasn't and it nearly put me off NLog because I couldn't see why.

Of course the problem boiled down to an assumption I'd made with the configuration that carried over from Log4Net.

When writing to a file I assumed it would be relative to the folder where my application was running and so I specified a relative path for the log file NLog was to write to.

Thanks to ProcMon from SysInternals I saw the error of my ways and then defined absolute paths for NLog. Of course, don't forget to make sure the account the worker process is running under has permissions to write to the location of your log files.

So like magic my application was now happily logging messages into the folder I designated for it.

And now I am happy and plan to use NLog in all my future applications.

Until something new takes my fancy of course...

NOTE: I am not sure how long Rob Conery's site was down for but was back up again 25 minutes later when I checked again.