Corey Coogan

Python, .Net, C#, ASP.NET MVC, Architecture and Design

  • Subscribe

  • Archives

  • Blog Stats

    • 110,056 hits
  • Meta

Archive for the ‘ASP.NET’ Category

Calling ASP.NET Web Service (ASMX) from JQuery

Posted by coreycoogan on December 17, 2010


UPDATE: 12/17/2010 12:55 AM CST – Thanks to Dave’s comments below, I learned that the script service handles object serialization to JSON for me. This means that if your return type is that of an object, it will automatically serialize this object to JSON. If you want to create an anonymous object, such as you may do from a LINQ query, just set your return type to “object”. I thought I had to turn that into a string, but that’s not necessary. Thanks again Dave. I also removed the [ScriptMethod] attribute, which is isn’t necessary and actually causes the JSON returned to be a string and not a JSON object.

I’ve not done anything real meaningful in Web Forms in some time, so I was very surprised at how much trouble I had trying to call a simple HelloWorld service from a jQuery Post and have it return some JSON back to my screen.  It took a couple hours to finally get it right, and I know I’m not the only one.  There are Stack Overflow posts about this and many blog posts as well. Unfortunately, as helpful as those posts were, it seems that I was still missing things… the things I’m going to cover in this here post.

ASMX Web Service

First, let’s start with the old school web service that I’d like to use to communicate with the client.  Sure I could go WCF, but an ASMX is just fine for my needs and darn simple. The important things to note on the service:

  • To call a service from JavaScript, the service class must be decorated with the [ScriptService] attribute.
  • The service method should not decorated with the [ScriptMethod] attribute, only the [WebMethod] attribute. The ScriptMethod causes the return JSON to be a string that needs to be deserialized on the client. Without it, it comes down as a valid JSON object, automatically deserialized by jQuery for me.
  • If you are going to return a hardcoded JSON string for jQuery to parse, it has be formated with double quotes around the names and properties.  I was using single ticks, which I have gotten away with in some cases, but not here (return “{\”response\”:\”Hello World\”}”).
  • Mark the return type of the method to “object” if you want to return with an anonymous object from a LINQ query or something like that. 

This is an example of a working service:

    [ScriptService]
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class HelloWorld : System.Web.Services.WebService
    {
        [WebMethod]
        //[ScriptMethod(ResponseFormat = ResponseFormat.Json)] Don't need this attribute.  
        public HelloWorldResponse SayIt(string name)
        {
            //the Identity of the logged in user is available
            var userName = HttpContext.Current.User.Identity.Name;
            
           return new HelloWorldResponse() {Name = name, NickName = "Mad Dog"};
        }

        public class HelloWorldResponse
        {
            public string Name { get; set; }
            public string NickName { get; set; }
        }
    }

AJAX and jQuery

Now for the jQuery, for which I’m using version 1.4.4.  Here’s the things that tripped me up:

  • I was using a JQ $.post call in my web pages to communicate with the server.  That caused me some problems in that the data was always returned as XML, no matter what I tried.  Knowing that $.post is a shortcut against the $.ajax method, I switched to using that so I could explicitly set the contentType to “application/json”.  I do realize that I can probably set that on the $.post method, as I’m pretty sure I’ve done that in the past, but that can cause confusion, especially with new developers.
  • If you are accessing more than one service in more than place, create a utility method or use the $.ajaxSetup method to configure the defaults.
  • If you don’t set the dataType to “json”, the response data is returned as xml.
  • If you don’t pass empty data when there are no parameters needed for the service, the response data will be returned as xml.
  • The dictionary passed to the service in the data parameter must be quoted or the service will throw a 500 error.  Web Service parameters are passed with the name of the parameter as the key (see example).
  • This is discovered soon enough, but the response from the service comes wrapped in another JSON object, available at the ‘d’ key.  If the value for ‘d’ is a JSON string, it will have to be deserialized into a proper JSON object.  I use jQuery’s $.parseJSON function for that. This example will return ‘d’ as a proper JSON object.
<script>
    $(document).ready(function() {

        //this would be done in a common script file if you are going to
        //make a lot of these calls
        $.ajaxSetup({ type: 'POST', dataType: 'json', contentType: 'application/json', data: {} });

        $('#btn').click(function() { 
             //call the web service with the button is clicked
            $.ajax({ url: 'webservices/helloworld.asmx/SayIt',
                data: '{ "name": "Corey" }', //ensure the data is enclosed in a quote
                success: function(data) {
                    var responseJson = data.d; //the real json is wrapped, get it and parse it
                    $('#sayit').html(responseJson.Name + ' aka ' + responseJson.NickName); //put the response value from the return json
                }
            });

            //return false to avoid a postback
            return false;
        });

    });
</script>
<div>
	<button id='btn'>Load It</button>
	<div id='sayit'></div>
</div>

Authorization and Authentication

Any ASMX service written in our web project will be available to the world.  If you are using a ROLES and MEMBERSHIP provider and your site requires authentication, use the <location> tag in your web.config to lock down the directory where you put all your services.  In my example, I’ve put all my services in a WebServices directory and only authenticated users in the Admins role have access.

 <location path="WebServices">
    <system.web>
      <authorization>
        <deny users="?"/>
        <allow roles="Admins"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>

If the user is logged in, there will be an active IIdentity in HttpContext.Current.User.Identity, so your service can use that for authorization where necessary.

var userName = HttpContext.Current.User.Identity.Name;
Advertisements

Posted in Ajax, ASP.NET, jQuery | Tagged: , , , , , | 9 Comments »

Castle Windsor Tutorial in Asp.Net MVC

Posted by coreycoogan on November 6, 2009


Castle Windsor is one of the more popular IoC containers in the .NET space today.  Others include StructureMap, NJect, AutoFac, Unity and others.  My top choices are StructureMap and Castle, but I’ve never really used NJect or AutoFac and it’s my opinion that Unity is the weakest of them all and hardly worth mentioning.  I’ll show some of the basics of Castle Windsor – enough to get you setup in your ASP.NET MVC, or any other .NET application. I’ll show you enough to handle 90%+ of the most common IoC needs. Much of my examples come from the S#arp Architecture, which I’m using in my current project.

Castle Windsor Configuration Options

Windsor offers 2 configuration options – .config file or code.  Like many others, I have moved away from trying to do everything in my .config file and do more in code, practicing Convention or Configuration (CoC).  Because the novelty of .config files is so early 2000’s, I’ll focus on configuring Castle using good ‘ole C# and some conventions I follow in my applications.

Common Conventions

Nothing ground breaking here, but I like to keep my controllers as light as possible.  Therefore, I keep my application logic in an application service layer.  My app services have one ore more repositories injected into them where domain objects can be retrieved for performing operations.  My repositories, application services and interfaces all reside in different layers, which in my case is a physical assembly.  Some folks prefer to inject repositories directly into the controller, which works as well, but using services works better for me because I feel I get better separation and it simplifies the controller’s constructor, which is how I handle dependency injection.

So here’s the breakdown of my layers (assemblies/projects):

Application Layer:
Application Services, Application Service Interfaces

Data Layer:
Repository Implementations

Domain Layer (Core):
Repository Interfaces

UI Layer:
Controllers

Configuring Castle to Handle My Conventions

All of my dependency injection is through the object’s constructor.  As long as Windsor can resolve all the dependencies required by the constructors, it will be able to create and resolve the dependent objects as well.  IoC configuration is typically left to the application (MVC, WinForms, WPF, etc.), so you would bootstrap the configuration in some sort of Application Start event, which in the case of ASP.NET is available from the Global.asax.  All the code you’re about to see will exist in a class responsible for the IoC configuration that gets called from my Application_Start event.

First, a sample of a repository class and its interface, then how to automatically register all repositories in one swoop.


//my repository class from the Data assembly
namespace S2sol.Rpo.Data
{
     public class ClassroomRepository : S2sol.Rpo.Core.DataInterfaces.IClassroomRepository
    {
    }
}

//my Repository interface from the Core assembly
namespace S2sol.Rpo.Core.DataInterfaces
{
    public interface IClassroomRepository
    {
    }
}

//this is how I would resolve an IClassroomRepository to its implementation from Castle
IClassroomRepository repo = container.Resolve<IClassroomrepository>();

To make things simple, I’ll use Castle’s AllTypes.Pick() method, which effectively scans the types in an assembly. In my example below, I’m scanning my Data assembly and looking for non-generic interfaces that are the first interface defined on the classes in my Core assembly and register them with the container.

private static void AddRepositoriesTo(IWindsorContainer container)
{
    container.Register(
    AllTypes.Pick()
    .FromAssembly(typeof(UserRepository).Assembly) //get the assembly where this repository lives
    .WithService.FirstNonGenericCoreInterface("S2sol.Rpo.Core") //look for interfaces from this assembly
    );
}

I’m going to want to automatically register all my Application Services as well so they can be injected into my controllers. This syntax is a little simpler because those interfaces and implementations are in the same assembly.

private static void AddApplicationServicesTo(IWindsorContainer container)
{
      container.Register(
        AllTypes.Pick()
        .FromAssembly(typeof(ProfileService).Assembly)
        .WithService.FirstInterface());
}

Now I’ll want to make sure that all my controllers are registered. This done by using the RegisterControllers extension method from the MvcContrib.Castle library.

private static void AddControllersTo(IWindsorContainer container)
{
	container.RegisterControllers(typeof(HomeController).Assembly);
}

Now all that’s left is to show the simple part, and that’s how to register any one-offs that may not fit into your conventions. For example, I have an IValidator interface that I want to resolve to the Validator implementation I’m using in this project.

container.AddComponent<IValidator,Validator>();

It’s as simple as that. Once this has been put in place, I can just continue to develop repositories, application services, controllers and their respective interfaces and never have to remember to register any of them as long as I follow my conventions.

Castle’s Factory Facility

Facilities are how Castle handles extensibility. These are plugins for Castle that can be used for just about anything. Some of the more popular ones support NHibernate, WCF and logging. The one that comes in handy for my needs is the FactorySupportFacility. This facility allows me to configure a factory method in the container and control how objects get resolved.

The RoomParentsOnline MVC application makes use of a custom IPrincipal object that gets injected into my UserSession class, along with an HttpSessionStateBase implementation. The UserSession class is used for interacting with the current user, and by passing it an IPrincipal and HttpSessionStateBase, I have a testable design that I can develop using TDD.

//constructor for the UserSession implementation
public UserSession(IProfileService profileSerivce,
            HttpSessionStateBase session, IPrincipal principal)

The first thing to do is make sure that Castle knows about the Factory Facility that I wish to use. To do this, you can either register the facility in the .config file or in code. I’ll show you how to add it in code. This would be done in your registrar class’s constructor to make sure it’s available right away.

container.AddFacility<FactorySupportFacility>();

Now that Castle knows I’m using the Factory facility, I can tell it how I want to resolve the IPrincipal and HttpSessionStateBase. I also have to tell it how to resolve an IIdentity because of the way my code is accessing it (for testability). In the code below, I am telling Windsor to keep the registered objects available during the scope of a request. I then pass it the Function expression for how to create the object, which is all coming from the HttpContext.

private static void AddSecurityConcernsTo(IWindsorContainer container)
{
	container.Register(Component.For<IIdentity>()
	  .LifeStyle.PerWebRequest
	  .UsingFactoryMethod(() => HttpContext.Current.User.Identity));

	container.Register(Component.For<IPrincipal>()
	  .LifeStyle.PerWebRequest
	  .UsingFactoryMethod(() => HttpContext.Current.User));
	
	container.Register(Component.For<HttpSessionStateBase>()
		.LifeStyle.PerWebRequest
		.UsingFactoryMethod(() => new HttpSessionStateWrapper(HttpContext.Current.Session)));


}

I’m sure you’ll agree that this code makes it very simple to invert some of those pesky dependencies that come from the core ASP.NET plumbing. This technique is very effective for designing testable classes that need to interact with some of the “ugly stuff”.

The MvcContrib WindsorControllerFactory

Now that we have our Windsor container all configured to resolve our controllers, why not let the MVC framework use that container for creating our controllers. This can be done quite easily using the WindsorControllerFactory from the MvcContrib project. This is an implementation of ASP.NET MVC’s IControllerFactory interface. Using it is simple – just create an instance and give it your container and then register the factory with MVC. This is something that needs to be done during Application_Start.

ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));

Common Service Locator

The last thing that I’ll mention is the CommonServiceLocator project. If you already have your IoC configured, you might as well make it available to all your code that may need to get object implementations without dependency injection. The CommonServiceLocator makes this easy by adapting all the major IoC containers to work under a common interface with a few key static methods. This is something that should also happen in the Application_Start.

ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));

Bringing it all Together

Now I’ll just put everything together for your copy/paste pleasure.

Global.asax

protected void Application_Start()
{
	InitializeServiceLocator();

	//do everything else here
}

/// <summary>
/// Instantiate the container and add all Controllers that derive from 
/// WindsorController to the container.  Also associate the Controller 
/// with the WindsorContainer ControllerFactory.
/// </summary>
protected virtual void InitializeServiceLocator()
{
	//create the container
	IWindsorContainer container = new WindsorContainer();
	//set the controller factory
	ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));
	//configure the container
	ComponentRegistrar.AddComponentsTo(container);
	//setup the common service locator
	ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
}

ComponentRegistrar.cs

public class ComponentRegistrar
    {
        public static void AddComponentsTo(IWindsorContainer container)
        {
            container.AddFacility<FactorySupportFacility>();

            AddControllersTo(container);
            AddGenericRepositoriesTo(container);
            AddCustomRepositoriesTo(container);
            AddApplicationServicesTo(container);
            AddOneOffs(container);
            AddSecurityConcernsTo(container);
        }

		//add all my controllers
        private static void AddControllersTo(IWindsorContainer container)
        {
            container.RegisterControllers(typeof(HomeController).Assembly);
        }

		//handle any one off registrations that aren't convention based
        private static void AddOneOffs(IWindsorContainer container)
        {
            container.AddComponent<SharpArch.Core.CommonValidator.IValidator,Validator>("validator");
        }

       //handle registrations for my security classes
        private static void AddSecurityConcernsTo(IWindsorContainer container)
        {
            container.Register(Component.For<IIdentity>()
              .LifeStyle.PerWebRequest
              .UsingFactoryMethod(() => HttpContext.Current.User.Identity));

            container.Register(Component.For<IPrincipal>()
              .LifeStyle.PerWebRequest
              .UsingFactoryMethod(() => HttpContext.Current.User));
            
            container.Register(Component.For<HttpSessionStateBase>()
                .LifeStyle.PerWebRequest
                .UsingFactoryMethod(() => new HttpSessionStateWrapper(HttpContext.Current.Session)));


        }


		//register my application services
        private static void AddApplicationServicesTo(IWindsorContainer container)
        {
            container.Register(
                AllTypes.Pick()
                .FromAssembly(typeof(ProfileService).Assembly)
                .WithService.FirstInterface());
        }
		
		//register all custom repositories (not generic)
        private static void AddCustomRepositoriesTo(IWindsorContainer container)
        {
            container.Register(
                AllTypes.Pick()
                .FromAssembly(typeof(UserRepository).Assembly)
                .WithService.FirstNonGenericCoreInterface("S2sol.Rpo.Core"));
        }

		//register all my SharpArch generic repos
        private static void AddGenericRepositoriesTo(IWindsorContainer container)
        {
            container.AddComponent("entityDuplicateChecker",
                typeof(IEntityDuplicateChecker), typeof(EntityDuplicateChecker));
            container.AddComponent("repositoryType",
                typeof(IRepository<>), typeof(Repository<>));
            container.AddComponent("nhibernateRepositoryType",
                typeof(INHibernateRepository<>), typeof(NHibernateRepository<>));
            container.AddComponent("repositoryWithTypedId",
                typeof(IRepositoryWithTypedId<,>), typeof(RepositoryWithTypedId<,>));
            container.AddComponent("nhibernateRepositoryWithTypedId",
                typeof(INHibernateRepositoryWithTypedId<,>), typeof(NHibernateRepositoryWithTypedId<,>));

        }
    }

Conclusion

This post ended up being longer than I originally intended, but hopefully you gleaned some nice little gems here. Castle Windsor is really easy to setup and use and there are many contributions out there that add more great functionality. Sometimes it’s hard to know how to use these types of tools without some concrete examples and I hope to have you shown you some useful ones here.

Posted in Alt.Net, Architecture and Design, ASP.NET, ASP.NET MVC, Design Patterns, IoC, Uncategorized | Tagged: , , , , , , , , , , , , , | 23 Comments »

Adding Icons to ValidationSummary and Information Boxes with JQuery

Posted by coreycoogan on November 2, 2009


What’s so special about ValidationSumary and Information Boxes?

When there are errors or important information that you need to call out to your users, it is important to make it unmistakably noticeable. You want to stack the odds in your favor as much as possible that the user will see your call outs and act on them accordingly. Unfortunately, the ValidationSummary in ASP.NET and ASP.NET MVC comes very vanilla. You can change the appearance in MVC by defining the “validation-summary-errors” CSS class that is set to the ValidationSummary by default, but this isn’t always enough. The same goes true for an Information Box, which is what I call a box that contains important information that I want the user to see.

It is very typical for users to gloss over these important messages when they are rendered as text only. Placing the text in a colored box with a brightly colored border can help, but I’ve still experienced frustrated users claiming that registration is broken because they miss the message that says their email has already been used. To combat this, it’s a good practice to use familiar operating system icons for Error, Information, Warning, etc. Most users will recognize familiar icons and have learned to pay attention when they see them.

Here’s an example of what we’re going to achieve:

Error callout box

Info Callout Box

Styling the “Callout Box”

I use the same technique to style all my callout boxes. It’s very simple to do with JQuery, CSS and a few icons. I’ll demonstrate this for both an Error and Info callout.

First, the CSS classes. Each type of callout (error, info, warning) will require 2 classes. One class will style the box that contains the text and the other will be used to hold the applicable icon.

.infobox
{
    border: solid 1px #228ef1; 
    padding: 5px 8px 5px 8px;
    text-align:left;
    vertical-align:middle;
    background-color:#F1E7D1;
}

.infoimage
{
   padding: 5px 15px 5px 15px;
    background:#F1E7D1 url(/images/icons/info-24x24.png) no-repeat;
    background-position:left center;
}

.errorbox
{
    border: solid 1px red; 
    padding: 5px 8px 5px 8px;
    text-align:left;
    vertical-align:middle;
    background-color:#F1E7D1;
}

.errorimage
{
   padding: 5px 15px 5px 15px;
    background:#F1E7D1 url(/images/icons/err-24x24.png) no-repeat;
    background-position:left center;
    vertical-align:middle;
    display:inline-block;
    height:100%;
}

For my error callouts, I want to add one more class. This will handle the heading of my errors, which typically reads something like “Please fix the following errors”.

.errorhead
{
    color:#CC0000;
    font-weight:bold;
    font-size:15px;
    padding-left:18px;
}

Using JQuery to Construct the Callout Box

The HTML used to put the icon in the callout box requires nested DIV or SPAN elements. I don’t want to depend on my memory to always add the nested elements each time I want a callout, I want to simply write something like this:

<div id="CustomSearchSelect" class="infobox">
            <strong>Can't Find Your School?</strong> Try a <a id="CustomSearchLink" href="#">Custom Search</a>.
</div>

<div class='errorbox'>
This action is not allowed!
</div>

That’s where JQuery is able to help us. By using the prepend function, we can have the appropriate icon automatically injected into our callout box. We do this by adding the following to our JQuery ready function in our Master Page.

$(document).ready(function() {
$(".infobox").prepend("<span class='infoimage'>&nbsp;</span>");
$(".errorbox").prepend("<span class='errorimage'><span class='errorhead'>Looks like we have a small problem...</span></span>");
});

Pretty simple, right? Here’s what’s happening here. The script is finding the elements styled with the infobox and errorbox class and sticking in a SPAN element styled with the corresponding icon class. The errorbox gets the additional heading added here as well. You could do the same thing for Warn, Question or any other conventions you wish to follow.

Styling the ValidationSummary

The ValidationSummary requires a little bit of extra effort. This is because I’m using the xVal 1.0 and a ValidationSummary for client-side error handling as described in my last blog post. The only thing I need to do is define the HTML for my ValidationSummary, but hide it unless I have Model Errors in my MVC application. This is done by wrapping my ValidationSummary in a div styled with the errorbox class like so.

<% string display = ViewData.ModelState.IsValid ? "none" : "block"; %>
<div class="errorbox" id="validationSummary" style="display:<%=display%>"> 
    <%= Html.ValidationSummary() %>
</div>

Finding the Icons

I found some pretty nice icons on various free icon websites. It took a bit of time to run them all down, so I’m including them here for you in a zip file.

Icon Zip File

Posted in ASP.NET, ASP.NET MVC, CSS, jQuery, UI | Tagged: , , , , | 4 Comments »

ASP.NET MVC Auto Model Validation with xVal

Posted by coreycoogan on October 30, 2009


Overview

Validation is one of those necessary evils of software development.  Every application needs it and there are about as many ways to handle it as there are opinions.  No matter how you slice it, it’s usually a pain and just plain boring.  One of the things that has helped ease that pain are the assortment of validation frameworks that are available that allow the use of Attribute decorated models to specify validation rules.  If you are like me and prefer the View Model pattern when developing your Asp.Net MVC apps, then this is a perfect fit.  Now add the well crafted xVal Validation framework with automatic client-side validation via JQuery Validation and things begin to get easier.  In this post, I’ll take this one step further by showing how to use an
Action Filter approach, which I borrowed from the Code Camp Server code base, with NHibernate Validator to automatically validate the View Model via a ValidateModelAttribute that can be placed on the controller.  I’ve applied the same code in the past using Castle Validator by using the Adapter Pattern in a couple hours.

First things first, make sure you get everything you need by getting the latest versions of xVal, JQuery Validation, NHibernate Validator and/or Castle Validator.  I will warn you that if you get either of the mentioned Validators from the source trunk, you may have to recompile the xVal Rules Providers against those bits.  I had this problem with a breaking change from NHibernate Validator version 1.2.0.1003, but fortunately I found a patch here for xVal and was able to build the source and get everything working.  If anyone needs help with that, leave a comment and I’d be glad to lend a hand.

xVal Setup

There are a few basic steps to getting xVal available to your MVC project.  This post by xVal’s creator, Steve Sanderson, is a great place to get this introductory stuff.

Step 1:  Reference xVal.dll and xVal.RuleProviders.XXX.dll.

Step 2: Add the xVal.jquery.validate.js and jquery.validate.js libraries to your project and reference them in a masterpage or view.

Step 3: Add the xVal namespaces to the web.config so you won’t have to fully qualify your calls and can take advantage of the extension methods.

<add namespace="xVal.Html"/>
<add namespace="xVal.Rules"/>

Step 4: Add the validator to the xVal Rule Providers collection in the Global.asax Application_Start event handler.

xVal.ActiveRuleProviders.Providers.Add(new NHibernateValidatorRulesProvider());

View Model Decoration

Now that we have the basics out of the way, we can start setting up our View Model for validation.  The first step is to decorate the properties on our model with the validation attributes.  In the case of NHibernate Validator, there are many to choose from, including [Email], [NotNullNotEmpty] and [Pattern].  Here’s an example of a RegisterViewModel class from the Room Parents Online project. By including a value for the Message parameter, I’ve provided a useful error message that will get displayed to the user.

[NotNullNotEmpty(Message = "Email is Required"), Email(Message = "Invalid Email"), Length( 50)]
public virtual string Email { get; set; }

[NotNullNotEmpty(Message = "Confirm Email is Required"), Email(Message = "Invalid Email"), Length( 50)]
public virtual string ConfirmEmail { get; set; }

[NotNull(Message="Please specify the best time to be contacted")]
public virtual BestTimeToContact BestTimeToContact { get; set; }

[NotNull(Message = "Please specify if you wish to be contacted through email")]
public virtual bool AllowNotification { get; set; }

[NotNull(Message = "Please specify who can see your contact info")]
public virtual UserVisibleTo UserVisibleTo { get; set; }

[NotNullNotEmpty(Message="Nickname is required"), Length(50)]
public virtual string Nickname { get; set; }

[Pattern(@"^(\d{4})?$", Message = "The area code of your phone number are not valid")]
public virtual string Phone1 { get; set; }

The View

The next thing to do is prepare the View for xVal validation. First, make sure you have the xVal and JQuery validation scripts reference, either in the particular View or the Masterpage.

Step 1: If you prefer for all your errors to be grouped together like I do, create a Validation Summary with an ID assigned:

<div id="validationSummary" >
<%= Html.ValidationSummary() %>
</div>

Step 2: Use the xVal extension method to emit the JQuery Validation script.  The sample below takes the type of View Model as a generic parameter and tells xVal what Validation Summary to use for displaying error messages.  The .AddRule methods are handy little AJAX rule executions that are new in version 1.0.  Get more details in Steve’s post.

<%= Html.ClientSideValidation&lt;S2sol.Rpo.Web.Models.Profile.RegisterModel&gt;()
.AddRule("Email", new RemoteRule((Url.Action("ValidateUniqueEmail"))))
.AddRule("Nickname", new RemoteRule((Url.Action("ValidateUniqueNickname"))))
.UseValidationSummary("validationSummary") %>

The ValidateModelAttribute Filter

We’re almost there. Now we only need to hook up the filter to validate the model automatically. First, a quick peek at what the Action method looks like that will invoke the automatic model validation via the filter:

[AcceptPost]
[ValidateModel(typeof(RegisterModel))]
[Transaction]
public virtual ActionResult Register(RegisterModel model)

Now let’s have a look at the code for the validation filter itself:

namespace S2sol.Rpo.Web.Security.Filters
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
	public class ValidateModelAttribute : ActionFilterAttribute
	{
		private readonly Type _viewModelType;
		private readonly IValidator _validatorRunner;

		public ValidateModelAttribute(Type viewModelType)
            : this(viewModelType, ServiceLocator.Current.GetInstance<IValidator>())
		{
		}

		public ValidateModelAttribute(Type viewModelType, IValidator validatorRunner)
		{
			_viewModelType = viewModelType;
			_validatorRunner = validatorRunner;
		}

		public override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			object model = GetModelFromActionParameters(filterContext);

            var errors = _validatorRunner.ValidationResultsFor(model);

            //check if the model has ICompositeValidationResult
            if (model is ICompositeValidationResult)
            {
                ICompositeValidationResult validate = model as ICompositeValidationResult;
                if (!validate.IsValid())
                {
                    foreach (var err in validate.GetResults())
                        errors.Add(err);
                }
            }

			if (errors.Count > 0)
			{
				AddErrorsToModelState(filterContext, model,errors);
			}
		}

		private object GetModelFromActionParameters(ActionExecutingContext filterContext)
		{
			foreach (var kvp in filterContext.ActionParameters)
			{
				if (kvp.Value == null)
				{
					continue;
				}

				if (kvp.Value.GetType() == _viewModelType)
				{
					return kvp.Value;
				}
			}

			throw new NullReferenceException("The action parameter was null.  Check the binding prefix.");
		}

		private void AddErrorsToModelState(ControllerContext context, object model, ICollection<IValidationResult> results)
		{
                   //IValidationResult is defined in the SharpArchitecture
                   foreach (IValidationResult result in results)
                   {
                     context.Controller.ViewData.ModelState.AddModelError(result.PropertyName, result.Message);
                   }
		}

		private static string FlattenErrors(string[] errorsForProperty)
		{
			return string.Join(", ", errorsForProperty);
		}
	}
}

After it’s all done and compiled, here’s an example of a failed registration attempt with client and server side validation and the only thing I have to do is decorate my model with my chosen validation constraints and decorate my action method with the ValidateModelAttribute filter.

Posted in ASP.NET, ASP.NET MVC | Tagged: , , , , , , , | 4 Comments »

Asp.Net MVC and Server Controls

Posted by coreycoogan on August 25, 2009


I’m involved on the fringe of an MVC project right now and the core group of developers have no experience in ASP.NET MVC.  This group is more experienced in traditional Web Forms development and didn’t take the time to learn anything about MVC and how it works.  Unfortunately, this led to some major problems.  I’d like to reiterate here for anyone who stumbles across this post one major lesson that this development team learned.
DON’T EVER USE SERVER CONTROLS AND VIEW STATE IN ASP.NET MVC.

Some controls may be work some of the time, but it’s best to just stay away.  If you are going to use ASP.NET MVC, then go all in.  Everything you want to do in Web Forms is possible in MVC, just in a different way.  Embrace the truth of web development!

Posted in ASP.NET, ASP.NET MVC | Tagged: , , , , , | 1 Comment »

Mockup Alternative to Visio and PowerPoint

Posted by coreycoogan on July 24, 2009


As  I was writing the title for this post, I ran through many iterations before settling on this one soley for the purpose of being more targeted towards search terms.  Here’s some of the runner ups:

  • Mockups in Visio and PowerPoint Suck!
  • Say goodbye to Visio and PowerPoint mockups
  • Mockups in Visio and PowerPoint….Never!

Sample Mockup It should be clear now just how much I hate Visio and PowerPoint for doing mockups.  Neither of these tools were built for this purpose, so it’s no surprise that the process is awkward and usually time consuming.  Thankfully, I came across a far superior tool a while back in a DDD post by Casey Charlton.

The tool is called Balsamiq and it’s pretty amazing.  It’s whole reason for existence is for doing mockups – not presentations,  flow charts or anything else.  It runs on Adobe Air, so the installation can take a while if you don’t have this runtime on your machine already, but updates are free for life and come down pretty quick.

Balsamiq comes in 2 flavors, the desktop edition and the web edition, as well as plug-ins to some popular CMS and Project software packages.  The license is cheap, only $79 for a single license and cheaper for multiple seats.  The project file is saved in an XML format, so it can be checked into source control and easily shared.  It has a ton of built-in controls to allow you to mock everything from Maps to Browser Windows to Grids to Buttons and just about any other UI element you can think of.  The only downside is that you can’t make reusable components, which means a simple change to something like a header could result in hand-editing every mockup file you created.

Sample MockupI won’t go into too much detail here.  If this sounds good to you and you want to learn more, watch the quick demo video and then take a test drive with the browser edition (no setup required).

Posted in Architecture and Design, ASP.NET, ASP.NET MVC | Tagged: , , , | 2 Comments »

Beginning ASP.NET MVC

Posted by coreycoogan on May 28, 2009


I’ve thought about starting a blog for quite some time now, so this is it – I’m finally doing it.  I made the decision to actually do this a couple weeks ago, even setup my account here on WordPress.  The only thing stopping me was this – where to begin?  What should my first post be?  Since I’ve been interested in ASP.NET MVC for some time and now have a need to write a production app with the technology, it seemed right.

So where to get started with ASP.NET MVC?  I’ve read through most of the tutorials from the ASP.NET MVC website.  I’ve read many blog posts over the last year from Scott Hanselman, David Hayden, Jeffrey Palermo and others.  Now it’s time to step up to the plate and actually make things happen.

The first thing I’m doing is buying the Pro ASP.NET MVC book by Scott Guthrie, Scott Hanselman, Rob Conery and Phil Haak.  I’ve read many reviews that say this is a pretty good book to have on hand and I’m sure it will come in handy.

Now the fun begins.  My first task is to setup the project solution.  I’m very meticulous about how a solution gets setup, as once it’s done it’s usually set in stone becuase it can be a pain to change later.  I’ve played with Billy McCafferty’s S#arp Architecture, which is a framework for starting an ASP.NET MVC project in a Domain Driven Design fashion.  I like the way things are broken up and will probably mock much of his structure.  It’s got great samples for how/where to register your routes and configure your IoC container, for which I’ll be using Windsor.

We’re using LLBLGen for an ORM, with LINQ support, so we’ll likely be handing those generating objects around the app, so I’ll have to account for that with the design.

The team that’s working on this project has no experience with ASP.NET MVC, and mine is very limited, so it will be a learning experience for all.  I’m really stoked to get going on this one and will keep you posted on our architectural decisions and how things turn out.

Posted in ASP.NET, ASP.NET MVC | Tagged: , , , | 1 Comment »