SQL Pagination

I have often encountered the culture of query for thousands of results, estimate the paging and then only display a small segment of the results that were retrieved from the database. This is particularly bad in a web environment. This results in the following issues:

  • A large amount of data to be transferred from the database to the website
  • Longer than necessary database queries
  • Script Errors and timeouts
  • Frustrated users/customers

Continue reading SQL Pagination

Websites Responsive to Screen Size

I own a desktop, laptop, iPad and an HTC Android phone. Each device has a different screen size. I had never tried my website on the iPad and the Android phone until after the DIG 2011 conference in London Ontario. Jeffery Zeldman and Derek Featherstone spoke on the importance of having your website visible on multiple devices and this struck home to me. Continue reading Websites Responsive to Screen Size

How I Achieved Decent Search Ranking

I recently showed my hit stats for my website to a friend, which include the GOOGLE and Yahoo queries. I was asked how I achieved my ranking. I typically see a rank between 3 and 20, which I consider respectable. Most of my ranking is under 10, which is really good.   I am actually surprised how people find me as it can be a very obscure search.

Could it be better? Probably, but this seems to work for me

Example ( real rankings 11/03/2011 ):
Ranking 22: www.google.co.uk — c#/ .net blogs in london + cv
Ranking 02: www.google.ca — software developer london ontario
Ranking 05: www.google.com — how to use equalsignorecase in javascript
Ranking 01: wwww.google.lv — excel interop in web service
Ranking 14: www.google.ca — london ontario computer programmer

Here is how:
1. Fresh Content ( Blog, Twitter Feed, Other Dynamic Content )
2. Have description and keyword meta tags relevant to your content on the page ( Each Page should be unique )
3. Put title attributes on links / menu items
4. Put alt attributes on images describing the image
5. Have unique titles on each page
6. Do not use tables to structure your web page
7. Use H1 and H2 tags for page and paragraph titles
8. Optimize your webpage and images for speed.
9. Have a site map ( link page ) outlining links to your content
10. Use GOOGLE’s and Yahoo’s webmaster tools for site maps and analytics
11. Use and understand GOOGLE Analytics tool
12. Have other sites link back to you that our relevant to your site.
13. Use Twitter, LinkedIn and Facebook to promote your fresh content.

Code Reviews

Developers often seem scared to allow another person to look at their code.  It is like they have a fear of someone stealing what they had done or that someone is looking over their shoulder.  Software developers and web developers often hold tight to their projects.  In almost every business work is proof read or reviewed.   It is not because a lack of trust, but rather many eyes will catch mistakes.

Why do we do code reviews?
The reason for code reviews may be obvious, but since the resistance it needs to be mentioned.  Code reviews are primarily to catch logic mistakes, missing business rules and team coding standards.

When a developer is so close to a project and looks at the same code for days, weeks or months, it is easy to invert logical expressions or entirely miss basic variable checks.  Assuming both purposely and by accident that routines return the perfect values is often the biggest mistake and we are suddenly surprised when a NULL value sneaks in.

Often when we start a project we are handed pages and pages of business rules and requirements.  It is very easy to miss the small things and even the big things.  As easily it is to cross items off a list, it is just as easy to entirely miss one.  It is very viable to have a second set of eyes to review what we had just written.  Better to catch mistakes before the customer does.

Lastly team coding standards;  they are standards that either the team lead or the team together decided they would follow.  These standards are to ensure that the team writes the code in the same structure and using the same variable naming convention.  Having coding standards allows the team to work together and have the ability to read each other’s code.  It allows quick debug and editing by any team member.  Without these standards projects would be a wild wild west and would differ from team member to team member.

Types of Code Reviews

  1. Team Code Reviews – Team members together would focus on a method or a group of methods.  The team together would offer suggestions and ideas to enhance the code for which they are reviewing.  It is not a time to rip the developer apart, but to offer constructive suggestions.  If a developer gets out of line, that person should be asked to leave the room.  A projector should be used if available; otherwise printing off the code or have each developer view it on their laptops are adequate methods as well.  The team lead should take a leadership role in this method guiding conversation and making notes to send out after the meeting.
  2. Colleague Code Reviews – These reviews should be done by a senior or a team lead person.  The senior can be greater or equal in experience.  Same as a team review, everything should be done in a constructive manner.  If a senior developer is doing the review; the senior should be assigned by the team lead to prevent a biased review.  When the review is complete – the review should be covered in person with all developers involved.

Tips for the Reviewer

  1.  Ask questions, do not make statements
  2. Do not be too critical, remember to praise
  3. Be sure you have your company coding standards available as a reference
  4. Keep the review on the code and not the coder.   Do not make it personal
  5. Keep in mind that there is more than one way to do something

Tips for the Developer

  1. Remember, you wrote the code, but the code is not you.
  2. Make a check list of things that are often found in the code reviews
  3. Be involved in the maintenance of the coding standards
  4. Always do your best and do not look for short cuts

Building a C-Sharp Class

I have created this example of a C# class to demonstrate one way of creating a basic class cbject representing one employee.  This class could be used as a starting point for just about any object.

Take note that there are no business rules in this example.  It is of my opinion that you create a basic object first and create a business class second which extends the basic object.  In the business class you may put an EmployeeNumber generator, MaxLength controls on the fields, Phone number validation and other rules that may apply based on your business practices.  A business class will be demonstrated in a later blog.

You may also want to create a collection class.  A collection class or a manager class would manage a collection of objects with Add, Remove, Select, Sort type functions.  This too will be demonstrated in a later blog.

    /// <summary>
    /// Class Object Representing Employee
    /// </summary>
    public class Employee : Dictionary<String, Object>, IEmployee
    {
        // ***********************| Properties |***********************
        /// <summary>
        /// Employee Number
        /// </summary>
        public String EmployeeNumber
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's First Name
        /// </summary>
        public String FirstName
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's Last Name
        /// </summary>
        public String LastName
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }
        /// <summary>
        /// Employee's Address Line 1
        /// </summary>
        public String Address1
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's Address Line 2
        /// </summary>
        public String Address2
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's City
        /// </summary>
        public String City
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's Province / State
        /// </summary>
        public String Province
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's Country
        /// </summary>
        public String Country
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's ZIP / Postal Code
        /// </summary>
        public String ZipPostal
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's Home Phone Number
        /// </summary>
        public String HomePhoneNumber
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's Cell Phone Number
        /// </summary>
        public String CellPhoneNumber
        {
            get { return (String)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's Full Name ( ReadOnly )
        /// </summary>
        public String FullName
        {
            get { return String.Format("{0}, {1}", FirstName, LastName); }
        }

        /// <summary>
        /// Employee's Start Date
        /// </summary>
        public DateTime StartDate
        {
            get { return (DateTime)this[GetName()]; }
            set { this[GetName()] = value; }
        }

        /// <summary>
        /// Employee's TerminationDate ( Nullable )
        /// </summary>
        public DateTime? TerminationDate
        {
            get { return (DateTime?)this[GetName()]; }
            set { this[GetName()] = value; }
        }
        // ***********************| Constructor(s) |***********************
        /// <summary>
        /// Constructor
        /// </summary>
        public Employee()
        {
            Initialize();
        }

        /// <summary>
        /// Employee
        /// </summary>
        /// <param name="employeeNumber">Initial Employee Number</param>
        public Employee(String employeeNumber)
        {
            Initialize();
            EmployeeNumber = employeeNumber;
        }
        // ***********************| Methods |***********************

        /// <summary>
        /// Initialize the Class
        /// </summary>
        private void Initialize()
        {
            EmployeeNumber = "";
            FirstName = "";
            LastName = "";
            Address1 = "";
            Address2 = "";
            City = "";
            Province = "";
            Country = "";
            ZipPostal = "";
            HomePhoneNumber = "";
            CellPhoneNumber = "";
        }

        /// <summary>
        /// Get Method Name
        /// </summary>
        /// <returns>First and Last Name</returns>
        public String GetName()
        {
            StackTrace stackTrace = new StackTrace();
            StackFrame stackFrame = stackTrace.GetFrame(1);
            MethodBase methodBase = stackFrame.GetMethod();
            return methodBase.Name.Replace("set_", "").Replace("get_", "");
        }

        /// <summary>
        /// Re-initializes the Class
        /// </summary>
        public void Reset()
        {
            this.Clear();
            Initialize();
        }
    }

Importance of Code Refactoring

By continuously improving the design of code, we make it easier and easier to work with. This is in sharp contrast to what typically happens: little refactoring and a great deal of attention paid to expediently adding new features. If you get into the hygienic habit of refactoring continuously, you’ll find that it is easier to extend and maintain code.
—- Joshua Kerievsky, Refactoring to Patterns

I had recently seen the above quote while sifting through some periodicals that I read and it reminded of the importance of Code Refactoring. Refacotring is a mindset that you must put yourself into. You have to decide that you do not write perfect code the first time and that there may be some room for improvement. An hour or two a day may be all you need to review your own code.

I recently spent two hours reviewing code from one of my modules that I had written. It had the same or similar code written in 5 sections in the code and had the same purpose to these sections. Each section had 11 or more lines of code in it. I took one of those sections of code and converted it to a function and then replaced the 5 sections with this new function. Ultimately I had eliminated 51 lines of code out of one module.

Reasons for Refactoring Code
1. Consolidating and eliminating “Like” or “Similar” Code
2. Breaking out a extraordinary long function into more manageable bites
3. Make error trapping easier to handle
4. Make code more readable and maintainable
5. Removing nested IF or logic Loops
6. Make it easier to document
7. Create Reusable code
8. Better class and function cohesion.

The benefits now are the following:
1. Similar code is now the same which is the way it was meant to be ( coded over three days, the code morphed a bit ).
2. Since the code had the same purpose, it looks the same now and behaves the same.
3. Code is in one spot instead of 5 – makes it easier for a base change
4. Error trapping is much more controlled.

If you cannot review your own code ( some people cannot and should not be ashamed for it ), you should get yourself someone you can trust to review the code for you. The do not have to modify the code, they can either insert comments to you, print out and scribble on the pages or meet with you. Never take it as bad thing if someone wants to change your code; take it as a learning experience. If you are using someone else, challenge them back. Make sure they know what they are talking about. A face to face meeting is always a good idea. A mentor, or team lead should be taking on the role of code reviewer. Code reviewer should be recommending ways to refactor your code. This should be done prior to release, deployment and ending a project. The review should always be done with the developer(s) responsible for writing the code. Should never be done without as that undermines the developer(s) and no one learns anything from it.

What Languages do I Use

I was recently asked what I use to develop software and websites. I mostly use DotNet Technologies as it is often interchangeable between websites, web applications and desktop applications. I can often use the same data access classes and business logic between multiple platforms. I find that DotNet allows me to easier structure objects visually and logically.  I prefer to develop using C-Sharp, but I get requests to use VB.NET and J-Sharp on a regular basis.

When I went to college, I had learned C, Pascal, COBOL and some Mainframe language that I cannot remember.  Upon graduating I taught myself VisualBasic 3, RPG.  My first programming job was Visual COBOL.  I had created a company in the Caribbean Islands programming public utility and insurance software in RPG.   I can honestly say since I sold my shares of the company, I cannot foresee myself developing in RPG again.

Why don’t I use PHP?  Well I do use PHP, but for specific purposes and upon request by a customer. A specific purpose is when I create a WordPress site or other content driven sites. I will not often create a website or web application from scratch using PHP as Microsoft made ASP.NET easy for rapid development.

Do I use JAVA? Yes; I do believe there are cases where JAVA is still relevant. JAVA is still a good tight platform for developing small single purpose applications.  I have used JAVA 3 times in the past 2 years for applications that I believe fit the bill well.

Now, I am curious;  What do you use and why?

Shortcut To Creating Properties in C-Sharp

I was looking for an easy and consistent way of creating properties for classes.  I sometimes find that it can be a long drawn out process creating 5 to 100 properties for database classes.  Here is a quick example of what I did.
You will need the following references to make this example work.

  1. System.Diagnostics;
  2. System.Reflection;
  3. System.Collections;
public class ErrorLogRecord
{
     Hashtable _hsh = new Hashtable();
     public DateTime DateOfOccurance
     {
          get { return (DateTime?)_hsh[GetName()] ?? DateTime.Now; }
          set { _hsh[GetName()] = value; }
     }        
     public String ErrorText
     {
          get { return (String)_hsh[GetName()]; }
          set { _hsh[GetName()] = value; }
     }

     public String GetName()
     {
          StackTrace stackTrace = new StackTrace();
          StackFrame stackFrame = stackTrace.GetFrame(1);
          MethodBase methodBase = stackFrame.GetMethod();
          return methodBase.Name.Replace("set_", "").Replace("get_", "");        
     }
}

While this method is probably not perfect and could be argued there is a better way, this seems to satisfy the need. I would welcome alternatives.

Alternate Reading: Shortcut To Creating Properties in C-Sharp (revisited)