dotNetChris @ Marisic.Net

November 10, 2009

Great Blog on URL Rewriting with URLRewriter.net

Filed under: Uncategorized — dotnetchris @ 3:54 pm

It’s been a while since I posted anything and I came across this great post on Run Tings Proper, Advanced url rewriting for the rest of us – how to create a custom transform in UrlRewriter.net.

This is a great post that really sumarizes the most common needs in URL rewriting and how to handle it with URLRewriter.net (does anyone else find it ironic this website is php, of course I suppose it could be php in asp.net) while I didn’t try out what was on here yet or download the demo it definitely all looks right. At some point I wanted to implement an URL rewriting scheme in my applications and this post will be a great help when I actually start on that.

September 1, 2009

Using jQuery to create a scrolling sidebar

Filed under: Uncategorized — dotnetchris @ 1:45 pm

The easiest way to start this post is with an image explaining the concept.

layout

So now as you can see we have a basic site layout a 2 column with a fixed header and footer. For this example I’m dealing with a fixed header & footer for simplicity but you’ll see you can easily handle dynamic sizing also. The content column is a dynamic size column that can contain a large amount of text that if you scroll down past the fold of the page you will lose track of the sidebar. So the goal I was seeking was a way to have the sidebar follow the scroll bar in an aesthetically pleasing manner.

At first I attempted a fixed width layout but then ran into all of the browser compatibility issues so I turned to jQuery. The first thing we need to achieve is to make the sidebar track the scrollbar.

<script type="text/javascript">
$(window).scroll(function() {
    $('#sidebarPage1').animate(
        { top: $(window).scrollTop() + 'px' }
    );
});
</script>

This will achieve the tracking we desire however it is a very jerky and unpleasant effect so lets see what we can do to tune it up.

<script type="text/javascript">
$(window).scroll(function() {
    $('#sidebarPage1').animate(
        { top: $(window).scrollTop() + 'px' },
        { queue: false, duration: 500, easing: 'easeInOutSine' }
    );
});
</script>

This will produce a much nicer effect. The queue parameter we included is to allow jQuery to create a series of events that happen in a certain order to create animation. We don’t want our animation waiting for anything so we set queue: false to make it run immediately. The duration parameter is how long in milliseconds the animation to take, so setting 500 is one half of a second. This lowers the amount of jumping the sidebar does significantly. Lastly the easing parameter allows us to setup an easing algorithmthat influences how the animation handles the start and ends of the effects. If you look at the easing plugin’s site you can play around with the different options that are built into jQuery natively. I chose the easeInOutSine as it seemed to produce a very nice animation where it spends more of the animation time at the start and end where jerkiness can be more easily noticed, but this was just a personal preference.

Now the real fun, polishing this and fixing the “quirks” this code creates. If you make your browser view port very small you can actually scroll the sidebar off the entire screen because of the footer taking up space at the bottom and the sidebar is already offset from the top because it’s below the header. The first is to get it to stop scrolling off the page. This will involve doing some math to calculate limits on the scrolling.

<script type="text/javascript">
    $(window).scroll(function() {
        var dynamicSidebarHeight = $('.sidebar').height();

        if ($(window).height() > dynamicSidebarHeight) {
            var fixedFooterOffset = 150;
            var scrollTo = $(window).scrollTop()
            var calculatedMaxTop = $('#footer').offset().top - dynamicSidebarHeight - fixedFooterOffset;
            var fixedHeaderOffset = 150;

            if (scrollTo > calculatedMaxTop) {
                scrollTo = calculatedMaxTop;
            }

            $('#sidebarPage1')
            .animate(
                { top: scrollTo + 'px' },
                { queue: false, duration: 500, easing: 'easeInOutSine' }
            );
        }
    });
</script>

To explain what each of these variables mean:

  • dynamicSidebarHeight – this is the jQuery calculated height at run time of the sidebar
  • fixedFooterOffset and fixedHeaderOffset – are the height in pixels of the static headers and footers, which for this example are said to be 150px.
  • calculatedMaxTop – This is the equation to know the farthest down the sidebar’s top can be set to that it won’t crash into the footer.

The first check is make sure the browser viewport is atleast as big as the sidebar. If it’s smaller than the sidebar scrolling is pointless because you will never be able to see the bottom of the sidebar because when you’d scroll down to see the rest of the sidebar it will move off screen. After that we calculate the Max value for the Top of the sidebar which is the based off the location of the top of the footer which is what calling .offset().top returns, let’s say 2000px for this example. We’ll assume the sidebar height is 500px and we have our fixed footer height of 150px.

So top of footer is at 2000px we subtract the height of the bar 500px and the height of the footer 150px so in this example the furthest you could set the top of the sidebar would be 1350px since if the top of the sidebar is 1350px, the next 500px is the sidebar and the next 150px is the footer. So we want to check if scrollTo is > than this value and if it is we want it to set it to the maximum length we would allow.

The final part is to handle once we scroll past the page fold the sidebar is now 150px offset from the top of the window due to the header being at the top that has scrolled up off the screen so it would look alot better if the bar stays stuck at the top edge. This is the reason I have the unused fixedHeaderOffset so far which accounts for the height of the header. The final code we will have is this

<script type="text/javascript">
    $(window).scroll(function() {
        var dynamicSidebarHeight = $('#sidebar').height();

        if ($(window).height() > dynamicSidebarHeight) {
            var fixedFooterOffset = 150;
            var scrollTo = $(window).scrollTop()
            var calculatedMaxTop = $('#footer').offset().top - dynamicSidebarHeight - fixedFooterOffset;
            var fixedHeaderOffset = 150;

            if (scrollTo > calculatedMaxTop) {
                scrollTo = calculatedMaxTop;
            }
            else if (scrollTo < fixedHeaderOffset) {
                scrollTo = 0;
            }
            else
            {
                scrollTo -= fixedHeaderOffset - 18; //18 is for a top margin
            }

            $('#sidebarPage1')
            .animate(
                { top: scrollTo + 'px' },
                { queue: false, duration: 500, easing: 'easeInOutSine' }
            );
        }
    });
</script>

So far we’ve asserted that the viewport is larger than the sidebar, we now cannot scroll the sidebar under the footer or off the page. To make handle the calculation of where to have it in relation to the top of the page we add

else if (scrollTo < fixedHeaderOffset) {
    scrollTo = 0;
}
else
{
    scrollTo -= fixedHeaderOffset - 18; //18 is for a top margin
}

To our if statement. The first case is we’ve scrolled back up to the top of the page and want the sidebar to sit under the header so scrollTo is < the height of the header. At this point we set scrollTo to 0 (I have a position: relative wrapper around my content and sidebar columns) if you don't have a position: relative tag around the sidebar you would set this to the fixedHeaderOffset and probably some margin say 18px.

Now we have the case where we're scrolling the bar down and we want it to be at the top of the viewport this is the else case. So the condition for this is scrollTo is shorter than the maximum allowed value AND scrollTo is further down than the header. Since the position of scrollTo includes the height of the header we need to subtract that off of the value of scrollTo and then subtract a little more so the sidebar sits 18px below the top of the page. If you don't have the position: relative container around the sidebar this would most likely just be the offset from the top of the page so scrollTo – 18px.

Unfortunately I don't have a demo for this but this should be very easy to test. I'll throw up a zip file with the html in it to let you test it out.

August 4, 2009

More Team Foundation Server Voodoo

Filed under: Team Foundation Server — Tags: , , — dotnetchris @ 8:28 pm

After finally getting TFS installed I went to create my first project under it and was greeted with a new lovely error message:

TF30004: The New Team Project Wizard encountered an unexpected error while initializing the Microsoft.ProjectCreationWizard.Reporting plug-in.

Explanation
TF30171: The Microsoft.ProjectCreationWizard.Reporting plug-in used to create the new team project could not be initialized and returned the following error: TF30224: Failed to retrieve projects from the report server. Please check that the SQL Server Reporting Services Web and Windows services are running and you have sufficient privileges for creating a project..

After alot of googling and reading the primary solution came down to reinstall Visual Studio 2008 SP1 again which I put off figuring there had to be a less voodoo solution to this but eventually broke down and tried it. Surprisingly that fixed THIS problem and then immediately I was confronted with ANOTHER problem.

Trying to view the created project on Windows Sharepoint the first thing that shows up is:

An error has occurred during report processing. (rsProcessingAborted)
Cannot create a connection to data source ‘TfsOlapReportDS’. (rsErrorOpeningConnection)
For more information about this error navigate to the report server on the local server machine, or enable remote errors

More google hoop jumping which buried deep down in this post on How do I fix the TfsOlapReportDS user problem? I saw a comment from MattPil29

I had the same problem which was not solved by the “Allow log on locally” fix until I removed the same account from “Deny log on locally” !!!!

So I fixed that with:

NTRIGHTS -u TFSSERVICE -r SeDenyInteractiveLogonRight

Finally I have a successfully created Team Foundation Server project!

August 3, 2009

Flash CS4 Publish to Gif file sucks

Filed under: Uncategorized — dotnetchris @ 8:19 pm

So today I had to convert a swf flash movie I made for an advertisement to an animated gif file so it could be added to an email newsletter and when I’d publish it using Flash CS4 it was just epic… fail. The fading/transparency effects would flicker massively, shift between colors that didn’t even exist in the movie then when text would appear it just turned into a giant blob of black smear in my image.

How very useful…. NOT.

Luckily I found a program that just saved my day E.M. Magic Swf2Gif I also tried a similar product from Aleosoft, Aleo SWF GIF Converter. I’m not sure if this was related to the fact the Aleosoft is a limited functionality trial (watermarks output images) but the resulting quality was substantially lower than E.M. Magic Swf2Gif. So if anyone else has issues with their Flash CS4 Gif publishing looking horrible I recommend taking a look at E.M. Magic Swf2Gif.

July 17, 2009

Team Foundation Dual Server Installation Headaches

Filed under: Uncategorized — Tags: , , , — dotnetchris @ 4:18 pm

Finally I was able to complete the installation of Team Foundation Server (TFS) successfully. I definitely ran into some major headaches along the way.

Firstly, you cannot install TFS on a Domain Controller (DC). This might be a semi-acknowledged limitation but I had no idea of this prior to my first attempt at installation. Working at a small business we only have 2 servers, 1 being the DC. I’m lucky that I was able to have the other server to install it on in the first place and didn’t have to use my local machine.

Since Sql Server was installed on the DC as it’s the more powerful server this requires me to do a dual server setup (Sql Server on one machine and TFS application tier on another.) This isn’t even possible to do using the DVD image or media setup on it’s own. You will need to modify files on the install disk, more on that later.

Another fact I was unaware of is TFS cannot be installed with Sql Server 2008 out of box. The installation needs to have TFS Sp1 slip streamed into the the setup files. I find it rather daunting that I needed to research these options so far in depth to just complete an installation.

First extra steps that need to be done to configure your Sql Server 2008 machine to support TFS.

Change the Sql Server Reporting Services (SSRS) service from using the local system account to a domain account. This account must be configured with the privileges to log on locally, I named the account TFSREPORTS. After creating this account in the active directory you need to configure the rights on it. The easiest way is with the command prompt (start < run < “cmd” ) while still on the server.

NTRIGHTS -u TFSREPORTS +r SeInteractiveLogonRight

While your creating account information you should also create a domain account for TFS to use for it’s service interaction, this requires the Log On as a Service right. I named mined TFSSERVICE. To assign that logon right with NTRIGHTS.

NTRIGHTS -u TFSSERVICE +r SeServiceLogonRight

Now that you have these accounts created you need to either install Sql Server and Reporting Services and when you get to the SSRS configuration the install to designate the TFSREPORTS account to be the account to use. If you already have installed Sql Server + SSRS contrary to the install instructions with TFS you can not just change the account Sql Server Reporting Services using in the services.msc you actually need to use the “Reporting Services Configuration Manager.” By default there is a start menu entry for it under Start < Programs < Microsoft SQL Server 2008 \ Configuration Tools. Open the tool and connect to the server (most likely localhost, unless you’re doing it remotely) under the Service Account tree menu item check Use Another Account supply the account you created in DOMAIN\AccountName form along with the password you created for the account.

Following these steps either updating or your current install or installing new, now it’s time to update Sql Server 2008 to SP1 if it hasn’t already been done so before continuing on to the TFS installation.

At this point you need to dump the files from the TFS dvd image or media onto your hard drive. You will need to slipstream the TFS Sp1 release into your copy of regular TFS. This is included in the TFS documentation or you can view it online How to: Integrate the Installation of Team Foundation Server and Service Pack 1 on devCatharis.

Now you need to modify InstallMedia\AT\msiproperty.ini you need to configure the VSTF_RS_SERVER, VSTF_RS_REPORTS_URI, VSTF_RS_REPORTSERVER_URI. For detail information for setting these values you can view Reporting Services Flexibility (Orcas RTM Only) by Microsoft MVP Sudhir Hasbe.

Now after all of these steps, you SHOULD be ready to install TFS as a dual server installation with Sql Server 2008 on a separate machine and have it complete successfully!

Does anyone else find this basically unacceptable to have to go through this long of a process to just INSTALL your copy of TFS? It sure ruined a few of my days.

BloggingContext.ApplicationInstance.CompleteRequest();

June 25, 2009

It’s been a while!

Filed under: Off Topic — dotnetchris @ 2:10 pm

It’s definitely been a while since I updated my blog with a new post that’s going to change starting again today. While this one really won’t have any new content I just felt like adding some personal thoughts. After my last blog post my software development contract ended unexpectedly which left me with alot of free time other than searching for a new contract to work on. My first thoughts were great, a vacation! Which I used to enjoy a few weeks of my time without having to do anything specific which I haven’t had in my life since probably high school during the summer.  After stepping back for a few weeks I did some casual development on StructuredWeb at home for a little while then started slacking on that. It really is hard to stay focused on the technology world when you’re not exposed to it every day at work especially since software development (especially when done well) isn’t easy and takes alot of will and drive to accomplish, well that ends today.

This Monday I started a new position at a small Insurance company / marketing firm to be their lead architect to drive their technology usage and provide them strategic applications far above their previous piecemeal approach with using some outside contracts for their website. I’m really looking forward to this because finally I don’t have to answer or justify using new technology or different technology (to an extent atleast) for solving software problems. Nothing has ever bothered me more in previous jobs at larger companies where most developers just choose mediocrity at best, or to be abysmal at worst and just don’t care to learn anything new as developers and to just apply bad practices to problems because that’s what they’re familiar with.

February 16, 2009

Creating a generic Model-View-Presenter framework

With all of the current talk about ASP.NET MVC it seem dated to bring up the model view presenter architecture but I still believe it’s a very strong pattern in separating UI logic from application design. This post is meant to offer a successor to the Web Client Software Factory (WCSF) framework provided by Microsoft. In last usage of WCSF I encountered numerous errors stemming from ObjectBuilder during the dependency injection of WCSF which is what lead me down the road of creating UnityWeb which has evolved into StructuredWeb. The rest of this post will include no specific dependencies except 1 to StructureMap to handle the actual resolution of objects through dependency injection. This could be very easily replaced by Unity or any other inversion of control framework that supports the BuildUp() method. For a framework that does not support a BuildUp operation it will make things more complicated and that will need to be solved by your case basis.

Firstly, what is the model-view-presenter (MVP) pattern? The View is defined as an interface that the Presenter will use for getting and setting data to and from the Model. The View implementation will instantiate the Presenter object and provide a reference to itself (the formal constructor parameter is the View interface while the actual parameter is a concrete View class). When the event methods of the View are triggered, they will do nothing but invoke a method of the Presenter which has no parameters and no return value. The Presenter will then get data from the View, through the View interface variable that the Presenter stored when the constructor was called. The Presenter then invokes methods of the Model, and sets data from the Model into the View through the View interface.

From a layering point of view, the Presenter class might be considered as belonging to the application layer in a multilayered architectured object-oriented system with common layers but it can also be seen as a Presenter layer of its own between the Application layer and the User Interface layer.

Now if you’re at all like me you will have almost no more of an idea what the MVP pattern is supposed to do after that explanation. To generalize on that statement it’s basically taking the interaction of the UI and the application logic which usually is coupled together and separating it into 3 areas.

The model – this is the application logic which will be housed in controller classes.

The view – which is an interface which abstracts the UI away, all data sent and retrieved from the UI is done through this interface

The presenter – this is a mediator that negotiates how the UI and application logic interact. The view is also a composition of this class.

Starting with the view:

public interface IView
{
}

This is the most basic of the basic of interfaces, for my needs it’s purely a marker interface. If every single one of your pages shares a common property perhaps an event message collection this would be a good place to define a property for it.

The presenter class:

public abstract class Presenter<TView> where TView : IView
{
    public TView View { get; set; }

    public virtual void OnViewInitialized()
    {
    }

    public virtual void OnViewLoaded()
    {
    }
}

The OnViewInitialized method is to represent any operations you would execute in Page_Load if(Page.IsPostback == false) so only on the initial page load. The OnViewLoaded method represents all page loads whether or not they are post backs. Currently I have no global page operations since I have no global view properties. This class is also constrainted that

Next creating a view:

public interface IEmployeeView: IView
{
    IList<Employee> Employees { get; set; }
    IList<Employee> EmployeesListDatasource { set; }
}

As you can see my view will have 2 properties one for getting or setting a collection and another for setting only the same type. The view also implements the marker interface IView.

Creating the presenter:

public class EmployeePresenter : Presenter<IEmployeeView>
{
    private readonly IEmployeeController _controller;

    public EmployeePresenter(IEmployeeController controller)
    {
        _controller = controller;
    }

    public override void OnViewInitialized()
    {
        View.Employees = _controller.GetEmployees();
    }

    public override void OnViewLoaded()
    {
        View.EmployeesListDatasource = View.Employees;
    }
}

I’m not going to go into the details of the IEmployeeController this is the “model” where actual application code is ran there is nothing special about this class or it’s interface and only contains logic specific to getting my set of employees. As you can see the EmployeePresenter implements Presenter. I overrided both of the methods provided by the Presenter base where the Initialize method gets list from the model and the loaded method binds the list to a datasource.

Now before I move onto implementing the IEmployeeView inside a page I’m going to create an abstract base page that will handle the dependency injection build up for my MVP framework.

public abstract class ViewBasePage<TPresenter, TView> : Page
    where TPresenter : Presenter<TView>
    where TView : IView
{
    protected TPresenter _presenter;

    public TPresenter Presenter
    {
        set
        {
            _presenter = value;
            _presenter.View = GetView();
        }
    }

    /// <summary>
    /// Gets the view. This will get the page during the ASP.NET
    /// life cycle where the physical page inherits the view
    /// </summary>
    /// <returns></returns>
    private static TView GetView()
    {
        return (TView) HttpContext.Current.Handler;
    }

    protected override void OnPreInit(EventArgs e)
    {
        ObjectFactory.BuildUp(this);
        base.OnPreInit(e);
    }
}

This class might look quite a bit strange, the majority of it is from the class definition it’s setup to only allow you to inherit it in a valid way such as: ViewBasePage<EmployeePresenter,IEmployeeView>. On the Presenter set method this is where the page actually becomes part of the composition of the Presenter (the description from Wikipedia said this).

The GetView method also probably looks strange what this is doing is getting the physical page that’s being instantiated by ASP.NET. The reason I’m doing this is it makes it easier to reference the page generically otherwise I would be required to do something smilar to

return (TView) (object) this

Which is borderline wrong since THIS technically refers to the ViewBasePage which does not implement the interface that TView consists of but at runtime eventually resolves correctly since a Page will implement the interface that makes up TView and not cause a runtime error.

This class overrides Page’s OnPreInit method to call ObjectFactory.BuildUp() which will cause all the dependency resolution to take place. In my specific usage of StructureMap I have it identify all Presenter properties as targets for dependency injection, in your case you may be required to use the [Setter] attribute from SturctureMap or the [Dependency] attribute from Unity or some other similar convention in other inversion of control frameworks.

Now finally onto the actual page.

public partial class _Default :
    ViewBasePage<EmployeePresenter, IEmployeeView>, IEmployeeView
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            _presenter.OnViewInitialized();
        }

        _presenter.OnViewLoaded();
        Page.DataBind();
    }

    #region Implementation of IEmployeeView

    IList<Employee> IEmployeeView.Employees
    {
        get { return ViewState["IEmployeeView.Employees"] as IList<Employee>; }
        set { ViewState["IEmployeeView.Employees"] = value; }
    }

    IList<Employee> IEmployeeView.EmployeesListDatasource
    {
        set { lstEmployees.DataSource = value; }
    }

    #endregion
}

This class inherits the ViewBasePage class and implements the IEmployeeView. The _presenter field is in the ViewBasePage and contains the fully resolved dependency to EmployeePresenter. As I stated in the portion of the presenter code you can see where OnViewInitialized() and OnViewLoaded() are called inside the page life cycle.

Implementing the IEmployeeView you have the properties target actual controls on the page or the ViewState / QueryString etc that is available to the page. Now if you remember the code in my actual EmployeePresenter it should make sense why in ViewInitialized the Employees property is set by the controller and on the ViewLoaded the Employees property is assigned to the EmployeesListDatasource since it’s just refreshing the data source to the view state collection on subsequent page post backs.

kick it on DotNetKicks.com

Shout it

BloggingContext.ApplicationInstance.CompleteRequest();

February 11, 2009

Creating a generic validation framework

Filed under: Architecture, Programming, StructuredWeb — dotnetchris @ 10:25 pm

Recently in a few discussions of system architecture I have brought up adamant complaints about coupling validation logic to your domain objects. This weekend Thomas Mayfield contacted me on how I would go about implementing this in a domain driven designed system. Initially I got sidetracked over what tool I would use for my rules engine and I’ve still not concluded which would be best so I went about creating my Validation layer and decided to leave the specific details of creating validation logic for later.

As always I start with an interface. In this case it ends up being a very simple interface.

public interface IValidator<T>
{
    ValidationResult Validate(T obj);
    ValidationResult Validate(T obj, bool suppressWarnings);
}

Basically I want this service to take in an object and validate it, and then return to me whether it’s valid and any warnings or error messages associated with the validation. Which lead me to creating a ValidationResult class (in lieu of the similarly named class in the Enterprise Library validation block).

First I created a very simple ValidationMessage class:

public sealed class ValidationMessage
{
    public string Message { get; internal set; }
    public bool Warning { get; internal set; }

    //Only allow creation internally or by ValidationResult class.
    internal ValidationMessage()
    {
    }
}

The ValidationResult class is a little more complex:

public sealed class ValidationResult
{
    private bool _dirty = true;
    private bool _valid;

    public bool Valid
    {
        get
        {
            //theoretically O(n) time but in pratice will be constant time
            //Still, no need for multiple traversals, Traverse only if it's changed
            if (_dirty)
            {
                _valid = Messages.FirstOrDefault(msg => msg.Warning == false) == null;
                _dirty = false;
            }

            return _valid;
        }
    }

    public ValidationResult()
    {
        Messages = new List<ValidationMessage>();
    }

    public IList<ValidationMessage> Messages { get; internal set; }

    /// <summary>
    /// Adds the error. 
    /// </summary>
    /// <param name="errorMessage">The error message.</param>
    public void AddError(string errorMessage)
    {
        _dirty = true;
        Messages.Add(new ValidationMessage {Message = errorMessage});
    }

    /// <summary>
    /// Adds the warning. 
    /// </summary>
    /// <param name="warningMessage">The warning message.</param>
    public void AddWarning(string warningMessage)
    {
        //No need to mark collection dirty since warnings never generate validation changes
        Messages.Add(new ValidationMessage {Message = warningMessage, Warning = true});
    }
}

Basically the only tricks to this class is that I only allow the creation of the internal list of ValidationMessages to be handled by the same assembly. I also appended factory methods to allow manual insertion of errors or warnings. The reason for this is in my workings with EntLib VAB was that the results were inflexible in letting me append some messages myself and then roll the results down to the screen. This resulted in me having to create marshaling classes to just transfer the messages from the results to a collection that I could add more information to.

Implementing a concrete validator, the EmployeeValidator:

public class EmployeeValidator : IValidator<Employee>
{
    #region Implementation of IValidation<Employee>

    public ValidationResult Validate(Employee employee)
    {
        return Validate(employee, false);
    }

    public ValidationResult Validate(Employee employee, bool suppressWarnings)
    {
        var result = new ValidationResult();

        //This code here would be replaced with a validation rules engine later

        if (employee != null)
        {
            if (!suppressWarnings && employee.HireDate > DateTime.Now)
                result.Messages.Add(new ValidationMessage {
                    Message = string.Format("Employee hire date: {0} is set in the future.", employee.HireDate),
                    Warning = true});

            if (employee.Person != null)
            {
                if (string.IsNullOrEmpty(employee.Person.FirstName))
                    result.Messages.Add(new ValidationMessage {Message = "Employee FirstName is required."});
                if (string.IsNullOrEmpty(employee.Person.LastName))
                    result.Messages.Add(new ValidationMessage {Message = "Employee LastName is required."});
            }
            else
                result.Messages.Add(new ValidationMessage {Message = "Employee person data is missing."});
        }
        else
            result.Messages.Add(new ValidationMessage {Message = "Employee data is missing."});

        return result;
    }

    #endregion
}

Nothing really complicated goes on here just simple very basic validation code that rolls in error messages if needed. This area here would be replaced by a ruleset engine later on, for myself atleast. Otherwise you could do any validation you wanted here.

Now to actually validate your objects I created a ValidationFactory method also simliar to the VAB.

public static class ValidationFactory
{
    public static ValidationResult Validate<T>(T obj)
    {
        try
        {
            var validator = ObjectFactory.GetInstance<IValidator<T>>();
            return validator.Validate(obj);
        }
        catch (Exception ex)
        {
            var messages = new List<ValidationMessage> {new ValidationMessage {
                Message = string.Format("Error validating {0}", obj)}};

            messages.AddRange(FlattenError(ex));

            var result = new ValidationResult {Messages = messages};
            return result;
        }
    }

    private static IEnumerable<ValidationMessage> FlattenError(Exception exception)
    {
        var messages = new List<ValidationMessage>();
        var currentException = exception;

        do
        {
            messages.Add(new ValidationMessage {Message = exception.Message});
            currentException = currentException.InnerException;
        } while (currentException != null);

        return messages;
    }
}

Once again beauty comes with simplicity I take advantage of StructureMap to handle my dependency injection with the GetInstance method. Then just call Validate. I added a helper method that will allow me to roll out a complex exception message (most likely it’d only ever be you forgot to register a validator for some type) if any occur.

Registering this for StructureMap is extremely simple inside you registry setup for SM you would just add

ForRequestedType<IValidator<Employee>>().TheDefaultIsConcreteType<EmployeeValidator>();

And then onto a quick usage example

[Test]
public void InvalidEmployeeTest()
{
    var employee = new Employee {Person = new Person {FirstName = string.Empty, LastName = string.Empty}};

    var results = ValidationFactory.Validate(employee);

    Assert.IsNotNull(results);
    Assert.IsFalse(results.Valid);
    Assert.IsTrue(results.Messages.Count > 0);
}

At this point you have en entirely decoupled validation framework that will allow you to validate your objects with any kit, ruleset engine, or static validation you wish. Now if you wondered where I would put this in my architecture I would have it validate at the presenter level right after the screen scrape of data.

public bool SaveEmployee()
{
    var employee = View.Employee;

    var results = ValidationFactory.Validate(employee);

    if (results.Valid)
        _controller.SaveEmployee(employee);
    else
        View.Errors = results.Messages;
}

kick it on DotNetKicks.com

Shout it

BloggingContext.ApplicationInstance.CompleteRequest();

February 3, 2009

20,000 views!

Filed under: Off Topic — Tags: — dotnetchris @ 1:49 pm

Wow, I honestly feel pride. A year ago when I started my blog I never imagined this is where it would be at today. At first I started it to share the information I learned about the problems I faced with Oracle since I spent over 3 days trying to accomplish a simple task of writing an xml string to oracle over 2,000 characters! When I initially wrote that post, my blog had the only conclusive answer that I could find as I had to spend lots of time searching both java and microsoft forums related to oracle to get any information.

Since then I’ve watched my blog grow from a handful of visitors and a few comments to 20,000 views and over 100 comments. I want to thank everyone of you that’s taken the time to read any of rantings or design ideas and I especially want to thank every person that has taken the time to offer input on anything I’ve wrote. See you all again at 50,000!

BloggingContext.ApplicationInstance.CompleteRequest();

StructuredWeb Alpha 1

After my long road down the rabbit hole of object orientated design, inversion of control, NHibernate, Fluent NHibernate I’ve finally reached a point where I feel my codebase is stable enough to almost warrant my beta 1 release. I switched from Unity as my DI container to StructureMap and definitely feel this was a good call especially the timing of the 2.5.3 release of StructureMap where it natively includes the BuildUp method and natively includes the functionality I had to add with custom lifetime managers for wrapping my objects into the HttpContext and HtttpSession.

Just recently I published my implementation of Business Conversation per Transaction session management along with my repository pattern I followed for StructuredWeb. I still haven’t gotten my second level caching for NHibernate running yet but that will on slate for Beta 2.

See my StructuredWeb Installation page for details for setting it up.

This still needs a little bit of work for me to qualify it as a beta but since I checked everything into Assembla I figured I’d announce it’s alpha release since the code is already available online.

BloggingContext.ApplicationInstance.CompleteRequest();

Older Posts »

Blog at WordPress.com.