Strategy Design Pattern

Please check out my latest video on the Strategy Design Pattern.

This video link posted above describes two very simple and practical examples of the Strategy Design Pattern. The first example explains strategy in terms of a floor cleaning Robot. A tool that is best suited for a floor type can be attached to the floor cleaning robot and that each such tool represents a concrete strategy. Each tool has to fit a generic slot in the Robot and that represents an abstract strategy. The Robot itself represents a context. Class diagram of this scenario is
:

In another example, a simple application is shown that implements two approaches to read an XML file. The first approach loads the entire XML file into memory and uses XPath searches to find a node matching a criteria. The second approach uses line-by-line file reading approach. The class diagram of this implementation is

Source Code of the XML File Search Application:

Abstract Strategy:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace StrategyPatternConsoleApplication
{
//this is the abstract strategy
public interface ISearchXmlFileStrategy
{
// All concrete strategies must implement this method
string GetCustomerNameByCustomerID(String customerId, String filePath);
}
}

Concrete Strategy:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
 
namespace StrategyPatternConsoleApplication
{
//concrete strategy loads xml document into memory
//then does in memoryreading
public class MemorySearchXmlFileStrategy : ISearchXmlFileStrategy
{
///
 
/// Invokes strategy interface method
///
 
///Customer identifier
///Xml file name with path
/// Customer name
public string GetCustomerNameByCustomerID(String customerId, String filePath)
{
 
XmlDocument Doc = new XmlDocument();
//load the entire document into memory
Doc.Load(filePath);
StringBuilder CustomerName = new StringBuilder(); //local variable
//stores last name and first name
XmlNode RootNode = Doc.DocumentElement;
XmlNode ResultNode = 
RootNode.SelectSingleNode("Customer[@id=" + "'" + customerId + "'" + "]");
if (ResultNode != null)
{
        //read the last name
        CustomerName.Append(ResultNode.SelectSingleNode("LastName").InnerText);
        //append space in between last and first name
        CustomerName.Append(" ");
        //append first name
        CustomerName.Append(ResultNode.SelectSingleNode("FirstName").InnerText);
}
//return customer name formatted as last name first name
return CustomerName.ToString();
}
}
}

Another Concrete Strategy:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
 
namespace StrategyPatternConsoleApplication
{
//this is another concrete strategy
//that reads an xml file sequentially
//may be suitable for large files
//not suitable for loading into memory
public class SequentialSearchXmlFileStrategy : ISearchXmlFileStrategy
 
{
///
 
/// Invokes strategy interface method
///
 
///Customer identifier ///Xml file name with path /// Customer name
public string GetCustomerNameByCustomerID(String customerId, String filePath)
{
XmlReader Reader = XmlReader.Create(filePath);
//local variable stores last name and first name
StringBuilder CustomerName = new StringBuilder(); //local variable
 
while (Reader.Read()) //read the xml file
{
if (Reader.IsStartElement()) //check if its starting element
{
var attr = Reader["id"]; //get the id attribute
//if attribute matches input customer id
if (attr != null && attr == customerId)
{
//move to last name element
if (Reader.ReadToFollowing("LastName"))
{
Reader.Read(); //read last name
//append the last name value
CustomerName.Append(Reader.Value);
}
 
if (Reader.ReadToFollowing("FirstName"))//move to first name element
{
Reader.Read(); //read first name
//append space between last name and first name
CustomerName.Append(" ");
//append the first name value
CustomerName.Append(Reader.Value);
break; //found record get out of loop
}
}
}
}
 
Reader.Close(); //close the reader
//return the formatted full name
return CustomerName.ToString();
}
}
}

Context:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StrategyPatternConsoleApplication
{
//this is the context class
public class CustomerFinder
{
//holds a reference to the strategy
ISearchXmlFileStrategy _strategy = null;
 
///
 
/// Strategy setter
///
 
///The concrete strategy public void SetStrategy(ISearchXmlFileStrategy strategy)
{
_strategy = strategy;
}
 
//invoke strategy method
///
 
/// Invokes strategy interface method
///
 
///Customer identifier ///Xml file name with path /// Last name and first name as string
public String GetCustomerNamebyId(String customerId, String filePath)
{
return _strategy.GetCustomerNameByCustomerID(customerId, filePath);
}
}
}

Client:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace StrategyPatternConsoleApplication
{
class Program
{
///
 
/// Main Method - entry point to the console application
///
 
///Command Line arguments static void Main(string[] args)
{
 
Console.WriteLine("Please supply value of customer id");
String Id = Console.ReadLine();
ISearchXmlFileStrategy Strategy = new MemorySearchXmlFileStrategy();
CustomerFinder Context = new CustomerFinder();
Context.SetStrategy(Strategy);
String CustomerName = Context.GetCustomerNamebyId(Id, "C:\\Code\\StrategyPatternSolution\\CustomerData.xml");
//display result
if (String.IsNullOrEmpty(CustomerName))
{
Console.WriteLine("No Customer Found");
}
else
{
Console.WriteLine(CustomerName);
}
Console.WriteLine("Press any key to exit...");
//keep the console window open till the user presses any key
Console.ReadKey();
 
}
}
}

All other details on the Strategy Design Pattern are included in this video. I’d love you get your feedback and would also like to know how you have applied this design pattern.

UPS Tracking Service API

Introduction

This post covers the steps needed to use the Tracking Service Application Programming Interface (API) of United Parcel Service (UPS). We will cover the steps of registering with UPS first to get credentials/license key from UPS and then use the street address validation API in a C# console application. We will use Visual Studio 2015 as Integrated Development Environment (IDE) and build a Windows Communication Foundation (WCF) client to invoke the UPS API.

Assumptions:

  1. You are familiar with a .net programming language (preferably C#) and Visual Studio .Net.
  2. You understand the basics of Windows Communication Foundation and how to consume a web service with the help of a WSDL file.

If you perform an internet search on the keywords ‘UPS Developer API’, you will get the link to the web page that covers all the documentation you need. The link is:

https://www.ups.com/upsdeveloperkit

In order to access UPS API, you need a userid/password credential and an access key.

Step 1: Get Security Credentials

Get a userid and password by registering with My UPS if you don’t have one already. This is step 1 on UPS web page.

1

Step 2: Get Access Key

Login to the same page mentioned above by using the credentials obtained in step 1 and request access key (Step 5 on the page). The access key will be displayed on your browser window. You will also get an email with the same access key information.

2

Now we are ready to write code.

Step 3: Build Code

Step 3a: Download API Files

UPS exposes different APIs for different types of functionality. In this tutorial, we will use their ‘Tracking’ API. Please go ahead and download the API documentation.

 

The API will be downloaded as a zip file. Extract the zip file to a folder of your choice. Navigate to the folder that contains the WSDLs of the Address Validation Service. If you extracted the zip file to a folder called ‘C:\UPS\Tracking’, you will have to do the following:

Navigate to:

C:\UPS\Tracking\Tracking\TrackingPACKAGE\TRACKINGXMLTools\Schemas

Copy all the schema files (.xsd) files from this folder to:

C:\UPS\Tracking\TrackingPACKAGE\TRACKINGWebServices\SCHEMAS-WSDLs

The ‘SCHEMAS-WSDLs’ folder will look like this:

Please note that the WSDL file and all its dependencies (XML schemas) exist in the same folder.

Step 3b: Create Console Project with the name ‘UPSTrackingConsoleApplication’

Step 3c: Add Service Reference

Right click on the console project and add service reference to the UPS tracking service.

Now provide the full path of the WSDL file. Rename the proxy namespace to UPSTrackingProxy.

Also, please note how Visual Studio adds WCF client configuration to your app.config file. You don’t need to change this please note the address of the service and the types of binding and contract. The service endpoint URL is the URL of UPS test environment.

Step3d: Add code

Add the following code to the Program.cs project startup class. I have tried to document the code as much as possible so it becomes self-explanatory.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using UPSTrackingConsoleApplication.UPSTrackingProxy;</code>
 
namespace UPSTracking
{
class Program
{
static void Main(string[] args)
{
try
{
//create the client proxy
TrackPortTypeClient track = new TrackPortTypeClient();
 
//create username token
UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
//this is your my UPS userid
upssUsrNameToken.Username = "your userid";
//this is your my UPS password
upssUsrNameToken.Password = "your password";
 
UPSSecurityServiceAccessToken upssSvcAccessToken = 
new UPSSecurityServiceAccessToken();
//this is your my UPS access key
upssSvcAccessToken.AccessLicenseNumber = "your access token";
//create UPS security object
UPSSecurity upss = new UPSSecurity();
//set the user name token
upss.UsernameToken = upssUsrNameToken;
//set the service access token
upss.ServiceAccessToken = upssSvcAccessToken;
 
//create the request object
RequestType request = new RequestType();
//must be hard coded to 15
String[] requestOption = { "15" };
//set the request option
request.RequestOption = requestOption;
 
TrackRequest tr = new TrackRequest();
tr.Request = request;
//this is your UPS tracking id like 1Z123455....
tr.InquiryNumber = "1Zxxxxxxxxxx";
 
//added to handle the intermittent error with SSL/TLS connection
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | 
SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | 
SecurityProtocolType.Tls12;
 
//open channel
track.Open();
 
//invoke the service
TrackResponse trackResponse = track.ProcessTrack(upss, tr);
 
//close channel
track.Close();
 
Console.WriteLine("The transaction was a " + 
trackResponse.Response.ResponseStatus.Description);
Console.WriteLine("Shipment Service " + 
trackResponse.Shipment[0].Service.Description);
 
//print tracking process result
foreach (ShipmentType shipment in trackResponse.Shipment)
{
foreach (PackageType package in shipment.Package)
{
 
foreach (ActivityType Act in package.Activity)
{
Console.WriteLine("City {0} {1}, Date {2}, Time {3}, Status {4}", 
Act.ActivityLocation.Address.City, 
Act.ActivityLocation.Address.StateProvinceCode, Act.Date, Act.Time, 
Act.Status.Description);
}
 
}
 
}
 
}
catch (Exception ex)
{
Console.WriteLine(String.Format("Error in processing tracking request: {0}", 
ex.Message));
}
 
Console.ReadKey();
 
}
}
}

Step 4: Test the code

Run the project and test with different values of address input. The output of the program will look similar to this.

The transaction was a Success
Shipment Service UPS GROUND
City XYZ CA, Date 20161129, Time 115600, Status Delivered
City XYZ CA, Date 20161129, Time 044000, Status Out For Delivery
City XYZ CA, Date 20161129, Time 042400, Status Out For Delivery
City XYZ CA, Date 20161129, Time 032500, Status Arrival Scan
City MNP CA, Date 20161129, Time 014600, Status Departure Scan
City MNP CA, Date 20161128, Time 082400, Status Arrival Scan
City EFG FL, Date 20161123, Time 103800, Status Departure Scan
City EFG FL, Date 20161123, Time 020400, Status Arrival Scan
City ABC FL, Date 20161122, Time 224300, Status Departure Scan
City ABC FL, Date 20161122, Time 173900, Status Origin Scan
City , Date 20161121, Time 193111, Status Order Processed: Ready for UPS

Please note:

  1. Make sure you pass value of “15” as RequestOption. Please see code comments for more details.
  2. I found UPS documentation to be dated and out of synch with their current code. But it is still a good idea to read their documentation to get some general ideas about their service.
  3. The code in this post works at the time of writing this post (December 1, 2016).
  4. No warranty is provided with the code or any documentation in this article.

This code could be refactored into multiple helper methods but I wanted to provide one block of code with no dependencies to keep things simple for this post.

Singleton Design Pattern

Singleton Design Pattern is one of the simplest and commonly used design patterns in object oriented design. Implementation of singleton classes ensures that only one instance of a class can be created. Please check out my latest video on this design pattern.

All the details are in the video. This blog post reiterates a few concepts that are discussed in this video and also includes source code that is used in the video.

Firstly, why does one need a singleton class? If an instance of a class does not hold any state that makes it distinguishable from other instances, that class becomes a candidate for Singleton. This becomes compelling in situations where class instantiation is a costly process. In general, I prefer to keep my controller classes stateless and those are generally declared singleton. There are posts on the internet that advocate static classes in place of singleton. My personal opinion is that static classes are easier to implement but static classes and methods have other shortcomings and that is why my preference is still singleton over static. This discussion is out of scope of this post and so I will cover my opinion in another post.

How do you make a class singleton?

a. Make it’s constructor private

b. Expose it’s only instance via a static property

c. Implement the ICloneable interface and throw an exception in the Clone method. This ensures that another program cannot create multiple instances of this program by calling ClassName.SingletonInstance.Clone().

Even though steps a – c appear fairly standard and easy to implement, there is another concern here which causes Singleton implementation to be problematic – thread safety.

In the YouTube video, I have taken the example of a “global setting” class that stores global settings for an application that are initialized once and never updated as long as the application runs. This is the implementation of a singleton class.

public class GlobalSettings: ICloneable
{
//the only instance of this class is created just once
private static readonly GlobalSettings SingletonInstance
= new GlobalSettings();
 
// private constructor
private GlobalSettings()
{
Console.WriteLine("constructor of GlobalSettings..");
}
 
// Exposes the only instance
public static GlobalSettings Instance()
{
return SingletonInstance;
}
// this is a sample setting value
public String SomeSetting()
{
return "I am Global Settings";
}
 
// Throws exception if any program tries to create another
// instance by cloning
public object Clone()
{
throw new ArgumentException("cannot clone this object");
}
} //end of class

To call a method on the singleton instance, a client program needs to use this expression. I have taken the example of the instance method called “SomeSetting”. Any instance method or property could be invoked in the same way as described below.

GlobalSettings.Instance().SomeSetting();

Please note that the class implements the ICloneable interface. So if another program tries to create another instance of this class by invoking code like shown below, they will get an exception.

GlobalSettings.Instance().Clone()

Hope you liked this post and video. Your feedback, as always, is valuable to me. Also, I’d like to hear from you how you implemented Singleton or the reasons why you do not use Singleton.

 

Abstract Factory Design Pattern

A factory is an object that produces something. In the world of software design, you need a factory object to create a “product” object so you can decouple the logic of the product’s creation from the objects that use that product. The product and its factory are naturally coupled and the logic of creating a product is centralized in the factory. Abstract Factory Design Pattern is a great way of implementing factories. Each factory can produce different families of products. And there can be more than one factory. Two factories can produce same family of products.

I was trying to implement something that is easy to related to and comprehend. So I took an example that involves two factory objects – Honda and Toyota. Each factory can produce two types of products – one car and one aircraft. And the entire object interaction is initiated via a simple client class. The cars expose a ‘drive’ behavior whereas the aircrafts expose a “fly” behavior. All the coding work was using the Visual Studio 2015 Integrated Development Environment and c# programming language.

I have uploaded two videos on the Abstract Factory. The first video mainly focuses on the class diagram of the prototype.

Abstract Factory Design Pattern (Part 1):

The second video does a walkthrough of the implementation. I have tried to create code “on the fly” so I can do a slow walk-through of the design and the code.

Abstract Factory Design Pattern (Part 2):

All the details are in the two videos. Hope you like the videos. If you have any questions, concerns or comments, please feel free to post those in the comments area. Also, I’d like to hear from your a scenarios where you used the concrete factory pattern or the abstract factory pattern. This is part of a series of posts on different design patterns and I’ll post several videos in the near future.

Template Method Design Pattern

Please check out my new video on the Template Method Design Pattern:

This post complements the video tutorial by adding the source code used in the video and also provides some additional information.

As per Wikipedia, the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in an operation, deferring some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm’s structure.

Let me explain the Template Design Pattern first and then we will revisit the definition. Lets assume that we are implementing an algorithm that has three steps that are executed sequentially. There is a “main” method invokes the three sub steps in the right sequence. The “main” method is called the template method and is what is invoked to execute the algorithm. The idea here is that we cannot change sequence of the three steps but what happens in these steps can be overridden or implemented differently by different classes. So the main/template method and the three methods that implement the three sub steps can be defined in a class. The three steps can be overridden in a sub class but the algorithm would still be executed from the parent class’s template method. The parent class can be declared as abstract that will force the consumers of this algorithm to always use a subclass. But the template method will be available by inheritance to each sub class.

In our prototype, the algorithm is the sequence of steps to register a student. The three steps are:
1. VerifyPrerequisites (check if the student meets the required pre-requisites for a course)
2. ProcessPayment (process course fee if the student meets prerequisites)
3. SendNotification (Send a notification to the student to confirm their registration if payment is processed successfully)

The main/template method is defined as RegisterStudent and it invokes steps 1-3 in the correct order. Lets take a look at the parent class. In our case, steps 1 and 3 have to be overridden by a sub class. But step 2 is implemented in the parent class because the ProcessPayment step is expected to to be common to all sub classes of CourseRegistrationHelper.

 public abstract class CourseRegistrationHelper
    {
        //template method
        public void RegisterStudent()
        {
            VerifyPrerequisites(); //step 1
            ProcessPayment(); //step 2
            SendNotification(); //step 3
        }
 
        //must be overridden by sub classes
        //this is step 1
        protected abstract void VerifyPrerequisites();
        //default implementation of this step is provided
        //this is step 2
        protected void ProcessPayment()
        {
            Console.WriteLine("Processing Payment the generic way");
        }
 
        //must be overridden by sub classes
        //this is step 3
        protected abstract void SendNotification();
    }

Two universities implement this abstract class in two different ways. The implementation is methods in the entire prototype is trivial but the idea here is to understand the structure of the Template Method Design Pattern.

This is the way University A implements this.

public class UniversityACourseRegistrationHelper : CourseRegistrationHelper
    {
        //step 1
        protected override void VerifyPrerequisites()
        {
            Console.WriteLine("Validate transcript");
        }
 
        //step 3
        protected override void SendNotification()
        {
            Console.WriteLine("Send a letter");
        }
    }

This is the way University B implements this:

 public class UniversityBCourseRegistrationHelper : CourseRegistrationHelper
    {
        //step 1
        protected override void VerifyPrerequisites()
        {
            Console.WriteLine("Validate university records");
        }
 
        //step 3
        protected override void SendNotification()
        {
            Console.WriteLine("Send email");
        }
    }

Now we can invoke the two algorithms in a c# console application.

class Program
    {
        static void Main(string[] args)
        {
            var HelperA = new UniversityACourseRegistrationHelper();
            //invoke template method
            HelperA.RegisterStudent();
 
            var HelperB = new UniversityBCourseRegistrationHelper();
            //invoke template method
            HelperB.RegisterStudent();
 
            Console.WriteLine("Press any key to close this window...");
            //wait for user to input a key
            Console.ReadKey();
        }
    }

The output looks like this:

Validate transcript Processing Payment the generic way Send a letter Validate university records Processing Payment the generic way Send email Press any key to close this window...

The template method RegisterStudent is available to both UniversityACourseRegistrationHelper and UniversityBCourseRegistrationHelper by inheritance but steps 1 and 3 are overridden by each class. But when RegisterStudent is invoked on either class, step 2 (ProcessPayment) is executed because its implemented in the parent class. This makes it flexible for us to implement a step in the algorithm either in the parent class or in the derived class. Can we have the flexibility to provide a ‘default’ implementation of a step in the parent class and override the step in a sub class if necessary? Yes, absolutely.

Lets tweak the parent class slightly and make the ProcessPayment method virtual (overridable in a sub class).

 protected virtual void ProcessPayment()

Now lets override this method implementation in the UniversityACourseRegistrationHelper like this:

    public class UniversityACourseRegistrationHelper : CourseRegistrationHelper
    {
        //step 1
        protected override void VerifyPrerequisites()
        {
            Console.WriteLine("Validate transcript");
        }
 
        //step 2
        protected override void ProcessPayment()
        {
            Console.WriteLine("Processing payment University A way");
        }
 
 
        //step 3
        protected override void SendNotification()
        {
 
            Console.WriteLine("Send a letter");
        }
    }

Now the output of this program will look like this:

Please note that UniversityBCourseRegistrationHelper is still using the default implementation of ProcessPayment. But all sub classes have the flexibility of either using the default implementation in the parent class or provide it’s own implementation.

Those steps that are different for each concrete implementation in a sub class must be declared as abstract so each subclass will have to provide an implementation.

Lets revisit the Wikipedia definition. The ‘program skeleton’ on the Wikipedia page is defined in the RegisterStudent template method and that cannot be changed. But the individual steps are deferred to a subclass (like UniversityACourseRegistrationHelper). The individual steps in our case are VerifyPrerequisites, ProcessPayment and SendNotification.

The Wikipedia link has an excellent example in multiple programming languages and can be viewed here.

Hope you liked this post and the video. Your feedback is valuable to me. Also, i’d like to hear your experience with the Template Method Design Pattern.

Command Design Pattern

My new video on the command design pattern is online at:

Introduction

Any object oriented software operates on interaction of various software components called objects. A typical interaction between two objects is a “client-server” interaction where one object sends a request and the other object processes the request and returns a response. The command design pattern provides a way for the client to encapsulate each request as an object (command) and submit each such request object to a another object called the invoker.

Key Features of the Command Design Pattern:

  1. All the invoker knows is that it holds a collection of commands and it can execute those commands immediately or later. Also, the invoker does not know the details of what each command does.
  2. Since all commands implement a common interface, the invoker can execute those via the common interface and that way its not coupled to any concrete command and the details of what each command does.
  3. Another key player in this type of interaction is the receiver object. Each command encapsulates its receiver object. And there can be more than one receiver involved in the command pattern object interaction if necessary.
  4. A command is initiated by the invoker object but it is the receiver object that eventually processes the command.
  5. A command object is self-contained – it knows its receiver and all the data that is needed to execute that command. So a command can be persisted in a  “queue” and executed later.

So one advantage of using command pattern is that creation of commands is independent of when it is executed. Also, the commands can be grouped in multiple groups and executed in a batch like a macro. So if we were implementing an airplane’s navigation system, all the commands for a plane to depart (taxi to runway, takeoff, adjust altitude and speed to go up to 10000 feet) and arrive (reduce speed and altitude to be able to land, land and taxi to gate) can be two sets of commands. Each set is basically like a macro and can be executed at different points of time by the invoker which is the cockpit dashboard. Another advantage of the command design pattern is that the commands can be executed as a transaction where either all commands are executed or none of these are executed. In such as case, the command interface could provide two stubs – execute and undo. The ‘undo’ operation would reverse all the actions of a command. So if the invoker encounters an error, it would execute undo operation on all commands executed to that point and this will essentially be an “all or nothing” transnational operation.

The video link at the beginning of this post includes all the details of the command design pattern with an implementation of a logging framework. The source code is provided below.

Abstract Command:

//common contract for all logger commands
//this is the abstract command
public interface ILogMessageCommand
{
  void LogMessage();
}

Concrete Command for File Logging:

//concrete command
public class LogMessagetoFileCommand: ILogMessageCommand
{
//receiver
FileLog _fileLog = null;
//the message to be logged
String _message = null;
 
public LogMessagetoFileCommand(FileLog filelog, String message)
{
_fileLog = filelog;
_message = message;
}
 
public void LogMessage()
{
//interact with the receiver to process the command
_fileLog.LogMessage(_message);
}
 
}

Concrete Command for Database Logging:

public class LogMessagetoDatabaseCommand : ILogMessageCommand
{
   DatabaseLog _dbLog = null; //receiver
   String _message = null; //the message to be logged
 
  public LogMessagetoDatabaseCommand(DatabaseLog dblog, 
          String message)
   {
    _dbLog = dblog;
    _message = message;
   }
 
public void LogMessage()
   {
   //interact with the receiver to process the command
    _dbLog.LogMessage(_message);
   }
}

FileLog Receiver:

public class FileLog
{
   //singleton instance
   public static readonly FileLog Instance = new FileLog();
  //constructor should be private for singleton implementation
    private FileLog()
    {
    }
   //read the log file path from the application configuration file
    String _filePath = 
    ConfigurationManager.AppSettings["LogFilePath"].ToString();
   //write the log message to the file
   public void LogMessage(String message)
   {
    Console.WriteLine("Writing to a log file");
    string[] AllMessages = new string[] {message};
    File.WriteAllLines(_filePath, AllMessages);
   }
}

Database Log Receiver:

public class DatabaseLog
   {
    //singleton instance
     public static readonly DatabaseLog Instance 
     = new DatabaseLog();
   //constructor should be private for singleton implementation
    private DatabaseLog()
    {
    }
//read the connection string from the application configuration file
   String _connectionString 
   = ConfigurationManager.ConnectionStrings["LogDatabase"].ToString();
 
    //log the message to a database table
    //not implemented yet
   public void LogMessage(String message)
   {
     Console.WriteLine("Writing to a logging database");
     try
     {
      IDbConnection Conn = new SqlConnection(_connectionString);
      IDbCommand Cmd = new SqlCommand();
      Cmd.CommandType = CommandType.StoredProcedure;
      //stored procedure name for logging
      Cmd.CommandText = "usp_AddText";
 
      Cmd.Parameters.Add(new SqlParameter("@message", message)); 
     //Conn.Open();
     //Cmd.ExecuteNonQuery(); not implemented
     //Conn.Close();
     }
    catch (Exception ex)
     {
     //TODO: handle exception
     }
   }
}

Invoker:

public class LoggerFramework
{
   List _allCommands = null;
 
   //receive all commands
   public LoggerFramework(List allCommands)
    {
     _allCommands = allCommands;
    }
 
   //invoker them one by one
   //does not know concrete commands
   public void LogMessages()
   {
    foreach (ILogMessageCommand command in _allCommands)
    {
     command.LogMessage();
    }
  }
}

Invoker:

public class LoggerFramework
{
   List _allCommands = null;</code>
 
   //receive all commands
   public LoggerFramework(List allCommands)
   {
    _allCommands = allCommands;
   }
 
   //invoker them one by one
   //does not know concrete commands
    public void LogMessages()
    {
     foreach (ILogMessageCommand command in _allCommands)
    {
      command.LogMessage();
    }
  }
}

Client:

//create concrete command objects
//create log message to file command 
//and set the receiver and the message on it
ILogMessageCommand LogMessageToFileCommand = 
new LogMessagetoFileCommand(FileLog.Instance, "Message for file");
//create log message to database command and 
//set the receiver and the message on it
ILogMessageCommand LogMessagetoDbCommand = 
new LogMessagetoDatabaseCommand(DatabaseLog.Instance, 
"Message for database");
 
//create a list of commands
List _allCommands = new List();
_allCommands.Add(LogMessageToFileCommand);
_allCommands.Add(LogMessagetoDbCommand);
 
//create the invoker and set the commands on it
LoggerFramework framework = new LoggerFramework(_allCommands);
//request the invoker to execute all commands
framework.LogMessages();
 
//display a message for the user so thay can quit the program
Console.WriteLine("Press any key to quit.");
 
//wait for user input before console window is closed
Console.ReadKey();

Sorry this turned out to be a long post partly due to the inclusion of the source code. I’d love to hear from you how you have implemented the command design pattern. Any other feedback is always appreciated.

SQL Server Management Studio Error: Saving Changes is not Permitted

Problem: “Saving Changes is not permitted” error message in SQL Server Management Studio

This error is encountered when we attempt to alter a table in SQL Server Management Studio Designer and click the save button in the toolbar. This error message that pops up is:
Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can’t be re-created or enabled the option Prevent saving changes that require the table to be re-created.

1

You can prevent this error message from popping up by following these steps:
1. Click Tools -> Options

2

2. In the Designers -> Table and Database Designers form, uncheck the ‘Prevent saving changes that require table re-creation’ option.

3

Click OK and try to save the changes to the table. The error message would not popup again.

Proxy Design Pattern

Proxy is a very simple yet very powerful design pattern that is used a lot in software design. In fact, many people use Proxy Design Pattern but do not use the nomenclature. Please check out my video on the Proxy Design Pattern.

This post contains some additional information and source code of the applications shown in the video.

When we think of the Proxy Design Pattern, we think of a Proxy object that works like a “middleman”. This object sits in between the client object and the service object (called Real Subject in Proxy Design Pattern lingo), intercepts messages between the client and the service objects and provides additional functionality. The additional functionality could be one or more of the following:
1. Simply the communication between the the client and the service
2. Protect the service object from unauthorized access.
3. Do some additional data processing before the message is handed over to the service. The proxy object could do some data processing when the information is flowing back from the service to the client object.
4. Defer the instantiation of the service object as much as possible if the service object instantiation is costly.

And list of Proxy Object functionality is not confined to the bullets listed above. Any time we need a “middleman” to do any type of additional work, we could include a proxy object.

The class diagram of the Proxy Design Pattern is:

Proxy Design Pattern Class Diagram

 

The Proxy and the Real Subject are expected to provide a common interface to the client object. This is possible because their classes implement a common interface which is called AbstractSubject in the class diagram.

Wikipedia covers three usage scenarios of Proxy objects here.

The YouTube video covers the three usage scenarios described on the Wikipedia page. The scenarios are:
a. Remote Proxy – This proxy is useful when the client and the real subject reside in different address spaces. The service object in our example is a web service object hosted by United Postal Service (UPS). The methods on this remote service are invoked by the client object via a proxy that is generated by Visual Studio. To the client object, this service appears to be a local object and the service invocation appears just a local method invocation. But this proxy object (service reference) works with the .net runtime to convert these method invocations to web requests on the UPS Service object and so the service reference object works like a remote proxy. This video just shows how to create this service reference (remote proxy). If you are interested in using the UPS API for address validation and package tracking, it is discussed here and here.

b. Protection Proxy – This proxy prevents unauthorized access to an object. In our example, a protection proxy checks the security principal of the logged in user in a windows desktop application and allows or prohibits access to the real subject if the logged in user is in the administrators security group. This is the source code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
 
namespace ProxyDemoConsoleApplication
{
    class Proxy
    {
        public void DoSomething()
        {
            //code snippet in protection proxy method
            //get security principal associated with the
            //logged in user
 
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
 
            //check user access
            //is the user admin
            if (principal.IsInRole("Administrators"))
                RealSubject = new RealSubject();
                //invoke real subject method
                RealSubject.DoSomething();
            else  //if not, throw an exception
            {
                throw new SecurityException("Cannot access this object");
            }
 
        }
    }
}

c. Virtual Proxy – This proxy defers the instantiation of a real subject because the instantiation process is costly. The example in the video is a Customer Account class which holds a collection of Transactions. When you create Customer Account Class Instance, all the transactions on the customer account ever since it was opened is loaded an attribute on the object. The ShowBalance method on the class sums up the amounts associated with all transactions. This is the Customer Account class.

public class CustomerAccount: ICustomerAccount
    {
 
        IList AllTransactions = new List();
        String _customerId = null;
 
            public CustomerAccount(String customerId) {
 
            _customerId = customerId;
 
            //costly operation - load all transactions since the account was opened
            //.........
            //.........
 
        }
 
        public Decimal ShowBalance()
        {
            Decimal Balance = 0;
 
            //loop through each transaction and add the amount to determine total balance
            foreach(Transaction tr in AllTransactions)
            {
                Balance += tr.Amount;
            }
 
            return Balance;
        }
 
    }

The details of the Transaction object are not very relevant but the code is provided for the sake of completion.

    //abstract subject
    public interface ICustomerAccount
    {
        Decimal ShowBalance();
    }

Both Real Subject (CustomerAccount) and Proxy (ProxyCustomerAccount) implement a common interface.

public  class Transaction
    {
        DateTime _transactionDate; //date the transaction was done
        Decimal _amount; //transaction amount
        public Transaction(DateTime transactionDate, Decimal amount)
        {
            _transactionDate = transactionDate;
            _amount = amount;
       }
        public Decimal Amount
        {
            get
            {
                return _amount;
            }
        }
    }

The Proxy object’s constructor does not instantiate the real subject immediately. It creates the real subject only when the ShowBalance method is invoked. This is the code:

    //virtual proxy
    public class CustomerAccountProxy : ICustomerAccount
    {
 
        CustomerAccount realSubject = null;
        String customerID;
 
        public CustomerAccountProxy(String custId)
        {
            //store the customer ID as a private attribute
            customerID = custId;
            //defer the creation of customer account until
            //ShowBalance is called
            //do nothing for the time being
        }
 
        public Decimal ShowBalance()
        {
            //now create the real subject because the balance
            //cannot be determined until the real subject is loaded
            realSubject = new CustomerAccount(customerID);
            return realSubject.ShowBalance();
 
        }
    }

So the Client Object, which is a console application’s main method, can call methods on the Real Subject via the Proxy Object like this.

class Program
    {
        public static void Main()
        {
            //client code
            CustomerAccountProxy Proxy = new CustomerAccountProxy("12345678");
            //do some work
            //...
            //...
            //...
            //the real subject gets created when the next line is executed
            Console.WriteLine(Proxy.ShowBalance());
            Console.ReadKey();
        }
    }

All code is c# and targets .Net Framework 4.5. I’d love to hear from you on your experience with the Proxy Design Pattern and also your feedback on this post and the YouTube Video.

Facade Design Pattern

Facade Design Pattern is one of the simplest design patterns that is used frequently in software design. As per Wikipedia, the word ‘Facade’ is derived from the building architecture term Facade which is one exterior side of a building. This is the “interface” to the building. In the same way, a Facade is an interface to a larger body of code. More details are available at this Wikipedia link.

Please check out my new video on the Facade Design Pattern.

This video provides a simple example from real life where an individual acts like a “Facade”. A surveyor has a questionnaire that needs the following information:
1. Age Range of the person filling the survey
2. Income Range of the person filling the survey
3. Name of their favorite cafe in the city.

Lets assume that the person who wants to conduct this survey needs to visit an office building and collect this information from all the employees working in that building. One way to do this would be to speak to each employee and collect this data. This is, of course, assuming they will allow the survey person to speak to each employee. Another option is to speak to the location supervisor and hand over these survey to that person. The supervisor would talk to each employee, collect this information and hand over the responses on a stack of paper or electronic document to the survey person. This greatly simplifies the interaction between the survey person and the employees in that building. And in this case, the supervisor is the ‘facade’ to the employees in the building. Please note that the total number of interactions for data collection does not change but the interface between the survey person and the the employees is certainly simplified. This is application of the “Facade” pattern in terms of human interaction.

If we extend this model to software design, we could consider this scenario as an example. We have a class library called GeographicalServicesLibrary. The purpose of this library is to provide the distance between two addresses. This class library consists of the following classes:

a. Address Validator – This class exposes a solitary method that takes an address as a string parameter and returns a properly formatted address (format defined by postal service) to the caller. If the address is invalid, the returned string would contain an error code.

b. Geocode Helper – This class exposes a method that takes a properly formatted address and returns a Point object that contains the coordinates of that address (latitude and longitude).

c. Distance Calculator – This class provides a method that calculates the distance between two Point objects.

In order to calculate the distance between two addresses, the client object has to perform the following calls to this class library:

i. Call the Address Validator method and validate the first address.

ii. Call the Address Validator method and validate the second address.

iii. Call the Geocode Helper method and get the coordinates of the first address.

iv. Call the Geocode Helper method and get the coordinates of the second address.

v. Call Distance Calculator method and pass the coordinates of the two addresses and get the distance between the two coordinates.

This is shown in the c# code below:

//validate the first address
String ValidatedAddress1 = AddressValidatorObject.ValidateAddress(Address1);
//validate the second address
String ValidatedAddress2 = AddressValidatorObject.ValidateAddress(Address2);
//get the coordinates of the first address
Point p1 = GeocodeHelperObject.GetGeoCode(ValidatedAddress1);
//get the coordinates of the second address
Point p2 = GeocodeHelperObject.GetGeoCode(ValidatedAddress2);
//calculate the distance between the two addresses
Double Distance = DistanceCalculatorObject.GetDistance(p1, p2);

The total number of interactions between the client object and the class library members can be significantly reduced by introducing a “facade” object called the Geographical Service Facade. This class could expose a method that would take the two addresses as input parameters and return the distance between the two addresses. This facade object could interact with the members of this class library to get the desired output (distance between two addresses). The Facade class reduces the dependencies between the client and the class library members because only one class (the Facade) has dependencies on the class library. This is specially important if the class library is a third party library that may get replaced later. If a replacement is needed, only the one call in the Facade needs to change.

This is shown in the c# code below:

//calculate the distance between two addresses
Double Distance = 
GeographicalServicesFacadeObject.CalculateDistance(Address1, Address2)

Also, you could argue that the class library was poorly designed. If the goal of the class Library is the return the distance between two addresses, all it had to do was to keep expose this functionality perhaps as a Facade object. And the library could hide the three classes –  Address Validator, Geocode Helper and Distance Calculator. This brings forward another advantage of the Facade Pattern that it simplifies interactions with a poorly designed library. In general, Facade Pattern makes a library or any collection of components easy to use and test. This is because the interface to the components is greatly simplified due to the introduction of the Facade object. Please note that Facade does not necessarily has to hide a large collection of components or a class library. It could just be introduced to simply interactions among any collection of objects.

Thanks for visiting this site and reading this post. Hope you liked the explanation. I’d love to get your feedback on this post and also your experience with the Facade Design Pattern.

Invoke UPS Address Validation API using C# and Visual Studio 2015

Introduction

This post covers the steps needed to use the Street Address Validation Application Programming Interface (API) of United Parcel Service (UPS). We will cover the steps of registering with UPS first to get credentials/license key from UPS and then use the street address validation API in a C# console application. We will use Visual Studio 2015 as Integrated Development Environment (IDE) and build a Windows Communication Foundation (WCF) client to invoke the UPS API.

Assumptions:

  1. You are familiar with a .net programming language (preferably C#) and Visual Studio .Net.
  2. You understand the basics of Windows Communication Foundation and how to consume a web service with the help of a WSDL file.

If you perform an internet search on the keywords ‘UPS Developer API’, you will get the link to the web page that covers all the documentation you need. The link is:

https://www.ups.com/upsdeveloperkit

In order to access UPS API, you need a userid/password credential and an access key.

Step 1: Get Security Credentials

Get a userid and password by registering with My UPS if you don’t have one already. This is step 1 on UPS web page.

1

Step 2: Get Access Key

Login to the same page mentioned above by using the credentials obtained in step 1 and request access key (Step 5 on the page). The access key will be displayed on your browser window. You will also get an email with the same access key information.

2

Now we are ready to write code.

Step 3: Build Code

Step 3a: Download API Files

UPS exposes different APIs for different types of functionality. In this tutorial, we will use their ‘Address Validation – Street Level’ API. Please go ahead and download the API documentation.

3

4

The API will be downloaded as a zip file. Extract the zip file to a folder of your choice. Navigate to the folder that contains the WSDLs of the Address Validation Service. If you extracted the zip file to a folder called ‘C:\UPS’, you will have to navigate to ‘C:\UPS\Street Level Address Validation for SHIPPING\XAVWebServices\SCHEMAS-WSDLs’

5

Please note that the WSDL file and all its dependencies (XML schemas) exist in the same folder.

Step 3b: Create Console Project

6

Step 3c: Add Service Reference

Right click on the console project and add service reference to the UPS service.

7

Now provide the full path of the WSDL file. Rename the proxy namespace to XAVServiceProxy.

8

Also, please note how Visual Studio adds WCF client configuration to your app.config file. You don’t need to change this please note the address of the service and the types of binding and contract. The service endpoint URL is the URL of UPS test environment.

9

Step3d: Add code

Add the following code to the Program.cs project startup class. I have tried to document the code as much as possible so it becomes self-explanatory.

using System;
 
using System.Collections.Generic;
 
using System.Linq;
 
using System.Net;
 
using System.Net.Security;
 
using System.Security.Cryptography.X509Certificates;
 
using System.Text;
 
using System.Threading.Tasks;
 
using UPSStreetAddressValidationConsoleApplication.XAVServiceProxy;
 
namespace UPSStreetAddressValidationConsoleApplication
 
{
 
class Program
 
{
 
static void Main(string[] args)
 
{
 
try
 
{
 
//this is the remote proxy object
 
XAVPortTypeClient Proxy = new XAVPortTypeClient();
 
//build the username token object
 
UPSSecurityUsernameToken UPSSecurityUsernameTokenObj = new UPSSecurityUsernameToken();
 
//use your userid when youn registered with my UPS
 
UPSSecurityUsernameTokenObj.Username = "your user id";
 
//use the password associated with your userid
 
UPSSecurityUsernameTokenObj.Password = "your password";
 
//build the security access token object
 
UPSSecurityServiceAccessToken UPSSecurityServiceAccessTokenObj = 
new UPSSecurityServiceAccessToken();
 
//your access key provided by UPS
 
UPSSecurityServiceAccessTokenObj.AccessLicenseNumber = "your access key";
 
//set the username and service access objects on the UPSSecurity input parm object
 
//this is the first parameter of the ProcessXAV method on UPS service
 
UPSSecurity UPSSecurityObj = new UPSSecurity();
 
UPSSecurityObj.UsernameToken = UPSSecurityUsernameTokenObj;
 
UPSSecurityObj.ServiceAccessToken = UPSSecurityServiceAccessTokenObj;
 
//build the transaction reference type
 
TransactionReferenceType TransactionReferenceTypeObj = new TransactionReferenceType();
//pass any value
TransactionReferenceTypeObj.CustomerContext = "Customer Data"; 
//pass any value
TransactionReferenceTypeObj.TransactionIdentifier = "12335"; 
 
//build the request type
 
RequestType RequestTypeObj = new RequestType();
//this value has to be 1
RequestTypeObj.RequestOption = new String[1] { "1"}; 
 
RequestTypeObj.TransactionReference = TransactionReferenceTypeObj;
 
//this is the class where we will pass the address data elements
 
//passing address of new York stock exchange for testing purpose
 
AddressKeyFormatType AddressKeyFormatTypeObj = new AddressKeyFormatType();
 
AddressKeyFormatTypeObj.AddressLine = new String[1] { "11 Wall Street" };
 
//political division 1 is required for get valid address validation code 
//otherwise you get an exception
 
AddressKeyFormatTypeObj.PoliticalDivision1 = "NY"; //state code
 
AddressKeyFormatTypeObj.PoliticalDivision2 = "New York"; //city
 
AddressKeyFormatTypeObj.CountryCode = "US"; //country must be US or PR
 
AddressKeyFormatTypeObj.PostcodePrimaryLow = ""; //passing a blank value
 
//now let’s build the second parameter
 
XAVRequest XAVRequestObj = new XAVRequest();
 
XAVRequestObj.AddressKeyFormat = AddressKeyFormatTypeObj;
 
XAVRequestObj.Request = RequestTypeObj;
 
//added to handle the intermittent error with SSL/TLS connection
 
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | 
SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | 
SecurityProtocolType.Tls12;
 
//open channel
 
Proxy.Open();
 
//call the service
 
XAVResponse Response = Proxy.ProcessXAV(UPSSecurityObj, XAVRequestObj);
 
//parse the result
 
ItemChoiceType Result = Response.ItemElementName;
//found multiple matches
if (Result == ItemChoiceType.AmbiguousAddressIndicator) 
{
 
Console.WriteLine(String.Format("Ambiguous Address.Found {0} matching candidate addresses",
Response.Candidate.Length.ToString()));
 
//print each candidate address that was returned as response
foreach (CandidateType candidateAddress in Response.Candidate)
{
Console.WriteLine(String.Format("Consignee Name: {0}", 
candidateAddress.AddressKeyFormat.ConsigneeName));
Console.WriteLine(String.Format("Street Line 1: {0}", 
candidateAddress.AddressKeyFormat.AddressLine[0]));
if (candidateAddress.AddressKeyFormat.AddressLine.Length > 1)
Console.WriteLine(String.Format("Street Line 2: {0}", 
candidateAddress.AddressKeyFormat.AddressLine[1]));
Console.WriteLine(String.Format("City: {0}", 
candidateAddress.AddressKeyFormat.PoliticalDivision2));
Console.WriteLine(String.Format("State: {0}", 
candidateAddress.AddressKeyFormat.PoliticalDivision1));
Console.WriteLine(String.Format("Zip: {0}-{1}",
candidateAddress.AddressKeyFormat.PostcodePrimaryLow,
Response.Candidate[0].AddressKeyFormat.PostcodeExtendedLow));
 
}
 
}
//invalid address no match found
else if (Result == ItemChoiceType.NoCandidatesIndicator) 
 
Console.WriteLine("Invalid Address");
//valid address exactly one candidate returned
else if (Result == ItemChoiceType.ValidAddressIndicator) 
 
{
 
Console.WriteLine("Valid Address");
 
Console.WriteLine(String.Format("Consignee Name: {0}", 
Response.Candidate[0].AddressKeyFormat.ConsigneeName));
 
Console.WriteLine(String.Format("Street Line 1: {0}", 
Response.Candidate[0].AddressKeyFormat.AddressLine[0]));
 
if (Response.Candidate[0].AddressKeyFormat.AddressLine.Length > 1)
 
Console.WriteLine(String.Format("Street Line 2: {0}", 
Response.Candidate[0].AddressKeyFormat.AddressLine[1]));
 
Console.WriteLine(String.Format("City: {0}", 
Response.Candidate[0].AddressKeyFormat.PoliticalDivision2));
 
Console.WriteLine(String.Format("State: {0}", 
Response.Candidate[0].AddressKeyFormat.PoliticalDivision1));
 
Console.WriteLine(String.Format("Zip: {0}-{1}",
Response.Candidate[0].AddressKeyFormat.PostcodePrimaryLow,
Response.Candidate[0].AddressKeyFormat.PostcodeExtendedLow));
 
}
 
//close communication channel
 
Proxy.Close();
 
}
 
catch (Exception ex)
 
{
 
//please add code to handle SOAP exceptions
 
Console.WriteLine(ex.Message);
 
}
 
//do not close the console window unless the user presses a key
 
Console.ReadKey();
 
}
 
}
 
}

 

Step 4: Test the code

Run the project and test with different values of address input. I have used the address of the New York Stock Exchange as a test address in my code example.

Please note:

  1. As per their website, the UPS Test URL works only for California and New York State addresses.
  2. Make sure you pass ‘US’ or ‘PR’ as country code. If you do not pass one of two values, you will get a SOAP Exception. The current UPS API supports US and Puerto Rico country codes.
  3. Make sure you pass value of “1” as RequestOption. Please see code comments for more details.
  4. Pass the two character state code in Political Division 1. If you don’t, you will get an exception.
  5. Pass the city name in the PoliticalDivision2 field.
  6. I found UPS documentation to be dated and out of synch with their current code. But it is still a good idea to read their documentation to get some general ideas about their service.
  7. The code in this post works at the time of writing this post (December 1, 2016).
  8. No warranty is provided with the code or any documentation in this article.

This code could be refactored into multiple helper methods but I wanted to provide one block of code with no dependencies to keep things simple for this post.

I will continue to test their APIs and try RESTful invocation if their API supports it. If you have any questions, feel free to post those in the comments area. Your feedback, as always, is appreciated.