No Free Time

Because my therapist says I need to let things out

Archive for November, 2009

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: , , | 1 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 »