Pages

Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Friday, October 31, 2014

How to implode array in delphi

As in the previous post how to explode some string in delphi, we can also make the reverse, it is implode. In delphi we can make implode function as in php.

Below is the function:

//////////////////////////////////////////////////////////////////////////
// Procedure - implode
// Author    - Ronald Buster
// Remarc    - PHP like implode function
//
// Returns a string containing a string representation of all the array
// elements in the same order, with the glue string between each element.
//////////////////////////////////////////////////////////////////////////

function implode(const glue: string; const pieces: array of string): string;
var
  I: Integer;
begin
  Result := '';
  for I := 0 to High(Pieces) do
    Result := Result + Glue + Pieces[I];
  Delete(Result, 1, Length(Glue));
end;

To use function above you can copy the sample code below :

procedure TForm1.Button1Click(Sender: TObject);
var
  ls_glue:string;
  arr_fruit:array[0..3] of string;
begin
  ls_glue := ', ';
  arr_fruit[0] := 'banana';
  arr_fruit[1] := 'mango';
  arr_fruit[2] := 'pear';
  arr_fruit[3] := 'orange';

  ShowMessage('Here are my favourite fruit: ' + implode(ls_glue, arr_fruit));
end;
Thanks to Ronald Buster for this function

Friday, September 26, 2014

How to explode some string in delphi

How to explode some string in delphi

In delphi, you can make a function explode as in php, copy the code below to do that :

function explode(const separator, s: string; limit: Integer = 0): TDynStringArray;
var
  SepLen: Integer;
  F, P: PChar;
begin
  SetLength(Result, 0);
  if (S = '') or (Limit < 0) then
    Exit;
  if Separator = '' then
  begin
    SetLength(Result, 1);
    Result[0] := S;
    Exit;
  end;
  SepLen := Length(Separator);

  P := PChar(S);
  while P^ <> #0 do
  begin
    F := P;
    P := AnsiStrPos(P, PChar(Separator));
    if (P = nil) or ((Limit > 0) and (Length(Result) = Limit - 1)) then
      P := StrEnd(F);
    SetLength(Result, Length(Result) + 1);
    SetString(Result[High(Result)], F, P - F);
    F := P;
    while (P^ <> #0) and (P - F < SepLen) do
      Inc(P);
  end;
end;

How to use it? 

To use function above you can call it from button click as example below :
procedure TForm1.Button1Click(Sender: TObject);
var
  ls:string;
  i:integer;
  arr:TDynStringArray;
begin
  ls := 'apple;banana;mango;orange;melon';
  arr := explode(';', ls);
  for i := 0 to Length(arr)-1 do
    ShowMessage(arr[i]);
end;

Thursday, September 25, 2014

How to remove line breaks in delphi

How to remove line breaks from text in Delphi? 

You can use stringreplace function.
  • function StringReplace (const SourceString, OldPattern, NewPattern : string; Flags : TReplaceFlags) : string;
The StringReplace function replaces the first or all occurences of a substring OldPattern in SourceString with NewPattern according to Flags settings. The changed string is returned.

The Flags may be none, one, or both of these set values:
  • rfReplaceAll : Change all occurrences
  • rfIgnoreCase : Ignore case when searching
These values are specified in square brackets.

Below are the sample code :
var
   before, after : string;
begin
   before:='Some text with' + #10#13 + 'line break';
   after := StringReplace(StringReplace(before, #10, ' ', [rfReplaceAll]), #13, ' ', [rfReplaceAll]);
   ShowMessage(before);   
   ShowMessage(after);
end;


Wednesday, September 24, 2014

How to load sql file to ado command

Here is script to load sql file to adocommand at runtime.

var
f:TFileStream;
s:string;
begin
f:=TFileStream.Create('sql_commands.sql',fmOpenRead);
try
SetLength(s,f.Size);
f.Read(s[1],f.Size);
finally
f.Free;
end;
ADOCommand1.CommandText:=s;

Wednesday, November 13, 2013

How to replace string in power builder

In this post we will discuss about how to replace string in power builder using our custom routine. This routine works generically for any string.

For example, if old_str = "red" and new_str = "green", all occurrences of "red" inside of mystring will be replaced with "green".

Here is the script :

long ll_StartPos = 1

ll_StartPos = Pos(arg_str, arg_search, ll_StartPos)

DO WHILE ll_StartPos > 0

arg_str = Replace(arg_str, ll_StartPos, Len(arg_search), arg_replace)
ll_StartPos = Pos(arg_str, arg_search, ll_StartPos + Len(arg_search))

LOOP

return arg_str

Saturday, November 9, 2013

How to show prompt dialog in delphi


In this post we will discuss about How to show prompt dialog in delphi that will ask user to input some string to be processed. In delphi we can use inputbox function.

The InputBox function displays a simple dialog box with the given Caption and Prompt message. It asks the user to enter data in a text box on the dialog. A Default value is displayed in the text box.

If the user presses OK, the default or user entered data is stored in the return string, otherwise an empty string is returned.

If the user cancels the dialog, then the return value is the default string.

The script below are the sample of inputbox function usage :

var
  value : string;

begin
  // Keep asking the user for their town
  repeat
    value := InputBox('Name', 'Please type your name', 'Robert');
  until value <> '';

  // Show their name
  ShowMessage('Your name is '+value);
end;

Friday, November 8, 2013

How to Add Paging Widget For Blogger

In this post we will provide you tips to add page navigation for your blogger blog. Blogger default navigation shows only Older Posts and Newer Posts, many blogger want to change this into numbered page navigation.

In this post We will discuss step by step the guide of how to add paging widget to replace the blogger old navigation. 

How to Add Paging Widget For Blogger



Follow the steps below  on How to Add Paging Widget For Blogger :
  1. Log in into Blogger Dashboard
  2. Go to Layout and click on Add a Gadget link.
  3. Select HTML/JavaScript from list.
  4. Copy and paste below code into box :
    <style type="text/css">
    #blog-pager {
      height: 28px;
      padding: 10px 0 0;
      overflow: hidden;
      text-align: center;
    }
    
    .showpageArea a {
      text-decoration: underline;
      font-size: 16px;
      text-align: center;
    }
    
    .showpageNum a {
      font-size: 16px;
      text-decoration: none;
      border: 1px solid #cccccc;
      margin: 0 5px;
      padding: 5px;
    }
    
    .showpageNum a:hover {
      border: 1px solid #cccccc;
      background-color: #cccccc;
    }
    
    .showpagePoint {
      font-size: 16px;
      text-decoration: none;
      border: 1px solid #cccccc;
      background: #216FD9;
      margin: 0 5px;
      padding: 5px;
      color: #ffffff;
    }
    
    .showpageOf {
      text-decoration: none;
      padding: 5px;
      margin: 0 5px;
    }
    
    .showpage a {
      text-decoration: none;
      border: 1px solid #cccccc;
      padding: 5px;
    }
    
    .showpage a:hover {
      text-decoration: none;
      background: #cccccc;
    }
    
    .showpageNum a:link,.showpage a:link {
      text-decoration: none;
      color: #333333;
    }</style>
    <script>
        var pageCount = 7;
        var displayPageNum = 5;
        var upPageWord = "Previous";
        var downPageWord = "Next";
    </script>
    <a href="http://www.haakblog.com/" style="font-size: 0pt;">Blogger Widgets</a>
    <script src="http://netoopscodes.googlecode.com/svn/netoops-page-nav-v2.js"></script>
    
    
  5. You can changed number of page count with replace 3 as your required and for change display of page number change 5 as your requirement.
  6. Click on Save Button.
  7. In layout arranged this widget to below blog post widget.

Thursday, November 7, 2013

How to Add Facebook Fan Page Widget In Blogger

Facebook is the biggest way to promote your blog because almost everyone uses facebook. Many ways to promote your blog on facebook and facebook fan page is one of them. You can create facebook fan page for your blog or website and increase like for your fan page.
You can easily add your fan page like box widget on your blogger blog. In this post we will discuss  about How to Add Facebook like Box Widget for Blogger. 

Add Facebook Fan Page Widget

Here are the step to Add Facebook Fan Page Widget :
  1. Log in into Blogger Dashboard and Go to Layout then click on Add a Gadget link.
  2. Add HTML/JavaScript
  3. Insert below code into box
    [iframe allowtransparency="true" frameborder="0" scrolling="no" src="//www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2
    FIlkomerss&width=240&
    height=190&show_faces=true&
    amp;stream=false&header=false&show_border=false" style="border: none; height: 200px; overflow: hidden; width: 250px;"][/iframe]
    

  4.  Change Ilkomerss to your facebook page name. You can also change Width and Height as your requirement.
  5. Click on save button.

Thursday, July 18, 2013

How to join files and compress them into one destination files using zlib in delphi

Do you want to joining some files and compress them into one destination files?. You can do it with your own programming using delphi by copying this code snippet below :

uses Zlib;

procedure CompressFiles(Files : TStrings; const Filename : String);
var
  infile, outfile, tmpFile : TFileStream;
  compr : TCompressionStream;
  i,l : Integer;
  s : String;

begin
  if Files.Count > 0 then
  begin
    outFile := TFileStream.Create(Filename,fmCreate);
    try
      { the number of files }
      l := Files.Count;
      outfile.Write(l,SizeOf(l));
      for i := 0 to Files.Count-1 do
      begin
        infile := TFileStream.Create(Files[i],fmOpenRead);
        try
          { the original filename }
          s := ExtractFilename(Files[i]);
          l := Length(s);
          outfile.Write(l,SizeOf(l));
          outfile.Write(s[1],l);
          { the original filesize }
          l := infile.Size;
          outfile.Write(l,SizeOf(l));
          { compress and store the file temporary}
          tmpFile := TFileStream.Create('tmp',fmCreate);
          compr := TCompressionStream.Create(clMax,tmpfile);
          try
            compr.CopyFrom(infile,l);
          finally
            compr.Free;
            tmpFile.Free;
          end;
          { append the compressed file to the destination file }
          tmpFile := TFileStream.Create('tmp',fmOpenRead);
          try
            outfile.CopyFrom(tmpFile,0);
          finally
            tmpFile.Free;
          end;
        finally
          infile.Free;
        end;
      end;
    finally
      outfile.Free;
    end;
    DeleteFile('tmp');
  end;
end;
 
That's all the script to join files and compress using zlib library in delphi. If there is something error in code implementation, please contact me by leaving your comment below...

Monday, January 9, 2012

How to handle exception in delphi

Almost in all programming language, there are mechanism to handle exception. So do in delphi. We can use try...except mechanism. The following is the example of exception handling in delphi :
var
  bagi, nol : Integer;
begin 
  try
    nol   := 0;
    bagi := 1 div zero;
    ShowMessage('1/0 = ' + IntToStr(bagi));
  except
    on E : Exception do
      ShowMessage(E.ClassName + ' error raised, with message : ' + E.Message);
  end;
end;
In that example, if the try clause generates an exception, it will the execute except clause that will display window showing what type of error generated. This is used to take alternative action when something unexpected goes wrong. Beside that, the other form of handle exception can be done as follow :
var
  bagi, nol : Integer;
begin 
  try
    nol   := 0;
    bagi := 1 div zero;
    ShowMessage('1/0 = ' + IntToStr(bagi));
  finally
    if bagi = -1 then
    begin
      ShowMessage('Number was not assigned a value - using default');
      bagi := 0;
    end;
  end;
end;
In a try...finally construct, the finally statement will be executed absolutely whether thereis error or not. It is normally used to allow cleanup processing, such as freeing memory etc. Both kind of construct cannot be combined together using try..except..finally. So, the question is how to handle exception while we want to execute a set of clean up statements, in other words, how to tricky combine both except and finally ?? This can be done with nested try statements, as construct below :
Try
  Try
    ...
  Except
    ...
  End;
Finally
  ...
End;
Need to be noticed that when you want to test exception handling, don't do it using F9/Run. But do it by execute application (ctrl+f9 then double click application.exe created)

Saturday, January 7, 2012

How to install pear modules in xampp

Below is the step to install pear in xampp :
  1. Search the path of executable pear
    usually it is in 'C:\xampp\php\pear.bat'
  2. Run the following command, for example we will install MDB2 module :
    pear install MDB2
    Below is the look like :



Friday, January 6, 2012

How to insert post programmatically in wordpress

Sometimes, we need to insert post to our blog through code. This case occur in condition for example when we need to insert more than 1 post in 1 time.
Here is the code to do that :
  // Create post object
  $my_post = array();
  $my_post['post_title'] = 'My post';
  $my_post['post_content'] = 'This is my post.';
  $my_post['post_status'] = 'publish';
  $my_post['post_author'] = 1;
  $my_post['post_category'] = array(8,39);
  
  // Insert the post into the database
  wp_insert_post( $my_post );

Thursday, January 5, 2012

How to create xml document in PHP

Using domdocument, we can create xml document as we wish. Combined with the how-to-create-xml-in-php we will create xml directly in browser.
Here is the code to create xml from php :
$domDocument = new DOMDocument('1.0', "UTF-8");
  $domElement = $domDocument->createElement('field','some random data');
  $domAttribute = $domDocument->createAttribute('name');
  
  $domAttribute->value = 'attributevalue';
  
  $domElement->appendChild($domAttribute);

  $domDocument->appendChild($domElement);

  header("Content-type: text/xml");
  echo $domDocument->saveXML();
 
Here is the screenshot of the code above :

Wednesday, January 4, 2012

How to create xml in php

To create xml in php you can do the following step :
  1. You can use domdocument or create string in form of xml.
  2. Create header xml as code below :
    header("Content-type: text/xml");
    

Tuesday, January 3, 2012

How to get list files of a directory in delphi

Dear reader. Sometimes we need to get list of file names of a directory. This procedure below will do that for us :
procedure GetFilenames(Path: string; Dest: TStrings);
var
  SR: TSearchRec;
begin
  if FindFirst(Path+'*.*', faAnyFile, SR) = 0 then
  repeat
    Dest.Add(SR.Name);
  until FindNext(SR) <> 0;
  FindClose(SR);
end;
 
To use that function, for example you need to create a form with a button and listbox, we name it button1 and listbox1. Here is the code to use that procedure
procedure TForm1.Button1Click(Sender: TObject);
var
  path:string;
begin
  path := 'C:\Movies\';
  GetFilenames(path, ListBox1.Items);
end;
Here is the result when we click on button 'Get List Files Name'
get list files name in delphi

Monday, January 2, 2012

How to substring in delphi

There is almost in every programming language function to substring a string. As well as delphi. To substring a string in delphi use 'copy' function as below :
var s : string;
begin
  s:='Embarcadero';
  s := Copy(s,6,5);
  ShowMessage(s);
 
It will display message 'cader' as below :

Saturday, December 31, 2011

How to create close confirmation in delphi

This post will discuss about how to create a dialog box confirmation when user want to close a form in delphi. Below is the code :
  if MessageDlg('Are you sure you want to close the form?', mtConfirmation,
    [mbOk, mbCancel], 0) = mrCancel then
      CanClose := False;
Paste that code on event OnCloseQuery of form.

Friday, December 30, 2011

How to format strtodatetime in delphi

Because of regional setting computer that depend on each computer, it will output format time as regional setting. If we want to format datetime as we want regardless regional setting, we can write the script as below :
var
  MySettings: TFormatSettings;
  s: string;
  d: TDateTime;
begin
  GetLocaleFormatSettings(GetUserDefaultLCID, MySettings);
  MySettings.DateSeparator := '-';
  MySettings.TimeSeparator := ':';
  MySettings.ShortDateFormat := 'mm-dd-yyyy';
  MySettings.ShortTimeFormat := 'hh:nn:ss';

  s := DateTimeToStr(Now, MySettings);
  ShowMessage(s);
  d := StrToDateTime(s, MySettings);
  ShowMessage(DateTimeToStr(d, MySettings));
end;

Thursday, December 29, 2011

How to convert tstringlist to comma separated string

For some reasons, we may need to convert TListString to a comma separated String. for example to create query that use 'in'. Below is the routine to do that :
var
   oSL : TStringlist;
   sBuffer : String;
begin
   oSL := TStringlist.Create;
   oSL.Add('A');
   oSL.Add('B');
   oSL.Add('C');
   sBuffer := Stringreplace(oSL.Text,Char(13)+Char(10),',',[rfReplaceAll]);
   Showmessage( sBuffer );
   oSL.Free;
end;

Wednesday, December 28, 2011

How to create colored stringgrid in delphi

To make our program look more beautiful, we often add some functionality to handle it's look as well as stringgrid. One way to enhance the appearance is to set it's into the colorful. Below is the script to do that :
var
  dx: Integer;
begin
  with (Sender as TStringGrid) do
  begin
    if (ACol = 0) or (ARow = 0) then
      Canvas.Brush.Color := clBtnFace
    else
    begin
      case ACol of
        1: Canvas.Font.Color := clBlack;
        2: Canvas.Font.Color := clBlue;
      end;
      if ARow mod 2 = 0 then
        Canvas.Brush.Color := $00E1FFF9
      else
        Canvas.Brush.Color := $00FFEBDF;
      Canvas.TextRect(Rect, Rect.Left + 2, Rect.Top + 2, cells[acol, arow]);
      Canvas.FrameRect(Rect);
    end;
  end;
end;
 
Paste that function on event OnDrawCell in stringgrid. The result of your code will look like this :
alternate stringgrid
Don't Forget To Join Our Community
×
Widget