Wednesday, April 2, 2014

A Crash Course in Responsive Design



Preface

I am presenting this material, not as an expert of responsive design or even in CSS, but simply as a person that has gone through it once.  The main goal is to have a simple tutorial that will be useful to you.  Although I have worked with all layers from the User Interface to the Database Layer; I have always considered myself a back end developer.  This thinking primarily stems from my poor graphical ability.  If I drew you a stick figure, you might have a problem distinguishing what it is.  My handwriting has the readability of Egyptian hieroglyphics.   :)  Despite my shortcomings, this year I have tried my hardest to step into front end design.  Normally I have been on large enterprise application teams with super complex back ends.  That is where I usually thrive.  The user interface didn’t need to be anything but battleship gray because it was used internally with one browser type.  Additionally, we would have a person that would be half graphic designer and half front end CSS designer.  The front end designer would create the graphics, the colors, the CSS sheets, and the rest of the developers would simply use the styles and images that were created.  Things have changed drastically for the web in recent years.  Businesses and users are demanding rich responsive web designs.  If you don’t know responsive design, now is the time to learn it.  All my dress socks are black for a reason.  If I can do this, certainly any developer can do it.  I take that back, I do have one pair of green socks.  The color combinations are always exciting if I accidentally put those on in the dark of the morning.  

What is responsive design?

Responsive design is a technique for dynamically changing the layout of a web site for different browser widths giving priority to the most important content.  Ethan Marcotte coined the term.   He has a short book on the subject which is a must read.   
    
Responsive Design is not about creating a mobile specific site.  You have probably seen that done before; a website that has a desktop version and a mobile version.  There are so many devices being released every year that one cannot hope to have a site that will look good if you target a specific device or group of devices.  We don’t detect devices, we care about widths.  Furthermore, responsive design is less expensive to implement than creating a separate mobile site. 

Browser Compatibility

Responsive Design (specifically CSS Media Queries) work with these browsers:
  • Internet Explorer 9 and higher
  • Firefox 3.5 and higher
  • Safari 3 and higher
  • Chrome (any version)

Implementing Responsive Design Step by Step

1.  Create a base style sheet with the styles needed for desktop, laptops and older browsers.

<link rel="stylesheet" href="base.css">


2.  In the base style sheet, perform a CSS reset so that all modern browsers will render the same.

http://meyerweb.com/eric/tools/css/reset/

 

3.  In the base style sheet, tell images, embed, object, and video to resize to their maximum width.  


By specifying just the max-width, images and videos will keep their aspect ratio when resizing.  When the user shrinks their browser the images will automatically resize when their parent container becomes smaller.

/* Media Resizing */
img, embed, object, video
{
    max-width: 100%;
}




4.  In the base style sheet, make the minimum width for the body 320px.  


This is to prevent the user from resizing their browser smaller than the minimum width.  Set the font-size to 100%. We will need this later.

body {
     min-width: 320px;
     font-size: 100%;
}



5.  Add a meta tag

In your HTML page (or master page), add a meta tag to make the width of the browser port default to the device width with no zoom (scaling):

<meta name="viewport" content="width=device-width, initial-scale=1.0">



6.  Create a media query style sheet:

<link rel="stylesheet" href="mq.css">


7.  Create media query stubs

In the media query style sheet, create media queries based on common ports.  You will have ports in between these to tweak your site to look good in whatever size the user resizes the browser.   

/* Tablet Landscape */
@media screen and (max-width: 1024px) {
}

/* Tablet Portrait */
@media screen and (max-width: 768px) {
}

/* Big Smart Phones */
@media screen and (max-width: 640px) {
}

/* Mobile Landscape */
@media screen and (max-width: 480px) {
}

/* Mobile Portrait  */
@media screen and (max-width: 320px) {
}


8.  Decide what content is important.

Design for mobile first.  Ask, "How does this content or feature benefit our mobile users?"  http://www.lukew.com/ff/entry.asp?1117



9.  Define percentages for all your divs.

Below is the most important formula of your life (well concerning responsive design anyway).  Responsive design is about grid based percentages instead of the traditional fixed widths that you are used to.  You will need to convert fixed widths into percentages.

Result = Target / Context

Let’s say we have a navigation div and a main content div.

<div id="nav">
</div>

<div id="content">
</div>


Our wonderful designer, let's call him Doug, has said that the browser width is 1024 pixels and we have a 100 pixel navigation on the side and 924 pixels for the main content.  We are intentionally ignoring any padding or margin to keep things simple for this example. 

Navigation Percent = 100 / 1024

Main Content Percent = 924 / 1024

You would write something like the media query below, keeping all the decimal places you can from your calculator.  

/* Tablet Landscape */@media screen and (max-width: 1024px) {

     div#nav
     {
          width: 9.765625%;
     }

     div#content
     {
          width: 90.234375%;
     }
}


For nested divs, the context changes.  It would not be the width of the browser, but the width of the parent div.  So if we had a left inner div of 200 pixels and a right inner div of 262 pixels, the parent context would be 924 pixels because the content div is 924 pixels.  It might look like this:


<div id="nav">
</div>


<div id="content">
    <div id="left-content">
    </div>
   
    <div id="right-content">
    </div>
</div>


Here is the formula for the inner divs:

Inner Left Percent = 200 / 924

Inner Right Percent = 262 / 924


This is what we would have for the media query:

/* Tablet Landscape */@media screen and (max-width: 1024px) {

     div#nav
     {
          width: 9.765625%;
     }

     div#content
     {
          width: 90.234375%;
     }
   
     div#left-content {
        width: 21.64502164502165%;
     }
   
     div#right-content {
        width: 28.35497835497835%;
     }
}

10.    The strategy.  

My current strategy for remaining compatible with IE7 and IE8:
a.      Create a base style sheet that is percentage based (it needs to be outside of media queries).
b.      Create media queries from largest port to smallest port, overriding behavior as you get smaller.

11.   Change your fonts to use em-based.  

You are also used to creating fonts in points or pixels.  To make your site truly responsive, use the em-based fonts.  For example, to create a heading that is 3 times as large a normal font, it would be 3 em.  More information on em-based media queries:  www.cloudfour.com

h1
{
    font-size: 3em;
}


If the normal font of your page is 16px and you want a 24px heading do this to convert to ems.  You can leave the comments in there for reference.

h1 { font-size : 1.5em; /* 24px /16px */ }



Tips

  1. Don't use device-width or device-height for media queries.  We want the width of the browser port, not the width of the device.
  2. Use the Chrome Developer tools.  I have found that it is the easiest and fastest to use compared to Firebug and the IE Developer tools.  It is easy to change CSS percentages on the fly to see how it will look.  It updates in real time.  Right click and do an inspect element to see the tools.  Click on the width to change it.  After you are finished with the changes, go to the sources tab, select all and copy it into your development environment (Visual Studio, Eclipse, etc.).
  3. Use this piece of software to see if you converted the percentages correctly.  http://download.cnet.com/Pixel-Ruler/3000-12565_4-75312528.html
  4. Use this to make media queries work in IE5+ Firefox 1+ and Safari http://code.google.com/p/css3-mediaqueries-js/
  5. If you don’t want the older internet explorer to be responsive but you still want your website to render, you might need a separate style sheet for tweaks.  http://css-tricks.com/how-to-create-an-ie-only-stylesheet/

    <!--[if IE 7]>
        <link rel="stylesheet" type="text/css" href="/static/css/ie7.css">
    <![endif]-->
  6. IE10 may still have problems with some rendering.  Here is a workaround for that.  http://css-tricks.com/ie-10-specific-styles/

Example Responsive Design Sites


This is from the alist apart book:
http://responsivewebdesign.com/robot/

This is my first site doing responsive design:
www.kellermansoftware.com

This is my second site doing responsive design:
http://team.eas.com


These sites are mega cool
www.msj.edu
www.bostonglobe.com


References


Retrofitting
http://github.com/bencallahan/rwd-retrofitting

Media Queries
http://www.w3.org/TR/css3-mediaqueries

Media Types
http://www.w3.org/TR/CSS21/media.html#media-types

This is the best course on Responsive Design:
http://pluralsight.com/training/Courses/TableOfContents/responsive-web-design

Example Media Queries
www.mediaqueri.es









 



Thursday, March 20, 2014

Top Developer Training Resources

Columbus Developers have put together a list of our favorite training resources. 


Reference Sites



Learn HTML, HTML5, CSS, JavaScript, jQuery, jQueryMobile, AJAX, JSON and more
http://www.w3schools.com/

The defacto standard for jQuery information
http://jquery.com/

The Spring site
http://spring.io/

SharePoint Tech Center
http://technet.microsoft.com/en-us/sharepoint/default

SharePoint Dev Center
http://msdn.microsoft.com/en-us/SharePoint

MSDN Virtual Labs
http://msdn.microsoft.com/en-us/aa570323

MSDN Learning Resources
http://msdn.microsoft.com/en-us/bb188199.aspx

TechNet Virtual Labs
http://technet.microsoft.com/en-us/virtuallabs

Example Projects


Github
https://github.com/

CodePlex
http://www.codeplex.com

Interactive Training


Cool site that teaches you how to code
http://www.codecademy.com/

Video lessons, coding challenges and screen casts
https://www.codeschool.com/

Developer Video Tutorials


Video Training by AppDev
https://www.learnnowonline.com/

Introductory Videos on .NET
http://www.learnvisualstudio.net/

Lots of videos on Microsoft Technologies
https://channel9.msdn.com/

Video jump starts on Microsoft development
http://www.microsoftvirtualacademy.com

YouTube has development videos
http://www.youtube.com/

Hardcore Developer Training
http://www.pluralsight.com/training

Videos for developers, designers, business, 3D and Audio
http://www.lynda.com/

Videos on web design, rails, iOS, Android, PHP and WordPress
http://teamtreehouse.com/

Video Courses and eBooks on After Effects, Mobile, Software Development and Web Design
https://tutsplus.com/

Links to Videos, Whitepapers, Quick References, and PodCasts
http://www.dzone.com

Videos on Javascript and jQuery
http://learn.appendto.com/

College Courses


Free online college courses
https://www.coursera.org/

Free Courses from elementary to college level
https://www.khanacademy.org/

Online College Courses
https://www.edx.org/

Podcasts


Scott Hanselman's Podcast
http://www.hanselminutes.com/

Internet Audio Talk Show for .NET Developers
http://www.dotnetrocks.com/

Best Forums


http://www.stackoverflow.com

Books


Giant free collection of programming books
https://github.com/vhf/free-programming-books/blob/master/free-programming-books.md#professional-development


Other


An online regular expression tester
http://regexpal.com/

Connection Strings
http://www.connectionstrings.com/

Regular Expression Library
http://www.regxlib.com

Design Patterns
http://www.dofactory.com

Solid Design Principles
http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod

Law of Demeter
http://en.wikipedia.org/wiki/Law_of_Demeter

Test Driven Development
http://jonkruger.com/blog/2009/07/23/tdd-starter-kit-sample-projects-and-links/


Tuesday, March 18, 2014

Compare .NET Objects V2.0 Released

I have an open source project that I have worked on for several years now.  It is a .NET class library that has the ability to perform a deep comparison of .NET objects using reflection.  Initially it was a simple class that handled just lists, classes, properties and fields.  That single classes became bloated after years of adding features.  Version 2.0 refactors all the type comparers into separate classes.  I also made a portable class library build that targets Silverlight 5+, Windows RT 8+, Windows Phone 8+, Xamarin iOS, and Xamarin Droid.

Project Information

https://comparenetobjects.codeplex.com/



NuGet Package

http://www.nuget.org/packages/CompareNETObjects/

Monday, March 3, 2014

A Regular Expression That Parses Leap Years

We recently had some end users that put in some invalid dates that bypassed our standard regular expression for date validation.  Users put in 02/29/2014.  In case you didn't know, 2014 is not a leap year.  I found a great regular expression on RegexLib that handles leap years.  Even though we are talking about client side validation.  It should be said that server date validation should also be performed.


http://www.regexlib.com/REDetails.aspx?regexp_id=279

Here it is:
((^(10|12|0?[13578])([/])(3[01]|[12][0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(11|0?[469])([/])(30|[12][0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(0?2)([/])(2[0-8]|1[0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(0?2)([/])(29)([/])([2468][048]00)$)|(^(0?2)([/])(29)([/])([3579][26]00)$)|(^(0?2)([/])(29)([/])([1][89][0][48])$)|(^(0?2)([/])(29)([/])([2-9][0-9][0][48])$)|(^(0?2)([/])(29)([/])([1][89][2468][048])$)|(^(0?2)([/])(29)([/])([2-9][0-9][2468][048])$)|(^(0?2)([/])(29)([/])([1][89][13579][26])$)|(^(0?2)([/])(29)([/])([2-9][0-9][13579][26])$))

I was skeptical because the regular expression is so long and it is easy to make a mistake with something this complex.  I created some NUnit tests to verify the functionality.  I would have to say that Saurabh Nath did an excellent job.

Here is the set of NUnit tests that I created:

[TestFixture]
public class LeapDateTests
{
    private Regex _dateRegex;

    [TestFixtureSetUp]
    public void Start()
    {
        _dateRegex = new Regex(@"((^(10|12|0?[13578])([/])(3[01]|[12][0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(11|0?[469])([/])(30|[12][0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(0?2)([/])(2[0-8]|1[0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(0?2)([/])(29)([/])([2468][048]00)$)|(^(0?2)([/])(29)([/])([3579][26]00)$)|(^(0?2)([/])(29)([/])([1][89][0][48])$)|(^(0?2)([/])(29)([/])([2-9][0-9][0][48])$)|(^(0?2)([/])(29)([/])([1][89][2468][048])$)|(^(0?2)([/])(29)([/])([2-9][0-9][2468][048])$)|(^(0?2)([/])(29)([/])([1][89][13579][26])$)|(^(0?2)([/])(29)([/])([2-9][0-9][13579][26])$))", RegexOptions.Compiled);
    }

    [Test]
    public void TestDaysInMonthFor2014Positive()
    {
        for (int month = 1; month <= 12; month++)
        {
            for (int day = 1; day <= 31; day++)
            {
                //Thirty days hath September, April, June, and November
                if (month == 9 || month == 4 || month == 6 || month == 11)
                {
                    if (day > 30)
                        continue;                       
                }

                //Except February which has 28
                if (month == 2 && day > 28)
                    continue;

                string dateString = string.Format("{0}/{1}/2014", month, day);

                Assert.IsTrue(_dateRegex.IsMatch(dateString), dateString);
            }
        }
    }

    [Test]
    public void TestDaysInMonthFor2014Negative()
    {
        for (int month = 1; month <= 12; month++)
        {
            for (int day = 1; day <= 31; day++)
            {
                string dateString = string.Format("{0}/{1}/2014", month, day);

                //Thirty days hath September, April, June, and November
                if (month == 9 || month == 4 || month == 6 || month == 11)
                {
                    if (day > 30)
                        Assert.IsFalse(_dateRegex.IsMatch(dateString), dateString);
                }

                //Except February which has 28
                if (month == 2 && day > 28)
                    Assert.IsFalse(_dateRegex.IsMatch(dateString), dateString);
            }
        }
    }

    [Test]
    public void TestLeapYearsPositive()
    {
        for (int year = 3000; year > 1800; year--)
        {
            if (!IsLeapYear(year))
                continue;
           
            //February 29th
            string dateString = string.Format("02/29/{0}", year);
            Assert.IsTrue(_dateRegex.IsMatch(dateString), dateString);

            //February 30th
            dateString = string.Format("02/30/{0}", year);
            Assert.IsFalse(_dateRegex.IsMatch(dateString), dateString);

            //February 30th
            dateString = string.Format("02/31/{0}", year);
            Assert.IsFalse(_dateRegex.IsMatch(dateString), dateString);
        }
    }

    [Test]
    public void TestLeapYearsNegative()
    {
        for (int year = 3000; year > 1800; year--)
        {
            if (IsLeapYear(year))
                continue;

            //February 29th
            string dateString = string.Format("02/29/{0}", year);
            Assert.IsFalse(_dateRegex.IsMatch(dateString), dateString);

            //February 30th
            dateString = string.Format("02/30/{0}", year);
            Assert.IsFalse(_dateRegex.IsMatch(dateString), dateString);

            //February 30th
            dateString = string.Format("02/31/{0}", year);
            Assert.IsFalse(_dateRegex.IsMatch(dateString), dateString);
        }
    }

    private bool IsLeapYear(int year)
    {
        //See:  http://www.timeanddate.com/date/leapyear.html
        bool evenlyDivisibleByFour = year%4 == 0;
        bool evenlyDivisibleByOneHundred = year%100 == 0;
        bool evenlyDivisibleByFourHundred = year%400 == 0;

        if (!evenlyDivisibleByFour)
            return false;

        if (evenlyDivisibleByOneHundred && !evenlyDivisibleByFourHundred)
            return false;

        return true;
    }
}

Thursday, February 27, 2014

Creating Official Facebook, Twitter, and YouTube Share Buttons

With a little bit of Javascript, HTML, and Meta Tags it is quite easy to create the official buttons for Facebook, Twitter, and YouTube.

Create an official Facebook Share this button:

Generate a share button
https://developers.facebook.com/docs/plugins/share-button/

More information about open graph tags:
https://developers.facebook.com/docs/opengraph/howtos/maximizing-distribution-media-content

Add this to your HTML Tag:
<html xmlns:fb="http://ogp.me/ns/fb#">

Add these meta tags in between the <head> </head>:
<!-- Begin Facebook Meta Tags -->
    <meta property="og:title" content="My Page Title" />
    <meta property="og:url" content="http://www.myurl.com/" />
    <meta property="og:image" content="http://www.myurl.com/images/someimage.png" />
    <meta property="og:description" content="This is a description" />
<!-- End Facebook Meta Tags -->


Add this Javascript after the body:
<!-- Begin Facebook Button Javascript -->
<div id="fb-root"></div>
<script>
    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
</script>
<!-- End Facebook Button Javascript -->

Here is the actual button:
<fb:share-button href="http://www.myurl.com" type="button_count"></fb:share-button>

Create an official Twitter share button

https://about.twitter.com/resources/buttons#tweet

Create an official YouTube Subscribe button

https://developers.google.com/youtube/youtube_subscribe_button

Create buttons for Pinterest, Google Plus, and Linked In

http://www.sharelinkgenerator.com/