Request the Google PageRank the Delphi way

In this post I am implementing the Delphi way to request the Google Toolbar’s PageRank (PR). As an example, if I want to look up the PR of my blog (http://www.yanniel.info/), I will have to query the following URL:

http://toolbarqueries.google.com/tbr?client=navclient-auto&features=Rank&ch=64012521073&q=info:http://www.yanniel.info/

So, if you try

Writeln(Curl('http://toolbarqueries.google.com/tbr?client=navclient-auto&features=Rank&ch=64012521073&q=info:http://www.yanniel.info/'));

You will get the following output:

Rank_1:1:0

Oops, at this moment my PageRank is pathetic (PR = 0). Hopefully it will get better someday ;-)

You can find the implementation of the Curl function in my previous post: Fetching a web page with Delphi.

Now that you get the idea, it’s time to generalize our implementation in order to get the PR of any web page.

In the URL above there are two dynamic parameters that we need to understand:

Parameter q: This is the concatenation of “info:” plus the encoded URL for which we want to get the PR. It is mandatory to lead the encoded URL with “http://”. Don’t forget to put a “/” after the top domain, ei, “.info/”, not “.info”.

Parameter ch: Obtaining this parameter is the tricky part. We have to hash the concatenation of “info:” plus our target URL (ei. http://www.yanniel.info/) using the minimal perfect hashing algorithm invented by Bob Jenkins. The outcome will be a number, which corresponds to the value of our ch parameter. We are hashing something like “info:http://www.yanniel.info/”.

I didn’t have the time (or the desire) to understand and implement the minimal perfect hashing algorithm from scratch. So, I ported this C# implementation into Delphi code.

There’s one detail worth mentioning about the implementation. In the original C# code there’s a switch statement that falls all the way through the different cases. I needed to combine a case statement and some goto statements in order to accomplish the same in Delphi. Really, I tried to avoid the goto, I always do, but I couldn’t find a better and cleaner way of implementation. I was telling myself how bad programmer I was, and then, I read one entry in Delphi Feeds talking about the minimal perfect hashing algorithm, and more than that, highlighting the goto issue. Nick Hodges wrote the post: thank you Nick... now I can sleep again.

It seems that I am not the only one considering this goto usage as an exception to the good practice of “don’t use goto statements”. The funny thing is that I read Nick’s post without the intention of finding anything about the minimal perfect hashing algorithm or about the goto stuff. It’s really a big coincidence that we were considering to write about the minimal perfect hashing algorithm (and the goto gotcha) at the same time.

I wrote the strikeout text above initially; but Brian (first comment below) found a clean way to avoid the goto in this situation. I really thank Brian for his contribution, and next time, I won't quit that easily in removing the goto ;-)

I am putting everything together in the Delphi console application below. I bet you can reuse the BobJenkinsHash function in the Generics.Default.pas unit to make the PR implementation more compact. I didn’t know about the BobJenkinsHash function shipped with Delphi before reading Nick’s post; which is why I am keeping my original implementation.      

Finally, this is how you request the Google PageRank in Delphi:

Pascal Server Pages – Pascal Script

Without getting too technical, I would define a Pascal Server Page (PSP) as a dynamic web page containing embedded Pascal Script (PS) code.  When a web request is made, the PS code needs to be executed (interpreted) in the server side and outputted into the proper format (HTML, XML, JSON, text, etc). A PSP is commonly stored as a text file in the Web Server and it could be a mixture of PS code plus any other static content.

This is an example of PSP:

<html>
  <head>
    <title>This is a Pascal Server Page</title>
  </head>
  <body>
    <% begin
         Write('Hello World');
       end.
    %>
    <p>I am going to use Pascal Script to write a few numbers...</p>
    <% var
         i: Integer;
       begin
         for i:=1 to 10 do
           Writeln(i); 
       end.
    %>
  </body>
</html>

The code above is an HTML armature containing some PS code. The PS code has been isolated within the “<%” and “%>” tokens. The PS code is executed in the server and the output (if any) is embedded into the HTML template.

So, if a browser asks for the page above, it will actually get plain HTML code as the one below:

<html>
  <head>
    <title>This is a Pascal Server Page</title>
  </head> 
  <body>   
    Hello World
    <p>I am going to use Pascal Script to write a few numbers...</p>
    1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>
  </body>
</html>

This is all good. The only problem is that the PS code is not going to be magically executed. We need a server side component to do the PS interpretation.

I have seen a couple of intents to build such server side component in the Internet. Anyhow, I bring you my own proposal: create a Web Broker application with Pascal Scripting capabilities. To provide the Web Broker application with the scripting capabilities, I will use Pascal Script from RemObjects. You need to download and install Pascal Script if you want to try my code. 

The workflow goes as follows:
  1. The Web Broker application receives a Web Request.
  2. The Web Broker application finds the corresponding Pascal Server Page and loads its content to a buffer variable.
  3. The content of the buffer variable is parsed in order to find the PS tokens (I will use RegEx to do the parsing).
  4. Each PS block is compiled to Bytecode and then executed in the server. (I will use the Pascal Script library from RemObjects for this purpose). 
  5. The output generated from the execution of each PS block replaces its corresponding “<%......%>” block.
  6. The Web Broker app serves the response.
I developed a VCL standalone Web Broker application as a proof of concept (it could be an ISAPI dll as well). See it in action in the following video:



That application is just a prototype. I really believe that we could build a robust server side component to leverage enterprise Pascal Server Pages. I used Web Broker in this example, but we could also build Apache Modules with Free Pascal.

I am posting below the code of the TWebModule1 class, which is the core of the Web Broker app. The full source code and executable can be downloaded here. (the code was compiled with Delphi XE2). Note that the code is somewhat messy; this was taken directly from my sandbox. Ah, I copy-pasted (and adjusted) the Pascal Script routines from this example: Introduction to Pascal Script.

Salary Guide for Delphi developers: Let’s make it

If you work as an IT professional in North America, you should probably find very useful the 2012 Technology Salary Guide published by Robert Half Technology.

This guide exposes the compensation trends (salary trends) for pretty much every position in Information Technology. It covers the United States of America and Canada, and you could even obtain salary ranges for particular cities.

This guide is useful for both managers and non-managers individuals. In my particular case, I am always curious to know if I am getting paid decently.

The tables below are an excerpt taken from the guide:

 2012 Average Starting Salaries – United States

Job Title
2011
2012
% Change
Software Developer
$ 65,750 - $ 104,250
$ 70,000 - $ 111,000
6.5%

2012 Average Starting Salaries – Canada

Job Title
2011
2012
% Change
Software Developer
$ 56,250 - $ 94,000
$ 59,750 - $ 99,750
6.2%

There are further statistics in the guide about Java, .NET, C++, PHP and other programming languages. You can use that info in order to tune the indicators above even more. There are no details about Delphi in this guide.

I think that we (the Delphi community) could gather some statistics about the salary rates for Delphi Developers. I propose running poll surveys to gather such information. Once the polls are closed, we will publish the outcomes and we can draft our conclusions.

The polls are finally closed. Go to the end of this post and take a look at the outcomes. Thanks a lot to all the participants: 45 in the United States and 30 in Canada. It’s funny how the number of voters was a multiple of 5 in both countries :-)

Take a look at the right column of this page: I have published two polls to collect the information about the salary rates in the United States and Canada. I am only putting together the data for these two countries, because I already have some reference data to compare with. (I am referring to the data in the tables above). It would be really nice if someone else could take ownership of similar polls for other countries.


Important:
  • I will kindly ask to vote, IF and ONLY IF, you are (were) working as a Delphi Developer in the United States or Canada during the current year 2011.
  • We could make this better if you enroll your coworkers or any other Delphi developers in your area.
  • The poll is by nature anonymous: we are just gathering collective information.
Please, in order for this to work we need your vote!

What’s the salary for a Delphi Developer in the United States?

< $ 50,000                               5  (11%)
$ 50,000 - $ 60,000                 2  (4%)
> $ 60,000 - $ 65,000              1  (2%)
> $ 65,000 - $ 75,000              7  (15%)
> $ 75,000 - $ 85,000            12  (26%)
> $ 85,000 - $ 95,000              4  (8%)
> $ 95,000 - $ 105,000            5  (11%)
> $ 105,000 - $ 115,000          4  (8%)
> $ 115,000                             5  (11%)
                                                   
What’s the salary for a Delphi Developer in Canada?
                                                 
< $ 50,000                               6  (20%)
$ 50,000 - $ 60,000                 5  (16%)
> $ 60,000 - $ 65,000              2  (6%)
> $ 65,000 - $ 75,000              3  (10%)
> $ 75,000 - $ 85,000              2  (6%)
> $ 85,000 - $ 95,000              1  (3%)
> $ 95,000 - $ 105,000            5  (16%)
> $ 105,000 - $ 115,000          1  (3%)
> $ 115,000                             5  (16%)

Generating Fibonacci numbers in Delphi: Recursive and iterative algorithms

In this post, I want to implement a function that returns the Nth Fibonacci number. Initially, I will provide a recursive implementation that derives directly from the Fibonacci sequence definition. Afterwards, I will recode the same function using an iterative approach.

Why do I want to do (share) such a thing? Well, firstly for fun :-) and secondly, because I was asked to do something similar in one phone screen interview. Really? Yep, I was asked to code a function to return the factorial of a number and then, I had to read it over the phone. I implemented the recursive algorithm. At this point, I was asked why I decided to use recursion as opposed to iteration. My answer was that I find the recursive implementation easier (and cleaner) to write. The interviewer finally inquired me about the iterative implementation…

This motivated me to resolve similar programming tasks (recursively and iteratively) just as a training exercise. 

Well, enough with that blah, blah, blah.

Taken from Wikipedia:  

The Fibonacci numbers form a sequence of integers, mathematically defined by


    F(0)=0; F(1)=1; F(n) = F(n - 1) + F(n - 2) for n > 1.


This results in the following sequence of numbers:


    0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...

This simply means that by definition the first Fibonacci number is 0, the second number is 1 and the rest of the Fibonacci numbers are calculated by adding the two previous numbers in the sequence. 

Translating that into Delphi code:

function Fibonacci(aNumber: Integer): Integer;
begin
  if aNumber < 0 then
    raise Exception.Create('The Fibonacci sequence is not defined for negative integers.');

  case aNumber of
  0: Result:= 0;
  1: Result:= 1;
  else
    Result:= Fibonacci(aNumber - 1) + Fibonacci(aNumber - 2);
  end;
end;

The function above is the recursive implementation, which in my opinion fits naturally. Now, the iterative implementation might not be as cleaner as that:

function Fibonacci(aNumber: Integer): Integer;
var
  I,
  N_1,
  N_2,
  N: Integer;
begin
  if aNumber < 0 then
    raise Exception.Create('The Fibonacci sequence is not defined for negative integers.');

  case aNumber of
    0: Result:= 0;
    1: Result:= 1;
  else
    begin
      N_1:= 0;
      N_2:= 1;
      for I:=2 to aNumber do
      begin
        N:= N_1 + N_2;
        N_1:= N_2;
        N_2:= N;
      end;
      Result:= N;
    end;
  end;
end;

Finally, if you want to produce the first 21 Fibonacci numbers try this out:

program Project2;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

var
  I: Integer;

function Fibonacci(aNumber: Integer): Integer;
begin
  {Your implementation goes here}
end;

begin
  for I:=0 to 20 do
    Writeln(Fibonacci(I));
  Readln;
end.

Hopefully you are not bored to death :-)

Internationalizing your Delphi application: An ABC example

If you want to make your Delphi application general enough to address multiple locales, then you need to internationalize it. There are three common aspects that I want to emphasize (no necessarily in that order):
  • Resourcing
  • Unit conversions
  • Dynamic messages
We’ll cover the three of them with a very simple example. Consider the following code snipped intended for the en-US locale (English-United States of America):

procedure TForm1.DefineFever;
begin
  ShowMessage('If the body temperature rises above 99°F the person is considered to have a fever.');
end;

Resourcing is the process of removing hard-coded strings from the code by making them resourcestrings instead.

The code above is not localizable because the ShowMessage procedure is taking a hard-coded string. What do you do? Take a look:

procedure TForm1.DefineFever;
resourcestring
  strFeverDefinition = 'If the body temperature rises above 99°F the person is considered to have a fever.';
begin
  ShowMessage(strFeverDefinition);
end;

We defined strFeverDefinition as a resourcestring and used it as a parameter for the ShowMessage procedure. The functionality remains the same, but the function is now localizable.

Unit conversions: In some countries (like the United States and Belize) the temperature is given in the Fahrenheit scale, but in the rest is given in the Celsius scale. In order to internationalize this we can do the following:

function GetFeverTemperature: string;

var
 
LangID: LangID;
begin
  //By default
  Result:= '37.2°C';

  {read current system locale}
 
LangID := GetSystemDefaultLangID;

  //Assuming that only the United States and Belize use the Fahrenheit scale
  if (
LangID = {English - United States} 1033) or        
     (LangID = {English - Belize} 10249) then
  Result:= '99°F';
end;

procedure TForm1.DefineFever;
begin
  ShowMessage('If the body temperature rises above ' + GetFeverTemperature + ' the person is considered to have a fever');
end;

Wait a minute, we managed the unit conversion by introducing a dynamic message, but we reintroduced the hard-coded strings. That’s not good!

Dynamic messages: We consider the ShowMessage above to be a dynamic message, because the parameter depends on the GetFeverTemperature function, which of course can vary. 

To solve the pitfall above we can refactor the DefineFever function as follows:  

procedure TForm1.DefineFever;
resourcestring
  strFeverDefinition = 'If the body temperature rises above %0:s the person is considered to have a fever.';
begin
  ShowMessage(Format(strFeverDefinition, [GetFeverTemperature]));
end;

We are just using a format string (resourcestring) that we can format by using the Format routine. This allows resourcing and handling the dynamic message all at once.

The thing about dynamic messages goes beyond. In Spanish, for instance, the dynamic message would have been coded as follows:

ShowMessage('Se considera que la persona tiene fiebre si la temperatura corporal es superior a ' + GetFeverTemperature);

Note that the GetFeverTemperature is at the end of the ShowMesssage parameter, as opposed to the English implementation that has it in the middle. There’s no way you can localize something like this if you don’t internationalize it first.

So the ABC for Delphi localization is Resourcing, Unit Conversions and Dynamic Messages

Multiton Design Pattern in Delphi

The multiton is somewhat an extension of the singleton pattern. It is referred as registry of singletons by the GOF. I don’t know for sure who appointed the name multiton: it’s an analogy derived from the term singleton. So, singleton = single + ton; while multiton = multi + ton.

The singleton pattern guarantees that a class has only one instance; while the multiton allows keeping multiple instances by maintaining a map of related keys and unique objects.  Note that there can be only one instance per key when implementing the multiton pattern. Also, note that the key does not have to be a string value; it can be an object for example. Nonetheless, in our code sniped we will consider the key to be a string.

I am going to tweak my singleton class implementation so that I can make it a multiton instead:

unit Multiton;

interface

uses
  Generics.Collections;

type
  TMultiton = class
  private
    //Private fields and methods here...

     class var _registry: TDictionary<string, TMultiton>;
  protected

  public
    class function Create(aName: string): TMultiton;
    class destructor Destroy;
    class function Lookup(aName: string): TMultiton;
  
    destructor Destroy; override;

    //Other public methods and properties here...  
  end;

implementation

{ TMultiton }

class function TMultiton.Create(aName: string): TMultiton;
begin
  if not Assigned(_registry) then
    _registry:= TDictionary<string, TMultiton>.Create;

  if not _registry.TryGetValue(aName, Result) then
  begin
    Result:= inherited Create as Self;
    _registry.Add(aName, Result);
  end;
end;

class destructor TMultiton.Destroy;
begin
   if Assigned(_registry) then
   begin
     _registry.Values.ToArray[0].Free;     
   end;
end;

class function TMultiton.Lookup(aName: string): TMultiton;
begin
  if Assigned(_registry) then
    _registry.TryGetValue(aName, Result);
end;

destructor TMultiton.Destroy;
var
  _instance: TMultiton;
  ValuesArray: TArray<TMultiton>;         
begin
  if Assigned(_registry) then
  begin
    ValuesArray:= _registry.Values.ToArray;

    _registry.Clear;
    _registry.Free;
    _registry:= nil;

    for _instance in  ValuesArray do
      if _instance <> Self then
        _instance.Free;
  end;

  inherited;
end;

end.

A few things I want you to note:
  • Instead of a single instance, we are holding a registry of instances. We do so by introducing the class variable _registry of type TDictionary<string, TMultiton>.  
  • We register (create) the different instances by calling the class function Create. This function gets the key name as a parameter. A new instance is only created if no matches to the key name are found in the dictionary. If a match is found, then the corresponding value is returned from the dictionary data structure.
  • The Lookup class function allows retrieving a particular instance by giving its key name. Note that the Create function can also be used for this purpose, but it feels more natural to call Lookup for the searches, and Create for the registration (creation) of instances.
  • We have provided a regular destructor that once invoked releases all the memory: not only the current multiton instance, but the whole registry.    
  • We have also provided a class destructor in case that we forget to manually release the memory.  
This code was compiled with Delphi XE2, but it should also work for all versions above Delphi 2009. Comments, corrections and suggestions are most welcome.

Consider reading these books about design patterns if you haven’t yet:

Dependency Injection in Delphi: a simple example

I want to give a fairly simple Delphi example that will expose the dependency injection pattern. No framework, no third-party library will be needed here: just plain Delphi code.

I won’t dig into the different forms of dependency injection. I will explain the idea of the pattern as simple as possible.

Instead of giving you bunch of definitions, I will present you with some code. The need to inject a dependency will come naturally. You’ll see:

type
  IDependency = interface
  ['{618030A2-DB17-4532-81D0-D5AA6F73DC66}']
    procedure GetType;
  end;

  TDependencyA = class(TInterfacedObject, IDependency)
  public
    procedure GetType;
  end;

  TDependencyB = class(TInterfacedObject, IDependency)
  public
    procedure GetType;
  end;

 TConsumer = class
  private
    FDependency: IDependency;
  public
    constructor Create(aDependencyClassName: string);
    procedure GetDependencyType;
  end;

implementation


{ TDependencyA }

procedure TDependencyA.GetType;
begin
  WriteLn('Instance of type TDependencyA');
end;

{ TDependencyB }

procedure TDependencyB.GetType;
begin
  WriteLn('Instance of type TDependencyB');
end;

{ TConsumer }

constructor TConsumer.Create(aDependencyClassName: string);
begin
  if aDependencyClassName = 'TDependencyA'  then
    FDependency:= TDependencyA.Create
  else if aDependencyClassName = 'TDependencyB'  then
    FDependency:= TDependencyB.Create;
end;

procedure TConsumer.GetDependencyType;
begin
  if FDependency <> nil then
    FDependency.GetType;
end;

It is a good and recommended practice in OOP to decrease coupling as much as possible. This means that each component (class) should avoid knowing implementation details of the other components (classes).

In our example, the TConsumer class has a dependency of type IDependency. So far so good, since we are abstracting any implementation specifics by using an interface (contract). The problem becomes obvious when you take a look at the constructor of TConsumer.

TConsumer.Create is instantiating the concrete classes TDependencyA   or TDependencyB depending on the string parameter aDependencyClassName. As you can see, the design is not well decupled here, because the consumer class (TConsumer) is hard-coding implementation details about its dependency.  

The question is: can we decuple this design even more? Yes, the dependency injection pattern will do it for us.

It’s now time to refactor our code a little bit. We’ll start by changing the signature of the constructor of the TConsumer class:

constructor TConsumer.Create(aDependency: IDependency);
begin
  FDependency:= aDependency;
end;

Instead of choosing the concrete dependency to instantiate within the constructor, we are now injecting the dependency trough the aDependency parameter. Now the class TConsumer is completely independent of the dependency concrete class.

Ok, ok, but we still need to create the concrete dependency instance somewhere, right? Yes, we do. For that we will create a new class TDependencyInjector whose only purpose is to return the right dependency instance. This class will use reflection in order to create the right instance of IDependency. It will use just a string parameter that contains the dependency class name.

uses
  RTTI,
  Dependencies;

type
  TDependencyInjector =  class
  public
    class function GetDependency(aDependencyClassName: string): IDependency;
  end;

implementation

{ TDependencyInjector }

class function TDependencyInjector.GetDependency(aDependencyClassName: string): IDependency;
var
  RttiContext: TRttiContext;
  RttiType: TRttiInstanceType;
begin
  RttiType := RttiContext.FindType(aDependencyClassName) as TRttiInstanceType;
  if RttiType <> nil then
    Result:= RttiType.GetMethod('Create').Invoke(RttiType.MetaclassType, []).AsInterface as IDependency;
end;

Finally, let's put all the pieces together. Consider this console application that puts all the pieces in place:

program DependencyInjection;

{$APPTYPE CONSOLE}

{$R *.res}

uses
...

var
  SomeConsumerObj: TConsumer;
  Dependency: IDependency;

begin
  Dependency:= TDependencyInjector.GetDependency('Dependencies.TDependencyA');
  //Dependency:= TDependencyInjector.GetDependency('Dependencies.TDependencyB');
  SomeConsumerObj:= TConsumer.Create(Dependency);

  try
    SomeConsumerObj.GetDependencyType;
  finally
    SomeConsumerObj.Free;
  end;

  Readln;
end.

In the code above we get the Dependency instance at runtime by using the TDependencyInjector class. Then we inject that dependency using the constructor of the class  TConsumer. We have got a more decoupled design by using dependency injection. Don't you agree? ;-)

Get the full source code of this example here (written in Delphi XE 2).

How to apply for US visitor visa from Canada?

I immigrated to Canada under the Federal Skilled Worker Program on February 26th, 2010. This program granted me with permanent residency since the day I landed.

I wanted to visit the United States of America; but as a Canadian Resident (not yet a citizen) I was required to get a US visitor visa.

Merely 20 months after my relocation to Canada I applied for a visitor visa and I got it. I was granted a single entry visa which I used to visit Florida during Christmas time in 2011.

A few months later I applied again for a visitor visa and I got another single entry visa. This time I went to visit New York City on July 2012.

Both times I got a single entry visa. I think this had to do with the fact that I am of Cuban birth and you know, the governments of Cuba and the US have kept some animosity for more than half a century. I think most people actually get a multi entry visa, but this was not my case.

I have to say I was lucky: The Americans not only granted me 2 single entry visas, but on top of that they allowed me to enter the US once without a visa. Yes, you heard right, without a visa. This was quite an exceptional situation and I don't think they do it often. Read the whole story here.

Time has passed and I no longer require a visa to visit the US, because I am now a Canadian Citizen. Nonetheless, I got married and my wife is also a Cuban immigrant. At this time she is a Canadian Resident and because of that she requires a visitor visa to enter the US.

So, she applied for a visitor visa and she got it on March 2016. She was luckier than me. She got a multi entry visa valid for 10 years!

Enough of blah, blah, blah. The purpose of this article is to share my experiences in this regard. I would love if you show your appreciation by clicking the Google Plus (G+)  button at the beginning of this post.

Now, for the real stuff keep reading...

Visitor Visas allow you to enter the US temporarily: that’s why they are called nonimmigrant visas. These visas come in two flavors:
  • Business Visitor Visas (B-1)
  • Pleasure, Tourism, Medical Treatment - Visitor Visas (B-2)
In my case, I applied for a B-2 visa, since the purpose of my visit to the US was mainly recreational.

Step 1: You need to fill an Online Nonimmigrant Visa Electronic Application, Form DS-160. Don’t let the name scare you. You simply go to this website and fill in the information required as you go. There is a lot of information that you need to provide.  If you need to stop one day, then you can resume the filling process at the next day.
In this step you will be asked to upload a recent digital picture(s) of the applicant(s). For information about the photo requirements go here. When I filled my own applications I got my photos taken at Blacks. Blacks went out of business recently, so my wife took her pictures at a Walmart in Toronto.
It is important to get a digital picture and a printed picture. The digital picture will be given to you in a CD and the printed picture, well, in paper. Make sure you ask for both the "digital picture" and the "printed picture".
When you complete your DS-160 application online you will be given a confirmation page. You have to print that confirmation page and present it at the time of the interview. The confirmation page contains a bar code that should be legible; so make sure you have a good printer at hand.

Important: you need to complete step 1 before proceeding to step 2.

Step 2: You need to pay a fee for your visa application and then you have to schedule an appointment for your visa interview.  The fee for a B-2 visa is $160 USD. To fulfill this step you need to login (register) at this website: https://ais.usvisa-info.com/en-ca/niv

Once logged into your account, you will need to provide some basic information and then, you should be able to pay your visa fee online[1] (Paypal, Credit Card) and schedule the interview (you have to choose date, time and place[2]). 
[1] It is not mandatory to pay online; for a full list of fee payment options consult this URL: https://ais.usvisa-info.com/en-ca/niv/information/fee

[2] The visa interview can be scheduled in any of the following US Consulates: Calgary, Halifax, Montréal, Québec City, and Toronto or in the US Embassy in Ottawa. For addresses click the following link: https://ca.usembassy.gov/embassy-consulates/.
You will be asked to print a receipt after you have completed the fee payment. Make sure you print this receipt, since you will have to present it at the time of the interview.

When you complete step 2, the website will give you the option to print a Confirmation and Instructions document. Print it, since I was asked for it the day of the interview.

What do you need to bring the day of the interview?
  • A passport valid for at least 6 month beyond the applicant's intended period of stay in the US.
  • Your Canadian Permanent Resident card.
  • The confirmation page with the bar code (step 1).
  • The receipt of your visa fee payment (step 2).
  • The Confirmation and Instructions (step 2). 
  • One 5 x 5 cm (or 2" x 2") color photo taken within the last 6 months (this is the "printed" photo I was talking about earlier)
  • All the documents you think might support your case (in my case I gathered my work contract, bank statements, pay stubs, Option "C" Printout)
Important, make sure you read carefully the Confirmation and Instructions document. It contains all the required documents that you must bring with you the day of the interview. Don't rely on the information of this blog, since it might go outdated at anytime.

Ah, make sure you don't bring your cellphone, music player or any other electric device to the interview. You won't be allowed to enter the Consular Section with them. You will have to leave them outside of the facility, they won't hold them for you.
Take a look at the existing comments: there’s a lot of useful information in there that complements what I have written in the body of this post.

Please, note that I am a regular person, not an immigration or legal adviser. I am only posting here the facts about my own experience.

Good luck!

Decorator Design Pattern in Delphi. Multiple Decorations

In my previous post I introduced the decorator design pattern to you. I used a fairly simple example (a silly example if you wish) in order to give you a flavour of the pattern. I wrote Delphi code for that matter and I focused in having ONE, and only ONE, decorator class.

This was the situation in the original example: we implemented a TConsole class with a Write method that writes a text to the standard output. Then, we used a TUpperCaseConsole class to decorate a TConsole object. The decoration itself was simple: uppercasing the text to be shown.

Now I want to add a second decoration, which is framing the text to be shown within a rectangle of asterisks (*). For that I will create a new decorator class: TFramedConsole.

Let’s present a raw piece of code: (We will refine and refactor the code later)

var
  MyConsole: TConsole;
begin
  MyConsole:= TConsole.Create;
  MyConsole:= TUpperCaseConsole.Create(MyConsole); //first decoration
  MyConsole:= TFramedConsole.Create(MyConsole); //second decoration

  try
    MyConsole.Write('Hello World!');
  finally
    MyConsole.Free;
  end;
  Readln;
end.

In the code above we added a second decoration. The output for that code should be something like this:

**********************
**   HELLO WORLD!   **
**********************

This is cool: We can even add the same decoration several times. For example, to provide a double frame we would do something like this:

var
  MyConsole: TConsole;
begin
  MyConsole:= TConsole.Create;
  MyConsole:= TUpperCaseConsole.Create(MyConsole); //first decoration
  MyConsole:= TFramedConsole.Create(MyConsole); //second decoration
  MyConsole:= TFramedConsole.Create(MyConsole); //third decoration

  try
    MyConsole.Write('Hello World!');
  finally
    MyConsole.Free;
  end;
  Readln;
end

Can you guess the output now? It’s like this:

**********************
**********************
**   HELLO WORLD!   **
**********************
**********************

How are the decorated and decorator classes put together when multiple decorations are needed? There are two key things to remember:
  1. The different concrete decorators (TUpperCaseConsole and TFramedConsole) must inherit from a base decorator class. We will introduce the TDecoratedConsole class as the common ancestor for our decorators.
  2. The base decorator class forwards the calls to its Write method to the decorated object’s Write method.
The code looks like this:

interface

uses
  SysUtils, Windows;

type
  TConsole = class
  private
    FText: string;
  public
    procedure Write(aText: string); virtual;
  end;

  TDecoratedConsole = class(TConsole) //Base Decorator
  private
    FConsole: TConsole;
  public
    constructor Create(aConsole: TConsole);
    destructor Destroy; override;

    procedure Write(aText: string); override;
  end;

  TUpperCaseConsole = class(TDecoratedConsole) //Concrete Decorator
  public
    procedure Write(aText: string); override;
  end;

  TFramedConsole = class(TDecoratedConsole) //Concrete Decorator
  private
    procedure CreateFrame(var aText: string);
  public
    procedure Write(aText: string); override;
end;

implementation

{ TConsole }

procedure TConsole.Write(aText: string);
begin
  FText:= aText;
  Writeln(FText);
end;

{ TDecoratedConsole }

constructor TDecoratedConsole.Create(aConsole: TConsole);
begin
  inherited Create;
  FConsole:= aConsole;
end;

destructor TDecoratedConsole.Destroy;
begin
  FConsole.Free;
  inherited;
end;

procedure TDecoratedConsole.Write(aText: string);
begin
  FConsole.Write(aText);
end;

{ TUpperCaseConsole }

procedure TUpperCaseConsole.Write(aText: string);
begin
  aText:= UpperCase(aText);
  inherited Write(aText);
end;

{ TFramedConsole }

procedure TFramedConsole.CreateFrame(var aText: string);
var
  TextLength: Integer;
  AsteriskLine: string;
  RealText: string;
begin
  if Pos('*', aText) = 0 then
    aText:= '** ' + aText + ' **';

  RealText:= Trim(StringReplace(aText, '*', '', [rfReplaceAll]));
  TextLength:= Length(RealText);
  AsteriskLine:= StringOfChar('*', TextLength + 10);

  aText:= AsteriskLine + #13#10 +
          aText + #13#10 + AsteriskLine;
end;

procedure TFramedConsole.Write(aText: string);
begin
  CreateFrame(aText);
  inherited Write(aText);
end;

I know you are dying to say: the code above is awful because the decorators are bounded to a specific implementation of the decorated class. Indeed, we are going to fix that by introducing a TAbstractConsole class, which will be the common ancestor of the decorated and decorator classes. The TAbstractConsole class is abstract, meaning it has no implementation. You could have used an Interface type instated, something like IAbstractConsole. I’ll leave that to you.

Finally, I present you the consuming code plus the class definition code:

//Consuming code
var
  MyConsole: TAbstractConsole;
begin
  MyConsole:= TConsole.Create;
  MyConsole:= TUpperCaseConsole.Create(MyConsole); //first decoration
  MyConsole:= TFramedConsole.Create(MyConsole); //second decoration
  MyConsole:= TFramedConsole.Create(MyConsole); //third decoration

  try
    MyConsole.Write('Hello World!');
  finally
    MyConsole.Free;
  end;
  Readln;
end

//Class definition code
interface

uses
  SysUtils, Windows;

type
  TAbstractConsole = class //Abstract class ==> Interface
  public
    procedure Write(aText: string); virtual; abstract;
  end;

  TConsole = class(TAbstractConsole) //Concrete class
  private
    FText: string;
  public
    procedure Write(aText: string); override;
  end;

  TDecoratedConsole = class(TAbstractConsole) //Base Decorator
  private
    FConsole: TAbstractConsole;
  public
    constructor Create(aConsole: TAbstractConsole);
    destructor Destroy; override;

    procedure Write(aText: string); override;
  end;

  TUpperCaseConsole = class(TDecoratedConsole) //Concrete Decorator
  public
    procedure Write(aText: string); override;
  end;

  TFramedConsole = class(TDecoratedConsole) //Concrete Decorator
  private
    procedure CreateFrame(var aText: string);
  public
    procedure Write(aText: string); override;
  end;

implementation

{ TConsole }

procedure TConsole.Write(aText: string);
begin
  FText:= aText;
  Writeln(FText);
end;

{ TDecoratedConsole }

constructor TDecoratedConsole.Create(aConsole: TAbstractConsole);
begin
  inherited Create;
  FConsole:= aConsole;
end;

destructor TDecoratedConsole.Destroy;
begin
  FConsole.Free;
  inherited;
end;

procedure TDecoratedConsole.Write(aText: string);
begin
  FConsole.Write(aText);
end;

{ TUpperCaseConsole }

procedure TUpperCaseConsole.Write(aText: string);
begin
  aText:= UpperCase(aText);
  inherited Write(aText);
end;

{ TFramedConsole }

procedure TFramedConsole.CreateFrame(var aText: string);
var
  TextLength: Integer;
  AsteriskLine: string;
  RealText: string;
begin
  if Pos('*', aText) = 0 then
    aText:= '** ' + aText + ' **';

  RealText:= Trim(StringReplace(aText, '*', '', [rfReplaceAll]));
  TextLength:= Length(RealText);
  AsteriskLine:= StringOfChar('*', TextLength + 10);

  aText:= AsteriskLine + #13#10 +
          aText + #13#10 + AsteriskLine;
end;

procedure TFramedConsole.Write(aText: string);
begin
  CreateFrame(aText);
  inherited Write(aText);
end;

I hope this was useful and I am definitely waiting for you feedback. Corrections and suggestions are welcome in the comment section below. Thanks!

For further reading about design patterns get your hands on these classics:

Decorator Design Pattern in Delphi. Single decoration

Decorator (also referred as Wrapper) is classified by GoF as a structural pattern. Its purpose is to:

“Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.”  

Both inheritance and the decorator pattern aim towards extending the functionality. This is what they have in common.

There are a couple of remarkable differences:
  • Inheritance extends the functionality at compilation time (statically). The decorator pattern extends the functionality at runtime (dynamically).
  • Inheritance extends the functionality of a whole class (all objects of the extended class get the extended functionality). The decorator pattern allows extending the functionality of a selected object (or group of objects) without affecting the remaining objects.  

You can think of the decorator pattern as a way to add make-up to an object or even as a way to attach accessories to that object. All this is done on the fly after the object itself has been created.

Let’s walk through a simple task to get the idea. This example might sound silly. I want it silly so that you can focus on the decorator implementation, avoiding any extra complexity.

Please, be aware that this design is somewhat unfinished, since we are only covering the case for a single decoration (just one functionality to be extended). In real life, we will need multiple decorators in order to add multiple responsibilities. As this is a controlled example (just for the purpose of this discussion), I am enforcing that only ONE responsibility is going to be extended. This means, we will have ONE decorator class. Because of that, I have made some simplifications to the design; so that you get a taste of the decorator pattern in its simplest expression.

Later on, in other post, we’ll see how to add multiple responsibilities (with multiple decorator classes). For that, we’ll need a more complex design to overcome the shortcomings of this initial example. For now, just get the idea...we'll come back later to the multiple decorations scenario.

If you get some time, take a look at the discussion in the comments section.

Subtask 1: Let’s create a TConsole class which purpose is to output a given text to the standard output. The code might be something like this:

interface
type
  TConsole = class
  public
    procedure Write(aText: string);
  end;

implementation

procedure TConsole.Write(aText: string);
begin
  Writeln(aText);
end;

Subtask 2: Let’s use the TConsole class to printout “Hello World!”. The following code snipped does it:

var
  MyConsole: TConsole;
begin
  MyConsole:= TConsole.Create;
  try
    MyConsole.Write('Hello World!');
  finally
    MyConsole.Free;
  end;
  Readln;
end.

This is how the output looks like:

Hello World!

Subtask 3: Now, let’s decorate the object referenced by MyConsole (only that object, not the whole class). What I want is to upper case every text to be printed out. We need to define a decorator class TUpperCaseConsole for that purpose. See the code:

interface

uses
  SysUtils;

type
  TConsole = class
  public
    procedure Write(aText: string); virtual;
  end;


  //Decorator
  TUpperCaseConsole = class(TConsole)
  private
    FConsole: TConsole;
  public
    constructor Create(aConsole: TConsole);
    destructor Destroy; override;

    procedure Write(aText: string); override;
  end;

implementation

{ TConsole }

procedure TConsole.Write(aText: string);
begin
  Writeln(aText);
end;

{ TUpperCaseConsole }

constructor TUpperCaseConsole.Create(aConsole: TConsole);
begin
  inherited Create;
  FConsole:= aConsole;
end;

destructor TUpperCaseConsole.Destroy;
begin
  FConsole.Free;
  inherited;
end;

procedure TUpperCaseConsole.Write(aText: string);
begin
  aText:= UpperCase(aText);
 
FConsole.Write(aText);
end;

Notice in the code above that the decorator class (TUpperCaseConsole) inherits from the decorated class (TConsole). This makes both the decorated and the decorator objects to share the same public interface. Furthermore, the TUpperCaseConsole class Has-A field of the TConsole type. We’ll use this field to forward the printing functionality to the TConsole class, once we have applied the cosmetic (upper case transformation) to the text.

Subtask 4: Let’s now create some consuming code to decorate one TConsole object on the fly. Note how the TUpperCaseConsole constructor wraps (decorates) the object referenced by MyConsole.

var
  MyConsole: TConsole;
begin
  MyConsole:= TConsole.Create;
  MyConsole:= TUpperCaseConsole.Create(MyConsole);
  try
    MyConsole.Write('Hello World!');
  finally
    MyConsole.Free;
  end;
  Readln;
end.

This is how the output looks like after the decorator has been applied:

HELLO WORLD!  

In real life, you’ll have to judge whether the decorator pattern is the best alternative to be applied to solve a particular problem. Not always it the right way to go with. For more details get your hands on these classic books.

Anonymous Methods in Delphi

Under the scope of Delphi, an anonymous method is either a procedure or function that’s unattached to an identifier. In other words, anonymous methods don’t have names, which is why they are called “anonymous”.

Basically, you can assign a block of code (in the form of a procedure or function) directly to a variable.

I am going to give you a simplistic example. I am going to Keep it simple, Stupid! to avoid distracting you with any complexity.

This is the wording of the task: create a console application which prints “Hello world” and “Good bye” to the standard output. Constraint: use the Writeln function just once in the code.

To accomplish such reckless task in the old days (before the introduction of anonymous methods) you could do this:

program Project1;

{$APPTYPE CONSOLE}

procedure PrintString(aText: string);
begin
 Writeln(aText);
end;

begin
  PrintString('Hello world');
  PrintString('Good bye');
  Readln;
end.

How to do the same with anonymous methods? Take a look at the following code:

program Project1;

{$APPTYPE CONSOLE}

type
  TMyAnonymousProcedureType = reference to procedure(aText: string);

var
  A: TMyAnonymousProcedureType;

begin
  A:= procedure(aText: string) //No semicolon here
                begin
                  Writeln(aText);
                end;
  A('Hello world');
  A('Good bye');
  Readln;
end.

As you can see in the example above, we have assigned code directly to the variable A. Then, we called A with parameters, and Voilà!: we have accomplished our reckless task with anonymous methods as well.

Pay attention to this:  if you are tented to declare variable A like this:

var
  A: reference to procedure(aText: string);

Don’t! That shortcut doesn’t work. You’ll get a compilation error…like this:

Undeclared identifier: ‘reference’

So, you do need to declare:

type 
   TMyAnonymousProcedureType = reference to procedure(aText: string);


Only later you can define the type of variable A.

You might be asking by now: why to bother with all this? What's the benefit? Well, in the previous example there’s little or none benefit present.

Generally speaking, anonymous methods are handy in the following cases:
  • You have been trying to name a local method for hours. You cannot think of a name for it. Well, think no more: use anonymous methods. Don’t put a tasteless name like Foo(), XXX(), Aux(), etc.
  • You create a function that is called just once(it’s just called from one spot).
  • You can use anonymous methods to provide elegant and simpler implementations. This is the case when combining generics types with anonymous methods for example. I should write about this shortly. Subscribe to my feed and stay tuned :-)
With this post I wanted to introduce anonymous methods to you. It’s OK if you don’t see the benefits clearly right now. You’ll get there :-)