29 Aug 2010

The Girl Who Wrote A Shopping List

It was raining as Mikael Blomkvist took the first stop off the tunnelbana at Likstoerp and visited the late-night AftonMarket. He bought pickled herring, appelsaúce, two pakkenpanes of wholegrain bread, a strudel, some milk, Sverigen cheese, a packet of raisins, three pepparsausage Billy Pan pizzas, a sponge, some shoelaces, a coathanger, some poptarts, a tube of Sensodyne Pro-Enamel toothpaste, a new washbag and a carton of Thor-brand extra strong condoms.

He paid by American Express, and then walked into the Apple Store opposite where he treated himself to a new Apple MacBook Pro with 4Gb ram, a 3Ghz Intel processor, Nvidia graphics card, a 250Gb solid state disk drive and a WUXGA OLED screen with a 60Hz refresh rate. He also bought an extended warranty, an offical Apple MacPack storage case and some 2Gb SanDisk USB memory sticks.

Then he went home, shagged someone else's wife and solved the murder.

19 Aug 2010

ASP.NET MVC 2 - Force Password Change

How to force the user to change their password when they log on? Here's how. This assumes you're not using the Membership model's User Comments field, because we're going to use it to store a flag. You're going to want to put 'using System.Web.Security;' at the top of your files cos we use the Membership classes a lot.

First define a nice enum somewhere as I'm scared of string literals.

public enum MembershipFlagType
{
RequirePasswordChange
}

Next we'll put in the code that sets the flag - e.g. in an ActionMethod where the user password is reset:

MembershipUser user = Membership.GetUser(User.Identity.Name);
user.Comment = MembershipFlagType.RequirePasswordChange.ToString();
Membership.UpdateUser(user);
string newPassword = user.ResetPassword();

Now we define a new Action Filter Attribute to perform a check for the RequirePasswordChange flag:

public class EnforcePasswordPolicy : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
MembershipUser user = Membership.GetUser(filterContext.HttpContext.User.Identity.Name);
if (user.Comment == MembershipFlagType.RequirePasswordChange.ToString())
filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new {controller = "account", action = "changepassword"}));

base.OnActionExecuting(filterContext);
}
}

Then all you have to do is decorate your ActionMethods with the new attribute:

[Authorize]
[EnforcePasswordPolicy]
public ActionResult Index(IndexViewModel viewModel)
{
...
}

Don't forget to clear the comment field after the user has changed their password, otherwise they'll be stuck in a loop.

ASP.NET MVC Email Validation Attribute using Regular Expression

You want MVC 2 / 3 to automatically validate user-submitted email addresses? Stick the following class in your project:
using System.ComponentModel.DataAnnotations;

public class EmailValidationAttribute: RegularExpressionAttribute
{
    public EmailValidationAttribute() : base(@"^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-zA-Z0-9]{1}[a-zA-Z0-9\-]{0,62}[a-zA-Z0-9]{1})|[a-zA-Z])\.)+[a-zA-Z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$") {  }
}

Then you can use it on your model / model-metadata like this:
[EmailValidation(ErrorMessage="Not a valid Email Address")]
public string Email { get; set; }

NOTE: The regex is STRONG AND GOODLY because I found a definitive source. Scott Gu has a similar solution but for once THE MIGHTY GU HAS LET US DOWN. :p

1. His regex is incomplete and wrong (doesn't allow upper-case first part to the address)
2. His blogpost comments are disabled so I can't let him know about it.

NAUGHTY GU!

17 Aug 2010

JS Framework Roundup #834543

If you're a jaded Ajax monkey like me you'll have spent an age fighting the likes of Duffle, jSeraph and DOMinic trying to get cross-domain block blending right but with unsatisfactory results, either because of unspeakably low-grade filter belling or just the usual HIB/JSTFU squirrel poll chronlocks. I'll save you the hassle of surfing gitbox, mashStash or dumplocker for a better solution, because I have just been using it and it rocks: Cherub for SquirrelNuts.

We've seen stuff from Slutw4re before, anyone remember Shizbazz Tourette or the mNugget KPlaya extension? Paragons of REST/CHEST, and unlike other Web 4.0 JS hiblibs, they always just "felt right" when you decamped them into whatever framework is your homeboy, from MicMacMock to jQuirk. Even H-Christ got a look in, and that wasn't even at Alpha yet (What's before Alpha? Answers on an eCard...)

Anyway, Cherub is their latest baby, and of course it's GPL'd with the NeoMoose caveats so you're fine on uBert, Chuzzle or Medley but might have problems if you have Bonob:OO up to patch 59.9.7.9. But who's rocking Bonob:OO anymore, anyway? What is this, late march 2009?

But I digress! Okay, so you've decamped Cherub and slipstreamed with Mon2WonTon as usual. Now what? Well, look at the new chops and grooves like so:

$.fn.Cherub(bs.mode.throb);
var myCherub *= this.Cherub({Cherubim: Seraphim});
myCherub.Blend('rubicon/framework');

I know what you're thinking. Exactly! YAY!

More info here: http://dailyjs.com/

11 Aug 2010

ASP.NET MVC 2 Controller - Use Custom Attribute to intercept call to Action

I was thinking that it would be good to have certain MVC Actions run some common code every time they are called. Naturally we could just call a common method on the first line of our Action methods, but that would not be MVC sexeh. After all, we use special Attributes such as [Authorize] and [HttpPost] to intercept the Action, so why not roll our own?

Microsoft have done the hard work for you - all you have to do is extend an attribute called ActionFilterAttribute (a type of FilterAttribute) and override its calls to the following events as required:

- OnActionExecuting
- OnActionExecuted
- OnResultExecuting
- OnResultExecuted

For example, I wanted to update the User's LastActivity timestamp whenever certain Actions were called, so I created the following:


public class LogUserActivityAttribute: ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
... Do your log activity stuff here ...

base.OnActionExecuted(filterContext);
}
}


I could then have that code executed on a per-Action basis like so...


[HttpPost]
[LogUserActivity]
public ActionResult DeleteItem(int id)
{
...
}


HTH! Incidentally, don't forget that instead of this funky MVC apprioach, you can set the Application_BeginRequest method in the global.asax file, which runs at the start of every web request to the application, e.g.

protected void Application_BeginRequest(Object sender, EventArgs e)
{
... Do your per-request stuff here ...
}

10 Aug 2010

ASP.NET 4 Session State asp_regsql

Erm, are Microsoft being deliberately obtuse or what? asp_regsql.exe runs a wizard for membership and profile storage but utterly fails to offer a pretty GUI option for creating SQL Session State storage. Noooo, that's hidden away in the command line options. This does the trick:


C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regsql.exe -ssadd -S yourDbServer -E -sstype c -d yourDatabaseNameHere

2 Aug 2010

Share desktop with other users / view computer remotely

How come I'm the last to find out about Microsoft SharedView, which is free, excellent, and works over the internet like a charm?

Because I've got my head in a bucket, that's why.

Sharepoint 2010 - Disable / Turn off "Check In" / "Check Out" and "Approval" requirements

I found that the requirement to check out my master page and CSS files was becoming a pain, every time having to check them back in and approve them too. Clearly I don't need to do this while I'm developing a site and nobody else is on the system.

I thought there would be some kind of master setting for this in Central Administration or Site Settings, but my investigations suggest this is a per-library thing. Anyhoo, the following instructions worked for me:

• Go to Site Actions / Site Settings and click View All Site Content
• Go to the library that contains the file(s) you wish to edit
• In the Ribbon, select the Library Tools / Library tab
• Click Library Settings in the Ribbon
• Click General Settings / Versioning Settings
• See the settings for Content Approval and Require Check Out
If I helped you out today, you can buy me a beer below. Cheers!