Tag Archives: .NET

FluentValidation and Emails with White Space

Quite often, users will copy and paste an email address into an email text input. And that email address will contain trailing white space. If that gets past your client-side validation code, you need to trim it at the server. That’s usually not a problem. But, if you are using the email validator in FluentValidation, such an address will fail validation and the message sent back to the user will be a generic one that the email address is not valid. It won’t mention a trailing space. And for most users, it can take quite a bit of time to figure out that the email address has some trailing whitespace. If our help-desk is anything to go by, many users didn’t figure that out at all and so it was down to me to address this.

After a lengthy discussion with our domain experts, we decided that we did not want an email address to be considered invalid, just because of a trailing space. Technically it is invalid. But it is easy enough to trim it in the Services layer. But we must first get past server-side validation. So, my existing validator, which was returning an error message about an invalid email address looked something like this:

RuleFor(m => m.NewEmail)
	.EmailAddress()	
	.WithMessage(ValidationConstants.SymbolIsNotAValidEmailAddress, x => x.NewEmail)
	.WithName("NewEmail"); 

As I mentioned above, the EmailAddress() validator will fail the validation of an email address with a trailing space. Before I move onto the custom validator I ended up writing, I just want to quickly note something we tried, but which turned out to be a bad idea. First, I tried the following:

RuleFor(m => m.NewEmail.Trim())
	.EmailAddress()
	.When(m => m.NewEmail != null)
	.WithMessage(ValidationConstants.SymbolIsNotAValidEmailAddress, x => x.NewEmail)
	.WithName("NewEmail"); 

Trimming the email property (in the 1st line) immediately felt wrong. We also ran into a few problems with that approach, which are beyond the scope of this post. But most importantly, mutating the property in the RuleFor lambda is not the way FluentValidation is meant to be used.

The right approach, the way we saw it, was to write a custom validator which would basically validate the email in the same way as the normal EmailAddress validator does, except permitting trailing whitespace. Step 1 in this process was to grab the source of the EmailAddress validator, which can be found here. Step 2 was to create the new validator itself, based on the EmailValidator referred to in Step 1, which I creatively named NonTrimmedEmailValidator:

    public class NonTrimmedEmailValidator : PropertyValidator, IRegularExpressionValidator, IEmailValidator
    {
        private readonly Regex regex;

        const string expression = @"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-||_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+([a-z]+|\d|-|\.{0,1}|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])?([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$";

        public NonTrimmedEmailValidator()
            : base(new LanguageStringSource("NonTrimmedEmailValidator"))
        {
            regex = new Regex(expression, RegexOptions.IgnoreCase);
        }


        protected override bool IsValid(PropertyValidatorContext context)
        {
            if (context.PropertyValue == null) return true;

            // only interested in whether the trimmed string is a valid email address.
            var trimmedEmail = ((string)context.PropertyValue).Trim();

            if (!regex.IsMatch(trimmedEmail))
            {
                return false;
            }

            return true;
        }

        public string Expression
        {
            get { return expression; }
        }
    }
}

Step 3 was to create an extension method to make it usable like the other fluent validators:

public static class FluentValidationExtensions
{
    public static IRuleBuilderOptions<T, TProperty> NonTrimmedStringIsValidEmailAddressWhenTrimmed<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder)
    {
        return ruleBuilder.SetValidator(new NonTrimmedEmailValidator());
    }
}

Now, we can validate objects which have properties that are email addresses, where the email has a trailing space.

RuleFor(m => m.NewEmail)
	.NonTrimmedStringIsValidEmailAddressWhenTrimmed()
	.WithMessage(ValidationConstants.SymbolIsNotAValidEmailAddress, x => x.NewEmail)
	.WithName("NewEmail");

And, like I am doing anyway, trim the string in the services layer. Now, the user does not get a validation failure when they copy and paste an email address from somewhere that happens to grab a bit of white space on the end.

Viewing the GAC

The GAC is located in C:\WINDOWS\assembly (“the GAC Folder”) on standard installations, and a screenshot of that directory in Windows explorer looks like this:

The Global Assembly Cache

That “magical” view of the GAC Folder is pulled off by shfusion.dll (“the Viewer”), located in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\. As you can see from viewing the directory at the command prompt, the actual contents of the GAC Folder are somewhat different:

I recently had cause to seek out the actual dll for mscorlib, and the magical view of the GAC Folder was not of much use to me. After a bit of hunting around, I found a couple of ways of exposing the actual dlls in the GAC:

  1. you can uninstall/disable the Viewer. I consider this to be a really bad idea (even though you can re-install/enable it fairly easily). But I want to record it here (for future reference). Using “the run command” in the Start menu, run the following: regsvr32 -u C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\shfusion.dll  To re-install, run: regsvr32 C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\shfusion.dll
  2. the good old SUBST command. This old DOS command substitutes paths on physical and logical drives as virtual drives. To make the GAC Folder available by bypassing the Viewer, you can enter subst x: C:\Windows\assembly and you will find an “x” drive in your drives folder which exposes the GAC Folder’s contents, but not through the prism of the Viewer. To “unmount” that virtual drive, you can enter subst x: /D.
  3. you can alter the Registry (not for the faint-of-heart). To do this, bring up the regedit snap-in by entering regedit at the run command. Add a new DWORD under the key HKEY_LOCAL_MACHINE/Software/Microsoft/Fusion called DisableCacheViewer and set it value to 1. (By setting it to 0, the viewer will become enabled again).

For me, turing off the Viewer is only ever a temporary thing. I went with option 2, as I believe this to be the safest approach. I think there are a few other ways to bypass the view of the GAC which the Viewer presents, but you really start getting into some horribly wrong hacks, which I did not think had merit enough to mention here.

Delegates Explained – Part 4

The Delegates Series:

  1. Delegates Explained – Part 1
  2. Delegates Explained – Part 2
  3. Delegates Explained – Part 3
  4. Delegates Explained – Part 4 <<

In this last post in this series, I want to examine what the event keyword buys us in the subscriber model for handling events.

Consider our previous example. Recall that the notification delegate of the DvdStore class is public. Now, what would happen if we set the Notification delegate to a totally new delegate object? It would blow away the list of delegates which had previously been subscribed, is the short answer. Try it yourself and see.

        static void Main(string[] args)
        {
            DvdStore theStore = new DvdStore();

            theStore.notification += new NotifyDvdArrived(BroadcastArrivalOfDvdByBatSignal);
            theStore.notification += new NotifyDvdArrived(BroadcastArrivalOfDvdByLoudSpeaker);
            theStore.notification += new NotifyDvdArrived(BroadcastArrivalOfDvdBySnailMail);

            theStore.notification = delegate
                                        {
                                            Console.WriteLine("The Thing is not a good movie. " +
                                                              "Go home and take a good hard look at your life.");
                                        };

            theStore.SendOutNotification("The Thing");

            // end of app
            Footer();
        }

Line 9 is where the damage is done, publishing a sacriligious message which should be disregarded at all costs.
Now, add the event keyword on the custom delegate, keep that member public and try and set it to a new delegate object as we just did above:

            public event NotifyDvdArrived notification;

Notice how … we can’t. You will get a compile error with a message along the lines of The event ‘DelegatesExplained.Program.DvdStore.notification’ can only appear on the left hand side of += or -= (except when used from within the type ‘DelegatesExplained.Program.DvdStore’

So, with encapsulation back in tact, we now have a safe way to subscribe handlers to, and removing them from, “event” delegates. This enables the delegate to be public (which it needs to be for subscribers), but protects it from being changed/written over.

Not bad, for one little word.
Get the code:

Delegates Explained – Part 3

The Delegates Series:

  1. Delegates Explained – Part 1
  2. Delegates Explained – Part 2
  3. Delegates Explained – Part 3 <<
  4. Delegates Explained – Part 4

A quick detour (as in my last post I said I would talk about events in this post).

There was something I left out of the last post which should be covered before we move onto events.

Recall our subscription methods:

            public void SubscribeMeForNotifications(params NotifyDvdArrived[] notificationMethod)
            {
                if (notificationMethod != null)
                {
                    //  Create a new Delegate array for the overload of the Combine method which takes a Delegate array as a parameter.
                    Delegate[] listOfDelegates = new Delegate[notificationMethod.Length + 1];

                    //  Now, add the existing notification to the array, along with the ones passed in as a parameter (the params array).
                    if (this.notification != null)
                    {
                        listOfDelegates[0] = notification;
                        notificationMethod.CopyTo(listOfDelegates, 1);
                    }
                    else
                    {
                        notificationMethod.CopyTo(listOfDelegates, 0);
                    }

                    notification = NotifyDvdArrived.Combine(listOfDelegates) as NotifyDvdArrived;
                }
                else
                {
                    throw new ArgumentException("The notificationMethod argument was null. It must have a value for a subscription to be successful.");
                }
            }

and

            public void SubscribeMeForNotifications(NotifyDvdArrived notificationMethod)
            {
                notification = NotifyDvdArrived.Combine(notification, notificationMethod) as NotifyDvdArrived;
            }

The good news is, you don’t need to write those methods when using multicast delegates. I only wrote those methods to expose you to the Combine method of the Delegate. However, there is a succinct piece of C# syntax that results in the Combine method being called. It abstracts away the need to write those 2 subscription methods. It is +=:

            theStore.notification += new NotifyDvdArrived(BroadcastArrivalOfDvdByBatSignal);
            theStore.notification += new NotifyDvdArrived(BroadcastArrivalOfDvdByLoudSpeaker);
            theStore.notification += new NotifyDvdArrived(BroadcastArrivalOfDvdBySnailMail);

So, we can re-factor our DvdStore class:

        public class DvdStore
        {
            public NotifyDvdArrived notification;

            public DvdStore()
            {
                // default constructor
            }

            public void SendOutNotification(string titleOfDvd)
            {
                notification(titleOfDvd);
            }
        }

Note that in addition to removing the subscription methods, I also made the notification member public. In my next post in this series, I will refactor this even further (it’s probably not a good idea making the notification member public).

Delegates Explained – Part 1

I thought I would write a small series of articles on delegates for students. I can recall as a student, how I learnt many things from blog posts of enthusiastic developers.

The Delegates Series:

  1. Delegates Explained – Part 1 <<
  2. Delegates Explained – Part 2
  3. Delegates Explained – Part 3
  4. Delegates Explained – Part 4

I will firstly explain what delegates are. Then I shall go through various code examples to show the syntax for their use. The series will start off with the basics and evolve the concept of delegates in bite-size chucks.

What is a Delegate?

From a (very good) textbook*:

a delegate is a type-safe object that points to another method (or possibly a list of methods) in the application, which can be invoked at a later time. Specifically speaking, a delegate object maintains three important pieces of information:

  • The address of the method on which it makes calls
  • The arguments (if any) of this method
  • The return value (if any) of this method

What this gives us is a type-safe way to implement callbacks.

Tangent! What is a Callback?
I think of callbacks like this (using humans as an analogy): I say to you, “Here, take this phone number. Now go off and do a task and when you are done, ring this number.” Or if we are talking asynchronous, “Here, take this email address. Now go off and do a task and when you are done, send an email to that address.” The act of ringing that number, or sendng that email, is the callback.

Ok. We’re back.

An Example – The DVD Store Notification Subscription

I’ll go through a simple example in this post. There is a DVD store which we want to tell us when a new DVD arrives. So, we are going to subscribe for that. The DVD store says to the world at large, “If you provide us with a notification method that adheres to a certain specification, then we will notify you of new releases using that method.” In this case, the specification for that method is the delegate called NotifyDvdArrived.

        public delegate void NotifyDvdArrived(string title);

This requires the method to have a void return type and take a single string parameter. Lets take a look at the DVDStore class:

        public class DvdStore
        {
            private NotifyDvdArrived notification;

            public DvdStore()
            {
                // default constructor
            }

            public void SubscribeMeForNotifications(NotifyDvdArrived notificationMethod)
            {
                notification = new NotifyDvdArrived(notificationMethod);
            }

            public void SendOutNotification(string titleOfDvd)
            {
                notification.Invoke(titleOfDvd);
            }
        }

The SubscribeMeForNotifications method is the one by which we can tell the DVD Store that we want to receive notifications. It takes a NotifyDvdArrived delegate as a parameter which enables us to tell them how we want to receive that notification. As the name suggests, the SendOutNotification method is what the DVD store uses to broadcast its notifications. Any object that has subscribed to receive notifications will do so in the way in which it has specified to do so, when it subscribed for the notification (I will show how more than 1 object can subscribe in a future post).

The contents of the Main method are quite simple:

        static void Main(string[] args)
        {
            DvdStore theStore = new DvdStore();
            theStore.SubscribeMeForNotifications(new NotifyDvdArrived(BroadcastArrivalOfDvd));

            theStore.SendOutNotification("The Thing");             
            
            Footer();
        }

We (the Main method) go to a DVD Store, subscribe for notifications, and we do so supplying the BroadcastArrivalOfDvd method, which is:

        private static void BroadcastArrivalOfDvd(string titleOfDvd)
        {
            Console.WriteLine("The Dvd called {0} has arrived.", titleOfDvd);
        }

Looking back at the SendOutNotification method, it calls the Invoke method of the delegate object which calls (calls back) the BroadcastArrivalOfDvd method which we subscribed with, passing it the string parameter which is passed to SendOutNotification.

What’s the Benefit?

Delegates allow us to decouple, which is the first step to a scalable, maintainable architecture. This benefit will probably be lost on you students, until you enter the world of enterprise development. Translation – just trust me, it’s a good thing.

In my next Delegates post, I will take the example a little further to unlock a few more features that you need to know about delegates. The source code for this article can be
downloaded here:

*Andrew Troelsen’s Pro C# 2008 and the .NET 3.5 Platform at p.341