Sunday, December 20, 2009

Holiday Reminder: Keep your Web Best Practices sharp!

As we near the end of the year and bump up next to all the hustle and bustle of holiday shopping, professional golfer scandals, dealing with those crazy family members, and over-eating, we find ourselves being a little less focused at work.  This is a universal truth no matter how much you or your manager don’t want to admit it. 

I wanted to take an evening to remind you of all those great web principles that we tend to lose sight of as we get pre-occupied with our daily lives.  So who cares, right?  Well, a lot of people that you never met and likely will never meet.  The web is something that I’ve found many developers take for granted.  We forget how the fancy IDEs and RAD development tools can lead us towards lazy and often inconsiderate programming, no matter how unintentional it is.

If I can be allowed to stereotype based on my experiences, the typical web developer is focused on three things…

  1. Does the site functionally meet the requirements?
  2. Is it visually attractive? (or what I refer to it as the “good enough” approach)
  3. Was it completed on time?

The BIG picture

We need to care about the people that utilize our web applications and resources.  As a human being, its hard to think about but everyday there are people who are born with or develop physical challenges that require us, as web developers, to provide accessible ways for them to utilize the web.  I can’t express to you how often I hear the statement, “It doesn’t matter, this screen is only accessed by our internal staff.”.   Believe it or not, internal staff is no different than external users in that regard and therefore everyone should be given the same considerations.  We shouldn’t have to be told to support this segment of our user base.  We should want to!

What is the right approach?

  1. Be knowledgeable about accessible development (we will talk about some of these techniques down below)
  2. Don’t forget the following rule… It takes longer to do things right than it does to do things wrong.  Include the extra time in your estimates and make sure your efforts are known and understood.  The typical user will likely not know the effort you put into this unless you inform them. 
  3. Develop an implementation strategy and ensure your development team is on the same page.
  4. Introduce accessibility test into your code reviews and QA testing
  5. Maintain it.  As development staff changes and subsequent phases of the project are implemented, processes either become stronger and more disciplined or they break down.  Make sure you aren’t allowing it to break down.

Accessible Development Principles

  1. Write well-formed markup.  Sloppy markup such as opening tags without closing tags may render fine in Internet Explorer but some screen reading software may not be as flexible preventing certain users from using your site.

  2. Markup was designed with a purpose.  Use (X)HTML tags in they way they were specified.  This is especially important when developing HTML forms but should be applied to the entire page.  This is an example that I see a lot… 

    DO THIS
    <label for=”firstName”>First Name</label>
    <input type=”text” id=”firstName” name=”firstName” />

    NOT THIS
    <span>First Name</span>
    <input type=”text” id=”firstName” name=”firstName” />

    Another example …

    DO THIS (note: in real-world apps, don’t use inline styles when not necessary)
    <h1 style=”text-indent: –9999px; display: block; height: 100px; width: 200px; background: transparent url(logo.png) top left”>My Cool Website Title</h1>

    NOT THIS
    <img src=”logo.png” height=”100” width=”200” />

    There are many examples of misused markup usage beyond these two.  If you write HTML then know HTML.  Secondly, don’t focus on using tags because they render a certain way.  That is what CSS is for.  Remember, HTML is for structure and content definition and CSS is for presentation.  Keep them separate.

  3. Take a stance against table based layouts.  This goes very closely with the second development principle listed but I think this is such a huge problem that it deserves its own bullet point.  Tables are meant to be used for tabular data not site presentation.  When used to layout a web page, it creates confusion among accessibility software and makes pages less functional across media types such as print, braille, and screen.

  4. Provide tags such as caption or title and attributes such as alt and title when appropriate with verbose text.

  5. Avoid using elements and text which assume visual context to understand.  This can be something such as a link that says “click here”.  When accessibility screen readers parse and read the contents of your page back to the user, it becomes quite obvious that there is no clear understanding of where “here” is.

  6. Create pages that gracefully degrade without JavaScript enabled or provide alternate views that don’t contain client side programming.  Some accessibility tools aren’t able to process JavaScript thus making your application not usable.  This is a very good practice regardless of accessibility.

  7. No surprises.  When users have partial vision related impairments, it isn’t easy to recognize things that may be hiding/showing or changing in subtle ways such as normal to italic font.  Also create common user interface elements for navigation menus, headings, links, and buttons.

  8. Keep your designs minimalistic if possible.  This is very much a web 2.0 trend from a design perspective but it helps users identify content quickly and use the site much more effectively than one filled with excessive graphics or flashy content.

  9. Use CSS rules for appropriate media types.  Did you know that there is a media type of “braille” for tactile output devices?  Print versions of your site are important as well.  Make sure your site is very easy to read and consistent in its printed form.

  10. Describe your page and provide keywords about it.  Not only does this help with SEO to some degree but it also helps clarify the pages content to screens.

  11. Make sure you use HTTP GET and POST appropriately.  Certain web technologies like ASP.NET are extremely POST heavy when not being disciplined about the intentions of actions on your site.  Choosing the wrong method could present usability challenges when trying to navigate back and forth.  We’ve all received the “Page has Expired” message before when trying to go back after a POST.  This is an important feature but also can be extremely frustrating when your POST action didn’t really do anything POST-worthy.  (note: If you aren’t familiar with when do use which method, do a quick Google search as there is a slew of material on the subject)

Wrapping Up

I really hope I helped put some perspective around developing web software with accessibility in mind.  It is something most developers and business stakeholders don’t fully appreciate until it directly affects them.  The point of this post is to really emphasize that it doesn’t have to directly affect you to make a difference.  It is really important to me as I enter this holiday season thinking about ways to help out my fellow man and as a developer, this is one way I know I can make people’s lives and the web a better place. 

I would love to hear other people’s techniques on accessibility and help make this post a great resource for people looking to improve their development techniques.  Happy Holidays!

Tuesday, December 15, 2009

Are Google's Android OS and SDK ready for prime time?

Ever since Google's Android OS was announced, I had mild interest but admittedly jumped on the Apple iPhone bandwagon and never really stopped to take a peek at Google's offering. Well, today was that day. Let's be honest with each other, Apple has dominated the marketplace and its App Store has exploded with popularity (perhaps to over-saturation). Maybe I decided to take a look cause of all the DROID commercials flashed into my brain or maybe I just wanted to rejuvenate my Java skills after taking a lengthy hiatus to focus on .NET. Truth be told, I’m not sure why I went to Android but I’m glad I did.

No hate here for iPhone (or other technologies)

I'm not going to really go into details about the iPhone SDK and comparing each other. I will say that I found Objective-C to be a strange syntax to get used to but the SDK and tools were manageable. Ultimately I'd have to agree with other developers on the point that Apple has created an SDK that is generally clean and promotes ease of development.

Android is impressive

So why develop for Android? I don't own an Android-enabled device at the moment but I fired up the Virtual Device (Android emulator) and just explored the capabilities. I thought it was a very impressive piece of software. I was excited to start cranking out code. The user interface is beautiful and provided a more desktop like environment with a large Google search box shining brightly at the top. There is a main slide-up menu that pretty much provides access to your applications, settings, etc... much like the home screen on iPhone. I did really like the ability to add widgets to the desktop and application shortcuts wherever I wanted.

Robust SDK

Android has called upon the Eclipse IDE to house its development plug-ins. If you aren't familiar with Eclipse, it is a very popular choice among J2EE developers but is essentially an open IDE for other languages and tools to build upon (i.e., Adobe's Flex Builder is built upon Eclipse as well).


Android Eclipse Tools and Virtual Device

The Android development environment allows for debugging capabilities as well as targeting various versions of their APIs from 1.1 to 2.0.1 presently.

All you need to get setup to start development for Android on Windows is:
From there, setting up everything is just as follows:
  1. Simply download and extract the Eclipse software. (Note: There is no installer so make sure you put the extracted files in a place that best suits you.  I usually copy the eclipse folder into C:\Program Files\ and make a shortcut within my Programs list.)

  2. Open Eclipse and choose Help > Install New Software and then paste the following URL into the displayed dialog.  Select the Development Tools and then follow through the steps to install them.

  3. https://dl-ssl.google.com/android/eclipse/

    adt install
  4. Restart Eclipse

  5. Extract the downloaded Android SDK from the link about and then run Setup_SDK.exe.  This will install the SDK.

  6. Go to Eclipse and choose Windows > Preferences.  Locate the Android preferences and specify the path to the SDK if it isn’t listed.  That is it!  You are ready to start developing.

Programming

While I could write some tutorials on how to program Android, I think Google has provided great documentation and some sample applications to help get started.  I would suggest if you haven’t done any Java programming before that you read a primer and do some basic sample applications (non-Android) before jumping into to the SDK.

Check out some of their sample applications and how to get a basic Hello World going here.  This is a “first impressions” post so after I get more experienced with the Android APIs, I’ll begin to post more tutorials on best practices and techniques.

Final thoughts

At a high level, the reasons I would suggest to you to get into Android is…

  • Google isn’t going anywhere in the foreseeable future and is finally releasing their own phone that will be a pure Google vision of the Android OS.  Android is out to compete and it can provide capabilities beyond what the iPhone currently offers.

  • XML based views make programming views very easily (especially if you are a web or Flex developer).  They are backed by an Activity API that reminds me in some ways to an ASP.NET or Flex code-behind file.  Strongly typed resource files make internationalization and externalization easy to work with from the start.

  • Strongly proven programming language and runtime backed by a popular IDE.  Java has been around for quite some time and a great competitor to take on Apple and its Objective-C counterpart.

  • A young marketplace.  If you are looking to get into the mobile application space with the hopes of making a few bucks, this could be the next best opportunity if you have a fantastic idea.  Unfortunately, the time is gone where thinking you can retire from an iPhone venture is possible. 

  • You don't need to rush out and buy a Mac. Multiple platforms are supported
Enjoy!  I look forward to hearing about your experiences with Android!

Sunday, December 13, 2009

Blogging with Code Snippets using Windows Live Writer

Microsoft recently released a tool called Windows Live Writer.  While many bloggers pretty much need only images and text, technical posts often require inserting samples of source code.  Quite frankly, I personally hate reading posts that have source code displayed as images because I want to copy and paste it so that I can try out whatever I’m reading about.  

Windows Live Writer allows plug-ins to be installed to enhance your blog.  I came across one that enables you to paste source code snippets from Visual Studio into your blog.  You can download the “Paste From Visual Studio” plug-in at http://gallery.live.com/liveItemDetail.aspx?li=d8835a5e-28da-4242-82eb-e1a006b083b9&bt=9&pl=8

Here is an example of some source code pasted from Visual Studio using Windows Live Writer and the “Paste From Visual Studio” plug-in.

private void RegisterRoutes(RouteCollection routes)
{
routes.Add(new Route
(
"home",
new WebFormRouteHandler("~/Default.aspx")
));
}

As you can see the syntax color is maintained as well as indentations.  The only issue I’ve seen with it as that pasting ASP.NET markup seems to not function but to me this is still a huge time saver.  Enjoy!

Microsoft Office: Can't find those old menu commands in the new Office ribbon? Problem solved!

When Microsoft Office 2007 was released, some were furious and many were warming up to the new Ribbon interface. While each camp presents reasons for or against it, it seems that Microsoft hasn't been ready to abandon their innovative design.

While I was installing Microsoft Office 2010 Beta, I ran across an online resource that shows end-users just exactly where those old trustworthy menu commands have been moved to in the Ribbon interface. The best part about it is that it is fully interactive.

This is a must have guide for users who loved the menus but haven't quite got comfortable with the Ribbon interface. Check it out at the following links and click "Start the Guide"...
Note: If you are in the 1% of users that doesn't have Adobe Flash installed, you'll need to borrow someone's computer or install it before you can view them.

Thursday, December 10, 2009

NHibernate: Better Criteria API Usage with T4 Templates

UPDATE 12/22/09 - The mapping file and T4 template code have been updated to reflect a more typical NHibernate mapping file which contains the XML namespace attribute of the <hibernate-mapping> element.


In this post, we are going to take a look at NHibernate's Criteria API and see how T4 templates, which are built into Visual Studio 2008, can help create clean queries and reduce your application's technical debt.

Before we begin

NHibernate is a very powerful object-relational mapping (ORM) library that was ported from the Hibernate library for Java EE to .NET. If you aren't familiar with the core principles of NHibernate or any ORM, I suggest you read more about it here.

Also, it doesn't hurt to have a little background on what a T4 template is. A simple Google search for "Visual Studio T4 Templates" can deliver you plenty of information about the technology.

The problem

NHibernate provides a set of APIs for querying data and getting results back as fully hydrated entities. This is called the Criteria API (or sometimes referred to as ICriteria since this is the interface type that is usually being worked with).

Criteria was written with the mindset that you are invoking methods and passing string representations of your entity's associations and properties (not database columns or tables). These are then used under-the-hood to create SQL statements based on your entity's mapping file.

A simple demonstration

To better explain the issue, let's create a table called Employee as defined below.



A simple SQL Statement to retrieve all the users who were named John and 65 or older would be
SELECT EmployeeID, Name, Age, Title 
FROM Employee 
WHERE Age >= 65 AND Name LIKE 'John%'
Now lets write this using NHibernate's Criteria API that will give us back the same results as hydrated Employee entities.
//get NHibernate session instance somehow
ISession session = this.GetNHibernateSession();
ICriteria criteria = session.CreateCriteria<Employee>();

criteria.Add(Expression.Ge("Age", 65));
criteria.Add(Expression.Like("Name", "John", MatchMode.End));
IList<Employee> employeesAtRetirementAge = criteria.List<Employee>();
Did you see how we had to specify our Age and Name property as a string? Yuck!

At this point, you may be thinking "what is the big deal?". Well, often with simple examples its difficult to fully appreciate the impact on maintenance but as your application scales out to several entities, many queries, and multiple design changes later you will find that keeping all that in sync can be cumbersome. Even further, having multiple hardcoded strings can introduce typos that just stand in your way of getting the job done.

So lets say you've coded this but a few weeks later when code reviews are being done, someone on your team tells you that "Name" is too ambigous and should be changed to "FullName" for clarity (yes this scenario is silly but lets go with it).

Wouldn't it be nice to not have to go find all the places you've hard coded "Name" and fix them or worry about making typos?

The solution

We are going to solve this by writing a T4 template that will read through our Employee.hbm.xml file and generate a static metadata class for us to use in our Criteria API.

Let's start by creating a new T4 template next to our Employee.cs and Employee.hbm.xml mapping file. Visual Studio doesn't show templates listed in the New Item dialog so I choose "Text File" and then rename it from a .txt to .tt extension.



After it has been added, you will see that a "code generation" file of the same name will be created along with your .tt file. This additional file will contain the code we are going to generate and include in our project.



Before we can write our template code, we need to know exactly what our mapping file looks like. Here is our Employee.hbm.xml. It basically defines our properties and what columns they map to.

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <class name="NHibernateSample.Data.Employee" table="Employee">

        <!-- Primary Key Mapping -->
        <id name="ID" column="EmployeeID" unsaved-value="0">
            <generator class="native" />
        </id>

        <!-- Column Mapping -->
        <property name="Name" column="Name" />
        <property name="Age" column="Age" />
        <property name="Title" column="Title" />
    </class>
</hibernate-mapping>
Now to the good stuff. Here is our definition for our T4 Template which leverages Linq to XML. At the heart, there is one method called ProcessMappingFiles that loops through each mapping file in the specified directory. It then looks for any property definitions and builds out a static string for it.

<#@ template language="c#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Xml.Linq" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Xml.Linq" #>
using System;

<#= ProcessMappingFiles() #>

<#+ 
    private static string ProcessMappingFiles()
    {
        StringBuilder builder = new StringBuilder();
        DirectoryInfo currentPath = new DirectoryInfo(@"C:\NhibernateSample.Data\");
        
        builder.AppendLine("namespace NHibernateSample.Data.Meta");
        builder.AppendLine("{");
        
        foreach (FileInfo file in currentPath.GetFiles("*.hbm.xml"))
        {
            StreamReader reader = new StreamReader(file.FullName);
            XElement xmlReader = XElement.Parse(reader.ReadToEnd());
            XNamespace xmlns = "urn:nhibernate-mapping-2.2";
            
            XElement classElement = xmlReader.Element(xmlns + "class");
            string fullName = classElement.Attribute("name").Value;
            string className = fullName.Substring(fullName.LastIndexOf('.') + 1);
            
            builder.AppendLine(string.Format("\tpublic static class {0}Meta", className));
            builder.AppendLine("\t{");
            
            foreach(XElement element in classElement.Elements(xmlns + "property"))
            {
                builder.AppendLine(string.Format("\t\tpublic static readonly string {0} = \"{0}\"", element.Attribute("name").Value));
            }
            
            builder.AppendLine("\t}");
            builder.AppendLine();
        }    
        
        builder.AppendLine("}");
        return builder.ToString();
    }
#>

Final usage

So you can see in our code snippet below that after we have our template, we can replace our hardcoded strings with a more strongly typed property definition.

//get NHibernate session instance somehow
ISession session = this.GetNHibernateSession();
ICriteria criteria = session.CreateCriteria<Employee>();

criteria.Add(Expression.Ge(EmployeeMeta.Age, 65);
criteria.Add(Expression.Like(EmployeeMeta.Name, "John", MatchMode.End);
IList<Employee> employeesAtRetirementAge = criteria.List<Employee>();
Obviously there is much more to mapping files besides just properties. You can easily extend out the template to parse your associations for usage in Criteria joins or aliases.

That is all there is to it. I encourage NHibernate users that rely on mapping files and ICriteria to give this a shot. I presently use this on my current project and it has saved a ton of time as well as made my code less error prone.

Wednesday, December 9, 2009

Welcome

Hi, my name is Scott Gainous and I'm a .NET developer, architect, and general technology enthusiast. This is my first post just to welcome everyone to my blog and let everyone know what type of posts that you can expect to see from me in the future.

Generally, the reason why I started a blog is not unlike other developers that have similar blogs. I found that I like to be on the bleeding edge of technology and there are advantages and drawbacks to this. As you probably have experienced at some point in your technical career, there are simply problems that you need to solve quickly and there just doesn't seem to be an answer on the web. The reasons are many but often it is because the technology is really new or the issue is so rare that nobody seems to have a good answer. If you do stumble across the answer, its likely because of someone's awesome blog post.

Well to get to the point, the other day at work, I was documenting a solution regarding ASP.NET WebForms (not MVC) and the System.Web.Routing capabilities in .NET 3.5 SP1 and thought to myself, I really need to share my experiences with others. This is exactly what I aim to do. While my blog is called "Ramblings about .NET", I hope to share my knowledge in a variety of areas such as:
  • SharePoint
  • Office
  • ASP.NET
  • Visual Studio
  • Windows
  • NHibernate
  • ...and any other cool things I have to share
I hope you will find my upcoming posts to be informative and generally enjoyable to read. I know I can't wait to hear your feedback and help make technology just a tad less tedious and a lot more exciting.