Showing posts with label Pascal. Show all posts
Showing posts with label Pascal. Show all posts

The source code history of Free Pascal and Lazarus visualized with Gource

Gource is a software version control visualization tool. I thought it would be fun to visualize Delphi’s source code with Gource, but that is not possible for obvious reasons. So, I decided to try-out Delphi’s cousins: Free Pascal and Lazarus.

I checked-out the respective code bases and ran them through Gource.

Below are the Gource commands I used:

gource -1280x720 -o C:\\gource\\fpc.ppm -s 0.01 --hide dirnames,filenames,progress,mouse C:\\gource\\fpc

gource -1280x720 -o  C:\\gource\\lazarus.ppm -s 0.01 --hide dirnames,filenames,progress,mouse C:\\gource\\lazarus

Gource shows the filenames and directories of the source code by default; still, I decided to hide them in these videos, because they were overlapping. You can play more with Gource, FPC and Lazarus on your own :-) For a comprehensive list of the command line options and arguments of Gource click HERE.

The above gource calls create two files: fpc.ppm and lazarus.ppm. I guess these are some kind of uncompressed video format. The files were huge: ~60GB and ~100GB respectively.

Then, I used FFmpeg to encode the above .ppm files into .avi files. The FFmpeg commands are below:

ffmpeg -y -r 60 -f image2pipe -vcodec ppm -i C:\\gource\\fpc.ppm -vcodec libx264 -preset ultrafast -pix_fmt yuv420p -crf 1 -threads 0 -bf 0 C:\\gource\\fpc.x264.avi

ffmpeg -y -r 60 -f image2pipe -vcodec ppm -i C:\\gource\\lazarus.ppm -vcodec libx264 -preset ultrafast -pix_fmt yuv420p -crf 1 -threads 0 -bf 0 C:\\gource\\lazarus.x264.avi

Finally, I uploaded fpc.x264.avi and lazarus.x264.avi to YouTube. You can see them below:

Free Pascal source code history visualized with Gource 



Lazarus source code history visualized with Gource 



If you liked this post; please, show your appreciation but clicking the Google Plus (G+) button at the beginning of the article. Thanks!

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.

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 :-)

My contributions to the Delphi community at RosettaCode

RosettaCode is a wiki site that gathers a collection of programming tasks being resolved in as many programming languages as possible.

You can post solutions to a particular task using a particular language (Delphi, Java, C++, C#, Ruby, the list goes and goes).  All solutions to the same task are coded in the same page, allowing a fast knowledge transfer from one language to the other. Also, you can compare how suitable is a particular language for a particular task.

Furthermore, you can add programming languages to be considered for implementation and of course, you can suggest new tasks to be resolved.

There is very little about Delphi at RosettaCode. I encourage the Delphi community to fill the pending tasks for Delphi and suggest new tasks as well.

Delphi is very powerful, let’s share it with everybody.

These are my contributions so far:
Finally, I want to highlight that RosettaCode is about all programming languages. Resolving tasks in a single language is not enough. Don’t be shy, add the solutions in all the languages you can :-)

Parameterized Factory Method in Delphi

Factory Method is a creational design pattern, whose intent (according to Design Patterns: Elements of Reusable Object-Oriented Software) is to:

“Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.”

Do you want to know more about design patterns? Check reference [1] at the bottom for extra reading.

In this post we will consider a variation of the pattern referred as parameterized factory method. This variation just refers to the first part of the intent, that is, “define an interface for creating an object”. Why is that?  What about the rest of the intent? Well, there are times in which sub-classing is not possible or not suitable; nonetheless, it is useful to define a factory method to encapsulate the creation of an object.

Let’s proceed with the example we used in our previous post (template design pattern); that is: Design an application that allows drawing different styles of houses (ei. country house, city house) using ASCII art.

The GUI of our app contains some VCL components as you can see in the images below. Clicking the buttons will result in an ASCII house printed out in the memo area. Depending on the Draw… button being clicked, the house will look differently: it can be a country house or a city house.
Factory Pattern Example (Delphi) – Country House

Figure1 A Country House (Draw Country House button was clicked)

Factory Pattern Example (Delphi) – City House

Figure 2 A City House (Draw City House button was clicked)


Behind the scenes, assume that we have implemented the following class hierarchy:

Factory Pattern Example (Delphi) – Class diagram

THouse is an abstract class that defines several methods for displaying the different parts of the house [2] or the house as a whole [3].

TCountryHouse and TCityHouse are two concrete (non-abstract) classes that actually override some of the methods of its superclass, allowing this way different look-and-feel; that is, a house in the country and a house in the city look differently.

When a button is clicked, the corresponding OnClick event is triggered. We have to provide logic (source code) to define what the button is going to do in response to the OnClick event. Using fancy words, we have to implement the event handler for the OnClick event. I have created the following event handler which is going to be shared by both buttons [4]:

//OnClick event handler for the buttons
procedure TfrmMain.btnDrawGenericHouseClick(Sender: TObject);
var
  House: THouse;
begin
  //If the "Sender" object is not a button do nothing
  if not(Sender is TButton) then Exit;

  //The concrete house object being created depends
  //on the button being clicked
  if TButton(Sender).Name = 'btnDrawCountryHouse' then
    House:= TCountryHouse.Create
  else if TButton(Sender).Name = 'btnDrawCityHouse' then
    House:= TCityHouse.Create;

  with House do
  begin
    //cmbHasChimney is a combo box (TComboBox) that allows
    //to decide whether to add a chimney or not to the house
    case cmbHasChimney.ItemIndex of
      0: HasChimney:= True;
      1: HasChimney:= False;
    end;
    //"memFrame" is a memo (TMemo) used to print out the house.
    memFrame.Text:= BuildIt;
    Free;
  end;
end;


This works of course, but it lacks flexibility. What happens if we want to add a third button, or a fourth, or a five in order to add new types of houses? In that case, you will have to rework the code above and the fragment in blue will grow up big as new house types are added. You will end coding something like this:

  if TButton(Sender).Name = 'btnDrawCountryHouse' then
    House:= TCountryHouse.Create
  else if TButton(Sender).Name = 'btnDrawCityHouse' then
   
House:= TCityHouse.Create
else if TButton(Sender).Name = 'btnDrawDogHouse' then
   
House:= TDogHouse.Create
else if TButton(Sender).Name = 'btnDrawTreeHouse' then
   
House:= TTreeHouse.Create
else if TButton(Sender).Name = 'btnDrawGhostHouse' then
   
House:= TGhostHouse.Create;

That is the only part changing within the method. Why don’t we take that chunk of code and place it somewhere else? For that, we can create a factory method. The factory method will take one parameter to decide the concrete house type to instantiate [4]. The return type of the factory method will be THouse, because THouse enfolds all the other house subtypes. What about this?

function TfrmMain.MakeHouse(Sender: TObject): THouse;
begin
  if TButton(Sender).Name = 'btnDrawCountryHouse' then
    Result:= TCountryHouse.Create
  else if TButton(Sender).Name = 'btnDrawCityHouse' then
   
Result:= TCityHouse.Create
else if TButton(Sender).Name = 'btnDrawDogHouse' then
   
Result:= TDogHouse.Create
else if TButton(Sender).Name = 'btnDrawTreeHouse' then
   
Result:= TTreeHouse.Create
else if TButton(Sender).Name = 'btnDrawGhostHouse' then
   
Result:= TGhostHouse.Create;
end;

MakeHouse is a parameterized factory method. It is called factory because its only purpose in life is to create an object. It is adorned with the parameterized term, because it takes a parameter (Sender) to decide the concrete class to instantiate.

What does this mean to our previous code (event handler method)? Well, see it by yourself:

//OnClick event handler for the buttons
procedure TfrmMain.btnDrawGenericHouseClick(Sender: TObject);
var
  House: THouse;
begin
  //If the "Sender" object is not a button do nothing
  if not(Sender is TButton) then Exit;

  //The concrete house object being created depends
  //on the button being clicked
  House:= MakeHouse(Sender); //See our factory method in action

  with House do
  begin
    //cmbHasChimney is a combo box (TComboBox) that allows
    //to decide whether to add a chimney or not to the house
    case cmbHasChimney.ItemIndex of
      0: HasChimney:= True;
      1: HasChimney:= False;
    end;
    //"memFrame" is a memo (TMemo) used to print out the house.
    memFrame.Text:= BuildIt;
    Free;
  end;
end;

Now, as you can see, the event handler will remain the same no matter how many different subtypes of houses we have (add). Everything about the creation of a house object is isolated in the factory method.

One final comment: Delphi is a hybrid programming language, allowing both structured and object oriented programming. In Delphi, we can have functions outside all classes’ scope. That’s not very Object Oriented. Isn’t? Besides, you can’t do that in languages like Java, Python, Ruby or C#.

In general, you should have a Factory class containing the factory method. In this particular Delphi example you might argue that we are just adding code for nothing. Yes, I give you that. But there are cases, in which having a hierarchy of factory classes comes naturally and the subfactories decide the concrete object to be created. We’ll cover that scenario in future posts :-)
 
Notes:

[1] Books about Design Patterns:



[2] BuildFloor(), BuildWalls(), BuildRoof(), BuildChimney(). These methods draw out the floor, walls, roof and chimney (if any) respectively.

[3] BuildIt(): this method calls the methods in [2] and as a result it draws the whole house.

[4] You can define the event handler for the buttons at design time using Delphi’s Object Inspector

Template Method Design Pattern in Delphi. A working example

The Template Method Pattern is very easy to understand and implement. Here’s the definition borrowed from Design Patterns: Elements of Reusable Object-Oriented Software book:

“Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.”

Let’s try to understand the pattern walking through a simple example. For implementing the solution we’ll use Delphi XE, but it should work for previous versions as well.

This is the wording of the example:

Design an application that allows drawing different styles of houses (ei. country house, city house) using ASCII art [1].

In the following image there’s a prototype of the user interface.
Template Pattern Example (Delphi) – Country House
The GUI is composed by a form, a memo [2], two buttons, a label and a combo box. Using the combo box you can choose whether your house will have a chimney or not. Clicking the buttons will result in an ASCII house printed out in the memo area. In the example above, the Draw Country House was clicked. If you click the other button, you will get city house like the one below:
Template Pattern Example (Delphi) – City House
What happens if you select “No” in the combo box? Try it and let me know :-) Here’s the link to the EXE. This EXE is harmless; I am not a bad guy: no Trojans, no viruses, just Delphi :-)

Now, what classes do we need to make this work? Take a look at the following class diagram and try to make sense of it:
Template Pattern Example (Delphi) – Class diagram
We have an abstract superclass THouse, which contains four abstract (pure virtual) methods: BuildFloor, BuildWalls, BuildRoof and BuildChimney. These methods are implemented in the descending classes TCountryHouse and TCityHouse. Pay special attention to the method BuildIt in THouse. This method is an instance method that is inherited by both concrete subclasses: TCountryHouse and TCityHouse.  

I want to be more detailed:

The BuildIt method is implemented just once in the class THouse. The subclasses TCountryHouse and TCityHouse don’t have to implement the BuildIt method.

The BuildFloor, BuildWalls, BuildRoof and BuildChimney methods have no implementation under the THouse class. The TCountryHouse has one implementation of these methods, while TCityHouse have a different implementation of them.
    
This is how the BuildIt method looks like:

function THouse.BuildIt: string;
begin
  Result:= BuildRoof  +  //Step 1
           BuildWalls +  //Step 2
           BuildFloor;   //Step 3

  if FHasChimney then
    Result:= BuildChimney+ Result;  //Step 4 (conditional)
end;

This method defines a general algorithm to build a house…it doesn’t take into consideration the kind of house that’s been built. Notice that the steps for building the roof, walls, floor and chimney (if any) have been deferred to the subclasses. The BuildIt method is known as a template method that gives the name to this pattern.

Let me give you an idea of the implementation of the BuildFloor method. This method is implemented directly by the subclasses. Take a look:

function TCountryHouse.BuildFloor: string;
begin
  Result:=

  '~~~~~"   "~~~~~~~~~~~~~~~~~~~~~~~~  ';
end;

function TCityHouse.BuildFloor: string;
begin
  Result:=

  '******************____****************'#13#10 +
  '**************************************';
end;

Notice that the implementation of the BuildFloor method is different in both subclasses TCountryHouse and TCityHouse.

For the implementation of the remaining methods refer to reference [5]. For the full source code refer to [3].

In conclusion, the template method pattern needs an abstract superclass to implement a template method (common for all subclasses). The steps within this template method are deferred into methods that are implemented by the concrete subclasses. Did you get it? :-)

Do you want to know more about design patterns? The books in reference [4] are just what you need.

References:

[1] I am borrowing the ASCII designs from Asciiworld.com : House.

[2] Make sure to use a fixed-width font (Courier, Monaco, Courier New, Lucida Console, etc.) for the memo, otherwise the drawing will look fuzzy.

[3] Get the full source code of this example here.

[4] Books on Design Patterns:




[5] The full source code of the unit:

unit TemplatePatternExample;

interface
type
  THouse = class
  private
    FHasChimney: Boolean;
  public
    constructor Create;

    property HasChimney: Boolean read  FHasChimney
                                 write FHasChimney;

    function BuildFloor: string;   virtual; abstract;
    function BuildWalls: string;   virtual; abstract;
    function BuildRoof: string;    virtual; abstract;
    function BuildChimney: string; virtual; abstract;

    function BuildIt: string;
  end;

  TCountryHouse = class(THouse)
  public
    function BuildFloor: string;   override;
    function BuildWalls: string;   override;
    function BuildRoof: string;    override;
    function BuildChimney: string; override;
  end;

  TCityHouse = class(THouse)
  public
    function BuildFloor: string;   override;
    function BuildWalls: string;   override;
    function BuildRoof: string;    override;
    function BuildChimney: string; override;
  end;

implementation

{ THouse }

constructor THouse.Create;
begin
  inherited Create;
  FHasChimney:= True;
end;

function THouse.BuildIt: string;
begin
  Result:= BuildRoof  +  //Step 1
           BuildWalls +  //Step 2
           BuildFloor;   //Step 3

  if FHasChimney then
    Result:= BuildChimney+ Result;  //Step 4 (conditional)
end;

{ TCountryHouse }

function TCountryHouse.BuildChimney: string;
begin
  Result:=

  '              (   )                '#13#10 +
  '             (    )                '#13#10 +
  '              (    )               '#13#10 +
  '             (    )                '#13#10 +
  '               )  )                '#13#10 +
  '              (  (                 '#13#10 +
  '               (_)                 '#13#10 +
  '               [ ]                 '#13#10;
end;

function TCountryHouse.BuildRoof: string;
begin
  Result:=

  '       ___________________       '#13#10 +
  '      /\        ______    \      '#13#10 +
  '     //_\       \    /\    \     '#13#10 +
  '    //___\       \__/  \    \    '#13#10 +
  '   //_____\       \ |[]|     \   '#13#10 +
  '  //_______\       \|__|      \  '#13#10 +
  ' /XXXXXXXXXX\                  \ '#13#10 +
  '/_I_II  I__I_\__________________\'#13#10;
end;

function TCountryHouse.BuildWalls: string;
begin
  Result:=

  '  I_I|  I__I_____[]_|_[]_____I'#13#10 +
  '  I_II  I__I_____[]_|_[]_____I'#13#10 +
  '  I II__I  I     XXXXXXX     I'#13#10;
end;

function TCountryHouse.BuildFloor: string;
begin
  Result:=

  '~~~~~"   "~~~~~~~~~~~~~~~~~~~~~~~~  ';
end;

{ TCityHouse }

function TCityHouse.BuildChimney: string;
begin
  Result:=

  '                           ====  '#13#10 +
  '                           !!!!  '#13#10;
end;

function TCityHouse.BuildRoof: string;
begin
  Result:=

  '      ==========================      '#13#10 +
  '    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    '#13#10 +
  '  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  '#13#10 +
  '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'#13#10;
end;

function TCityHouse.BuildWalls: string;
begin
  Result:=

  '  ||      _____          _____    ||'#13#10 +
  '  ||      | | |          | | |    ||'#13#10 +
  '  ||      |-|-|          |-|-|    ||'#13#10 +
  '  ||      #####          #####    ||'#13#10 +
  '  ||                              ||'#13#10 +
  '  ||      _____   ____   _____    ||'#13#10 +
  '  ||      | | |   @@@@   | | |    ||'#13#10 +
  '  ||      |-|-|   @@@@   |-|-|    ||'#13#10 +
  '  ||      #####   @@*@   #####    ||'#13#10 +
  '  ||              @@@@            ||'#13#10;
end;

function TCityHouse.BuildFloor: string;
begin
  Result:=

  '******************____****************'#13#10 +
  '**************************************';
end;

end.

New certifications available for Delphi Developers

Last June 12th, 2011, I received an Embarcadero Community Newsletter pointing out that “certification exams are now available for Delphi developers.  Embarcadero's Delphi Certification Program offers two levels: Delphi Certified Developer and Delphi Certified Master Developer. “

I just passed the Delphi Developer Certification exam and thus I became a Certified Delphi Developer.
Certified Delphi Developer
 Now, I want you to become certified as well :-) So, mind this: 
  • This exam is conducted over the Internet without supervision. That means you can take the exam at home (or wherever you prefer) at your own pace. You don’t need to go to a particular place to take the exam: you just need an Internet connection and that’s pretty much it.
  •  The exam is cheap. It only costs $49USD.Consider for example that the prices for .NET or Java certifications are much higher.    
  • You can pay for the exam code online (you need an exam code to take the certification exam). Theoretically, you can pay it using VISA, MasterCard and Paypal. Warning: I tried with my VISA and Master Card cards and it didn’t work. It seems that there is (was) something wrong with the payment system. At the end, I managed to perform the payment through Paypal.
  • The exam contains 60 questions to be answered in 60 minutes. The time is plenty; so, don’t worry about it.
  • Be careful with the syntax questions: even if you are an experienced Delphi programmer, I would advise you to review the syntactical elements of the language before taking the test. Most times our memory becomes dusty after too much time relaying on the code completion features of the IDE.
  • Take a look at the Delphi Developer Certification Study Guide. Make sure you cover all the topics targeted for the exam. Remember: all topics go under examination.
I wanted to take the Delphi Master Developer Certification exam as well, but guess what? - This exam is supervised and I would need to travel to USA to take it. I think I will wait until it becomes available (hopefully) in Canada.

I belief the introduction of these certification programs is proof that Embarcadero is willing to gain a good portion of the programming market. By taking the exams you become part of the effort of bringing Delphi to the arena once more…I believe it’s worthy.

I recently found this Delphi Certification Webinar video by Andreano Lanusse.

Fetching a web page with Delphi

This function fetches the HTML content of a given web page. It takes the page's URL as parameter and returns the corresponding HTML text. The name CURL comes from the PHP Client URL Library that can be used (among other things) for the same purpose.
.................
implementation

uses
  IdHTTP;

function Curl(aURL: string): string;
const
  cUSER_AGENT = 'Mozilla/4.0 (MSIE 6.0; Windows NT 5.1)';
var
  IdHTTP: TIdHTTP;
  Stream: TStringStream;
begin
  Result := '';
  IdHTTP := TIdHTTP.Create(nil);
  Stream := TStringStream.Create;
  try
    IdHTTP.Request.UserAgent := cUSER_AGENT;
    try
      IdHTTP.Get(aURL, Stream);
      Result := Stream.DataString;
    except
      Result := '';
    end;
  finally
    Stream.Free;
    IdHTTP.Free;
  end;
end;
.................

You can modify this routine to have the web page saved to a file instead. For that, you only need to use the TStringStream.SaveToFile method in substitution of TStringStream.DataString.

One final observation: you may change the cUSER_AGENT constant to whatever value you decide. If you don’t specify a user agent, then a default value will be provided.

Ah! Don’t forget to add IdHTTP to the uses clause!

String compression/decompression routines using Delphi

I wrote the following two functions (in bold) with the purpose of compressing/decompressing string values within a Delphi application:

.........................
implementation

uses
  ZLib;

function ZCompressString(aText: string; aCompressionLevel: TZCompressionLevel): string;
var
  strInput,
  strOutput: TStringStream;
  Zipper: TZCompressionStream;
begin
  Result:= '';
  strInput:= TStringStream.Create(aText);
  strOutput:= TStringStream.Create;
  try
    Zipper:= TZCompressionStream.Create(strOutput, aCompressionLevel);
    try
      Zipper.CopyFrom(strInput, strInput.Size);
    finally
      Zipper.Free;
    end;
    Result:= strOutput.DataString;
  finally
    strInput.Free;
    strOutput.Free;
  end;
end;

function ZDecompressString(aText: string): string;
var
  strInput,
  strOutput: TStringStream;
  Unzipper: TZDecompressionStream;
begin
  Result:= '';
  strInput:= TStringStream.Create(aText);
  strOutput:= TStringStream.Create;
  try
    Unzipper:= TZDecompressionStream.Create(strInput);
    try
      strOutput.CopyFrom(Unzipper, Unzipper.Size);
    finally
      Unzipper.Free;
    end;
    Result:= strOutput.DataString;
  finally
    strInput.Free;
    strOutput.Free;
  end;
end;

.........................

The main advantage of the above functions over the ZCompressStr and ZDecompressStr routines shipped with ZLib.pas, is that you won’t have potential data lost when handling Unicode <->Ansi conversions. In other words, the above functions will work in both Ansi Delphi versions (previous to Delphi 2009) and Unicode Delphi versions (Delphi 2009, 2010, XE and so on).

Note that you need to include ZLib in the uses clause. ZLib.pas is a high level wrapper to the ZLib library created by Jean-Loup Gailly and Mark Adle for data compression.

In addition, using the TZCompressionStream and TZDecompressionStream classes you can also create (compress) and decompress ZIP files.

What did (do) I need this for? Well, the applicability for data compression is wide...

A real life example? I needed to store JSON strings in a MySQL database. As a way to optimize resources I compressed all JSON strings before the insertion into the database. After the retrieval, I was able to decompress each string to its original value. The compression rate was huge: I packed ~9000 chars in ~300 per JSON on average. This is a considerable saving: my table contains more than one million rows. Do the math yourself! :-)

Delphi Developers in Toronto

There are very little opportunities for Delphi developers in Toronto (Canada). The job market for software developers in this area is monopolized by .NET (C#, VB), Java and C++ in a huge percentage. Objective C, Python, PHP, Ruby are more popular than Delphi around here.

I don’t blame the Torontonian companies for deprecating Delphi. It‘s a reality that after the release of Delphi 7, Borland drove “the once most useful and popular IDE of the world” into a dark era.

Nonetheless, there is hope for Delphi. Lately, it has improved quite a bit, catching up to some degree for the time lost in the Borland's apocalypse. Some important milestones archived by Delphi lately:
  • Unicode support.
  • 64 Bits support.
  •  Mufti-platform support (with the introduction of FireMonkey)
Finally, I would like to list a few companies using Delphi these days in Toronto (Greater Toronto Area) :

Null character in Delphi (Caret notation: ^@)

I was assigned with a new programming task and I found the following constant declaration in the base code (Delphi 2007):

const
  s1 : PChar = ^@;

I was not sure about the meaning of such statement: the first ideas in my mind pointed me to think about some kind of pointer related syntax. I was induced to think so for the caret (^) and the at (@) symbols (operators?), which allow dereferencing a pointer and returning the address of a variable respectively.

Despite my hunch, the meaning of the above constant declaration was very different from my initial thoughts. Actually, it’s quite trivial…it just declares a constant, named s1, as type PChar and with the null character as constant value. Such declaration might be substituted with the following alternatives:

const
  s1 : PChar = '';

const
  s1 : PChar = #0;

The original construction is known as Caret notation. “In caret notation, the null character is ^@. Since ^A is character 1, then 0 must use the character before 'A' which is '@' in ASCII.”

The Caret notation for the Null character works well in both Ansi and Unicode versions of Delphi; meaning that you can use such syntax all the way from Delphi 1 through Delphi XE. Anyhow, the Caret notation is not well known by all programmers: one good example was myself :-)

So, if you are going to use it, make sure you append a small comment. This comment will allow further readers of your code to understand the syntax on the fly.