Avoiding Herd Mentality by Asking “Why?”

My two-year-old daughter is in a phase of her development where she questions everything she  doesn’t understand. She throws questions at us faster than a 90mph curve ball. I’ll admit there are times where the incessant “why is this blue?” and “why did you open the bottle?” become hard to tolerate but this is an important stage of her development which we really need to encourage and not suppress.

You see, her search for deeper understanding of things is helping to build her internal decision-making engine. She’ll be able to make better choices once she understands “the why”. I guess this is something that I learned from my father who would hammer this point to me over and over again, “If you don’t know why you’re doing something, then there is a strong likely hood that you’re making a bad choice”.

 

 

The field of social psychology presents us with a very potent example. Soccer fans often breakout into fights before games for the most silliest reasons. What originally started as a misunderstanding between between two opposing fans might turn into a big riot. Why? Because people just jumped into the fight without understanding why they were even fighting. In psychology this is known as mob psychology or herd mentality.

As developers, we’re faced with similar but different choices. When you get that dream job you’ve been waiting for you’re whole life and you’re asked to build  a new feature, we often don’t question why things are being done the way they are and jump in head first. Let’s be honest, it’s easy to follow existing conventions without asking questions.

The problem with this approach is that, we become like soccer fans who start vandalizing existing structures without understanding why they’re doing it in the first place.

Questioning or seeking deeper understanding from your colleague,manager,wife or friend can sometimes come across as being rude or even disrespectful. When I first began my career I used to harbor feelings of animosity toward our team lead who would incessantly question my code choices. I later learned how beneficial this was in being able to make better choices.

Developing complex applications will always present tough challenges and choices. However, understanding why you’re choosing one development approach as opposed to another will definitely go a long way to enhance your chances of success. In code reviews it’s important that we not follow a “herd mentality” way of thinking and simple nod our heads. We must question and seek clarity in order to drive us on the path to success.

Guidelines for unit testing

Have you ever wondered what it takes to build a commercial Jet? It often blows my mind to think of the hours engineers spend assembling components together to build the plane. Interestingly enough there are similarities between building software and assembling planes. The individual units for each part of the software application or plane must be thoroughly tested to ensure the overall functionality of the app or plane. The testing of these units is what has become known as unit testing.

Unit testing requires you to test the functionality of individual units/parts/sections of your application in isolation. Testing in isolation ensures that you can confidently pinpoint bugs in code and verify that they have been fixed.

Phases of a Test – Arrange, Act, Assert

There are 3 generally accepted phases for any unit test.

The Arrange phase, is where you create an instance of the class you need to test and also setup up the initial state of any objects. The Act phase, requires you to call the functionality that represents the behavior being tested. Lastly, the Assert phase is where you check what actually happened was expected.

Tips for writing good unit tests?

The primary objective of unit tests is to prove correctness and you can do that by following these simple guidelines.

Prove a contract has been implemented

This is the most basic form of unit testing which verifies that the contract between the caller and method is being adhered to. For example this test validates a driver’s license number . Verifying that a method implements a contract is one of the weakest unit tests one can write.

[Test]
public void ShouldBeValidWhen8DigitsAndStartsWithLetter()
{
var sut = new DriversLicenseValidator();
const string driversLicenseNumber = "A5522123";
Assert.That(sut.IsValid(driversLicenseNumber), Is.True);
}

Verify Computation Results

A stronger unit test involves verifying that the computation is correct. It is useful to categorize your methods into one of the two forms of computation:

  • Data Reduction: occurs when a test accepts multiple inputs and reduces to one resulting output. For example, the verify division test accepts 2 parameters and returns a single output.
  • [Test] public void VerifyDivisionTest()
    {
    Assert.IsTrue(Divide(6, 2) == 3, "6/2 should equal 3!"); 
    }
  • Data Transformation : These tests operate on sets of values

Establish a method correctly handles an external exception

When your code connects to an external service, it is important to determine that your code will handle exceptions gracefully. Attempting to get an external service to throw a specific error is tricky and so the use of Mocking tools will help in this process.

Prove a Bug is Re-creatable

Tests should be repeatable in any environment. They should be able to run in production, QA or even on the bus.

Write positive and negative tests :

Negative tests prove that something is repeatedly not working.They are important in understanding the problem and the solution .Positive tests prove that the problem has been fixed. They are important not only to verify the solution, but also for repeating the test whenever a change is made. Unit testing plays an important role when it comes to regression testing.

[TestMethod] 
[ExpectedException(typeof(ArgumentOutOfRangeException))] 
public void BadParameterTest() 
{ 
    Divide(5, 0);
}

Verify Tests are independent:

Tests should not depend on each other. On test should not set up the conditions for the next test.

These simple guidelines will set you off on the journey of unit testing. Feel free to share any ideas you might have stumbled on.

Viewing application logs in realtime using Sentinel & NLog

We all know how important log files can be when trouble shooting issues in an application. While log files are great to have, sometimes you just want a stream of information which describes what is going on in your application. Sentinel and NLog provide a great way to achieve this.

Sentinel is a log-viewer with configurable filtering and highlighting which can be used in conjunction with nLog to view log entries of an application in real time.

NLog Quick Setup

You can download and install it or just add it through Nuget in Visual Studio

Configuration File

Add a config called NLog.config in the root of your project

If you have a separate config file, make sure you set the “Copy to Output Directory” is set to “Copy Always” to avoid many tears wondering why the logging doesn’t work.

Sample Config File
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.netfx40.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true">
    <variable name="log.dir" value="${basedir}" />
    <targets async="true">
      
      <target name="file" 
              xsi:type="File" 
              fileName="${log.dir}/log.txt" 
              archiveFileName="${log.dir}/log.{#}.txt" 
              archiveEvery="Day" 
              archiveNumbering="Rolling" 
              maxArchiveFiles="10" 
              layout="[${longdate} | ${level}][${threadid}] ${message}${onexception:${newline}EXCEPTION OCCURRED: ${exception:format=tostring}${newline}${stacktrace:format=Raw}}" />
      
      <target name="errors" 
              xsi:type="File" 
              fileName="${log.dir}/errors.txt"
              layout="[${longdate} | ${level}][${threadid}] ${message}${onexception:${newline}EXCEPTION OCCURRED: ${exception:format=tostring}${newline}${stacktrace:format=Raw}}" />

      <target name="debug"
             xsi:type="File"
             fileName="${log.dir}/debug.txt"
             layout="[${longdate} | ${level}][${threadid}] ${message}${onexception:${newline}EXCEPTION OCCURRED: ${exception:format=tostring}${newline}${stacktrace:format=Raw}}" />
           
      <target xsi:type="NLogViewer"
               name="viewer"
               address="udp://127.0.0.1:9999"  includeNLogData="false"/>
    </targets>
    <rules>
      <logger name="*" minlevel="Info" writeTo="file" />
      <logger name="*" minlevel="Error" writeTo="errors" />
      <logger name="*" minlevel="Debug" writeTo="debug" />
      <logger name="*" writeTo="viewer" minlevel="Debug" />
    </rules>
  </nlog>
The most important thing to note in setting up is the NLogViewer target which is setup to push log entires to the address “udp://127.0.0.1:9999”
<target xsi:type="NLogViewer"
               name="viewer"
               address="udp://127.0.0.1:9999"  includeNLogData="false"/>

Sentinel Setup

You can download and install sentinel from http://sentinel.codeplex.com/ It comes with an easy to follow wizard which should be fairly straight forward to setup.

Start Logging

To illustrate how easy it is to stream your log data, create a simply console application. Make sure to add references to Nlog and add the NLog.config file as illustrated above.

namespace Sentinel
{
    class Program
    {
        private static readonly Logger _log = LogManager.GetCurrentClassLogger();
        static void Main(string[] args)
        {
            try
            {
               _log.Debug("This is something new that I just added.");
                _log.Warn("Lets Go!!");
                throw new ApplicationException();
            }
            catch (ApplicationException e)
            {
                _log.ErrorException("Something went wrong...", e);
            }
        }
    }
}

 

Generating an iCalendar file

Situation: Generate an iCalendar file which will trigger a calendar application (eg. outlook) to open with an updated event.

The iCalendar file is a fairly common feature which most developers add to enable  users to add events to their personalized calendars via a custom calendar application.

Solution: Create a web handler which will create a plain text file with the ‘ics’ extension.

using System;
using System.Web;
namespace MyNamespace
{
 public class iCalendar: IHttpHandler
 {
 
  public bool IsReusable
  {
   get
   {
    return true;
   }
  }
 
  string DateFormat
  {
    get
    {
      return "yyyyMMddTHHmmssZ"; // 20060215T092000Z
    }
  }
 
  public void ProcessRequest(HttpContext context)
  {
   DateTime startDate = DateTime.Now.AddDays(5);
   DateTime endDate = startDate.AddMinutes(35);
   string organizer = "foo@bar.com";
   string location = "My House";
   string summary = "My Event";
   string description = "Please come to\nMy House";
 
   context.Response.ContentType="text/calendar";
   context.Response.AddHeader("Content-disposition", "attachment; filename=appointment.ics");
 
   context.Response.Write("BEGIN:VCALENDAR");
   context.Response.Write("nVERSION:2.0");
   context.Response.Write("nMETHOD:PUBLISH");
   context.Response.Write("nBEGIN:VEVENT");
   context.Response.Write("nORGANIZER:MAILTO:" + organizer);
   context.Response.Write("nDTSTART:" + startDate.ToUniversalTime().ToString(DateFormat));
   context.Response.Write("nDTEND:" + endDate.ToUniversalTime().ToString(DateFormat));
   context.Response.Write("nLOCATION:" + location);
   context.Response.Write("nUID:" + DateTime.Now.ToUniversalTime().ToString(DateFormat) + "@mysite.com");
   context.Response.Write("nDTSTAMP:" + DateTime.Now.ToUniversalTime().ToString(DateFormat));
   context.Response.Write("nSUMMARY:" + summary);
   context.Response.Write("nDESCRIPTION:" + description);
   context.Response.Write("nPRIORITY:5");
   context.Response.Write("nCLASS:PUBLIC");
   context.Response.Write("nEND:VEVENT");
   context.Response.Write("nEND:VCALENDAR");
   context.Response.End();
  }
 }
}

Geolocation using Advanced HTML 5

Geolocation is a feature in HTML5 which enables browsers to determine the geographical position of a user. For privacy reasons, geolocation is disabled by default in all supporting browsers. Users have to explicitly give permission to the browser before their position can be determined.

The geolocation API is published through the navigator.geolocation object.

Retrieving the current position

To obtain the user’s current location, you can call the getCurrentPosition() method. This initiates an asynchronous request to detect the user’s position, and queries the positioning hardware to get up-to-date information. When the position is determined, the defined callback function is executed. You can optionally provide a second callback function to be executed if an error occurs

Example

In the following example, the Get Location button triggers a call to the getCurrentPositon method. Once the call to getCurrentPosition() is complete  longitude and latitude are updated on the form and the view map link will open a new window with google maps.

<!doctype html>
<html lang="en">
    <head>
        <title>Geolocation</title>
        <link rel="stylesheet" href="/global.css" type="text/css"/>
        http://../scripts/jquery-1.6.2.js
        </head>
    <body>

Show Position

 

View Map Latitude Longitude

     

    /scripts/Geolocation.js </body> </html>

    $(function() {
    
        var mapLink = $("#mapLink");
        var log = $("#log");
    
        $("#getLocationButton").click(function() {
            navigator.geolocation.getCurrentPosition(showPosition, positionError);
        });
    
        function showPosition(position) {
    
            var coords = position.coords;
    
            $("#lat").val(coords.latitude);
            $("#long").val(coords.longitude);
            
            mapLink.attr("href", "http://maps.google.com/maps?q="
            + $("#lat").val() + ",+" +
                $("#long").val() + "+(You+are+here!)&iwloc=A&hl=en"
            );
            mapLink.show();
    
        }
    
        function positionError(e) {
            switch (e.code) {
                case 0:
                    logMsg("The application has encounterd an unknown error");
                    break;
                case 1:
                    logMsg("You chose not to allow this applicaiton to access your location");
                    break;
                case 2:
                    logMsg("The application was unable to determine your location");
                    break;
                case 3:
                    logMsg("The request to determine your location has timed out.");
                    break;
                
            default:
            }
        }
    
        function logMsg(msg) {
            log.append("<li>" + msg + "</li>");
        }
    })

    Links

    Configuring Glimpse diagnostic tool

    Glimpse is a free, open source diagnostic tool that can save you a lot time when it comes to troubleshooting and diagnosing issues in your application. Over the years more and more developers have contributed to glimpse making this a must have tool for daily .NET development.

    Glimpse works by inspecting web requests as they come through the request pipeline. Each request is visually broken down into various information tabs, which in turn allows you to dive deeper to diagnose an issue. Each tab contains data specific to various server side concerns.

     

    Installation :

    The official site has very good notes on how to install so I won’t bore you with those details.

    Features

    The Glimpse.AspNet package adds these tabs to Glimpse, which can be used for diagnosing problems common to ASP.NET based frameworks:

    Tabs

    • Configuration – The Configuration tab displays web.config entries that could be helpful when debugging.
    • Environment – The Environment tab displays information about the server that responded to the selected HTTP request.
    • Request – The Request tab shows basic HTTP request information as the server received it
    • Routes – The Routes tab shows the routes of the web application, along with default values and constraints
    • Server – The Server tab shows all web server variables available for the request.
    • Session – The Session tab shows the data that is associated with the current requestor’s session store

    Here are some of the awesome features glimpse comes with :

    • Visual Profiling – Glimpse profiles key server side activities and displays the timing of each in an easy to understand Gantt chart.
    • Transparent Data Access – Out of process database calls are expensive. Glimpse lists each of them, so excessive or under-performant queries can be reigned in.
    • Server Configuration – Know everything necessary about a request’s origin server including: timezone, patch version, process ID and pertinent web.configentries.

    Configuration Tips

    NOTE : These changes are all made in your web.config file

    After installation Glimpse will make several changes to you your web.config file you should be aware of.

    <configuration>
      <configSections>
      
      <section name="glimpse" type="Glimpse.Core.Configuration.Section, Glimpse.Core" /></configSections>
    
    <!-- For IIS 7 & greater -->
      <system.webServer>
        <!-- The Glimpse.ASP.Net Module will run on every request made to the application-->
          <modules>
                <add name="Glimpse" type="Glimpse.AspNet.HttpModule, Glimpse.AspNet" preCondition="integratedMode" />
        </modules>
    
        <handlers>
          <!-- The Glimpse.axd handler is used to turn Glimpse on and off-->
          <add name="Glimpse" path="glimpse.axd" verb="GET" type="Glimpse.AspNet.HttpHandler, Glimpse.AspNet" preCondition="integratedMode" />
        </handlers>
      </system.webServer>
      <!-- This is where you put custom configuration -->
    <glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd">
        </glimpse>
      </configuration>
    • How to configure tabs

    You can disable Glimpse tabs by instructing Glimpse to ignore their types:

    <glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd">
        <tabs>
            <ignoredTypes>
                <add type="{Namespace.Type, AssemblyName}"/>
            </ignoredTypes>
        </tabs>
    </glimpse>
    • How to Configure runtime policy

    Policies control what Glimpse is allowed to do to any given request. Policies can be disabled and customized to simplify some scenarios. For example, to run Glimpse on a remote server (like a server in Windows Azure), disable theLocalPolicy:

    <glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd" >
        <runtimePolicies>
            <ignoredTypes>
                <add type="Glimpse.AspNet.Policy.LocalPolicy, Glimpse.AspNet"/>
            </ignoredTypes>
        </runtimePolicies>
    </glimpse>

    Glimpse will never be allowed more permissions than the defaultRuntimePolicy allows. On and Off are the simplest configuration values.

     

    Eliminating If-else statements using a rule engine

    Nearly every developer at some time in their career has run into the dreaded long chain of if-else statements. The chain of conditional statements makes code difficult to read and debug. While working on a recent project, I discovered a new way to clean things up. I’ll first take you through the old approach with a simple example:

    private static void Getgrade()
            {
                //Classic grade program
                double finalGrade = 86.4;
                if (finalGrade >= 95)
                {
                    Console.WriteLine("Dan has obtained an A+, which is Outstanding");
                }
                else if (finalGrade >= 90 && finalGrade < 95)
                {
                    Console.WriteLine("Dan has obtained an A-, which is Excellent");
                }
                else if (finalGrade >= 85 && finalGrade < 90)
                {
                    Console.WriteLine("Dan has obtained a A, which is very good");
                }
                else if (finalGrade >= 70 && finalGrade < 85)
                {
                    Console.WriteLine("Dan has obtained a B+, which is good");
                }
                else if (finalGrade >= 60 && finalGrade < 70)
                {
                    Console.WriteLine("Dan has obtained a B, which is a pass");
                }
                else
                {
                    Console.WriteLine("Dan has obtained an F, which is poor");
                }
            }

    Now let’s take a look at how we can improve this with our rule engine. I’ll define two classes.

    public class Rule<T>
        {
            public Func<T, bool> Test { get; set; }
            public string DisplayMessage { get; set; }
        }
     
    public class Student
        {
            public string Name { get; set; }
            public double Grade { get; set; }
        }

    The first class provides us with our template to generate rules for our engine. It comprises of two properties that make use of the Func delegate.

    private static void GetGradeFromRuleEngine(Student freshman)
    {
       var rules = new List<Rule<Student>>
                     {
                     new Rule<Student>
                     {
                      Test = e => e.Grade >= 95,
                       DisplayMessage =string.Format("{0} has obtained an A+, Which is Outstanding", freshman.Name)
                     },
                     new Rule<Student>
                     {
                       Test = e => e.Grade >= 90 && e.Grade < 95,
                       DisplayMessage =string.Format("{0} has obtained an A-, which is Excellent", freshman.Name)
                     },
                     new Rule<Student>
                     {
                      Test = e => e.Grade >= 85 && e.Grade < 90,
                      DisplayMessage =string.Format("{0} has obtained a A, which is very good", freshman.Name)
                     },
                     new Rule<Student>
                     {
                      Test = e => e.Grade >= 70 && e.Grade < 85,
                      DisplayMessage =string.Format("{0} has obtained a B+, which is good", freshman.Name)
                     },
                     new Rule<Student>
                     {
                      Test = e => e.Grade >= 60 && e.Grade < 70,
                      DisplayMessage = string.Format("{0} has obtained a B, which is a pass", freshman.Name)
                     },
                      new Rule<Student>
                     {
                       Test = e => e.Grade >= 60 && e.Grade < 70,
                       DisplayMessage =string.Format("{0} has obtained an F, which is poor", freshman.Name)
                     },
     
                   };
     
                bool isValid = rules.Any(r => r.Test(freshman));
                if (isValid)
                {
                    var validRules = rules.Where(r => r.Test(freshman));
     
                    string message = validRules.SingleOrDefault().DisplayMessage;
     
                    Console.WriteLine(message);
                }
     
            }

    We then create a method that accepts a student object called GetGradeFromRuleEngine. The next thing we do is to build our rule engine. This structure makes it very easy to modify and even add new rules to our engine. Below is how you will run this and voila.

    class Program
        {
            static void Main(string[] args)
            {
                var dan = new Student()
                {
                    Name = "Dan",
                    Grade = 86.4
                };
     
                GetGradeFromRuleEngine(dan);
            }
     
    }

    Breaking down Interfaces

    I often hear heated debates between developers about the usage of interfaces. Unfortunately, many of these debates are skewed toward the personal preferences of developers who fail to understand what an interface is and what it does.

    So let me use a couple of minutes to break it down for you…..

    Take a Digital Video interface (DVI) port, which is used to connect a computer and a display device. The DVI port doesn’t need to know whether the display device is a Samsung flat screen monitor or Acer LCD monitor.Neither does it need to know how the Samsung monitor will connect internally to the computer. All the interface provides is a means of connecting any computer to any display device. Essentially, it says “Hey Computer, connect to this monitor” and ‘Hey Presto!’ they’re connected.

    In the realm of programming, an interface does exactly the same thing. It provides a way for objects to interact without each object having to specify the inner details of how they intend to interact with another object. Here is a brief summary of the role of an interace

    • An interface allows us to separate the usage of something from how it is implemented
    • Interfaces are like contracts which define what operations should be performed
    • An interface constitutes a declaration about intentions
    Benefits of Interfaces
    • Code readability: Using interfaces will improve your code readability because you’re interfaces will define and state your intentions. If you implement ISortable you’re clearly stating that your class can be sorted, same for IRenderable or IConvertible.
    • Code Semantics: By providing interfaces and implementing them you’re actively separating concepts in a similar way HTML and CSS does
    • Code maintainability: Interfaces helps to reduce coupling and therefore allow you to easily interchange implementations for the same concept without the underlying code being affected
    Things you should know
    • A class can implement multiple interfaces
    • Interface members are all implicitly abstract
    • An interface can contain only methods, properties, events and indexers
    Example

    In this example, we define a very simple interface called IConnectable. IConnectable defines a new contract which states that any class which implements me must define a method called connect. In a real world application, the connect method in the Lenovo and series9 objects would then provide the necessary details about how to connect.

    namespace InterfaceExample
    {
          public interface IConnectable
          {
                void Connect();
          }
     
          public class Computer : IConnectable
          {
                public void Connect()
                {
     
                      Console.WriteLine("I can connect to any display device attached to me");
                }
          }
          public class SamsungMonitor : IConnectable
          {
                public void Connect()
                {
                      Console.WriteLine("I can connect to any Computer attached to me");
                }
          }
     
          class Program
          {
                static void Main(string[] args)
                {
                      Computer lenovo = new Computer();
                      SamsungMonitor series9 = new SamsungMonitor();
     
                      lenovo.Connect();
                      series9.Connect();
     
                      Console.Read();
     
                }
          }
    }