Corey Coogan

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

  • Subscribe

  • Archives

  • Blog Stats

    • 110,056 hits
  • Meta

Posts Tagged ‘ASP.NET MVC’

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.

Advertisements

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, S#arp Architecture and Blood

Posted by coreycoogan on September 5, 2009


The Bleeding Edge

The Bleeding Edge

As mentioned in a previous post, I’ve embarked on a side project that provides tangible value to a relatively large mass of people.  This project, http://www.roomparentsonline.com, started some time ago and seemed like the perfect opportunity to move from toying with ASP.NET MVC and NHibernate to actually writing a production app with those tools.  Had I stuck with the same old stack I’m sure the project would be done by now, but instead I’m just getting started with developing actual features.  This is a very similar situation described in Rob Conery’s latest post, but I’m listening to Bad Corey and forging ahead because I really want to up my skills in this area.

So where was all my time spent?  Some was dedicated towards getting the design I got from Mark Sternig into the MVC framework.  Other time was spent getting the membership stuff setup and figuring out how I was going to lay all that out, but the other 90% was spent with Fluent NHibernate (FNH) and getting slashed by the bleeding edge of every cool OSS project out there.  Now I know why a common Alt.Net slogan is “Running with Scissors”.

S#arp Archecture 1.0 RTM

My first major hurdle was caused by the fact that I didn’t want to wait anymore for SharpArch to be released in 1.0, so I moved ahead with the latest.  I already had some significant development done when 1.0 was released 10 days later.  The RTM release was significant and fixed many issues, but there’s no way to simply upgrade the templates.  So I started by copying over all the 1.0 binaries, which caused some compatibility issues because dependencies were built against previous versions of Castle, NHibernate, etc.  I began upgrading bit by bit and found the updated classes in the new template and began to upgrade my project.  It was painful, but in the end it worked and all was good.  Time to move on to getting some mappings done.

Fluent NHibernate

For those of you not familiar with what Fluent NHibernate is, it basically lets you configure NHibernate through a fluent interface without requiring XML files.  I personally hate configuring with XML files, which is why I was so intrigued by this project.  The example project and articles I’ve read make FNH seem so simple.  It was only after I began to dive deep that I realized it seemed simple because the examples were simple.  When I tried doing things like mapping table-per-hierarchy relationships, I started pulling my hair out.  Things just didn’t work as I expected them to.  So I began to post to the FNH Group and got some great help, mostly from the creator himself, James Gregory.  Much of the advice was the same – get latest from the trunk as odds were this was a bug that’s already been fixed.

This is where the fun began.  Upgrading to FNH from the trunk meant upgrading NHibernate, meant upgrading multiple Castle projects, meant upgrading NHiberate Validator meant upgrading xVal meant upgrading all core Sharp Architecture libraries.  As you can imagine, this was going to be painful, but I saw no other option.  To make matters worse, the version from the trunk had many breaking changes so I was also breaking stuff that I actually had working.  Thankfully, Tom Cabanski informed the SharpArch group that he had rebuilt all the binaries against these latest versions and provided them in a tidy little zip file.  This was a huge help and I can’t thank Tom enough.

The Future

I’m now at a place where I can begin to actually implement features.  I’ve said a sad goodbye to my self-imposed deadline of having this app, at least registration, done by start of the 2009 school year, but I’ve learned a lot and have much more to learn.  During the upgrade process, I was also able to move to the 1.0 release of Linq to NHibernate.  It’s wonderful to think how many great projects came to fruition this summer after reading about them in their idea phase for so long.  The .NET OSS community is strong and I’m grateful to be enjoying the fruits of their labor.  Anyway, I finally figured out how to blend automappings and Fluent mappings, which was required to do class-per-hierarchy, but I’ll save that for another post.  I also have a nice validation implementation utilizing NHibernate Validator, JQuery Validation and xVal, but that post is coming as well.

Posted in ASP.NET MVC, Fluent Nhibernate, NHibernate, S#arp Architecture | Tagged: , , , , , , | 5 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 »

ASP.NET MVC and S#arp Architecture

Posted by coreycoogan on August 21, 2009


It’s been a while since I’ve posted.  I’ve been very busy with my paying job and my side project, Room Parents Online (RPO).  For RPO, I’m using the S#arp Architecture, developed by Billy Mcafferty.  It’s a great framework for getting a new MVC project started, but one of the real benefits of using it for me was the initial setup and configuration of Fluent NHibernate.  I have never written a real production app in NH at all, so this was something I’ve been wanting to do for a long time.  There’s been plenty of pain on the bleeding edge, but more on that in future posts.

Now that I’ve laid the ground work, expect to see more posts coming from the RPO project.  I’ve been working on this project for about a month, so I have a good bit of material already, and will find the time to blog about the project regularly.  Topics to come will include:

– Automatic Model validation with xVal (this post was started 10 days ago)
– Fluent NHibernate
– NHibernate
– The pains of running with scissors
– ASP.NET MVC
– Google integration
– JQuery
– S#arp Architecture

So stay tuned for some good Alt.net stuff.

Posted in Alt.Net, Architecture and Design, ASP.NET MVC, S#arp Architecture | Tagged: , , , , , | 1 Comment »

Asp.Net MVC HTML Helper Alternative

Posted by coreycoogan on June 11, 2009


I’m still learning ASP.NET MVC and gearing up for 2 projects.  At first glance of a typical View, I had a classic ASP flashback.  Now that I understand how it really works, I see that the only commonality is the use of the ASP delimiter tags (<%%>).

I’m not real crazy with the default ASP.NET MVC view engine and have examined some alternatives, such as MVC Contrib and Spark.  A new strategy has emerged however, developed by Eric Hexter.  Eric is dubbing his project Opinionated Input Builders.  It’s very early stage, but it’s definitely interesting and worth checking out.

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

MVC Project Architecture

Posted by coreycoogan on June 5, 2009


The MVC project I’ve talked about in my first 2 posts is still moving along.  I’ve continued to learn all I can about the new ASP.NET framework, but have a lot to learn.  It’s very different (read:better) from the MVC I used to do 5 years ago in the JSP days.

As the rest of the team ramps up, I thought it was important to layout the application architecture.  Being a fan and student of Domain Driven Design, I followed many of the patterns discussed by Evans, as well as others. The app requires a WCF service layer, so most the typical layering will reside behind the Service layer.  We’re also using LLBLGen, with Linq, as an ORM.  The client is anti NHibernate, so some other ORM had be chosen and in my opinion LLBLGen is the best database driven ORM around.

The app is an enterprise critical application and I’m trying to architect in a way that will support growth, foster SOLID principals and be easy to maintain.  Here’s the layers we’ll be using, with a description of each.

app.web (mvc)

app.web.controllers – has controllers for MVC.

app.application – DTOs, WCF service gateway, interface for WCF proxies.  Controllers will take WCF service proxy interfaces via DI.

app.service – WCF service that sends/recieves DTO’s defined in app.application.  Maps DTO’s to domain objects and interacts with the next layer to call Application Services.

app.service.application – application layer for the WCF service.  Contains application services that act as a facade to the domain (core) layer.  This is where all infrastructure and domain functions are coordinated.

app.core – where domain objects and repository interfaces live. This is where all business logic is essentially stored.

app.infrastructure – where the repository implementations live, as well as email gateways and other infrastructure stuff.

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

ASP.Net MVC Installation – Windows Installer Service Woes

Posted by coreycoogan on May 29, 2009


As discussed in my first post, I picked up the Pro ASP.NET MVC book and began reading it, as well as digging into some web resources.  I am all ready to start laying things out and working through some simple code for my first MVC production app, but on my daytime laptop, I’m having trouble with the installation.

During the installation/configuration of VS.NET templates, I got an error message stating that the Windows Installer Service had choked and ended my installation prematurely.  Through some digging, I came across this post from Phil Haak.  Turns out that previous VS.Net add-ons can cause trouble with the MVC installation.

I have the latest version of CodeRush Express loaded, as well as GhostDoc and TestDriven.net.  I let the patch run for about 10 minutes, at which point the progress bar began to move backwards.  The installation dialog just sat there for another 5 minutes before I got scared and hit cancel.  It doesn’t seem to be doing anything, as it sits there for now about 10 minutes, but certainly hope it’s doing something. I eventually killed the process and reboot, hoping for the best.  Thankfully, my machine came up and VS.NET fired up.

I uninstalled all my add-ons and rebooted, but still can’t install.  So I decided to try to the hot fix again, and after 5 mintues it works!  Now time to try MVC again, crossing my fingers…. it worked to!  Yay!  Time to put back my precious add-ons and voila, that’s all there is to it.  Nothing that can’t be accomplished in a morning.

More to come, but at least now I can get some real work going.

Posted in ASP.NET MVC | Tagged: , , | Comments Off on ASP.Net MVC Installation – Windows Installer Service Woes

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 »