Tuesday 11 March 2014

How to use Generic TList Class in Delphi?

How to use Generic TList Class in Delphi?

TList generic class is used to store a list of various data type variables in Delphi. Below is the simple program to illustrate the concept of TList generic class in Delphi.

  List: TList<Integer>;
  FoundIndex: Integer;

  { Create a new List. }
  List := TList<Integer>.Create;
  { Add a few values to the list. }
  List.AddRange([5, 1, 8, 2, 9, 14, 4, 5, 1]);

  writeln('Index of first 1 is ' + IntToStr(List.IndexOf(1)));
  writeln('Index of last 1 is ' + IntToStr(List.LastIndexOf(1)));
  writeln('Does List contains element 100? ' + BoolToStr(List.Contains(100)));

  { Add another element to the list. }

  writeln('There are ' + IntToStr(List.Count) + ' elements in the list.');

  { Remove the first occurrence of 1. }
  { Delete a few elements from position 0. }
  List.DeleteRange(0, 2);
  { Extract the remaining 1 from the list. }
  { Set the capacity to the actual length. }
  writeln('Capacity of the list is ' + IntToStr(List.Capacity));

  { Clear the list. }
  { Insert some elements. }
  List.Insert(0, 2);
  List.Insert(1, 1);
  List.InsertRange(0, [6, 3, 8, 10, 11]);

  { Sort the list. }

  { Binary search for the required element. }
  if List.BinarySearch(6, FoundIndex) then
    writeln('Found element 6 at index ' + IntToStr(FoundIndex));

  { Reverse the list. }
  writeln('The element on position 0 is ' + IntToStr(List.Items[0]));


How to use TDictionary Generics Collection in Delphi?

How to use TDictionary Generics Collection in Delphi?

TDictionary is used to store key-value pair in Delphi. TDictionary is an example of Generic Collections in Delphi. Below is the simple Delphi program to illustrate the concept of TDictionary in Delphi.

  TCity = class
    Country: String;
    Latitude: Double;
    Longitude: Double;

  EPSILON = 0.0000001;

  Dictionary: TDictionary<String, TCity>;
  City, Value: TCity;
  Key: String;

  { Create the dictionary. }
  Dictionary := TDictionary<String, TCity>.Create;
  City := TCity.Create;
  { Add some key-value pairs to the dictionary. }
  City.Country := 'Romania';
  City.Latitude := 47.16;
  City.Longitude := 27.58;
  Dictionary.Add('Iasi', City);

  City := TCity.Create;
  City.Country := 'United Kingdom';
  City.Latitude := 51.5;
  City.Longitude := -0.17;
  Dictionary.Add('London', City);

  City := TCity.Create;
  City.Country := 'Argentina';
  { Notice the wrong coordinates }
  City.Latitude := 0;
  City.Longitude := 0;
  Dictionary.Add('Buenos Aires', City);

  { Display the current number of key-value entries. }
  writeln('Number of pairs in the dictionary: ' +

  // Try looking up "Iasi".
  if (Dictionary.TryGetValue('Iasi', City) = True) then
    'Iasi is located in ' + City.Country +
    ' with latitude = ' + FloatToStrF(City.Latitude, ffFixed, 4, 2) +
    ' and longitude = ' + FloatToStrF(City.Longitude, ffFixed, 4, 2)
    writeln('Could not find Iasi in the dictionary');

  { Remove the "Iasi" key from dictionary. }

  { Make sure the dictionary's capacity is set to the number of entries. }

  { Test if "Iasi" is a key in the dictionary. }
  if Dictionary.ContainsKey('Iasi') then
    writeln('The key "Iasi" is in the dictionary.')
    writeln('The key "Iasi" is not in the dictionary.');

  { Test how (United Kingdom, 51.5, -0.17) is a value in the dictionary but
    ContainsValue returns False if passed a different instance of TCity with the
    same data, as different instances have different references. }
  if Dictionary.ContainsKey('London') then
    Dictionary.TryGetValue('London', City);
    if (City.Country = 'United Kingdom') and (CompareValue(City.Latitude, 51.5, EPSILON) = EqualsValue) and (CompareValue(City.Longitude, -0.17, EPSILON) = EqualsValue) then
      writeln('The value (United Kingdom, 51.5, -0.17) is in the dictionary.')
      writeln('Error: The value (United Kingdom, 51.5, -0.17) is not in the dictionary.');
    City := TCity.Create;
    City.Country := 'United Kingdom';
    City.Latitude := 51.5;
    City.Longitude := -0.17;
    if Dictionary.ContainsValue(City) then
      writeln('Error: A new instance of TCity with values (United Kingdom, 51.5, -0.17) matches an existing instance in the dictionary.')
      writeln('A new instance of TCity with values (United Kingdom, 51.5, -0.17) does not match any existing instance in the dictionary.');
    writeln('Error: The key "London" is not in the dictionary.');

  { Update the coordinates to the correct ones. }
  City := TCity.Create;
  City.Country := 'Argentina';
  City.Latitude := -34.6;
  City.Longitude := -58.45;
  Dictionary.AddOrSetValue('Buenos Aires', City);

  { Generate the exception "Duplicates not allowed". }
    Dictionary.Add('Buenos Aires', City);
    on Exception do
      writeln('Could not add entry. Duplicates are not allowed.');

  { Display all countries. }
  writeln('All countries:');
  for Value in Dictionary.Values do

  { Iterate through all keys in the dictionary and display their coordinates. }
  writeln('All cities and their coordinates:');
  for Key in Dictionary.Keys do
    writeln(Key + ': ' + FloatToStrF(Dictionary.Items[Key].Latitude, ffFixed, 4, 2) + ', ' +
    FloatToStrF(Dictionary.Items[Key].Longitude, ffFixed, 4, 2));

  { Clear all entries in the dictionary. }

  { There should be no entries at this point. }
  writeln('Number of key-value pairs in the dictionary after cleaning: ' + IntToStr(Dictionary.Count));

  { Free the memory allocated for the dictionary. }

Generic Types in Delphi

Generic Types in Delphi

Generics, a powerful addition to Delphi, were introduced in Delphi 2009 as a new language feature. Generics or generic types (also know as parametrized types), allow you to define classes that don't specifically define the type of certain data members.

As an example, instead of using the TObjectList type to have a list of any object types, from Delphi 2009, the Generics.Collections unit defines a more strongly typed TObjectList.

Simple Generics Type Example in Delphi

Here's how to define a simple generic class:

  TGenericContainer<T> = class
  Value : T;

With the following definition, here's how to use an integer and string generic container:

  genericInt : TGenericContainer<integer>;
  genericStr : TGenericContainer<string>;
  genericInt := TGenericContainer<integer>.Create;
  genericInt.Value := 2009; //only integers

  genericStr := TGenericContainer<string>.Create;
  genericStr.Value := 'Delphi Generics'; //only strings

Basic WCF Interview Questions and Answers for .NET Developers

Basic WCF Interview Questions and Answers for .NET Developers

If you are preparing of .NET interview, must brush up WCF concepts also. Mostly in every .NET project, WCF is used. So, every .NET developer must know at least basics of WCF. By keeping that in mind, I have tried to list down some basic WCF interview questions and answers which every .NET developer should know before going to the interview room. These WCF interview questions and answers cover basic concepts of WCF, SOA, difference between WCF and web services, need of WCF, endpoints in WCF like Address, Contracts and Bindings, types of Bindings in WCF, types of contracts in WCF, components of WCF, transport schemas in WCF, transactions in WCF, isolation levels in WCF, how to host WCF services, generating proxies for WCF services etc. So, lets have a look upon thes basic WCF interview questions and answers.

1. What is WCF (Windows Communication Foundation)?

Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types.

WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it. WCF is Microsoft’s unified programming model for building service-oriented applications with managed code. It extends the .NET Framework to enable developers to build secure and reliable transacted Web services that integrate across platforms and interoperate with existing investments.

Windows Communication Foundation combines and extends the capabilities of existing Microsoft distributed systems technologies, including Enterprise Services, System.Messaging, Microsoft .NET Remoting, ASMX, and WSE to deliver a unified development experience across multiple axes, including distance (cross-process, cross-machine, cross-subnet, cross-intranet, cross-Internet), topologies (farms, fire-walled, content-routed, dynamic), hosts (ASP.NET, EXE, Windows Presentation Foundation, Windows Forms, NT Service, COM+), protocols (TCP, HTTP, cross-process, custom), and security models (SAML, Kerberos, X509, username/password, custom).

2. What is SOA (Service Oriented Architecture)?

Service-oriented architecture (SOA) is an evolution of distributed computing based on the request/reply design paradigm for synchronous and asynchronous applications. An application's business logic or individual functions are modularized and presented as services for consumer/client applications.

3. What is the difference between WCF and Web Services?

1. Web services can only be invoked by HTTP. While Service or a WCF component can be invoked by any protocol and any transport type.

2. Second web services are not flexible. But Services are flexible. If you make a new version of the service then you need to just expose a new end point. So services are agile and which is a very practical approach looking at the current business trends.

4. What was the code name for WCF?

The code name of WCF was Indigo . 

WCF is a unification of .NET framework communication technologies which unites the following technologies:- 

NET remoting 
Web services 

5. How does WCF work?

Follows the ‘software as a service’ model, where all units of functionality are defined as services.

A WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal (connection) for communication with either clients (applications) or other services.

Enables greater design flexibility and extensibility of distributed systems architectures.

A WCF application is represented as a collection of services with multiple entry points for communications.

6. What are the main components of WCF?

1. Service: The working logic or offering, implemented using any .Net Language©.

2. Host: The environment where the service is parked. E.g. exe, process, windows service

3. Endpoints: The way a service is exposed to outside world.

7. What is the endpoint in WCF? 

Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service.

In WCF the relationship between Address, Contract and Binding is called Endpoint. The Endpoint is the fusion of Address, Contract and Binding.

1. Address: Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this location to communicate with our service.

2. Contract: Specifies the interface between client and the server.It’s a simple interface with some attribute.

3. Binding: Specifies how the two paries will communicate in term of transport and encoding and protocols.

8. What is the binding in WCF and how many types of bindings are there in WCF?

A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary).

A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.

WCF supports nine types of bindings.

1. Basic binding:

Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.

2. TCP binding:

Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.

3. Peer network binding:

Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.

4. IPC binding:

Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.

5. Web Service (WS) binding:

Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.

6. Federated WS binding:

Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.

7. Duplex WS binding:

Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.

8. MSMQ binding:

Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.

9. MSMQ integration binding:

Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.

9. What are the contracts in WCF?

In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.

WCF defines four types of contracts.

1. Service contracts: Describe which operations the client can perform on the service.

2. Data contracts: Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.

3. Fault contracts: Define which errors are raised by the service, and how the service handles and propagates errors to its clients.

4. Message contracts: Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.

10. What is address in WCF and how many types of transport schemas are there in WCF?

Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas. 

WCF supports following transport schemas:

2. TCP
3. Peer network
4. IPC (Inter-Process Communication over named pipes)

The sample address for above transport schema may look like


11. Explain transactions in WCF.

Transactions in WCF allow several components to concurrently participate in an operation. Transactions are a group of operations that are atomic, consistent, isolated and durable. WCF has features that allow distributed transactions. Application config file can be used for setting transaction timeouts.

12. What are different isolation levels provided in WCF?

The different isolation levels:

1. READ UNCOMMITTED: An uncommitted transaction can be read. This transaction can be rolled back later.

2. READ COMMITTED: Will not read data of a transaction that has not been committed yet

3. REPEATABLE READ: Locks placed on all data and another transaction cannot read.

4. SERIALIZABLE: Does not allow other transactions to insert or update data until the transaction is complete.

13. How do I serialize entities using WCF?

LINQ to SQL supports serialization as XML via WCF by generating WCF serialization attributes and special serialization specific logic during code-generation. You can turn on this feature in the designer by setting serialization mode to ‘Unidirectional’. Note this is not a general solution for serialization as unidirectional mode may be insufficient for many use cases.

14. What are various ways of hosting WCF Services?

There are three major ways of hosting a WCF services 

1. Self-hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of Service Host class and the service closes when you call the Close of the Service Host class. 

2. Host in application domain or process provided by IIS Server

3. Host in Application domain and process provided by WAS (Windows Activation Service) Server. 

15. What is Transport and Message Reliability?

Transport reliability (such as the one offered by TCP) offers point-to-point guaranteed delivery at the network packet level, as well as guarantees the order of the packets. Transport reliability is not resilient to dropping network connections and a variety of other communication problems. 

Message reliability deals with reliability at the message level independent of how many packets are required to deliver the message. Message reliability provides for end-to-end guaranteed delivery and order of messages, regardless of how many intermediaries are involved, and how many network hops are required to deliver the message from the client to the service.

16. What is service and client in perspective of data communication?

A service is a unit of functionality exposed to the world. The client of a service is merely the party consuming the service.

17. What is Proxy and how to generate proxy for WCF Services?

The proxy is a CLR class that exposes a single CLR interface representing the service contract. The proxy provides the same operations as service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service. The proxy completely encapsulates every aspect of the service: its location, its implementation technology and runtime platform, and the communication transport. 

The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference. This brings up the Add Service Reference dialog box, where you need to supply the base address of the service (or a base address and a MEX URI) and the namespace to contain the proxy. 

Proxy can also be generated by using SvcUtil.exe command-line utility. We need to provide SvcUtil with the HTTP-GET address or the metadata exchange endpoint address and, optionally, with a proxy filename. The default proxy filename is output.cs but you can also use the /out switch to indicate a different name. 

SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs 

When we are hosting in IIS and selecting a port other than port 80 (such as port 88), we must provide that port number as part of the base address: 

SvcUtil http://localhost:88/MyService/MyService.svc /out:Proxy.cs

Encoding and Decoding a String in Delphi XE4 using Indy 10

Encoding and Decoding a String in Delphi XE4 using Indy 10

I am using Delphi XE4 and Indy 10. I want to share how I encoded and decoded a file in Delphi XE4 using Indy 10 client. Include IdCoder, IdCoder3to4, IdCoderMIME units and use TIdEncoderMIME and TIdDecoderMIME classes for this purpose. Following are two simple Delphi functions which illustrate the way of encoding and decoding a file in Delphi XE4 in very simple way. 


IdCoder, IdCoder3to4, IdCoderMIME;

//Encoding function in Delphi XE4

procedure TMyForm.EncodeMIME_Example;
  EncodeMIME: TIdEncoderMIME;
  myEncryptedFile: WideString;
  stringToBeEncoded: WideString;
  EncodeMIME :=  TIdEncoderMIME.Create(Self);
    myEncryptedFile := EncodeMIME.Encode(stringToBeEncoded);

//Decoding function in Delphi XE4

procedure TMyForm.DecodeMIME_Example;
  DecodeMIME: TIdDecoderMIME;
  myDecryptedFile: WideString;
  stringToBeDecoded: WideString;
  DecodeMIME :=  TIdDecoderMIME.Create(Self);
    myDecryptedFile := DecodeMIME.Decode(stringToBeDecoded);

Friday 7 March 2014

How to Insert, Append, Edit and Delete Rows in a Dataset in Delphi?

How to Insert, Append, Edit and Delete Rows in a Dataset in Delphi?

You can insert, append, edit and delete rows in datasets in Delphi. Following are the methods for performing these operations:

Insert: Add a new record to the dataset at current position
Append: Add a new record to the dataset at the end
Edit: Sets the dataset in the 'edit' mode
Post: Post changes to database
Cancel: Cancel an edit/insert action
Delete: Removes the active record

Inserting/Appending a row in the dataset: The Append and Insert methods allow you to begin the process of adding a row to the dataset. The only difference between these two methods is the Insert method will insert a blank row buffer at the current position in the dataset, and the Append method will add a blank row buffer at the end of the dataset. This row buffer does not exist in the physical datset until the row buffer is posted to the actual dataset using the Post method. If the Cancel method is called, then the row buffer and any updates to it will be discarded. Also, once the row buffer is posted using the Post method it will be positioned in the dataset according to the active index order, not according to where it was positioned due to the Insert or Append methods.

Suppose I have two fields in the dataset "PROGRAMMING_LANGUAGE" and "VERSION". I insert the records in these fields.

with DataSet1 do
  Insert; //Set the dataset in the insert mode
  FieldByName('PROGRAMMING_LANGUAGE').AsString := 'DELPHI'; //Fill in the values
  FieldByName('VERSION').AsString := 'XE4';

Same thing with Append method:

with DataSet1 do
  Append; //Set the dataset in the append mode
  FieldByName('PROGRAMMING_LANGUAGE').AsString := 'DELPHI'; //Fill in the values
  FieldByName('VERSION').AsString := 'XE4';

Editing a row in the dataset: The Edit method allows you to begin the process of editing an existing row in the dataset. Suppose I want to change the version of Delphi from XE4 to XE5.

with DataSet1 do
  Edit; //Set the dataset in the edit mode
  FieldByName('VERSION').AsString := 'XE5'; //Update the field

Delete a row in the dataset: The Delete method allows you to delete an existing row in a dataset. Unlike the Append, Insert, and Edit methods, the Delete method is a one-step process and does not require a call to the Post method to complete its operation. A row lock is obtained when the Delete method is called and is released as soon as the method completes. After the row is deleted the current position in the dataset will be the next closest row based upon the active index order.

The following example shows how to use the Delete method to delete a row in a dataset:

with DataSet1 do

Cancelling an Insert/Append or Edit Operation: You may cancel an existing Insert/Append or Edit operation by calling the Cancel method. Doing this will discard any updates to an existing row if you are editing, or will completely discard a new row if you are inserting or appending. The following example shows how to cancel an edit operation on an existing row:

with DataSet1 do
  Edit; //Set the dataset in the edit mode
  FieldByName('VERSION').AsString := 'XE5'; //Update the field

Thursday 6 March 2014

Why you should choose Dedicated Web Server Hosting for your business website?

Why you should choose Dedicated Web Server Hosting for your business website?

If you are starting a website for your business and are thinking to go for a dedicated web server hosting, here are some points to which you should give a thought before making any decision. A dedicated web server hosting provides you good bandwidth to handle massive traffic to your website. You can easily scale your website with dedicated web server hosting. Also, you will get flexibility, security and full control on the various resources in a dedicated web server hosting. 

Do you need to handle huge traffic?

If your website encounters a huge traffic everyday, you need to opt for dedicated web hosting. In shared hosting, your website is being hosted on a server with other clients, you are at risk of not having enough memory or ample bandwidth because other websites are sapping it all up. Sometimes it may happen that a massive traffic hit your website and your shared hosting is already running with low performance due to other websites sharing the same server, and obviously you have no idea and clue how good or bad is the performance of your shared hosting server. At that moment your hosting is not ready to handle the load and when your website will exceed its bandwidth and CPU usage your website will immediately get taken offline by your hosting provider in order to avoid high loading issues on server.

Dedicated hosting is much more reliable. Dedicated hosting will keep you up and running to encounter the web traffic. Dedicated web hosting ensures that you enjoy the resources and functions of an entire server, rather sharing with others. Since a whole server is completely dedicated to your site, you won’t run into bandwidth bottle necks and will have plenty of memory to handle mammoth amounts of web traffic, whether objects or sessions. A shared web hosting solution can cost you potential clients. The cost of downtime depends on how long you site stays down, so don’t risk it.

Is your business scaling very fast?

If your business is scaling very fast, dedicated web hosting provides a better solution for scaling the resources easily. When you’re on a shared server with other clients, a lot is not in your command. Dedicated Hosting gives you the power to scale up when expanding your business. A good dedicated host manages everything from dot to done for you.

Do you need more control and flexibility?

A dedicated web hosting server offers you a lot of controls and flexibility. A dedicated web hosting server gives you full control to access root level of your server and you can delete or install software. If you want to install custom software’s and packages on your server you can do it without the interference of you hosting provider. For example you can manage your Webmail interface, if you want to remove Squirrel mail interface and install another one, you are free to do this. With a dedicated web hosting server, you can customize resources like Hard disk, Memory, Bandwidth, Database etc. for each of your website you host without affecting others and without being affected. You can also create different user accounts and set different level of permissions. And there are many more like this.

So if you know how to manage your server and you need these advance features then you should go for dedicated web hosting server. You will get many options for hosting providers all over the world offering you different packages, it’s really very important to ascertain your needs first and then compare among the top plans available. 

Is security your concern?

If you concern about the security of your website, you should give a thought to dedicated web hosting. When you are starting a new website or when you know that there is not massive traffic falling on your website in such cases a shared hosting is probably something you can count on, but remember as your business grows and so will your website, then you will need more security and uptime. With a shared hosting server where many other unknown websites are also sharing the same server you are less secure and your privacy cannot be cast iron. You can suffer because of other websites running on the same server. 

In dedicated web hosting, the entire resources on server are dedicated exclusively to your site/sites. A good dedicated hosting service should offer 24/7 tech support. It should also have regular operating system and control panel updates as well as security patches. Dedicated hosting insures security.


High level security and state of the art scalability options make a dedicated web hosting solution perform at high standards. When your site gets bombarded with requests and sessions, photos, videos, you name it. With all the power to you, dedicated hosting can be counted on when it comes to security and reliability. Dedicated server hosting keeps running things spick and span!

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.