No Free Time

Because my therapist says I need to let things out

Naming Your Action Methods in ASP.Net MVC

Posted by andrewmyhre on November 24, 2009

Something that I always do now and might in fact be quite obvious to regular people but I’m quite slow so it took me a little while to realise this was a good practise.

Let’s say I have a page for editing a blog post. I want the form to be at /BlogManagement/Edit/postId.

So I write my first action method:

[Authorize(Roles = "administrator")]

 

public ActionResult Edit(int ID)

And here’s what the URL looks like in my browser:

Cool. Now I write the method for the edit form view to post to:

public ActionResult UpdateBlogPost(FormCollection formData)

{

}

This will work of course. But what happens if validation fails? We get send back to the edit form. But we don’t want to redirect, we’ll just return the appropriate view and viewdata. So what will the URL be now?

Oh dear. That’s no good at all. Now our visitors have this erroneous entry in their history. No, this will not do.

To tidy this up we’ll make use of method overloading and the AcceptVerbs action method attribute. Here’s the signature of the GET action method which displays the edit form view:

[AcceptVerbs(HttpVerbs.Get)]

[Authorize(Roles = "administrator")]

public ActionResult Edit(int ID)

{

and here’s the signature of the POST action method that validates, updates and redirects:

[ValidateInput(false)]

[AcceptVerbs(HttpVerbs.Post)]

[Authorize(Roles = "administrator")]

public ActionResult Edit(FormCollection formData)

{

This works because the ASP.Net MVC routing engine understands method overloading and, providing you are using the AcceptVerbs attribute, it will route each request to the appropriate method.

Doing this will make sure that the URL in the browser stays the same during the whole process. Much neater, no?

Posted in .net, mvc | Tagged: , , | 1 Comment »

My Current log4net Setup

Posted by andrewmyhre on November 24, 2009

Because I’m waaaaay interested in logging, tracing, diagnostics, analytics – basically, what’s going on with my shit – I spent some time today tweaking our log4net configuration here at work. The actual motivation for sitting down and doing this was that I wasn’t getting any notification from uncaught exceptions in our sites, and I saw a couple in the event log on our live box. Naturally I flew into a blind rage and immediately set up an SmtpAppender for the existing log4net config for that site. After an hour or so I have a configuration that I like, so here it is.

I added two things:

  • Split configuration files so we can drop a new log4net configuration into a site without worrying too much about the main web.config
  • SmtpAppender for any log messages at WARN level or above

Here’s the template web.config file with the log4net configSource attribute:

<?xml version=1.0?>

<!–

Note: As an alternative to hand editing this file you can use the

web admin tool to configure settings for your application. Use

the Website->Asp.Net Configuration option in Visual Studio.

A full list of settings and comments can be found in

machine.config.comments usually located in

\Windows\Microsoft.Net\Framework\v2.x\Config

–>

<configuration>

<configSections>

<section name=log4net type=log4net.Config.Log4NetConfigurationSectionHandler,Log4net/>

</configSections>

<log4net configSource=log4net_debug.config />

<!–

log4net debugging

if debugging log4net uncomment this line to specify a file output for trace messages

<system.diagnostics>

<trace autoflush=”true”>

<listeners>

<add

name=”textWriterTraceListener”

type=”System.Diagnostics.TextWriterTraceListener”

initializeData=”log4net.txt” />

</listeners>

</trace>

</system.diagnostics>

–>

</configuration>

The debug log4net config file:

<log4net debug=true>

<logger name=default>

<level value=INFO/>

<appender-ref ref=LogFileAppender/>

</logger>

<appender name=LogFileAppender type=log4net.Appender.RollingFileAppender>

<param name=File value=log.txt/>

<param name=AppendToFile value=true/>

<rollingStyle value=Size/>

<maxSizeRollBackups value=10/>

<maximumFileSize value=1KB/>

<layout type=log4net.Layout.PatternLayout>

<conversionPattern value=%-5p %logger %d{yyyy-MM-dd hh:mm:ss} – %m%n/>

</layout>

</appender>

<!–

<appender name=”SmtpAppender” type=”log4net.Appender.SmtpAppender”>

<to value=”[admin email address]” />

<!– noreply@websiteurl –>

<from value=noreply@websiteurl />

<!– EXCEPTION:[environment]:[Website name] –>

<subject value=EXCEPTION:[environment]:[Website name] />

<!–

smtp servers

live: localhost

staging: TEQ-STG01

–>

<smtpHost value=[smtp server] />

<bufferSize value=512 />

<lossy value=true />

<evaluator type=log4net.Core.LevelEvaluator>

<threshold value=WARN/>

</evaluator>

<layout type=log4net.Layout.PatternLayout>

<conversionPattern value=%newline%date [%thread] %-5level %logger [%property{NDC}] – %message%newline%newline%newline />

</layout>

</appender>

–>

<root>

<level value=ALL/>

<appender-ref ref=LogFileAppender />

<!–

<appender-ref ref=”SmtpAppender”/>

–>

</root>

</log4net>

And the release log4net config file:

<log4net debug=false>

<logger name=default>

<level value=WARN/>

<appender-ref ref=LogFileAppender/>

</logger>

<appender name=LogFileAppender type=log4net.Appender.RollingFileAppender>

<param name=File value=log.txt/>

<param name=AppendToFile value=true/>

<rollingStyle value=Size/>

<maxSizeRollBackups value=3/>

<maximumFileSize value=1KB/>

<layout type=log4net.Layout.PatternLayout>

<conversionPattern value=%-5p %logger %d{yyyy-MM-dd hh:mm:ss} – %m%n/>

</layout>

</appender>

<appender name=SmtpAppender type=log4net.Appender.SmtpAppender>

<to value=[admin email address] />

<!– noreply@websiteurl –>

<from value=noreply@websiteurl />

<!– EXCEPTION:[environment]:[Website name] –>

<subject value=EXCEPTION:[environment]:[Website name] />

<!–

smtp servers

live: localhost

staging: TEQ-STG01

–>

<smtpHost value=[smtp server] />

<bufferSize value=512 />

<lossy value=true />

<evaluator type=log4net.Core.LevelEvaluator>

<threshold value=WARN/>

</evaluator>

<layout type=log4net.Layout.PatternLayout>

<conversionPattern value=%newline%date [%thread] %-5level %logger [%property{NDC}] – %message%newline%newline%newline />

</layout>

</appender>

<root>

<level value=WARN/>

<appender-ref ref=LogFileAppender />

<appender-ref ref=SmtpAppender/>

</root>

</log4net>

I’ll be suggesting that this configuration is adopted as standard for all new builds and I’ll go and reconfigure a few of our other active sites too.

Posted in .net, logging | Tagged: , , | Leave a Comment »

Handling Exceptions in ASP.Net MVC 1

Posted by andrewmyhre on November 20, 2009

Here’s a handy way to handle uncaught exceptions in ASP.Net MVC 1.

Make a base controller with the following code:

public class BaseController : Controller

{

ILog log = LogManager.GetLogger(“BaseController”);

string actionName = “”;

string controllerName = “”;

protected override void OnActionExecuting(ActionExecutingContext filterContext)

{

base.OnActionExecuting(filterContext);

actionName = filterContext.ActionDescriptor.ActionName;

controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

}

protected override void OnException(ExceptionContext filterContext)

{

log.Fatal(“Unhandled Exception”, filterContext.Exception);

//Displays a friendly error, doesn’t require HandleError

filterContext.ExceptionHandled = true;

this.View(“Error”, new HandleErrorInfo(filterContext.Exception, controllerName, actionName)).ExecuteResult(this.ControllerContext);

}

}

Then make your other controllers derive from this one and hey presto, friendly(er) error messages and better exception logging in your site.

Sources:

http://geekswithblogs.net/SanjayU/archive/2009/11/09/error-handling-in-asp.net-mvc-1-part-2-of-2.aspx

http://stackoverflow.com/questions/362514/asp-net-mvc-current-action

 

 

Posted in .net | Tagged: , , | Leave a Comment »

Linq to SQL and Serialization : A circular reference was detected while serializing an object of type [whatever]

Posted by andrewmyhre on November 4, 2009

Okay so I created a Linq to SQL model today. It includes tables for Blog Posts and Blog Comments which have a one-to-many relationship, hence a BlogComment has a .BlogPost property and a BlogPost has a .BlogComments property. Pretty standard.

When I attempted to serialize a collection of BlogPosts and their related BlogComments I was met with the following error:

A circular reference was detected while serializing an object of type BlogPost.

Fairly obvious why – the serializer is working through each property on a BlogPost using reflection, then enumerating each comment on the blog post, enumerating each property on the comment which includes a reference back to the blog post – which is where the circular reference joins up.

Obvious problem, but how to get around it? What I actually need to do is instruct the XmlSerializer to ignore the BlogComment.BlogPost property – I want it to enumerate the comments attached to a blog post but I don’t want it to walk back up to the blog post. To accomplish this I don’t want to have to mess with my DBML file or the C# class definitions, because as soon as I modify the database in the future I’ll have to reimplement those changes. A partial class implementation won’t help me because I need to modify the original class, not patch new functionality onto it. I was thinking I needed to add an [XmlIgnore] attribute somewhere, and that this would be a nightmare.

Well it turns a much simpler solution is to just mark the relationship as an Internal property in the Linq to SQL designer.

linq_to_sql_designer_association_property

This works because the XmlSerializer only serializes public properties.

Posted in Uncategorized | 1 Comment »

AltNet Beers October 28

Posted by andrewmyhre on October 27, 2009

AltNet Beers tomorrow night (October 28, 2009) is being hosted by Tequila London at their office at 82 Dean St in Soho. Nearest tube is Tottenham Court Road station which is on the Central and Northern lines.

Map with directions from the tube station: http://tinyurl.com/tequilalondon

To get there after StackOverflow DevDays your best route is to walk north from Kensington Town Hall to Notting Hill Gate station which is on the central line. From there travel east to Tottenham Court Road station.

Directions from Kensington Town Hall to Notting Hill Gate: http://tinyurl.com/ylrvekz

See you at Tequila!

Posted in Uncategorized | Tagged: | Leave a Comment »

Calling a footer a footer

Posted by andrewmyhre on September 4, 2009

SharePoint MVP Randy Drisgill points out that if you’re creating a stylesheet for a Sharepoint site with a rule for #footer meaning, ostensibly, the footer for the page, you won’t get the result you intended.

That’s because when the guys created the SharePoint engine they decided to use the element id ‘footer’ for particular div that SharePoint outputs in the middle of your page. Nice going guys! I can’t wait to explain this to the HTML team at our agency.

Posted in sharepoint | Tagged: | Leave a Comment »

New Digital Wall

Posted by andrewmyhre on August 19, 2009

I launched a new Digital Wall this week.
I want to rewrite it already :) .

http://wall.tequila-uk.com/

Posted in Digital Wall | Leave a Comment »

Microsoft.Expression.Blend.Silverlight.targets was not found

Posted by andrewmyhre on July 29, 2009

Recently I encountered the following error when trying to open a Silverlight 3 project:

01

Unable to read the project file ‘X.csproj’.
The imported project “c:\program files\MSBuild\Microsoft\Expression\Blend\3.0\Silverlight\Microsoft.Expression.Blend.Silverlight.targets” was not found.
Confirm the path in the <Import> declaration is correct, and that the file exists on disk.

The scenario is that I had fired up the new RC of Expression Blend 3.0 and created a Silverlight 3 project. At some point along the way I had also been messing with a TextBlock and I had ticked the ‘Embed’ checkbox to embed the font I selected into the project. Then when I tried to open the project on another machine I was met with the above error and my Silverlight project wouldn’t load.

Unni Ravindranathan was helpful enough to point out that when using Blend 3 features such as embedded fonts you must have the Blend 3.0 SDK installed, and sure enough that’s exactly what I’d done. I had thought I needed to installed Expression Blend 3.0 on my machine in order to open the project, but the SDK was all I needed. Unni is Program Manager on the Expression Blend team and I appreciate his quick and direct help.

I’d like to know why I could always embed fonts in Silverlight projects without needing Blend 3.0 but I’m sure there’s a perfectly reasonable explanation. Not to mention – why is the SDK not an optional part of the Silverlight 3 SDK install? It’s only a 3mb download…

Grab the SDK here: http://www.microsoft.com/downloads/details.aspx?FamilyID=F1AE9A30-4928-411D-970B-E682AB179E17&displaylang=en

Posted in silverlight | Tagged: , | Leave a Comment »

I’m Back and a Non-Programming Related Reference

Posted by andrewmyhre on July 16, 2009

Well I’m finally back from an extended stay in my home country, New Zealand. The particulars that brought about my prolonged visit to NZ are boring and long-winded so I won’t go into them here. While I’m grateful to my employers for allowing me to work remotely while I was over there, I’m also thoroughly grateful to be back home, in London. Yes, my time back in NZ has brought the realisation into stark relief that London is, presently at least, home. It’s a nice feeling.

Moving swiftly to the point of this post, that being what I want to share.

It’s a testament to the connected world we live in that keeping up to date with the latest findings and speculations of scientific research no longer requires subscriptions to obscure publications and painstaking focus, analysis and consideration. Nowadays you can just have that stuff piped straight into your computer apparatus and consequently into your brain, in a much more passive and relaxing way. How, you may ask? YouTube!

I was introduced to Daniel Dennett a few weeks ago, and I’ve added him to my list of Great Human Beings. If you don’t know who he is, here’s a nice taster for his work: Ants, Terrorism, and the Awesome Power of Memes. It’s a quick TED lecture, so it’s a sample of his ideas which is suitable for untraumatic digestion, whatever your persuasion. If you watch that video and find yourself hungry for more, there are schools of in-depth, full-length lectures available on the YouTube also, so you know how to plunge further into this sumptuous mind-steak. This lecture for instance is a fuller expansion on the TED talk linked above. Let me google that for you.

I’d be interested in hearing from anyone at all in London who finds the above interesting and would enjoy meeting up to, er, talk utter nonsense about it? Leave a comment or hit me on twitter. If there are, say, half a dozen such doomed souls I’ll organise something.

Posted in Uncategorized | Leave a Comment »

Google Chrome OS

Posted by andrewmyhre on July 9, 2009

Posted in Uncategorized | Leave a Comment »