Tag Archives: Code

Create configurable Angular services using providers

With Angular 2 on its way, it seems like a lot of developers are now afraid of Angular 1.x. I have nothing bad to say about Angular. Sure, some things could be made easier but that’s why Angular 2 is on its way. I’ve played with Angular 2 a bit, and it only works in Chrome. I’m fairly confident Angular 1.x will be around for quite a while.

In that light, let’s talk about creating configurable services. One reason why AngularJS is so popular is because you can easily create modular, reusable code. This code can encapsulate logic, directives, extensible services and factories (via decorators), as well as configurability. I’ll talk about creating directives and decorators in future articles.

This example will be a simple URL constructor for placekitten.com. Any AngularJS service can be written to be configurable (if there’s reason to configure the service, of course).

First of all, let’s see how this service will be used.

.controller('View1Ctrl', ['$scope', 'kittyService', function ($scope, kittyService) {
    $scope.kittycat = kittyService.getUrl();
}])
  <p>How about a kitty cat?</p>
  <p><img ng-src="{{kittycat}}"/></p>

Pretty simple. We’ll call kittyService.getUrl() and use the string returned from the service as the src for an image.

To create a configurable service, we’ll use an angular provider instead of a service or factory. The structure I use for a provider is this:

(function () {
    'use strict';
    var module = angular.module('myApp.services', []);

    module.provider('serviceName', function ServiceName() {
        // use `this` for configurable properties or functions

        this.$get = [function () {
            var service = {};
            // This can be any valid return that you'd normally use
            // with module.service or module.factory
            return service;
        }];
    });
})();

This structure is only a little different from a service or factory. Rather than return an object or constructor function, you use this.$get to create your reusable code. What you assign to this property is the array injector for your service definition. You’ll feel comfortable with this syntax if you define your services using the array-based dependency injection:

angular.module('myApp')
.service('serviceName', [function (){
            var service = {};
            // This can be any valid return that you'd normally use
            // with module.service or module.factory
            return service;
}]);

You can use instance properties and methods on the provider definition to configure your service, then use the private context of your provider to share the configuration with the service. Here’s the full code for the kittyService:

(function () {
    'use strict';
    var module = angular.module('myApp.services', []);

    module.provider('kittyService', function KittyServiceProvider() {
        var height = 100,
            width = 100;

        this.setHeight = function (h) {
            height = h;
        };
        this.setWidth = function (w) {
            width = w;
        };

        this.$get = [function () {
            var service = {};

            service.getUrl = function () {
                return 'http://placekitten.com/g/' + width + '/' + height;
            };

            // This can be any valid return that you'd normally use
            // with module.service or module.factory
            return service;
        }];
    });
})();

The provider has two private variables: height and width. The two methods on the provider object allow you to update these values, but only during the config phase. After your application’s config function has completed, your provider’s functions are no longer accessible.

One problem with this service is that placekitten.com shows the same image for a given combination of height and width. In the config phase of our application, the service’s height and width can be configured randomly:

.config(['kittyServiceProvider', function (kittyServiceProvider) {
    var widths = [200,300,400,500,600];
    var heights = [300,400,500,600,700];
    kittyServiceProvider.setHeight(heights[Math.floor(Math.random()*heights.length)]);
    kittyServiceProvider.setWidth(widths[Math.floor(Math.random()*widths.length)]);
}]);

The name injected into the config phase is kittyServiceProvider and not kittyService. This is important. AngularJS knows that when you request kittyServiceProvider in the config phase, you want the object containing your service definition (the KittyServiceProvider function in the example above). Once the config phase completes, the $injector service will prepare your service from the this.$get definition of your service.

If you load the example code, refresh the page a few times and you’ll receive a new kitty image.

NOTE: The heights and widths may not always combine in a way that retrieves an image. Just refresh for another example.

Why not do this in a service?

True, you could do this directly in the service if this was just your code. The benefit here is when you want to share a service with other developers, perhaps on a different project within your company or publicly on GitHub. What if your team wants a 200×300 kitty and HR wants a 500×500 kitty? In these situations you can’t just modify the code with your hard-coded values. True, in this example you could use constants or values instead but then your service would have a dependency on the consumer (this is bad).

A service that dumps a string for displaying a cat image is probably not that useful in the real world. Consider other possibilities. I’ve used providers for creating a reusable notification display which allows you to define whether a notification will automatically close and how long notifications will be displayed if they auto-close. Suppose your application often receives 40x errors when users leave their browsers unattended long enough for an authenticated session to time out; you could create a provider which caches failed requests and retries up to X (configurable) times before giving up. Or, you could create a configurable service which caches those failed requests, displays a login dialog, then automatically retries the failed requests X (configurable) milliseconds after logging in successfully. Those examples would require the use of an http interceptor, and would have been quite a bit more complex than a kitty image linker.

Code

Sample code for this blog post is available on github at jimschubert/blogs.

Further Reading

If you really want to dig into the guts of Providers (versus services, factories, constants, or values), check out Adrian Castillo’s blog post, AngularJS Providers under the hood.

For reference to each recipe, check out AngularJS Provider Recipes on the official docs.

Flattr this!

Tips for debugging a WiX MSI

WiX is an excellent technology that simplifies the creation of MSI files using an XML abstraction on top of the Windows Installer APIs. WiX doesn’t change the underlying MSI architecture and it can be a huge pain in the ass sometimes. I thought I would share some tips for debugging what’s going on with an MSI. These tips aren’t specific to WiX, that’s just the technology I’m familiar with.

Logging

The first thing you should try is to add the log switch when you run your installer. To do this, open a command prompt in the directory where your MSI file is located and run it with the following parameters:

msiexec yourinstaller.msi /L*v install.log

The /L*v says to log verbose messages to a file.

For a full list of msiexec switches, check out MSDN’s documentation for msiexec.

Re-cache MSI

If you think your package was somehow corrupted or you’ve made a simple such as changing a file’s guid or a feature condition, you can re-cache the package with the following command:

msiexec /fv yourinstaller.msi

This is generally used when you install a product and then thing “oops, I forgot something…”. You don’t want to create a whole new release, so you can update the installed/cached MSI.

Be careful to read the documentation. With the /f parameter, you can’t pass properties on the command line.

Increased Debug Messages

You can actually increase the amount of messages exposed to MSI logs by setting a machine policy for Windows Installer.

Open regedit and go to HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\Installer (you may need to create this key). Add a DWORD key called Debug with a value of 7.

The value of 7 will write all common debugging messages to the log as well as command line information. If you’re passing sensitive data to the installer on the command line, be warned that this information gets dumped via the OutputDebugString function. This means that anyone with physical access to the machine or access to the machine via TCP/IP may be able to read these messages. The documentation for the policy settings warns that this setting is for debugging purposes only and may not exist in future versions of Windows Installer.

For a full list of available settings, check out Microsoft’s Windows Installer Machine Policies.

System Debugging

Passing the logging switch and log file name to an MSI every time you run an MSI can be annoying. You can set the Logging machine policy to have Windows Installer write a log to a temp file, but then you have to track down the temp file.

Instead, you can run Sysinternals’ DebugView. This utility allows you to catch debugging information exposed by the Win32 OutputDebugString function on local and remote machines. This doesn’t just gather information from MSIs. For example, you can open a TFS query editor in Visual Studio 2013 and inspect the queries made via TFS.

Orca

Lastly, the Windows SDK contains a file called Orca.msi. Orca is a tool to inspect the contents of an MSI. An MSI is essentially just a database of tables and fields with values. You can open an existing MSI, edit a condition, and save it. This can make investigation a little easier. For instance, if you’re trying to figure out why a condition on a custom action doesn’t seem to be passing, you can edit the MSI and modify the condition instead of rebuilding the MSI. It’s also helpful if you’re trying to figure out how another MSI implements some logic.

I’m sure there are plenty of other techniques for debugging MSI files.

Flattr this!

Your IDE’s font matters: Fantasque Sans Mono

A good development environment is crucial to your productivity, there’s no question about it. The phrase ‘good development environment’ is subjective. For example, I’m pretty efficient using WebStorm and VisualStudio. I use vim pretty often but I’m nowhere near ‘efficient’. Matias Niemelä, on the other hand can easily manipulate text in vim.

A year or two ago, I read a blog post somewhere that suggested a font is just as important as your tool of choice. I thought, “yeah, right!”, but downloaded the font anyway. After a day of using the font, I realized how much more quickly I could read through code and how much easier it was to visually identify code blocks. I know that sentence sounds trivial, but after two years of using what I consider a better font I definitely notice a difference when I’m not using the font.

My font of choice these days is called Fantasque Sans Mono.

Here’s a screenshot comparison of Arial and Fantasque Sans Mono, both at 14pt.

Atom: arial 14pt
Atom: arial 14pt
Atom: fantasque sans mono 14pt
Atom: fantasque sans mono 14pt

The first thing to notice is how uncluttered letters are in Fantasque. On line 17, the word ‘function’ feels like it runs together in Arial but the letters clearly stand out in Fantasque. Also notice how the letter ‘g’ is unmistakable on line 18. On line 21, the kerning between parentheses, braces, brackets, and vertical pipes all make the line of code slightly easier to read. On line 23, the zero in Arial and many other fonts often resembles the capital letter ‘O’. For literals, this is obviously a number but it can be an easy typo to overlook within a string. In Fantasque, a zero has a line through it to clearly differentiate the number from the letter. Line 25 is easily consumed in the Arial screenshot mostly because the Atom editor clearly distinguishes between patterns and operations in the regex literal. Take a look at the difference without JavaScript syntax highlighting:

Atom: arial 14pt plain text
Atom: arial 14pt plain text
Atom: fantasque sans mono 14pt
Atom: fantasque sans mono 14pt

The actual code tends to be wider than other fonts. In the Arial screenshot, the image stops at the 80 character vertical indicator, which can easily be seen in the Fantasque screenshot. I actually like to use a 12pt or 13pt font size with Fantasque, which gives me a little more code on screen.

Although these points may seem trivial, I challenge you to at least give a few different fonts a try. You’ll be as surprised as I was to find that subtle differences in your font can improve productivity.

Download Fantasque Sans Mono from OpenFontLibrary.

Flattr this!

System.ComponentModel.DataAnnotations for ASP.NET Web Forms

Although I’m primarily an ASP.NET Web Forms developer, I regularly dabble in new and interesting technologies.  I’ve toyed with other Microsoft technologies such as ASP.NET MVC and Dynamic Data web sites.

ASP.NET MVC offers an interesting mechanism for validating view models called DataAnnotations.   Examples can be seen here and here.

Some of the more useful attributes for validation include:

  • RequiredAttribute
  • RegularExpressionAttribute
  • RangeAttribute
  • DataTypeAttribute

I recently decided to implement a data validation schema (for lack of a better term) for web forms similar to that of ASP.NET MVC. This would allow us to maintain validation of a model object via attributes at the class level, instead of dispersing these validation rules through the web form code or any of the business logic layers. However, there will be occasions where an object’s validity depends upon some state or validity of another object. I’ve handled this by allowing the validation method to accept any action to be called after the object has been validated.

In order to make a domain object validatable, I’m going to implement the following interface:

IValidatable.cs

namespace Validatable
{
    interface IValidatable
    {
        System.Type EntityType { get; set; }
        System.Collections.Generic.List<object> Errors { get; set; }

        /// <summary>
        /// Determine whether the object is valid.  If invalid, errors are added to item.Errors
        /// </summary>
        /// <returns>true if valid, false if invalid</returns>
        bool IsValid();

        /// <summary>
        /// Validate this item against a supplied action
        /// </summary>
        /// <param name="action">The action to use for validation</param>
        void Validate(System.Action action);

        /// <summary>
        /// Validate this object against a Repository.
        /// <example>
        /// Item a = new Item();
        /// a.Validate(new ItemRepository());
        /// </example>
        /// Note: Repository must have a Validate(T item) method
        /// </summary>
        /// <param name="repository">The Repository to use for validation</param>
        void Validate(object repository);
    }
}

As you can see, this abstract class adds a property accessor for the entity’s type, a list of validation errors, an IsValid method, and two Validate methods.

Validatable<T>

I’ll take the code in chunks, since there is a lot more than I usually post.
First of all, the using directives required for this class are pretty sparse:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Reflection;

The class definition is:

   [Serializable]
    public abstract class Validatable<T> : IValidatable where T : class, new()
    { /* class */ }

If you’re unfamiliar with generic constraints, the where T : class, new() above enforces the T passed as in to be a class and to have a parameterless constructor (new())

The properties can be auto-implemented properties, or they can implement any backing logic you prefer. The constructor as I have it is:

 protected Validatable()
 {
     Errors = new List<object>();
     EntityType = typeof(T);
 }

Now for the methods and a slight explanation of each:

IsValid()

        public virtual bool IsValid()
        {
            Errors = new List<object>();
            PropertyInfo[] props = this.GetType().GetProperties();

            foreach (PropertyInfo property in props)
            {
                foreach (ValidationAttribute va in
                    property.GetCustomAttributes(true).OfType<ValidationAttribute>())
                {
                    var value = property.GetValue(this, null);
                    if (!va.IsValid(value))
                    {
                        Errors.Add(va.ErrorMessage);
                    }
                }
            }

            return Errors.Count <= 0;
        }

As a side note, all DataAnnotation attributes inherit from ValidationAttribute. You can create your own Validation Attributes by inheriting from this class. This method clears the list of errors and repopulates it by looping over any properties with validation attributes of this object, validates that property’s value against the attribute, and adds the ErrorMessage associated with it to the list of Errors.

Validate Methods

        public virtual void Validate(Action action)
        {
            if (IsValid())
            {
                action();
            }
        }

        public virtual void Validate(object repository)
        {
            MethodInfo method = repository.GetType().GetMethods()
                .Where(x => x.Name.Equals("Validate")).FirstOrDefault();
            if (method != null)
            {
                object[] parameters = new object[] { this };
                Validate(() => method.Invoke(repository, parameters));
            }
        }

These two methods can be changed to throw an exception if the object is invalid. I’ll leave that up to you. The way these are set up is to allow you to validate the object and perform either some unknown action or call Validate(T item) against some other object, arbitrarily called a repository. In actuality, you could have a Validate method on some other object that takes an object of this type and essentially chain validations.

The simplicity of the Validate(Action action) method is what makes it beautiful. For instance, you can have an item (a) and cause it save after validation by doing something like:

a.Validate(() => new ItemDAL().Save(a));

As you can see, a Save method in your Item’s Data Access Layer taking Item as a parameter can be called only when a.IsValid() is true. Again, there are a number of ways to tweak this and change it to your liking, but I’ll leave that up to you.

DataAnnotationValidator

Here is the wonderful part about all of this. You can create a custom validator that validates in a similar way as the Validatable class. I’ll post the code and quickly explain what it does. I got the idea from this from another blog and tweaked it a little.

DataAnnotationValidator.cs

// DataAnnotationValidator.cs
namespace Validatable
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Reflection;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    [ToolboxData("<{0}:DataAnnotationValidator runat=\"server\" ControlToValidate=\"[Required]\" Display=\"Dynamic\" Text=\"*\" SourceTypeName=\"[FullyQualifiedTypeName]\" PropertyToValidate=\"[PropertyName]\" />")]
    public class DataAnnotationValidator : BaseValidator
    {
        /// <summary>
        /// THe Property that should be checked
        /// </summary>
        public string PropertyToValidate { get; set; }

        /// <summary>
        /// The object's type
        /// </summary>
        public string SourceTypeName { get; set; }

        protected override bool EvaluateIsValid()
        {
            Type source = GetValidatedType();
            PropertyInfo property = GetValidatedProperty(source);
            string value = GetControlValidationValue(ControlToValidate);

            foreach (ValidationAttribute va in property
                .GetCustomAttributes(typeof(ValidationAttribute), true)
                .OfType<ValidationAttribute>())
            {
                if (!va.IsValid(value))
                {
                    if (string.IsNullOrEmpty(ErrorMessage))
                    {
                        this.ErrorMessage = va.ErrorMessage;
                    }
                    return false;
                }
            }

            return true;
        }

        private Type GetValidatedType()
        {
            if (string.IsNullOrEmpty(SourceTypeName))
            {
                throw new InvalidOperationException("Null SourceTypeName can't be validated");
            }

            Type validatedType = Type.GetType(SourceTypeName);
            if (validatedType == null)
            {
                throw new InvalidOperationException(
                    string.Format("{0}:{1}", "Invalid SourceTypeName", SourceTypeName));
            }

            return validatedType;
        }

        private PropertyInfo GetValidatedProperty(Type source)
        {
            PropertyInfo property = source.GetProperty(PropertyToValidate,
              BindingFlags.Public | BindingFlags.Instance);

            if (property == null)
            {
                throw new InvalidOperationException(
                  string.Format("{0}:{1}", "Validated Property Does Not Exists", PropertyToValidate));
            }
            return property;
        }
    }
}

This creates a validator web control which has ‘PropertyToValidate’ and ‘SourceTypeName’. When a Validator web control is added to a page, it must have ControlToValidate, PropertyToValidate, and SourceTypeName specified or an error will be thrown. The validation method verifies the type and the property, gets the value of the property and finally, much like the Validatable abstract class, it loops over all ValidationAttributes and validates the value against that attribute. You can use this with multiple attributes, so it doesn’t hurt to add this validator to a property– that just means you can add an attribute in the future and everything is already wired up! That’s pretty cool.

Example

As an example, I’m going to create a single page to **input** a Customer object. The customer object is very simple:

 public class Customer : Validatable.Validatable<Customer>
    {
        [Required(ErrorMessage="UserId is Required")]
        public int UserId { get; set; }

        [DataType(DataType.PhoneNumber, ErrorMessage="Invalid Phone Number")]
        public string PhoneNumber { get; set; }

        [RegularExpression(@"(^\d{5}(-\d{4}){0,1}$)", ErrorMessage="Invalid Zip Code")]
        public string ZipCode { get; set; }
    }

And the Page in full is collapsed below:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Example._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Label ID="lblStatus" runat="server" />
    <asp:ValidationSummary ID="ValidationSummary1" runat="server" />
    <div>
        <asp:FormView ID="FormView1" runat="server" DataSourceID="srcRepository" 
            Width="119px" AllowPaging="True">
            <EditItemTemplate>
                UserId:
                <asp:TextBox ID="UserIdTextBox" runat="server" Text='<%# Bind("UserId") %>' />
                <example:DataAnnotationValidator ID="DataAnnotationValidator1" runat="server" ControlToValidate="UserIdTextBox" Display="Dynamic"
                    PropertyToValidate="UserId" ErrorMessage="Invalid User Identification Number" 
                    SourceTypeName="Example.Customer, Example, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" 
                    Text="*"/>
                <br />
                PhoneNumber:
                <asp:TextBox ID="PhoneNumberTextBox" runat="server" 
                    Text='<%# Bind("PhoneNumber") %>' />
                <example:DataAnnotationValidator ID="DataAnnotationValidator2" runat="server" ControlToValidate="PhoneNumberTextBox" Display="Dynamic"
                    PropertyToValidate="PhoneNumber" OnInit="GetTypeName" SourceTypeName="Example.Customer, Example, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" Text="*"/>
                <br />
                ZipCode:
                <asp:TextBox ID="ZipCodeTextBox" runat="server" Text='<%# Bind("ZipCode") %>' />
                <example:DataAnnotationValidator ID="DataAnnotationValidator3" runat="server" ControlToValidate="ZipCodeTextBox" Display="Dynamic"
                    PropertyToValidate="ZipCode" SourceTypeName="Example.Customer, Example, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" Text="*"/>
                <br />
                EntityType:
                <asp:TextBox ID="EntityTypeTextBox" runat="server" 
                    Text='<%# Eval("EntityType") %>' />
                <br />
                <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" 
                    CommandName="Update" Text="Update" />
                &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" 
                    CausesValidation="False" CommandName="Cancel" Text="Cancel" />
            </EditItemTemplate>
            <InsertItemTemplate>
                UserId:
                <asp:TextBox ID="UserIdTextBox" runat="server" Text='<%# Bind("UserId") %>' />
                <example:DataAnnotationValidator ID="DataAnnotationValidator1" runat="server" ControlToValidate="UserIdTextBox" Display="Dynamic"
                    PropertyToValidate="UserId"  OnInit="GetTypeName"  Text="*"/>
                <br />
                PhoneNumber:
                <asp:TextBox ID="PhoneNumberTextBox" runat="server" 
                    Text='<%# Bind("PhoneNumber") %>' />
                <example:DataAnnotationValidator ID="DataAnnotationValidator2" runat="server" ControlToValidate="PhoneNumberTextBox" Display="Dynamic"
                    PropertyToValidate="PhoneNumber" OnInit="GetTypeName"  Text="*"/>
                <br />
                ZipCode:
                <asp:TextBox ID="ZipCodeTextBox" runat="server" Text='<%# Bind("ZipCode") %>' />
                <example:DataAnnotationValidator ID="DataAnnotationValidator3" runat="server" ControlToValidate="ZipCodeTextBox" Display="Dynamic"
                    PropertyToValidate="ZipCode" OnInit="GetTypeName"  Text="*"/>
                <br />
                EntityType:
                <asp:TextBox ID="EntityTypeTextBox" runat="server" 
                    Text='<%# Eval("EntityType") %>' />
                <br />
                <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" 
                    CommandName="Insert" Text="Insert" />
                &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server" 
                    CausesValidation="False" CommandName="Cancel" Text="Cancel" />
            </InsertItemTemplate>
            <ItemTemplate>
                UserId:
                <asp:Label ID="UserIdTextBox" runat="server" Text='<%# Bind("UserId") %>' />
                <br />
                PhoneNumber:
                <asp:Label ID="PhoneNumberTextBox" runat="server" 
                    Text='<%# Bind("PhoneNumber") %>' />
                <br />
                ZipCode:
                <asp:Label ID="ZipCodeTextBox" runat="server" Text='<%# Bind("ZipCode") %>' />
                <br />
                EntityType:
                <asp:Label ID="EntityTypeLabel" runat="server" 
                    Text='<%# Bind("EntityType") %>' />
                <br />
                <asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" 
                    CommandName="Edit" Text="Edit" />
                &nbsp;<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False" 
                    CommandName="New" Text="New" />
            </ItemTemplate>
        </asp:FormView>
        <asp:ObjectDataSource ID="srcRepository" runat="server" 
            DataObjectTypeName="Example.Customer" InsertMethod="Save" 
            oninserted="srcRepository_Saved" onupdated="srcRepository_Saved" 
            SelectMethod="Get" TypeName="Example.CustomerRepository" UpdateMethod="Save"></asp:ObjectDataSource>
    </div>
    </form>
</body>
</html>

Of particular note here is in the EditTemplate, you’ll see

                  UserId:
                <asp:TextBox ID="UserIdTextBox" runat="server" Text='<%# Bind("UserId") %>' />
                <example:DataAnnotationValidator ID="DataAnnotationValidator1" runat="server" ControlToValidate="UserIdTextBox" Display="Dynamic"
                    PropertyToValidate="UserId" ErrorMessage="Invalid User Identification Number" 
                    SourceTypeName="Example.Customer, Example, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" 
                    Text="*"/>

in which the SourceTypeName must be the full Assembly Qualified Name. This is necessary if the Validatable and DataAnnotationValidator classes are in an external library. This is a rather tedious property to fill for each validator. Another way to get around this is to populate the SourceTypeName as seen in the InserItemTemplate, e.g.

                UserId:
                <asp:TextBox ID="UserIdTextBox" runat="server" Text='<%# Bind("UserId") %>' />
                <example:DataAnnotationValidator ID="DataAnnotationValidator1" runat="server" ControlToValidate="UserIdTextBox" Display="Dynamic"
                    PropertyToValidate="UserId"  OnInit="GetTypeName"  Text="*"/>

and the code in the code behind is very simple:

        protected void GetTypeName(object sender, EventArgs e)
        {
            DataAnnotationValidator validator = (DataAnnotationValidator)sender;
            validator.SourceTypeName = new Customer().EntityType.AssemblyQualifiedName;
        }

Also notice that the first validator (the one with the assembly qualified name) has an ErrorMessage property specified. Doing this allows you to override the error message returned from the validated object. We can do this if the model says “UserId” and you want the user to see this property referred to as “User Identification”.

Conclusion

Sometimes dabbling in other technologies can open the door for new and simpler ways of doing things. I like this example because it allows you to build web applications quickly and easily, while making them maintainable in the future (new validations only have to be added to the model, not to every control where the model must be validated).

For further reference, this project is linked below. Please download and modify if necessary.
Validatable.zip

Flattr this!

Finding a user’s local time from UTC offset

I answered a question over at StackOverflow, and I really liked the answer, so I thought I would share this nifty extension method:


        /// <summary>
        /// Convert a given DateTime object to a user's local time, 
        /// taking into account changes in TimeZone rules.
        /// For example, if you were to perform this operation on 
        /// a time now, during EST Daylight Saving, and that time falls 
        /// outside the scope of Daylight Saving time, the rule will adjust accordingly.
        /// </summary>
        /// <param name="dateTime">The DateTime object</param>
        /// <param name="offset">offset from UTC</param>
        /// <returns>User's local time</returns>
        public static DateTime ConvertToLocalDateTime(this DateTime dateTime, int offset)
        {
            TimeZoneInfo destinationTimeZone = TimeZoneInfo.GetSystemTimeZones()
               .Where(x => x.BaseUtcOffset.Hours.Equals(offset)).FirstOrDefault();

            var rule = destinationTimeZone.GetAdjustmentRules().Where(x =>
                x.DateStart <= dateTime && dateTime <= x.DateEnd)
                .FirstOrDefault();

            TimeSpan baseOffset = TimeSpan.Zero;
            if (rule != null)
            {
                baseOffset -= destinationTimeZone.IsDaylightSavingTime(dateTime) ?
                    rule.DaylightDelta : TimeSpan.Zero;
            }

            DateTimeOffset dto = DateTimeOffset.Parse(dateTime.ToString());
            return new DateTime(TimeZoneInfo
                     .ConvertTimeFromUtc(dateTime, 
                            destinationTimeZone).Ticks + baseOffset.Ticks);
        }

The summary basically says it all. I ran through a couple of tests with this, I’d like to know if anyone uses this and makes modifications to it!

Flattr this!

NHibernate.Criterion Extensions workaround

I’ve been working with Fluent NHibernate for the past month or so, and I realized while writing an NHibernate query that the NHibernate Criterion’s Restrictions class isn’t very refactor-friendly. The refactorability of Fluent NHibernate is ultimately why we’ve decided to use it. It does take a little longer to set up than some other ORMs, but in the long-run it’s nice to be able to change a property name and refactor.

… except the property names are hard-coded in the Criteria!

My workaround for this is to use a bit of static reflection a-la-FNH, and maintain code that is easily refactored.

For instance, I’ve created a static utility class (Showing the Restrictions.Eq() substitute):

  public static class CriterionExtensions
    {
        public static SimpleExpression Eq<T>(
                Expression<Func<T, object>> exp, object value
        )
        {
            var memberExpression = GetMemberExpression(exp);
            string propertyName = ((PropertyInfo)memberExpression.Member).Name;
            if (!string.IsNullOrEmpty(propertyName))
                return Restrictions.Eq(propertyName, value);
            else
                return null;
        }

        private static MemberExpression GetMemberExpression<T>(
                Expression<Func<T, object>> expression
        )
        {
            MemberExpression memberExpression = null;
            if (expression.Body.NodeType == ExpressionType.Convert)
            {
                var body = (UnaryExpression)expression.Body;
                memberExpression = body.Operand as MemberExpression;
            }
            else if (expression.Body.NodeType == ExpressionType.MemberAccess)
            {
                memberExpression = expression.Body as MemberExpression;
            }
            if (memberExpression == null)
            {
                throw new ArgumentException("Not a member access", "member");
            }
            return memberExpression;
        }
    }

And to use this code, you can create an aliased using directive and call it in code:

    using Ensure = MyNamespace.Extensions.Criterion.CriterionExtensions;
    /* class declarations and whatnot */
     internal IEnumerable<Product> GetAll(int shelfNumber)
      {
          var session = SessionManager.GetCurrentSession();
          return session.CreateCriteria<Product>()
              .Add(Ensure.Eq<Product>(x => x.ShelfNumber, shelfNumber))
              .List<Product>();
      }

It’s pretty simple to use and is easily refactored. You may be able to add your *extensions* to a namespace: NHibernate.Criterion and call your class Restrictions, but I didn’t try this (I don’t like mixing namespaces). Let me know what you think!

Flattr this!