Agile User Experience Design


Integrating Agile methodology and User Experience Design has long been a challenge. This diagram shows how the two can work in harmony with each other to produce profitable products that meet the demands of stakeholders.

Posted in User Experience, User Experience Design | Tagged , , , | Leave a comment

The UX Process


This diagram shows the stages and deliverables of the User Experience Design process.

Posted in Uncategorized, User Experience, User Experience Design | Tagged , | Leave a comment

Using Atalasoft DotImage to create blank Tiff image

Atalasoft DotImage is a great library for working with all kinds of images. I recently had the need for a Tiff image which met the following specification:

  • 300 x 300 dpi
  • Print at regular letter size (8 1/2 x 11)
  • Encoded using Group 4 compression
  • I created this Tiff file using only the following 5 lines of code:

    AtalaImage atalaImage = new AtalaImage(2550, 3263, PixelFormat.Pixel1bppIndexed);
    atalaImage.Resolution = new Dpi(300, 300, ResolutionUnit.DotsPerInch);
    TiffDocument testDoc = new TiffDocument();
    testDoc.Pages.Add(new TiffPage(atalaImage, TiffCompression.Group4FaxEncoding));
    testDoc.Save(YOUR_LOCATION);
    

    Prior to using this code I had simply scanned a blank sheet. I quickly realized this was not a good alternative due to inconsistencies with the scanner bed. Using this simple code I created a perfect Tiff.

    -Craig

    Posted in .NET Framework, Uncategorized | Tagged | Leave a comment

    Multi Tenant Architecture via Dependency Injection: Part 3

    In Part 1 we discussed web application Multi Tenant Architecture, and briefly discussed how dependency injection can allow us to manage our client customizations. In Part 2, we explored how to wire up Ninject to our ASP.Net MVC application and begin to use its dependency injection features.

    In Part 3 we will look at how to utilize Ninject’s features within our application, along with what kind of functionality can be delivered. At this point, let’s revisit our goals from Part #1:

    1. dynamically set which service object(s) we are using to perform our application logic
    2. dynamically set which view we are returning
    3. dynamically set which partial views we are using

    Hypothetically, let our application be a standard transactional system, with header records at the top level and child records below it. Furthermore, let it be an order entry system, so we will need to know about quantities, prices, have subtotals, etc. Our standard interface can be for Work Orders, and look something like the following:

    WorkOrders.aspx:
    Sample Work Orders Screenshot
    We have some header information (Work Order #, etc.) and child records, and the ability to interact with the application to modify child records and add new ones. At this point, a large customer likes what you’ve done so far and wants to use your application to manage their shop. But instead of work orders, they need to use Purchase Orders. You need to make some major modifications without affecting your existing functionality, so you create a new page and use Ninject to inject the right functionality into the application. Because we implemented Goal #2 in Part 2, we merely need to modify our source repository to provide the PurchaseOrders.aspx page instead of WorkOrders.aspx.

    From CompanyConfigProvider.cs:

                    // construct our list of Views to be used throughout the application
                    // for Goals #2 and #3
                    foreach (KeyValuePair<string, string> item in r.getViews())
                    {
                        cc.Views.Add(item.Key, item.Value);
                    }
    

    In addition, because these Purchase Orders are between your client and their own customers and not intra-company Work Orders, there are potential tax implications — as such, you will need to introduce a method of keeping track of tax when necessary. It will utilize the existing Purchase Orders functionality, but will need to augment it — the perfect usage of partial views.

    TotalNoTax.ascx:

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
    <p>Non-Profit Tax Code: <input type="text" name="taxinfo" /></p>
    

    TotalWithTax.ascx:

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
    <p>Tax Amount: <input type="text" id="taxinfo" name="taxinfo" /></p>
    <script type="text/javascript">
        function updateTax() {
            var qty = parseFloat($("#quantity").val());
            $("#taxinfo").val(qty * 150 * .06);
        }
    
        $(document).ready(function() {
            $("#quantity").blur(updateTax);
            $("#itemType").change(updateTax);
        });
    </script>
    

    Very simply, we will use jQuery to manage a new form element that will include tax when necessary. Let’s start putting it all together. First, let’s take a look at our controller:

    From OrdersController.cs:

    using {etc}
    
    namespace MultiTenantNinject.Controllers
    {
        [HandleError]
        [ProvideCompanyConfig]
        public class OrdersController : Controller
        {
    

    As you can see, we inherit from Controller like normal and utilize our ProvideCompanyConfig attribute so that we can be assured we have access to our company config upon rendering. Let’s take a look at an Action:

            public ActionResult Index()
            {
                ViewResult v = View(_companyConfig.Views["Order Management"]);
    
    			// add view data items for the header and children;
    
    			// add item to be used for determining if it's a taxable or non-taxable transaction:
    			v.ViewData.add("taxState",repository.TaxState);
    
                return v;
    
            }
    

    The first step in rendering the View to the user is ensuring we have an “Order Management” entry in our Views collection that establishes what type of major functionality to use. Our repository would load the config file with a text entry like “WorkOrders” or “PurchaseOrders” to correspond with “WorkOrders.aspx” or “PurchaseOrders.aspx”, respectively. We can set our ViewData at this point, perhaps using a service object (which we will explore soon) and then return the view. At this point, we have a solid understanding of achieving Goal #2, so let’s take a look at the few lines necessary to achieve Goal #3:

    From PurchaseOrders.aspx:

        <% var configSettings = (MultiTenantNinject.Models.ICompanyConfig)ViewData["companyConfigSettings"];  %>
    	<h3>Purchase Orders</h3>
    	... etc ...
        <p><% Html.RenderPartial(configSettings.Views[string.Format("Taxes_{0}",ViewData["taxState"])]); %>
    

    By utilzing the correct entry in our repository for the user’s state, we can provide the correct tax functionality. If the company’s location was in Florida, the repository could provide “TotalWithTax” for the “Taxes_FL” binding, and “TotalNoTax” for the other states. Obviously we can take it up a level of abstraction and determine whether or not this transaction is taxable in the controller or service object, but this serves as an adequate example of Goal #3. Lastly, let’s take a look at our solution for Goal #1 — it’s all well and good when we can provide custom front-end functionality for our users, but at some point we will need to implement logic and manipulate data. Let’s revisit the module where we inject our services:

    From OrderModule.cs:

            public override void Load()
            {
                // use reflection to bind a list of types (from our Config's "Bindings" collection)
                // to be used when called upon during injection
                string serviceLocationPrefix = "MultiTenantNinject.Services.";
                foreach (KeyValuePair<string,string> item in _config.Bindings)
                {
                    Bind(Type.GetType(serviceLocationPrefix + item.Key)).To(Type.GetType(serviceLocationPrefix + item.Value));
                }
            }
    

    We will need to provide an interface and an implementation for our service(s). Firstly, the interface:

    IOrderService.cs:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using System.Web.Mvc;
    
    namespace MultiTenantNinject.Services
    {
        public interface IOrderService
        {
            string Process(ViewDataDictionary viewdata);
            DataTable Orders { get; set; }
        }
    }
    

    and one of the implementations:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Data;
    using System.Web.Mvc;
    
    namespace MultiTenantNinject.Services
    {
        public class VideoCardOrderService: IOrderService
        {
    
            #region IService Members
    
            public string Process(ViewDataDictionary viewdata)
            {
                // here we do transactions pertaining to video cards
                return "Thanks for buying a video card!";
            }
    
            #region Orders
            private DataTable _Orders;
            public DataTable Orders
            {
                get
                {
                    return _Orders;
                }
                set
                {
                    if (_Orders == value) return;
                    _Orders = value;
                }
            }
            #endregion
    
            #endregion
    
        }
    }
    

    Service objects can perform most of the functionality of your application, and do not need to be gone over in great detail, as they are as varied as anything else can be. Suffice it to say that it’s a standard interface/implementation pattern of development. Ninject allows you to set it up for injection, as we did in Part 2, so that whenever you call a particular interface for this user a particular implementation is used. “VideoCardOrderService” could easily be “MotherboardOrderService” or “CarOrderService”:

    From OrdersController.cs:

            [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult Save()
            {
                _orderService.Process(ViewData);
                return new RedirectResult("Index");
            }
    

    Our controller, in the end, is completely agnostic of our major functionality, our minor (partial view) functionality, and our domain logic:

    OrdersController.cs:

    using {etc}
    using Ninject;
    
    namespace MultiTenantNinject.Controllers
    {
        [HandleError]
        [ProvideCompanyConfig]
        public class OrdersController : Controller
        {
            ICompanyConfig _companyConfig;
            IOrderService _orderService;
    
            public OrdersController(ICompanyConfig pCompanyConfig, IOrderService pOrderService)
            {
                _companyConfig = pCompanyConfig;
                _orderService = pOrderService;
            }
    
            public OrdersController()
            {
            }
    
            public ActionResult Index()
            {
                ViewResult v = View(_companyConfig.Views["Order Management"]);
    
    			// add view data items for the header and children;
    
    			// add item to be used for determining if it's a taxable or non-taxable transaction:
    			v.ViewData.add("taxState",repository.TaxState);
    
                return v;
            }
    
            [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult Save()
            {
                _orderService.Process(ViewData);
                return new RedirectResult("Index");
            }
        }
    }
    

    Thus, the conclusion to our series about utilizing dependency injection within ASP.Net MVC to enhance a Multi-Tenant Architecture. We can provide service objects without our controller (or anything else) performing logic switches, we can provide major changes to functionality without creating a new codebase, and we can provide in-place customizations truly in-place. In addition, we’ve created our application such that we can utilize any kind of data layer or repository and we can utilize testing frameworks to test our code without having to rewrite anything. And lastly, although it’s taken a moderate level of effort to get to this point, we can be secure in the knowledge that additional changes can be implemented without affecting existing functionality, and we can easily swap out functionality when the situation arises with very little additional effort.

    Posted in .NET Framework, Enterprise .NET, General | Tagged , , , | Leave a comment

    Multi Tenant Architecture via Dependency Injection: Part 2

    In Part 1 we discussed Multi Tenant Architecture as it pertains to web development, along with how dependency injection (specifically with Ninject) can allow us to manage our necessary customizations a bit cleaner.

    To start off with, let’s talk about using Ninject with ASP.Net MVC. You’ll need to download the appropriate Ninject version for your .NET framework. Our example will use Ninject 2.0 with ASP.Net MVC 1. Download Ninject from the homepage at http://ninject.org/ and visit the dojo and github to learn the basics. Ninject will manage our controllers for us (it needs to, so it can monitor for injection points) and so will need to be tightly integrated into our application. For starters, we’re going to need to change our global.asax.cs file. Take a look:

    Global.asax.cs:

    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using Ninject.Web.Mvc;
    using Ninject;
    using Ninject.Modules;
    using MultiTenantNinject.Controllers.Components;
    using MultiTenantNinject.Models;
    
    namespace MultiTenantNinject
    {
      // Inherit from NinjectHttpApplication instead of HttpApplication
      public class MvcApplication : NinjectHttpApplication
      {
        public static void RegisterRoutes(RouteCollection routes)
        {
          routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
          // hack for visual studio's web server
          routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });
    
          routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = "" } // Parameter defaults
          );
    
        }
    
        // we use OnApplicationStarted, because Ninject is using Application_Started
        protected override void OnApplicationStarted()
        {
          // no big surprise here -- register our routes.
          RegisterRoutes(RouteTable.Routes);
          // register every controller in our application for injection
          RegisterAllControllersIn(Assembly.GetExecutingAssembly());
        }
    
        // this is called automatically from within the Ninject framework
        protected override IKernel CreateKernel()
        {
          // create a Kernel to manage injections.
          // have the Kernel process our "SetupModule" class
          IKernel k = new StandardKernel(new SetupModule());
          // have the Kernel process our "ConfigModule" class
          k.Load(new ConfigModule());
          // have the Kernel process our "OrderModule class
          // pass an instance of our company config that our ConfigModule calls for
          k.Load(new OrderModule(k.Get<ICompanyConfig>()));
          return k;
        }
      }
    }
    

    You can see how the CreateKernel() method loads a number of Modules to manage our Dependency Injection. Let’s take a look at these modules. The first module to investigate will provide bindings for our .NET MVC dependencies.

    SetupModule.cs:

    using {etc}
    using Ninject;
    using Ninject.Modules;
    using Ninject.Web.Mvc;
    
    namespace MultiTenantNinject.Controllers.Components
    {
        // inherit from NinjectModule
        public class SetupModule : NinjectModule
        {
            // NinjectModule is an implementation of the Strategy design pattern and must implement "Load()"
            public override void Load()
            {
                // Let's inject .NET MVC framework dependencies, wow!
                Bind<IFormsAuthentication>()
                    .To<FormsAuthenticationService>();
                Bind<IMembershipService>()
                    .To<AccountMembershipService>();
                Bind<MembershipProvider>()
                    .ToMethod(ctx => Membership.Provider);
            }
        }
    }
    

    Our next module will bind the heart of our Multi Tenant Architecture, the “Company Config”. This configuration object will be lightweight, cached server-side (ideally once for each company) and will be available during most operations of the page lifecycle.

    ICompanyConfig.cs:

    using {etc}
    
    namespace MultiTenantNinject.Models
    {
        public interface ICompanyConfig
        {
            // Task #1 -- provide service objects
            Dictionary<string, string> Bindings { get; set; }
            // Task #2 & #3 -- provide views and partial views
            Dictionary<string, string> Views { get; set; }
    
            String CompanyName { get; set; }
    
        }
    }
    

    ConfigModule.cs:

    using {etc}
    
    namespace MultiTenantNinject.Controllers.Components
    {
        public class ConfigModule : NinjectModule
        {
            public override void Load()
            {
                // Ninject.Activation.Provider is a factory object.
                CompanyConfigProvider Provider = new CompanyConfigProvider(WebConfigurationManager.AppSettings);
    
                // Bind our service (ICompanyConfig) to its implementation using the
                // aforementioned Provider.  Bind it so that each request uses the same
                // instance of the service.
                Bind<ICompanyConfig>()
                    .ToProvider(Provider)
                    .InRequestScope();
    
            }
        }
    }
    

    Our next module will control the functionality for our example customizations revolving around Purchase Orders. In practice we could have multiple modules, perhaps one for each functional area of our application, but our single module will serve our purposes here:

    OrderModule.cs:

    using {etc}
    
    namespace MultiTenantNinject.Controllers.Components
    {
        public class OrderModule : NinjectModule
        {
            private readonly ICompanyConfig _config;
    
            // We see our first "Inject" attribute.
            // Here we will take an instance of our company config
            // and later use it to bind our application services
            [Inject]
            public OrderModule(ICompanyConfig companyConfig)
            {
                _config = companyConfig;
            }
    
            public override void Load()
            {
                // use reflection to bind a list of types (from our Config's "Bindings" collection)
                // to be used when called upon during injection
                string serviceLocationPrefix = "MultiTenantNinject.Services.";
                foreach (KeyValuePair<string,string> item in _config.Bindings)
                {
                    Bind(Type.GetType(serviceLocationPrefix + item.Key)).To(Type.GetType(serviceLocationPrefix + item.Value));
                }
            }
        }
    }
    

    Let’s briefly revisit our goals from Part #1:

    1. dynamically set which service object(s) we are using to perform our application logic
    2. dynamically set which view we are returning
    3. dynamically set which partial views we are using

    At this point we can see the pattern unfolding. We use our Modules to dictate to the Kernel what strategies to use when binding implementations to our services. We can use reflection, we can use strings and types, and we can use Providers inside of our Modules during binding. We will be coming back to OrderModule.cs, as that is part of our implementation for Goal #1. Let us take a look now at our Provider from our ConfigModule:

    CompanyConfigProvider.cs:

    using {etc}
    using Ninject.Activation;
    
    namespace MultiTenantNinject.Models
    {
        // inherit from Ninject.Activation.Provider
        public class CompanyConfigProvider: Provider<CompanyConfig>
        {
            // these settings are provided by our web.config in this example
            public CompanyConfigProvider(NameValueCollection settings)
            {
                Settings = settings;
            }
    
            protected NameValueCollection Settings { get; set; }
    
            // build and return an instance of our CompanyConfig using the specific context
            // IProvider is a Factory that will have its CreateInstance() method called
            // the first time that a CompanyConfig is injected
            protected override CompanyConfig CreateInstance(IContext context)
            {
                // use a caching mechanism to store our company config.  we cannot
                // cache in the Application cache because we have a Multi Tenant Application.
                // we can use Session in a pinch, although depending on your application's traffic,
                // you might need to use something else
                System.Web.SessionState.HttpSessionState Session = HttpContext.Current.Session;
                CompanyConfig cc = null;
    
                // if we don't have a cached company config:
                if (Session == null || Session["cc"] == null)
                {
                    cc = new CompanyConfig();
                    // our repository is extremely unsophisticated, but you should
                    // get the idea of how this works.  it may very well be passed in
                    // via constructor injection
                    MultiTenantNinject.Models.Repository r = new Repository();
    
                    // construct our list of Views to be used throughout the application
                    // for Goals #2 and #3
                    foreach (KeyValuePair<string, string> item in r.getViews())
                    {
                        cc.Views.Add(item.Key, item.Value);
                    }
                    // construct our list of service bindings to be used throughout the application
                    // for Goal #1 (previously seen in OrderModule.cs
                    foreach (KeyValuePair<string, string> item in r.getBindings())
                    {
                        cc.Bindings.Add(item.Key, item.Value);
                    }
                    // if we can cache our company config:
                    if (Session != null && Session["cc"] == null)
                    {
                        Session["cc"] = cc;
                    }
                    // set company name (normally would be from the repository)
                    cc.CompanyName = "Widgets, Inc.";
                }
                else  // we have a previously cached company config
                {
                    cc = (CompanyConfig)Session["cc"];
                }
    
                return cc;
            }
        }
    }
    

    To make our lives a little easier and yet more structured, let’s create an ActionFilterAttribute to inject our CompanyConfig into our Views:

    From ProvideCompanyConfigAttribute:

        public class ProvideCompanyConfigAttribute : ActionFilterAttribute
        {
            [Inject]
            public ICompanyConfig Settings { get; set; }
    
            public override void OnActionExecuted(ActionExecutedContext filterContext)
            {
                filterContext.Controller.ViewData.Add("companyConfigSettings", Settings);
            }
        }
    

    We use Ninject’s “Inject” attribute to provide the CompanyConfig to our Attribute, and then inject the config into the controller as a matter of course.

    At this point we’ve seen how Ninject positions itself within our application (a controller factory and application superclass) and how we can use Ninject’s modularity to manage our bindings. We’ve touched upon Goals #1, 2, and 3, and can see it taking shape before us. We have a company configuration that encapsulates the customizations for the currently logged in user and provides the customized bindings and views for that logged in user. We have basically everything we need to begin working with our customized functionality.

    To get this far we have made the following assumptions:

    1. Your repository works.
    2. You have an ASP.Net MVC application in otherwise working order.
    3. You have downloaded and referenced the Ninject libraries.

    In Part 3 we will look at our application controllers and views, and then explore what we can do to provide customized functionality to our users.

    Posted in .NET Framework, Enterprise .NET, General | Tagged , , , | 3 Comments

    Multi Tenant Architecture via Dependency Injection: Part 1

    Chances are, if you’ve been developing web applications for a number of years, you’ve noticed a few ways of provisioning your application for your users.

    1. Your users all log into a single codebase. It might be load balanced, cached, the whole nine yards, but everybody is on the same build and accesses the same data.
    2. Your users log into multiple codebases and/or multiple databases. Perhaps you have some high-powered customers who want custom functionality, and so you forked your codebase and created them their own functionality. Most likely, you can update your customer’s builds independently of one another.
    3. Your users all log into a single codebase, but you use flags, connection strings, config files, etc., to logically separate out your users from one another. Your high-powered customers see their custom functionality, but it’s part of the main codebase and you are able to update your application in one fell swoop.

    We’re going to talk more about option #3 — the Multi-Tenant Architecture. There is PLENTY of reading material out there for you to learn more about multi-tenancy. Suffice it to say that it allows you to satisfy multiple sets of requirements for your multiple customers via one codebase, and your customers, most likely, are logically separate in the database(i.e. they use one schema and one top-level data store) instead of physically separate.

    In the past, (and present, for novice developers), it was a usual practice to utililze config files, database flags, etc., to turn on and off functionality. Your code may have looked something like:

    <% if (showThisFunctionality) %>
    <-- this widget is shown -->;
    <% else %>;
    <-- this other widget is shown -->
    <% end if %>
    

    Fig 1: Classic ASP

    By utilizing a dependency injection framework you can provide features to your users, based on configuration and setup, without having to use logic switches inside of your application. This is above and beyond the existing benefits of using a dependency injection framework, which is not the scope of this essay but can be enumerated here, for instance. Our example will use Ninject and ASP.NET MVC, although you could use any DI and application frameworks.

    Our challenge for this example will be to:

    1. dynamically set which service object(s) we are using to perform our application logic
    2. dynamically set which view we are returning
    3. dynamically set which partial views we are using

    Our example will utilize dependency injection to provide order fulfillment functionality for our customers. For goal #1, we will use Ninject's MVC integration to provide service objects for our controllers. Once Ninject is wired up, we can have our service objects perform our application logic against our Model, and as a matter of fact, Behavioral design patterns are a good fit here. Goal #2 is achievable fairly easily with ASP.Net MVC. Setting which view you're returning via any MVC framework is often a very simple operation and comes down to returning a string variable which represents the view in question. For ASP.NET MVC we can 'returnView("viewName")' where "viewName" is the name of the view we wish to return. There is also the obvious "return View(viewNameVariable)" override. Our example will use a configuration object to set which view is being called. Accomplishing goal #3 can be thought of as an extension of #2, but "finer grained". Where you have general and reusable functionality within your view, your partial views allow you to have specific customizations exposed to your user in a consistent fashion.

    In Part 2 we will investigate both integrating Ninject with ASP.Net MVC as well as what shape our framework will take. In Part 3 we will finish up our framework architecture and explore how to use it to provide features to our users.

    Posted in .NET Framework, Enterprise .NET, General | Tagged , , , | 2 Comments

    Intro to PLINQ

    I recently had the opportunity to attend the Microsoft launch event for the new Visual Studio 2010. I was impressed with everything 2010 is bringing to the table, but what really caught my eye is the new Parallel FX library. Parallel FX provides developers with a set of tools which promises faster and less error prone development of multi-threaded applications. For this post I’m going to focus in on the new parallel LINQ, also known as PLINQ (which reminds me of Plinko every time I hear it).

    For those of you who aren’t familiar with LINQ, I’ll try to sum it up in a few sentences. LINQ stands for language-integrated query. It provides .Net developers with a new syntax which makes performing set based operations on a collection, or multiple collections easier. For example, if we have an unordered list of integers which we need to sort, in the past we would have to do something similar to this:

    public void RunSort()
    {
      var integerList = new List<int> { 5, 63, 23, 1, 0, 91 };
      QuickSort(0, integerList.Count, integerList);
    }
    
    public void QuickSort(int left, int right, IList<int> integerList)
    {
      var pivot = integerList[left];
    
      while (left < right)
      {
        while ((integerList[right] >= pivot) && (left < right))
        {
          right--;
        }
    
        if (left != right)
        {
          integerList[left] = integerList[right];
          left++;
        }
    
        while ((integerList[left] <= pivot) && (left < right))
        {
          left++;
        }
    
        if (left == right) continue;
        integerList[right] = integerList[left];
        right--;
      }
    
      integerList[left] = pivot;
      pivot = left;
    
      if (left < pivot)
      {
        QuickSort(left, pivot - 1, integerList);
      }
    
      if (right > pivot)
      {
        QuickSort(pivot + 1, right, integerList);
      }
    }
    

    The above example works fine, however as a developer we needed to make the decision of what sorting algorithm to use, and then go ahead and implement the sorting function. This wastes time and can sometimes be error prone. LINQ can solve this problem, and many other set based problems like it quickly and efficiently. Here is an example of the first example re-written to make use of LINQ:

    public void RunSort()
    {
        var integerList = new List { 5, 63, 23, 1, 0, 91 };
        var sortedIntegerList = from integer in integerList
                                orderby integer ascending
                                select integer;
    }
    

    LINQ takes care of the sorting here for us and provides a nice, easy to read syntax. When using LINQ, we can worry less about the details of working with data sets, and focus more about the business rules we are implementing. PLINQ takes LINQ a step further and extends this powerful set based functionality to take advantage of multi-core CPU’s. Here is an example of the second example converted to use PLINQ:

    public void RunSort()
    {
        var integerList = new List { 5, 63, 23, 1, 0, 91 };
        var sortedIntegerList = from integer in integerList.AsParallel()
                                orderby integer ascending
                                select integer;
    }
    

    When comparing the above example with the second example, only a couple of things have changed. One is obvious just by looking at the code. We are now calling the extension method .AsParallel on the list of integers. This tells PLINQ that it is OK to go ahead and try to parallelize the LINQ query. The second is a little more subtle. Instead of the LINQ query returning an IEnumerable type, it is returning an IParallelEnumerable. Luckily, IParallelEnumerable derives from IEnumerable, so existing code should work fine with this change.

    This is of course a very basic example of how LINQ and PLINQ differ. But hopefully I’ve sparked some interest.

    -Jon

    Posted in .NET Framework, Enterprise .NET | Tagged , , , | Leave a comment

    jQuery Part 2: More jQuery Basics

    Introduction

    Welcome to the second part of my overview of jQuery. This article is part of a 3 part series. If you did not read the first article, you may want to go back and read that first. This article is going to pick up where the last article left have and cover more jQuery basics. Specifically, the events and effects functionality will be discussed. Afterwords, I will show some example code that utilizes many of the techniques that we have learned.

    Events

    Event handling can sometimes be a problem when developing cross-browser applications. There are often at least two different ways of doing things depending on which browser is being used. jQuery helps us by abstracting the event handling logic. Behind the scenes jQuery will use feature detection to figure out which browser the code is being run on and then utilize the appropriate functionality for the specific browser. The user of the library is presented with a single, clean, unified API that they can use to add event handling to any element on the page in a cross browser fashion. The first of these functions that I am going to cover is the bind function. This function accepts two arguments; a string containing the type of event, and a function to handle the event. Multiple event handlers can be bound to an element this way. Here is an example:

    $('#myButton').bind('click', function() {
      $('p').css('color', 'red');
    });
    

    This code finds the element with an id of “myButton” and adds an event handler to it. The handler, when the element is clicked, will find all paragraph elements and make their text a red color. If you wish to remove an event handler from an element, you can use the unbind function. There are many useful overloads of the function. If you pass it no parameters then it will remove all events from the selected elements. If you pass it the name of the event it will remove all handlers for that event type. If you pass it the name of the event and the handler function it will remove only that handler from the element. If we run the follow code then the button will no longer respond to the click event we set up previously.

    $('#myButton').unbind('click');
    

    jQuery also provides shortcuts for most of the events. Instead of using the bind function you can use a specialized event function. An example of this is the click function. It takes a handler function as its sole argument. Here is a copy of the above code using the click function instead of bind:

    $('#myButton').click(function() {
      $('p').css('color', 'red');
    });
    

    All event handlers can optionally take in an argument of the event object. The event object also has cross browser differences. jQuery creates a cross-browser version of the event object for us to use in our handlers. The details of this object are described on the jQuery website.

    Effects

    Another cool feature of jQuery is its support for effects. jQuery provides a handful of simple effects out of the box, but allows for extending the library by adding new effects. We will cover a couple effects in this article. The hide and show effects can be used to make elements on the page appear and disappear. At their simplest they take no arguments, and when called simply make the element appear or disappear from the page. You can also pass them a number specifying the milliseconds that the effect should take. When a number is provided, the element will shrink in size while also becoming transparent until it disappears from the screen if using hide, or will appear on the screen and grow in size and opacity if using show. Here is a demo:

    $('img.hideable').click(function() {
      $(this).hide(2000);
    });
    $('#myButton').click(function() {
      $('img.hideable').show();
    });
    

    This demo selects all images with class “hideable” and assigns a click handler to them. If they are clicked on the will disappear from the screen over a two second interval. Because a time is given the image will shrink and become transparent over the time period. A click handler is also assigned to a button. When clicked it will make the image appear on the screen (if hidden). It is not passed a number so it will appear instantly. Another useful function is the toggle function. When used it will cause an element to appear if hidden, or disappear if visible. It also can take a time value. It is demonstrated below:

    $('#myButton').click(function() {
      $('img.magic').toggle(3000);
    });
    

    When the button is clicked the images with class “magic” either appear or disappear, depending on their current state. There are other available effects such as slideUp, slideDown, fadeIn, and fadeOut. If you wish to make more complex animations you can use the animate function which allows very fine control. You can read about all of these on the jQuery website and many other effects exist on the plugins page of the site.

    Example

    Now it is time to look at a complete example. You can download a zip file containing all of the source code here. In this example we are going to create a simple page containing nested lists. The levels of the list will be able to expand or collapse when clicked on. If there is no sublist under the current list element, then clicking on the element will do nothing. Here is the code for the HTML page:

    <html>
      <head>
        <title>jQuery Part 1 Example</title>
        <link rel="stylesheet" type="text/css"
              href="jQueryExample1.css" />
        <script type="text/javascript" src="jquery-1.4.2.min.js">
        </script>
        <script type="text/javascript" src="jQueryExample1.js">
        </script>
      </head>
      <body>
        <h1>jQuery Part 1 Example</h1>
        <p>Here is a list containing other nested lists.
             We can use jQuery to hide or show the list
             elements.</p>
        <ul>
          <li>
            jQuery Part 1: The Basics
            <ul>
              <li>
                Introduction
                <ul>
                  <li>What is jQuery?</li>
                  <li>Where to Get jQuery</li>
                </ul>
              </li>
              <li>
                Core jQuery
                <ul>
                  <li>Selectors</li>
                  <li>The Wrapped Set</li>
                  <li>The jQuery Function</li>
                  <li>Traversing the DOM</li>
                  <li>
                    Manipulation
                    <ul>
                      <li>Attributes</li>
                      <li>CSS</li>
                      <li>Other</li>
                    </ul>
                  </li>
                </ul>
              </li>
              <li>Events</li>
              <li>Effects</li>
              <li>Example</li>
              <li>
                Conclusion
                <ul>
                  <li>Summary</li>
                  <li>
                    Want To Learn More?
                    <ul>
                      <li>Next Article</li>
                      <li>jQuery.com</li>
                      <li>jQuery In Action</li>
                    </ul>
                  </li>
                </ul>
              </li>
            </ul>
          </li>
        </ul>
      </body>
    </html>
    

    And here is the JavaScript code for the example:

    $(function() {
      $('li &gt; ul').hide().each(function() {
        var sublist = this;
        $(this).parent().addClass('collapsed').click(function(event) {
          if (this == event.target) {
            $(this).toggleClass('collapsed expanded');
            $(sublist).toggle(1000);
          }
        });
      });
      $('li:not(:has(ul))').removeClass('collapsed
                                         expanded').addClass('leaf');
    });
    

    You will see that the HTML for the example is very clean. All styles are in an external stylesheet (not shown, but included in the download) and all the Javascript is in a separate file. The jQuery code starts with the jQuery function setting up a function to be run when the page is ready. We first select all of the ul elements on the page that are children of li elements. These are the sublists. We call the hide function to immediately hide the sublists. Next we use the each function to run code on each element of the wrapped set. The first thing we do inside of the each is set a variable called sublist to the current element (using ‘this’). This allows us to create a closure to access the element from within event handlers defined below it.

    Next, we get the parents of the wrapped set elements and make a wrapped set out of them using the parent function. This set contains the li elements that the sublists reside in. We then add a class called “collapsed” to the li elements. This refers to a style declared in the external stylesheet that makes the bullet for the li element into a plus sign. This makes it easier to see that the list can be expanded at this point. We create a click handler for the li elements which first check if the element handling the event is the actual element that was clicked. This is done to ensure that no other elements respond to the event when the event is bubbling up or down the DOM. Next we use the toggleClass function to set the class to either collapsed or expanded. We also use the toggle function to toggle the visibility of the sublist of that element. Finally, in a completely new jQuery statement, we select all li elements that do not contain sublists. We remove any existing collapsed or expanded class and add the leaf class to them. This replaces the bullet for the list element with an empty circle. This shows that there is no sublist below this node.

    That’s it! In this small about of code we were able to create some pretty cool functionality. I suggest that you download the code and try it out for yourself. Tweak the code to see what else you can do with it. Have fun!

    Conclusion

    That is all that I am going to cover in this article. We learned about how jQuery handles events as well as how to create some cool effects to liven up your page. Finally, we went through an example that brought everything we learned together.

    Want to Learn More?

    The next and final article in this series will cover some advanced jQuery functionality. I will be covering the topics of ajax, utilities, and plugins, as well as another exciting example! Again, keep in mind that I am only covering a very small subset of what is available in the jQuery library. I suggest you check out the jQuery documentation page at jQuery.com. The documentation for jQuery is excellent and provides many useful examples. I also recommend jQuery In Action by Bear Bibeault and Yehuda Katz. It is an excellent book and worth checking out. I hope you enjoyed this article. The next part should be out within the next couple of weeks.

    -Dylan

    Posted in JavaScript, jQuery | Tagged , | Leave a comment

    The Unstandard Tag Library: Using Constants Within JSPs

    Introduction

    The Unstandard Tag Library is a JSP tag library that was developed as part of the Jakarta Project. Its purpose is to provide a collection of useful tags that people have been requesting for JSTL. The library serves as a place to keep all of these tags until they are officially added to the Standard Tag Library. This article focuses on the use of one of the tags contained within the library, the useConstants tag.

    The Problem

    While working on a project for a client, I realized that they were using a Java class with constants to define strings used within the application. The idea was to use the constants everywhere in the application where the strings were needed so they could easily be maintained in one location without having to search through the whole application when making a change. This makes sense, and is a common best practice. I was working on a JSP page that needed to use the constants from the class. It is now considered bad practice to use Java Scriptlets in your JSP page. It is much better to use the Expression Language (EL) in combination with JSTL and other custom tags. Trying to keep to this rule I quickly ran into a problem. The EL does not allow and easy way to access constants from a Java class. That is where the Unstandard Tag Library’s useConstants tag comes in handy.

    How To Use It

    Once you have added the library to your project it is very simple to use. Let’s assume we have a java class containing constants such as the one below:

    package com.tallan.unstandard;  
    
    public class MyConstants {    
    
      public static final String MY_CONSTANT_1 = 'Hello World';
      public static final String MY_CONSTANT_2 = 'Goodbye World';  
    
    }
    

    Let’s also assume that we added the tag library to our page as follows:

    <%@ taglib uri="http://jakarta.apache.org/taglibs/unstandard-1.0"
               prefix="un"%>
    

    We can then utilize the useConstants tag as follows:

    <un:useConstants var="Constants"
                     className="com.tallan.unstandard.MyConstants" />
    

    After we run this line of code, an object called Constants will be available for use on the page. We can use it with the EL and access the constants as properties of the object. For example:

    <p>${Constants.MY_CONSTANT_1}</p>
    

    This solves our problem of using constants from a Java class within a JSP page without relying on scriptlets.

    Where To Get It

    You may be thinking “This is great, but where can I find this library?” Unfortunately the Jakarta project has stopped development of the library and no longer makes it obvious where you can get the code. If you look around on the Jakarta site you will find that they allow you to get the project out of source control and build it with Maven, but this is a little bit of a hassle. If you want an easier way to get the library just go here. This site contains old binaries of the library and they should work just fine.

    Conclusion

    The Unstandard Tag Library contains many useful tags that can help in the development of our JSP pages. While it is no longer being actively developed, it can still be a very useful tool. We covered how to access constants from a Java class using the library’s useConstants tag.

    Want to Learn More?

    If you want to learn more about the tags available in the Unstandard Tag Library and how to use them, then head over to the documentation page for the library located here.

    Posted in Enterprise Java | Tagged , | Leave a comment

    jQuery Part 1: jQuery Basics

    Introduction

    Welcome to my first blog post on the topic of jQuery. This is the first part of a three part series. This post will cover most of the basic features of jQuery. Then next post will wrap up the basic jQuery features and go through an example using what we learned. The final post will cover jQuery’s more advanced features and include another example.

    What is jQuery?

    jQuery is a Javascript library. At its core, jQuery enables authors to easily select and manipulate the elements of an HTML page. But jQuery is much more than just that. jQuery was designed for extension. There are over a thousand plugins available for jQuery with functionality ranging from rich UI features to Ajax. With all of this power it is easy to see why jQuery has become one of the web’s most loved Javascript libraries.

    Where to Get jQuery

    jQuery is available for download from jQuery.com. You can download the library right from the home page. There are two versions available. The production version has a tiny footprint of just 24KB! The code has been compressed though, so if you feel like reading through the actual library code to see how jQuery works then you should download the development version. Once you download the library, simply add the script reference to your HTML file and you are good to go!

    Core jQuery

    Selectors

    The central feature of jQuery is its ability to make finding the elements that you want to manipulate ridiculously easy. To find elements jQuery uses something called a selector. These are the same selectors that are available in CSS, so if you already know how to use CSS (If you don’t, then you should learn!) then you will be able to directly apply your knowledge to jQuery. For those of you who don’t know CSS, a selector is, in essence, a string that defines a pattern that identifies a set of elements that you would like to apply a style to or, in the case of jQuery, manipulate with Javascript. The selectors available in jQuery are very powerful and allow you to easily apply your code to whatever elements you like.

    There are many types of selectors. The most simple specify an HTML tag. For example, the selector img will match all image elements in the HTML. Other common types of selectors include:

    #identifier
    This will match all elements that have an id of the whatever follows the number sign (if you are following the rules of valid HTML, you should only have one element on the page per id)
    .class
    This will match all elements that have a class of whatever follows the period
    *
    This will match any element

    You can also combine selectors:

    img, p
    A comma between selectors will allow you to match many patterns. In this example we are matching any images AND any paragraph elements
    div p
    If a space separates selectors then it will match any element hierarchy that matches the pattern. An element following the space does not have to be a direct descendant of the previous element, but can also be any generation of descendant (for example, a grandchild) of the preceding element. In this example, we will match any paragraphs that are located somewhere within a div element
    div > p
    Using the greater than sign is similar to using a space, except the element on the right must be a direct child of the element on the left. In this example we are matching all paragraphs that are directly below the div tag in the hierarchy
    div.myClass
    You can combine an html element with the class syntax to specify the HTML element must have the class given. In this example, We are selecting all div elements with a class of “myClass”.

    jQuery selectors also include ways to filter the match:

    div:has(p)
    This will match only divs that contain a paragraph element somewhere within its descendent hierarchy.
    div:not(:has(p))
    This will match only divs that do not contain a paragraph element somewhere within its descendent hierarchy

    This is only the tip of the iceberg. jQuery supports many more selectors that allow you have very precise control over which elements you are selecting.

    The jQuery Function

    Now that we have covered selectors, we can talk about the jQuery function. The jQuery function is at the heart of the library and has many overloads. We will be covering two of these overloads. The first overload simply takes in a string containing a selector. This version of the jQuery function uses the selector passed to it to find and return all elements matched by selector. Another overload of the jQuery function takes in a function. The purpose of this overload is to be able to run the code in the passed in function once the DOM tree for the page is ready to be worked with. This works much better than the onready event because, unlike the onready event, this overload of the jQuery function does not need to wait for images or page assets to finish loading. This allows us to work with the page as soon as possible. By default, jQuery gives an alias for the jQuery function. The dollar sign ($) can be used in the place of “jQuery”.

    The Wrapped Set

    You may be wondering what the first version of the jQuery function returns. This functions returns an object called the wrapped set. The wrapped set is essentially an array of all the elements matched by the selector. Most jQuery functions are called upon the wrapped set and commonly returns the wrapped set after the main body of the function runs. This allows jQuery functions to be chained together, making it very easy to accomplish a lot with a single line of code.

    Traversing the DOM

    Sometimes once you have a wrapped set containing a group of DOM elements, you may want to obtain a new wrapped set based on the initial wrapped set. For example, we may want a wrapped set containing all of the parent elements of the elements of the current wrapped set. jQuery provides a number of functions that provide functionality like this. If we wish to obtain a set of all of the parent elements of all of the paragraph elements on the page we would write: $(‘p’).parent(). The first part of this statement uses the dollar sign alias of the jQuery function to find all of the paragraph elements on the page. Next, the parent function is called on the wrapped set of paragraphs and returns a wrapped set of all of the parent elements of the paragraphs.

    Manipulation

    Now that we can find the elements that we are interested in, what can we do with them?

    Manipulating Attributes

    jQuery provides functions which allow you to manipulate the attributes of wrapped set elements easily. If we wish to read the value of an attribute we can use the attr function. The attr function takes in a string of the attribute name and returns the value of the attribute for the first element of the wrapped set. An overload of the attr function allows you to set the value of an attribute for all elements of the wrapped set. This is done by passing a second argument containing the value. For example, if we wish to set the alt attribute of an image with an id of “myImage” to the value of the image’s title attribute we would write: $(‘#myImage’).attr(‘alt’, $(‘#myImage’).attr(‘title’)). If you wish to do this for each member of the wrapped set instead of just the first we can take advantage of the each function. The each function allows you to define a function that will be run on each element of the wrapped set. Within the function, the “this” keyword refers to the element. For example:

    $('img').each(function() {
      $(this).attr('alt', $(this).attr('title'));
    });
    

    This code will take all the images on the page and set their alt attribute to the value of their title attribute.

    Manipulating CSS

    jQuery also allows you to easily work with the styling of the elements of the wrapped set. We will cover four functions: css, addClass, removeClass, and toggleClass. The css function works similarly to the way the attr function works. Passing it the name of a CSS property will return the value of the property for that element. Passing it the name of the CSS property and a value will set the property to that value for the element. For example, $(‘div.special’).css(‘color’, ‘red’) sets the text within all div elements with class “special” to a red color.

    The addClass function allows you to add classes to HTML elements. The function accepts a string containing a space separated list of classes that you wish to add to the element. For example, $(‘div:has(p)’).addClass(’special’) will add the class “special” to all div elements that have a paragraph element within them. If the class already is associated with the element then nothing happens. The removeClass function is similar to addClass. It also accecpts a space separated string of classes. The classes you pass to the function will be removed if they are declared on the element. The toggleClass function will either remove a class from the element if it exists on the element or it will add a class to the element if it does not already exist on the element. Assuming we have a div with class “bad” and id “myDiv”, if we run the code $(‘#myDiv’).toggleClass(‘bad good’) then we will remove the bad class form the div and add the good class to the div.

    Other Manipulation

    Sometimes we may wish to manipulate the position of elements within the DOM. One example of this is the append function. This function will append an element to the end of the children of the selected element in the wrapped set. The overload we will be covering takes a single string containing valid HTML tags. The DOM objects for the HTML you specify will be generated and appended onto the elements you specify in the wrapped set. Take a look at this example: $(‘div.myClass > ul’).append(‘<li>New item</li>’). This code will append a new list element onto any unordered list that is a direct child of a div element with class “myClass”.

    Conclusion

    That’s about all that I am going to cover for now. We looked at the core features of jQuery that allow us to find elements on the page based on the power of CSS selectors as well as many functions that operate on the elements in the wrapped set. These functions allow us to easily manipulate any element on our page.

    Want to Learn More?

    If you want to learn more jQuery, be sure to read that next part of this article. I will be covering the topics of events and effects, as well as showing a fun example demonstrating all of the skills we have learned. Keep in mind that I am only covering a very small subset of what is available in the jQuery library. I suggest you check out the jQuery documentation page at jQuery.com. The documentation for jQuery is excellent and provides many useful examples. If books are more your style then I would strongly recommend the book jQuery In Action by Bear Bibeault and Yehuda Katz. I have read through the entire first edition of the book and it was very helpful. The second edition just came out and it looks very similar except that it contains much more coverage of the jQuery UI plugin (which will be covered a little in Part 3 of this article). You should definitely check it out. The next part of this article should be posted soon. See you then!

    Posted in JavaScript, jQuery | Tagged , | Leave a comment