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();
  }
 }
}

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();
 
            }
      }
}