Monday, 18 February 2013

How to Send Email with Attachments in Delphi XE2 using Indy Clients?

How to Send Email with Attachments in Delphi XE2 using Indy Clients?

This delphi programming language tutorial is based on sending email with attachments using indy clients in delphi XE2. Indy Clients provide TIdSMTP and TIdMessage delphi components using which we can send email easily.

First of all, you will have to declare the objects of TIdSMTP  and TIdMessage like following:

SMTP: TIdSMTP;
MailMessage: TIdMessage;

Now you have to initialize Host and Port for SMTP. You can use default emailing port as 25.

After this you have to initialize MailMessage with From Address, To Address, CC Addresses, Subject and Body of the email.
 
Lets have a look at the following very simple delphi program to send email with attachments.

function TMyForm.SendEmailDelphi : Boolean;
var
  FileName : String;
begin
  try
    Result := False;
    FileName := 'myfile.txt';
    //Setup SMTP
    SMTP := TIdSMTP.Create(nil);
    SMTP.Host := 'XXX.XXX.XXX.XXX';
    SMTP.Port := 25; //Default email port
    MailMessage.From.Address := admin@host.com;
    MailMessage.Recipients.EMailAddresses :=
TOperson@host.com + ',' + CCperson@host.com;
    MailMessage.Subject := 'Test Email from Delphi XE2';
    MailMessage.Body.Text := 'Hi! This is test email from delphi XE2';
    //Attach a file
    if FileExists(FileName) then
      TIdAttachmentFile.Create(MailMessage.MessageParts, FileName);
    //Send email
    try
      try
        SMTP.Connect;
        SMTP.Send(MailMessage);
        Result := True;
      except
        on E:Exception do
        begin
          ShowMessage('Cannot send E-Mail: ' + E.Message);
          Result := False;
        end;
      end;
    finally
      if SMTP.Connected then SMTP.Disconnect;
  end;
  except
    on E : Exception do
    begin
      ShowMessage('Error in the function SendEmailDelphi: ' + E.Message);
      Result := False;
    end;
  end;
end;

Sunday, 17 February 2013

How to format and update datetime in Javascript?

How to format and update datetime in Javascript?

There are a lot of datetime formats in which you can display the date and time on your webpage using javascript. There are a lot of javascript datetime functions available. In this javascript datetime tutorial, I will show you how to display the date on your webpage and keep on updating datetime every minute.

I have to show the javascript datetime in following format:

Monday, February 18, 2013 12:18

I will keep this time updating every minute without refreshing my webpage.

For this, I will make two arrays. One array will contain the names of the months and other array will contain the names of the days. I will use setInterval function which will keep on calling myDateTimer function after every minute.

Lets look at this javascript datetime code:
 
var myVar=setInterval(function(){myDateTimer()},1000);
  
function makeArray()
{
 for (i = 0; i<makeArray.arguments.length; i++)
 this[i + 1] = makeArray.arguments[i];
}
  
function myDateTimer()
{
 var months = new makeArray('January','February','March','April','May',
 'June','July','August','September','October','November','December');
 var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
 var date = new Date();
 var day = date.getDate();
 var month = date.getMonth() + 1;
 var yy = date.getYear();
 var year = (yy < 1000) ? yy + 1900 : yy;
 var hours = date.getHours();
 var minutes = date.getMinutes();
 var finaldate = days[ date.getDay() ] + ", " + months[month] + " " + day + ", " + year + " " + hours +" : " + minutes;
 document.getElementById("showDateTime").innerHTML=finaldate;
}

Thursday, 14 February 2013

How to use FieldName and FieldValue in Delphi XE2?

How to use FieldName and FieldValue in Delphi XE2?

In this delphi programming tutorial, we will come to know how to use FieldName and FieldValue in delphi. Sometimes while coding in delphi, we need to get the field or column name of the table depending upon some certain conditions. In this case FieldName and FieldValue come into play.

In the following delphi code, we have created a delphi function which will fetch various columns from a table in database and will return the name of that column. For example, following delphi program gets ColA, ColB, ColC, ColD from a table named tblABC. After getting all the columns, it iterate through the column list and finds out which one is null and returns it. If it finds no column which is null, it returns empty string.

(Note: ColA, ColB, ColC, ColD are numeric columns, so I am checking for null. If your columns are varchar, you can use '' for checking empty column)

Delphi Program to show usage of FieldName and FieldValue
 
function TForm.MyDelphiFunction : String;
var
  i : integer;
begin
  try
    Result := '';
    with qryABC do
    begin
      Close;
      SQL.Clear;
      SQL.Text := 'SELECT ColA, ColB, ColC, ColD FROM tblABC WHERE ID = :ID';
      ParamByName('ID').AsString := anyID;
      Open;
      if RecordCount > 0 then
      begin
        for i:=0 to FieldCount -1 do
        begin
          if (Fields[i].Value) = Null then
          begin
             Result := Fields[i].FieldName;
             Break;
          end;
        end;
      end;
      Close;
    end;
  except
    on E : Exception do
    begin
      Showmessage('Error occured in function MyDelphiFunction: ' + E.Message);
      Result := '';
    end;
  end;
end;

What is DNS (Domain Name Server)

What is DNS (Domain Name Server)

DNS (Domain Name Server) is used to translate a domain name into IP address. This makes it possible for a user to access a website by typing in the domain name instead of the website's actual IP address. DNS is similar to a telephone directory.

Meaning of COM, NET, ORG etc.

COM -- commercial Web sites, though open to everyone
NET -- network Web sites, though open to everyone
ORG -- non-profit organization Web sites, though open to everyone
EDU -- restricted to schools and educational organizations
MIL -- restricted to the U.S. military
GOV -- restricted to the U.S. government
US, UK, RU and other two-letter country codes -- each is assigned to a domain name authority in the respective country

Domain Names should be unique

A registrar is an authority that can assign domain names directly and register them with InterNIC, a service of ICANN, which enforces uniqueness of domain names across the Internet. Each domain registration becomes part of a central domain registration database known as the whois database. Network Solutions, Inc. (NSI) was one of the first registrars, and today companies like GoDaddy.com offer domain registration and many domain management services.

How DNS (Domain Name Server) works?

1. If it has the domain name and IP address in its database, it resolves the name itself.

2. If it doesn't have the domain name and IP address in its database, it contacts another DNS server on the Internet. It may have to do this multiple times.

3. If it has to contact another DNS server, it caches the lookup results for a limited time so it can quickly resolve subsequent requests to the same domain name.

4. If it has no luck finding the domain name after a reasonable search, it returns an error indicating that the name is invalid or doesn't exist.
 
Registering a domain

Each domain name must have at least two name servers listed when the domain is registered. These name servers are commonly named ns1.servername.com and ns2.servername.com, where "servername" is the name of the server. The first server listed is the primary server, while the second is used as a backup server if the first server is not responding.

Name servers are a fundamental part of the Domain Name System (DNS). They allow websites to use domain names instead of IP addresses, which would be much harder to remember.

What is Parked Domain?

Using the DNS servers from your registrar or hosting company means that you have a parked domain. This means that someone else owns the computer hardware for the DNS servers, and your domain is just part of that company's larger DNS configuration.

What is Domain Propagation?

Domain Propagation is the period of time, or delay, involved in sending your domain’s address information to all the other name servers in the world. Name servers intentionally keep track of addresses for domains in their memory for a specific period of time which is defined by the administrator of the name server. This speeds up the process of looking up an address for a domain name. Unfortunately this “cached” information also stays in the name servers when it has been changed at the source of the original information (the domain’s registrar).

Name servers refresh themselves from once an hour to once a day. Generally 2-3 days time is a good estimate when a domain’s DNS information is changed at the domain registrar, after which everyone in the world can see the change.

Monday, 11 February 2013

PHP Form Validation Script: PHP GET and POST Methods

PHP Form Validation Script: PHP GET and POST Methods

Form validation in PHP is very easy. Whenever you submit any form in PHP, you must validate the input data before storing that in database. Basic validations which you can put on your input data might be trimming the input form data, stripping the slashes from form data, handling special html characters and various functional things depending upon the need of your PHP application. Below is the PHP Form Validation Script using POST method.

HTML Page

<form action="validateForm.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>

PHP Script to Validate Form

<?php
$name = validateData($_POST['name']);
$email = validateData($_POST['email']);
?>

function validateData($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

Now lets discuss PHP Get and POST methods in detail:

PHP GET Method

The PHP GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character.


PHP Script to illustrate GET Method

<form action="index.php" method="get">
Name: <input type="text" name="name">
<input type="submit">
</form>

When the user clicks the "Submit" button, the URL sent to the server will look like this:


The index.php file can now use the $_GET variable to collect php form data (the names of the form fields will automatically be the keys in the $_GET array):

Hello <?php echo $_GET["name"]; ?>

The PHP provides $_GET associative array to access all the sent information using PHP GET method.

Limitations of PHP GET Method:

1. When using method="get" in HTML forms, all variable names and values are displayed in the URL. So, PHP GET method should not be used when sending passwords or other sensitive information.

2. The PHP GET method is not suitable for very large variable values. It should not be used with values exceeding 1024 characters.

3. PHP GET method can't be used to send binary data, like images or word documents, to the server.

Advantages of PHP GET Method:

1. Because the variables are displayed in the URL, it is possible to bookmark the page.

PHP Post Method

The POST method transfers information via HTTP headers. The information is put into a header called QUERY_STRING.

PHP Script to illustrate POST Method

<form action="index.php" method="post">
Name: <input type="text" name="name">
<input type="submit">
</form>

When the user clicks the "Submit" button, the URL sent to the server will look like this:


The index.php file can now use the $_POST variable to collect form data (the names of the form fields will automatically be the keys in the $_POST array):

Hello <?php echo $_POST["name"]; ?>

Advantages of PHP POST Method

1. No limit to send data. There is an 8 MB max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file).

2. Variables are not visible in URL. So one can easily send passwords and critical information using POST method.

3. You can even post binary data using PHP Post Method.

Limitation of PHP POST Method

1. You cannot bookmark a specific page unlike GET method.

Saturday, 9 February 2013

Online PHP Programming Tutorial: Learn Basics of PHP Scripting With Simple PHP Code and Examples (Part 1)

Online PHP Programming Tutorial: Learn Basics of PHP Scripting With Simple PHP Code and Examples (Part 1)

Introduction to PHP: PHP stands for Hypertext Preprocessor. PHP is a server scripting language and is used for creating dynamic web pages. PHP is an open source scripting language. We will discuss some similarities and differences between PHP and ASP.NET later in this tutorial.

Learning PHP Programming

Learning PHP programming and development is very easy. PHP has very simple syntax. In this online PHP tutorial, we will learn PHP step by step by simple PHP examples using short and simple PHP scripts and codes. Lets start learning PHP scripting now:

1. Simple PHP Code Snippet

<?php
echo "Lets learn PHP Programming!";
?>

Some basic things to note in PHP scripting:

1. A PHP script starts with <?php and ends with ?>.
2. Each code line in PHP must end with a semicolon.
3. PHP files have a default file extension of ".php".
4. In PHP, there are two basic statements to output text in the browser: echo and print.

2. Comments in PHP Programming

<?php
//PHP Single Line Comments
/*
PHP
Multi Line Comments
*/
?>

3. Rules for PHP Variables

1. PHP variable starts with the $ sign, followed by the name of the variable
2. PHP variable name must begin with a letter or the underscore character
3. PHP variable name only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
4. PHP variable name should not contain spaces
5. PHP variable names are case sensitive ($y and $Y are two different variables)
6. PHP has no command for declaring a variable
7. PHP variables can be local, global and static
8. PHP string variable is used to store and manipulate text. When you assign a text value to a variable, remember to put single or double quotes around the value.

PHP Variables Example

<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>

4. PHP is a Loosely Typed Language

You don't have to declare data type the variable in PHP. PHP automatically converts the variable to the correct data type, depending on its value. In a strongly typed programming language, we will have to declare datatype of the variable before using it.

Consider the following simple PHP example:

$txt="PHP is a loosely typed language";
$x=5;

After the execution of the statements above, the variable txt will hold the value Hello world!, and the variable x will hold the value 5. When you assign a text value to a variable, put quotes around the value.

5. Types of Array in PHP

In PHP, there are three types of arrays:

Indexed arrays - Arrays with numeric index
Associative arrays - Arrays with named keys - Associative arrays are arrays that use named keys that you assign to them.
Multidimensional arrays - Arrays containing one or more arrays

Similarity and Differences between PHP and ASP.NET

PHP is a strong competitor of Microsoft ASP.NET. PHP goes ahead of ASP.NET in some case like:

1. PHP runs on different platforms likeWindows, Linux, Unix, Mac OS X, etc. ASP.NET on the other hand, only runs fine on Windows.


2. PHP is compatible with both Apache, IIS while ASP.NET has compatibility only with IIS. You can configure ASP.NET to run on Apache, but that is cumbersome.

3. PHP is open source and free. No license required for using PHP for commercial purposes.
 
Similarity between ASP.NET and PHP

1. Both ASP.NET and PHP are used for dynamic webpage development.


2. Both ASP.NET and PHP are easy to learn and understand.

3. Both ASP.NET and PHP have support for a wide range of databases.

4. Both ASP.NET and PHP have large online developer forums to support web development. For example, you will find a large community of ASP.NET and PHP developers on StackOverflow.com.

Sunday, 3 February 2013

How to use Conditional Operators in Delphi XE2?

How to use Conditional Operators in Delphi XE2?

Conditional operators look so attractive because they let you write short and concise code. But delphi does not provide any conditional operators.

Lets have following example of conditional operators.

if a>b then
c:= 1
else
c:= 0;

I want to conclude it in one line using conditional operators like in C/C++.

c := (a > b ? 1 : 0);

But no, this is not possible in delphi. I don't know why? Why conditional operators are not included in delphi?

Workaround of Conditional Operators in Delphi?

Delphi provides a set of IfThen functions in the Math and StrUtils units. Delphi prism provides the utility of Iif that only evaluates one of its two value parameters. For example:

c:= Iif(a > b, 1, 0);

There are a number of available simple type handles on the overloaded IFTHEN function.

StrUtils.IfThen (String)
Math.IfThen (Integer)
Math.IfThen (Int64)
Math.IfThen (Double) (works for TDateTime as well)

Having or not having conditional operators don't make any difference because conditional operators have some drawbacks like less readability: Delphi is more centered on readability than the C Syntax languages which are more centered on character power (as much information per character as possible). The conditional operator is powerful but not readable.