Phone Number Validation

By eSamurai

At some point in time every web developer will need to validate the form fields email and phone number. The better methods for validating both of these fields require the use of a regular expression, and most of the web developers I know will do a quick Google search to find a regular expression and move on. This method will work for the most part — especially for email. When it comes to regular expression and validating, I rarely do a Google search but just write one myself. If you do do a Google search most of the regular expressions are going to simply match the (XXX) XXX-XXXX pattern. Some may require that exact pattern, others may be more flexible allowing different delimiters, optional parenthesis/delimiters, and so on. I haven’t seen any that actually go beyond that. I wonder if anyone else has really considered that possibility that one could go beyond that. So when I needed to validate phone numbers I didn’t search Google for the regular expression, instead I searched for information about telephone numbering plans. I found a lot of information, but since the websites I deal with cater mostly to North America I limited my research to just the North American Numbering Plan (NANP). What I eventually ended up with, was a phone number class that not only checks if the numbers fit the simple pattern above, but if the numbers themselves were legal entries based on the standards set forth in the NANP. As stated in the Wikipedia article above:

Current NANP number format can be summed up via the following:
+1-NPA-NXX-xxxx

If you’re curious as to what that means, I suggest reading the Wikipedia article. The algorithm I came up with is:

  1. Parse number into area code and the phone number.
    Regular Expression: ^\(?(\d{3})\)?[\s.-]*([0-9]{3}[. -]?[0-9]{4})$
  2. Validate the area code.
    Regular Expression: ^\(?[2-9][0-8][0-9]\)?$
  3. Validate the phone number.
    Regular Expression: ^[2-9](1(?!1)|[02-9])[0-9](?(?< =555)[. -]?(?!01)[0-9]{4}|[. -]?[0-9]{4})$

I created an IPhoneNumber interface and then created a NorthAmericanPhoneNumber class that implements IPhoneNumber. That way, if I ever need to support other phone numbering plans, I can easily add in the functionality. The interface is very simple:


    public interface IPhoneNumber
    {
        string CountryCode { get; set; }

        [Required]
        string AreaCode { get; set; }

        [Required]
        string Number { get; set; }
    }

The implementation of the North American phone number, isn’t that difficult either:


    public class NorthAmericanPhoneNumber : IPhoneNumber
    {
        public static bool IsValid(string number)
        {
            try
            {
                Parse(number);
                return true;
            }
            catch
            {
                return false;
            }

        }

        public static IPhoneNumber Parse(string number)
        {
            var phoneNumber = new NorthAmericanPhoneNumber();

            var parts = Regex.Matches(number, @"^\(?(\d{3})\)?[\s.-]*([0-9]{3}[. -]?[0-9]{4})$");

            if (parts.Count > 0)
            {
                phoneNumber.AreaCode = parts[0].Groups[1].Value;
                phoneNumber.Number = parts[0].Groups[2].Value;
            }

            return phoneNumber;
        }

        private string areaCode;

        private string number;

        public string CountryCode
        {
            get { return "+1"; }
            set { }
        }

        public string AreaCode
        {
            get { return areaCode; }
            set
            {
                Regex npa = new Regex(@"^\(?[2-9][0-8][0-9]\)?$");
                if (npa.IsMatch(value))
                    areaCode = value;
                else
                    throw new ArgumentException(String.Format("{0} is not a valid North American Area Code.", value));
            }
        }

        public string Number
        {
            get { return number; }
            set
            {
                Regex valid = new Regex(@"^[2-9](1(?!1)|[02-9])[0-9](?(?< =555)[. -]?(?!01)[0-9]{4}|[. -]?[0-9]{4})$");
                if (valid.IsMatch(value))
                    number = value;
                else
                    throw new ArgumentException(String.Format("{0} is not a valid North American phone number.", value));
            }
        }

        public override string ToString()
        {
            if (areaCode != null &amp;&amp; number != null)
            {
                var exchange = number.Substring(0, 3);
                var local = number.Substring(number.Length - 4);
                return String.Format("({0}) {1}-{2}", areaCode, exchange, local);
            }

            return String.Empty;
        }
    }

The IsValid function is static, and can be used anywhere to validate phone numbers. Notice that it’s validation is done by trying to assign the supplied number to the area code and phone number properties. If the number supplied is invalid, an exception will be thrown during assignment which is caught causing false to be returned by the function. I also overrided the ToString() function so that it will output the phone number in the normal format.

If anyone finds this helpful, I’d love to hear about it. I ask that if anyone goes on to implement any other regional phone numbers to please share the link to it.

Creative Commons License
NorthAmericanPhoneNumber by
Brian Cupples is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

Programmatically Setting FontFamily to an Embedded Font in WPF

By eSamurai

If you do a Google search you’ll find many articles on how to programmatically set the FontFamily on a WPF control to an embedded font. All the ones I read said the same thing as outlined on MSDN:


myControl.FontFamily = new FontFamily(new Uri("pack://application:,,,/"), "./resources/#Spiffy Font");

This is rather simple, you just need to define the base URI and then reference the font as you would in the XAML — well with the addition of “./”. Trying this resulted in an error message stating the the Uri wasn’t correct. After trying a few other things I finally thought, “Hey, let me run it through the debugger and see what the URI settings are for a control that has the font set in the XAML.” This revealed that the URI also contained the namespace, and a reference to the component. I copied the URI exactly from the other control, and voilà it worked! A couple more trials to see exactly what was required, and I have:


myControl.FontFamily = new FontFamily(new Uri("pack://application,,,/My.Namespace"), "resources/#Spiffy Font");

Notice that I didn’t need the component in the Uri or the “./” in the font family. Including the namespace might be obvious to a more seasoned WPF developer, but I’m still new to needing to include the URI. So remember kiddies, when specifying a URI in WPF include the namespace.

Mobile Skype

By eSamurai

I’ve used Skype a couple times to video chat with some friends, and to conference call with other friends, but I think the number of times I’ve done that is less than the number of times John Rhys-Davies name shows up when you search Google for “hot dwarves”. So when Skype showed up on my Blackberry, I didn’t think too much about it.

Skype recently was released for Android (and maybe some other phone platforms), so it’s being talked about on the tech shows right now. What I’m wondering is, if you have Skype on your phone, why do you even need phone service? If I were one of the big phone carriers like Verizon or AT&T, I would be investigating the possibility of phasing out the phone aspect, and dedicating all of my cellular bandwidth to data. I would integrate Skype into the phone so that when people make a call, it goes through Skype. This would mean that your customers can use their phone anywhere they can get a data connection. Which means my cell phone would work in my office (provided I can actually connect to the wireless network, which is always a 50-50 shot).

Blackboard Learn Web Services, Part 1

By eSamurai

I’ve previously posted about setting out to learn about the new web services exposed in Blackboard Learn 9.1. I found one blogger out there who did a bit of a write up about them, and no, I haven’t read through all the posts yet, but felt like I wanted to get started with the project anyway. So, first things first, I started by downloading the first application that he posted as an example of how to register a “proxy tool” with the Blackboard system. Seeing how the web services were handled by Axis 2, there really wasn’t much to see. Next step was to check out the documentation he provided in a documentation folder.

I knew that .Net and Visual Studio supports web services, so I didn’t think setting these up would be hard. In the admin section of our Blackboard Learn install, I enabled the Context, Course, CourseMembership, User, and Util web services, set them to require SSL, and set them to be discoverable. I switched to Visual Studio and added a Service Reference, and ack! Getting the services to load was really troublesome! I could load the URLs in a browser, but when Visual Studio tried to load the wsdl it would receive a 404 error. LONG story short, it looks like another instance of needing to restart the Blackboard services. After I restarted them, the problems with loading the wsdls disappeared.

So here we go, another bit of information thrown out there about Blackboard Learn Web Services: you may need to restart the Blackboard services to get them to work.

WPF KeyUp vs. KeyDown

By eSamurai

I’m working on a WPF application, and I want to be able to lock the application. So I created a new window, set it to open on a lock command, and then on any key pressed it displays the login screen where the previous user or an admin user can log in to unlock the application. I got everything set up, and started debugging the problems with the system, leaving the least important problem for last. The least important problem is: if using the keyboard to lock the application, or using the keyboard to dismiss the login window, the login window instantly appears.

After much Googling about why the event keeps bubbling to the “lock window”, I finally come across this post on MSDN. As it points out, command and button events respond to the KeyDown event. Since my lock window was listening for KeyUp events, it would catch the events from the previous keyboard presses. Changing it to listen for KeyDown events completely resolved the problem!

I knew the solution was going to be something simple. I was actually trying very simple solutions on my own, but never thought to just switch from KeyUp to KeyDown.

I hope I can tag this posting well enough, that anyone else out there who’s having the same issue can find this post within the first few search results.

Blackboard Learn 9.1 Web Services

By eSamurai

We are in the process of staging a migration from our really old version of Blackboard to the latest and greatest. The past couple of days has been spent looking at what’s new in Blackboard to see if there might be a better method for us to handle course enrollment. This is becoming more important in that our old method is running into errors while running on the new system. During my research, everything looked the same as in the previous version, but then I stumbled upon their included web services. There seems to be very little documentation on these at the moment, but I did find one blog by Bruce Phillips that goes through using the web services. Even his descriptions, so far, are a bit sparse and targeted at Java developers but I think I can extrapolate out from it, and do a .Net implementation. I will post my findings here. :)

Flash Trace Fixed

By eSamurai

My trace problem finally became troublesome enough to force me to figure out what was going on. Apparently, unlike the other environments I’m used to, “Publish” settings apply when using the “Test Movie” command. I assumed that “Publish” settings were for when you published the site, and that the “Test Movie” command would be the same as debugging in Visual Studio. So I never expected that when I clicked “Omit Trace” for Publish settings that it would kill trace output while debugging. Now I know better, so next time I won’t check “Omit Trace”. How counterintuitive is that?

Flash Debugging Troubles

By eSamurai

Over the years, working with Flash, I have always encountered difficulties debugging my projects. Why? Because for some reason trace() never wants to work for me. I did some Googling this weekend, and I think I’m the only person this every happens to. And it happens to me most of the time. Okay, so, you’re thinking maybe I’m using it in blocks of code that are never reached, or it is outputting empty text. Well, how about when I go to the first frame of my movie and put “trace(“Hi”);” at the very top (right above the “stop();”)? Running the movie through the debugger, I get to watch the pointer jump over all my trace calls. I wouldn’t care so much, but I can’t figure out how to check the value of _mc._x with the debugger. On the locals tab I have _mc, but when I open it up, it doesn’t display all the properties of a MovieClip like I would expect. So I try to add “_mc.x” to the “Watch” panel, but it doesn’t display anything. Well, it will display undefined before _mc is initialized, but after that it’s just totally blank.

My favorite thing is when I’m working with something created by someone else and their trace messages show up, but the ones I added don’t.

I should learn Silverlight . . . at least Visual Studio’s debugger works well. Unfortunately, knowing Silverlight wouldn’t help me right now as my current project is to customize a Flash game.

Minimized JavaScript Action

By eSamurai

I finally had some time to go back to a project that I’ve been using to implement some needed framework changes here at work. One of the changes I’ve implemented with this project was switching to jQuery for all of our image rotations (rotating banners, mouse over images, etc.). I felt that each functionality deserved to be in its own file and then be located at a centralized location, so any changes that we need to make would be made to all sites using the scripts. I updated our Dreamweaver template to make use of the new scripts. Then my time was consumed by other projects/admin duties.

Everything was working well, but linking to multiple JavaScript files slows down most browsers. So in the name of optimization, I decided to change my project to no longer link to each individual script, but link to a JavaScript action on my controller which will return all the files concatenated together.

The first iteration did just that:


public ContentResult JavaScript()
{
   string[] requiredScripts = {
       "http://code.jquery.com/jquery-1.4.2.min.js",
       "http://www.your-site.com/jsRepo/jQueryRollOvers.js",
       "http://www.your-site.com/jsRepo/jQueryRotatingBanner.js",
       "~/Scripts/SiteMasterScripts.js"
   };

   var webClient = new WebClient();
   webClient.Headers.Add("user-agent",
                         "ACM Javascript Concatenator 1.0");
   StringBuilder combineScripts = new StringBuilder();

   foreach (var script in requiredScripts)
   {
       if (script.StartsWith("http://"))
           combineScripts.AppendLine(webClient.DownloadString(script));
       else
       {
           var path = Server.MapPath(script);
           if (System.IO.File.Exists(path))
               using (var sr = new StreamReader(
                                   Server.MapPath(script)))
               {
                   combineScripts.AppendLine(sr.ReadToEnd());
               }
           }
       }

    return new ContentResult {
        Content = combineScripts.ToString(),
        ContentEncoding = Encoding.ASCII,
        ContentType = "text/javascript"
    };
}

Well, that’s all fine and good, but as long as we’re reading in the file and sending them out, why not minimize them by removing all the excess whitespace? This is easily done, and all I need to modify is our return statement:


    return new ContentResult {
        Content = Regex.Replace(
                       combineScripts.ToString(),
                       "[\\n\\r\\t]|\\s{2,}",
                       String.Empty),
        ContentEncoding = Encoding.ASCII,
        ContentType = "text/javascript"
    };

Basically, I just use a regular expression to replace any new lines (\n), carriage returns (\r), tabs (\t), or any occurrence of more than one whitespace with the empty string.

All right, now we have nice minimized JavaScript code going to our browsers, but this is making my controller action all messy looking. Not to mention that it’s not very reusable. Time to refactor!

To the Bat Cave! I open up my utility library and create a new project. After I change my mind about ten times as to what the appropriate name space and class name should be, I refactored the above into a new static class called “Minimizer”, which currently has a single static function called “Minimize”. I figure I can reuse this for CSS as well, so no mention of JavaScript is made.


public static class Minimizer
{
    public static string Minimize(ICollection<string> sourceFiles)
    {
        var webClient = new WebClient();
        webClient.Headers.Add("user-agent", "ACM Minimizer 1.0");
        StringBuilder combineScripts = new StringBuilder();

        foreach (var script in sourceFiles)
        {
             if (Regex.IsMatch(script, "https?://"))
                 combineScripts.AppendLine(
                                   webClient.DownloadString(script));
             else
             {
                 var path = HttpContext.Current.Server.MapPath(script);
                 if (File.Exists(path))
                     using (var sr = new StreamReader(path))
                            combineScripts.AppendLine(sr.ReadToEnd());
             }
        }
        return Regex.Replace(combineScripts.ToString(),
                             "[\\n\\r\\t]|\\s{2,}", String.Empty);
    }
}

Again, all that changes in my action is the return:


    return new ContentResult
    {
        Content = ACM.Html.Minimizer.Minimize(requiredScripts),
        ContentEncoding = Encoding.ASCII,
        ContentType = "text/javascript"
    };

Much better, but what’s with this array of magic strings? I think those should be passed in to the action from the page, rather than being hard-coded. You never know when it might be necessary to load a different set of scripts on a different page.

I had previously created an HtmlHelper called ScriptAction which works like all the other action HtmlHelpers (e.g. Html.ActionLink). That’s good, I can have the JavaScript load from an action, but how do I pass in an array of values? After a little Googling, I found enough to make the light-bulb come on. So after a littler refactoring we get:


Site.Master:
< %= Html.ScriptAction(
       "JavaScript",
       "Home",
       new RouteValueDictionary {
          {
               "requiredScripts[0]",
               "http://code.jquery.com/jquery-1.4.2.min.js"
          },
          {
               "requiredScripts[1]",
               "http://www.your-site.com/jsRepo/jQueryRollOvers.js"
          },
          {
               "requiredScripts[2]",
               "http://your-site.com/jsRepo/jQueryRotatingBanner.js"
          },
          {
              "requiredScripts[3]",
              "~/Scripts/SiteMasterScripts.js"
          }
      }) %>

Controller:
    public ContentResult JavaScript(List</string><string> requiredScripts)
    {
        return new ContentResult
        {
            Content = ACM.Html.Minimizer.Minimize(requiredScripts),
            ContentEncoding = Encoding.ASCII,
            ContentType = "text/javascript"
        };
    }

Now isn’t that beautiful? All my action does now is return the content; the controller isn’t doing things it really shouldn’t be. If it weren’t for the one call to HttpContext “Minimizer” would be easily testable. Now I have to decide if I want to remove the call to HttpContext or not. I could also make it not be static, and have the HttpContext passed in through the constructor. There’s always something!

I hope someone out there finds this useful.

WPF Problems = Visual Studio Problem

By eSamurai

Well, it looks like my problem is with my Visual Studio installation. I downloaded the project from home, and opened it here at work. It loaded up without any problems. I don’t think I even have the extra controls installed on my work machine, but since their DLLs were in the project it’s working just fine.

I guess I need to reinstall my Visual Studio, or just use Blend for designing my windows. :)