Pages

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

Tuesday, December 27, 2011

How to locate string in AdoQuery

Sometime for some reasons, we need to locate some values from adoquery result. Below is the function to do that :
if AdoQuery.Locate('NAME', 'jhon', [loPartialKey, loCaseSensitive]) then
Showmessage('Data is found')
else
Showmessage('Data not found');
If you want to locate in more than 1 field you can use ';' as code below :
AdoQuery.Locate('Name;Address',VarArrayOf(['jhon','Arizona']),[]);
The last parameter is optional. You can leave it blank of fill it with 'loPartialKey' or 'loCaseSensitive' as your need.

Monday, December 26, 2011

How to check if TCP Port is Open

When we create an application that open port using winsock, we need to anticipate that user may execute our application twice in order no port conflict error. So we need to check whether that port is already opened at OnCreate event of the form. Below is the function to check that :
uses
  Winsock;

function PortIsOpen(dwPort : Word; ipAddressStr:AnsiString) : boolean;
var
  client : sockaddr_in;
  sock   : Integer;
  ret    : Integer;
  wsdata : WSAData;
begin
 Result:=False;
 ret := WSAStartup($0002, wsdata);
  if ret<>0 then exit;
  try
    client.sin_family      := AF_INET;  
    client.sin_port        := htons(dwPort); 
    client.sin_addr.s_addr := inet_addr(PAnsiChar(ipAddressStr)); 
    sock  :=socket(AF_INET, SOCK_STREAM, 0);    
    Result:=connect(sock,client,SizeOf(client))=0;
  finally
  WSACleanup;
  end;
end;
 
To use that function, write down this code in OnCreate form event
procedure TForm1.FormCreate(Sender: TObject);
begin
if PortIsOpen(1521,'127.0.0.1') then
   showmessage('Port is already opened');
end;

Sunday, December 25, 2011

How to get idle time in delphi

Sometimes when we create a program, we want to know whether user doing some activity or not. For security reason we want to auto log off that user from application if his idle time over limit that we have been set.
Below is the function to get idle time of user :
function SecondsIdle: DWord;
var
   liInfo: TLastInputInfo;
begin
   liInfo.cbSize := SizeOf(TLastInputInfo) ;
   GetLastInputInfo(liInfo) ;
   Result := (GetTickCount - liInfo.dwTime) DIV 1000;
end;
 
To use that function we can do as below :
procedure TForm1.Timer1Timer(Sender: TObject) ;
begin
   showmessage(Format('You are idle in %d seconds', [SecondsIdle]));
end;

Saturday, December 24, 2011

mssql_connect(): unable to connect to server in xampp

xampp

Have you ever get such error when trying to access mssql server in another server except localhost with php using xampp??..
If so you need to this step below :
  1. download ntwdblib.dll.zip
  2. extract that file
  3. copy ntwdlib.dll to both folders 'xampp/php' and 'xampp/apache/bin'
  4. restart your apache web server

Friday, December 23, 2011

How to resolve #Error Code : 1235 in Mysql

error:1235 mysql
Have you ever got '#Error Code : 1235 This version of MySQL doesn't yet support multiple triggers with the same action time and event for one table'??. If so, this post will discuss about it.
This error:1235 occurs because of executing trigger update in the same table of trigger. For example, as in this code below :

DELIMITER $$
DROP TRIGGER IF EXISTS bfr_upd_billing$$
CREATE TRIGGER bfr_upd_billing
BEFORE UPDATE ON billing FOR EACH ROW
BEGIN
    update billing set flg_sync = '0' where billing_no = NEW.BILLING_NO;  
END$$
DELIMITER ;
In that code we will get #error:1235 because we want to update a field in table 'billing', whereas we create trigger on that table.
To resolve this error, we need to fix this code like below :

DELIMITER $$
DROP TRIGGER IF EXISTS bfr_upd_billing$$
CREATE TRIGGER bfr_upd_billing
BEFORE UPDATE ON billing FOR EACH ROW
BEGIN
  SET NEW.FLG_SYNC='0';  
END$$
DELIMITER ;
Well, actually we need not to run update again on trigger body.

Thursday, December 22, 2011

How to create trigger on mysql

mysql
Trigger is a procedure that automatically run when the trigger was invoked. For example: deleting data on a table will trigger a trigger to delete data on other tables. Below is an example of using triggers in MySQL database :
delimiter $$ 
create trigger auto_insert_test2
before insert on test for each row
begin
  insert into test2 (test_code, test_name) values (NEW.test_code,NEW.test_name);
end$$
 
create trigger auto_update_test2
before update on test for each row
begin
  update test2 set test_name=NEW.test_name where test_code=NEW.test_code;
end$$
 
create trigger auto_delete_test2
before delete on test for each row
begin
delete from test2 where test_code=OLD.test_code;
delete from trans where trans_test_code=OLD.test_code;
end$$
delimiter ;
In this code, it's assumed that we have 3 tables : test, test2 and trans.

Wednesday, December 21, 2011

How to search TStringlist Item in delphi

Sometimes we need to know whether a string is contained in a stringlist. This post will discuss about how to find a string inside the stringlist. If it is found, it will return true, otherwise false. Here is the sample code :
var MyList:TStringlist;
    Found:Boolean;
begin
 if MyList.IndexOf('item name') = -1 then
   Found := false
 else
   Found := true;
end;

Tuesday, December 20, 2011

How to display version info in delphi

As we know, in delphi we can set application version via IDE. To do that go to Project->Options->Version Info. Check 'Include version information in project'. The next question is how to display our version info in form??, For example in caption form.
Below is the steps to do that :
  1. Create function to get version info:
    function  GetAppVersion:string;
       var
        Size, Size2: DWord;
        Pt, Pt2: Pointer;
       begin
         Size := GetFileVersionInfoSize(PChar (ParamStr (0)), Size2);
         if Size > 0 then
         begin
           GetMem (Pt, Size);
           try
              GetFileVersionInfo (PChar (ParamStr (0)), 0, Size, Pt);
              VerQueryValue (Pt, '\', Pt2, Size2);
              with TVSFixedFileInfo (Pt2^) do
              begin
                Result:= ' Ver '+
                         IntToStr (HiWord (dwFileVersionMS)) + '.' +
                         IntToStr (LoWord (dwFileVersionMS)) + '.' +
                         IntToStr (HiWord (dwFileVersionLS)) + '.' +
                         IntToStr (LoWord (dwFileVersionLS));
             end;
           finally
             FreeMem (Pt);
           end;
         end;
       end;
    
  2. To make it display in form caption, write this script OnCreate events form
    Form1.Caption:=Form1.Caption+GetAppVersion;
    
Your application will look like this :

get version on form caption

Monday, December 19, 2011

How to restore grub in Ubuntu 11.04

If we have a dual-boot computers, especially Windows and Linux, we often get grub bootloader strucked by Windows bootloader when we reinstall windows. To restore GRUB from Linux, especially Ubuntu 11.04(Natty Narwhal), we can do the following steps :
  1. Prepare Ubuntu 11.04 live CD or live usb
  2. Set first boot on BIOS, to CD or Flashdrive
  3. Wait until the screen Boot Ubuntu appear, choose Try Ubuntu
  4. Once inside the Ubuntu Desktop, open the Terminal or press the key combination Ctrl+Alt+F2 to run terminal
  5. Check your Linux partition
    sudo fdisk -l 
  6. Once you know the Linux root partition, for example as on my laptop there are 2 partitions sda6 mounted as / and sda7 mounted as /home, Then do the following scripting :
    sudo mount -t ext4 /dev/sda6 /mnt
    sudo mount -t proc proc /mnt/proc
    sudo mount -t sysfs sys /mnt/sys
    sudo mount -o bind /dev/ /mnt/dev
    sudo chroot /mnt/ /bin/bash
  7. Now we will restore GRUB to the MBR, here is the command :
    grub-install /dev/sda
  8. Then comes a message as below:
    Installation finished. No error reported.
    This is the contents of the device map /boot/grub/device.map.
    Check if this is correct or not. If any of the lines is incorrect,
    fix it and re-run the script `grub-install
    (hd0) /dev/sda
    (hd1) /dev/sdb
    
  9. Now we will install it into the Linux root partition, in this case my linux partition is on sda6, here is the command:
    grub-install /dev/sda6
  10. Then comes a message like this:
    grub-setup: warn: Attempting to install GRUB to a partition instead of the MBR. This is a BAD idea.
    grub-setup: warn: Embedding is not possible. GRUB can only be installed in this setup by using blocklists. However, blocklists are UNRELIABLE and its use is discouraged.
    Installation finished. No error reported.
    This is the contents of the device map /boot/grub/device.map.
    Check if this is correct or not. If any of the lines is incorrect,
    fix it and re-run the script `grub-install
    (hd0) /dev/sda
    (hd1) /dev/sdb
  11. Now we need to update grub by typing this command:
    update-grub
  12. The message below will appear:
    Generating grub.cfg …
    Found linux image: /boot/vmlinuz-2.6.31-14-generic
    Found initrd image: /boot/initrd.img-2.6.31-14-generic
    Found memtest86+ image: /boot/memtest86+.bin
    Found Microsoft Windows 7 Loader on /dev/sda1
    done
  13. Reboot your computer

Sunday, December 18, 2011

How to disable root login in linux

For security reason, we need to configure linux operating system in order there is no intruder can access our system as root. one way is to disable login for root either in local or remotely. In this post we will discuss about it :
Disable root login locally
Below are the steps to do In order root can't login directly :
  1. Login as root
    #su -
  2. backup /etc/securetty
    # mv /etc/securetty /etc/securetty.bak
  3. create new file empty /etc/securetty
    # echo > /etc/securetty
  4. restart system
    # init 0
Now, root can't login from computer locally
Disable root login Remotely
This method will disable root logins from remote connections using ssh. Below are the steps to do that :
  1. edit file /etc/ssh/sshd_config
    # vim /etc/ssh/sshd_config
  2. change option "PermitRootLogin yes" become "PermitRootLogin no"
  3. restart sshd service
    # service sshd stop
    # service sshd start

Saturday, December 17, 2011

How to resolve HGFS is disabled in the host

Have you ever got error "can't mount hgfs, HGFS is disabled in the host" in vmware??. If so this post will discuss about How to resolve it.
As we know, this error eventually occured on boot, when restarting linux operating system guest. HGFS mounts allow the VM guest to connect to a share hosted on the ESX server/host.
It is installed when the VMware Tools service is installed. Actually this is not endanger our guest operating system and can be resolved as below :
  1. edit /etc/fstab
    # vim /etc/fstab
  2. Comment the line that starts with .hosts as below :

  3. restart server

Friday, December 16, 2011

How to unhide files hidden by viruses

I have Often got some problems in my computer, including the virus that infected the files. The effects of virus can be so various, one of them is hiding our file. so it become inaccessible. There are some tricks to retrieve that files and folders as below :
  1. Open command line using Start->Run and type cmd
  2. Go to drive of hidden files for example in drive D:
  3. type dir /a to view all files including the hidden files
  4. type attrib -r -h -s *.* /s /d to unhide all hidden files

Thursday, December 15, 2011

How to update antivirus ess 4

Here is the steps to update antivirus database Eset Smart Security (ESS) version 4 :
  1. Open ESS Window
  2. Press F5, Advanced Setup window will appear
  3. Click update in the left menu pane
  4. Click button edit on Update server in the right pane
  5. Insert directory where offline update has been extracted
  6. Click button Add
  7. Press button OK
Now you can update your antivirus using offline updater

Wednesday, December 14, 2011

Get value from trigger in mssql

This code below will show you about how to get value from trigger being executed :
CREATE TRIGGER aft_upd_mst
ON dbo.[table_name]
AFTER UPDATE
AS
DECLARE @ID int, @newValue nvarchar(30), @oldValue nvarchar(30)
IF (SELECT ID FROM inserted) <> (SELECT ID FROM deleted)
RAISERROR ('You are not allowed to change primary key field', 10,1)
ELSE
BEGIN
--set local variables
SET @ID = (SELECT ID FROM inserted)
SET @newValue = (SELECT [field_name] FROM inserted)
SET @oldName = (SELECT [field_name] FROM deleted)

--write to table
UPDATE [table_name] SET [field_name] = @newValue WHERE ID = @ID
-- write to archive
INSERT Log (type, ID, newValue, oldValue) VALUES('UPDATE', @ID, @newValue, @oldValue)
END
GO
Notes
Change [field_name] and [table_name] with your own
Inserted is same with new in oracle trigger
Deleted is same with old in oracle trigger

Tuesday, December 13, 2011

How to create win 7 bootable flashdisk

In earlier time, we often use the windows CD/DVD installation to install windows. How it can be done if the computer we want to install dont have a cd/dvd drive, for example netbook. The solution is install it using a flash disk.
In this post we will discuss about how to make a bootable Windows 7 flash natively, without using any additional software.
Below is the following steps :
  1. Plug the flash disk into computer
  2. Format your flash disk (don't forget to backup your data first)
  3. Run command prompt by choose Start - All Programs - Accesories - Command Prompt. Right click and then "Run As Administrator".
  4. Write "diskpart", we will enter in DISKPART mode
  5. Type "list disk" to display all available disk in our computer
  6. Write down these commands :
    select disk 1 
    clean
    create partition primary
    select partition 1
    active
    format fs=NTFS
    assign
    exit
    
  7. Insert your Windows 7 DVD installation
  8. Change command prompt to your DVD drive letter, for example in drive "d:"
  9. Write this command to enter to folder boot "cd boot"
  10. Write this command to make our flash disk bootable:
    bootsect /nt60 e:
    it is if our flash disk on drive e, for example. Change it as the environment of your system
  11. close command prompt
  12. copy all files in your DVD drive(d) to flashdisk drive (g)
  13. Now your flashdisk is bootable as below
boot from flashdisk

Monday, December 12, 2011

How to Get list files from a directory in delphi

This procedure below will list all files in a directory and add it to stringlist. Here is the function :
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;

Sunday, December 11, 2011

How to replace string in delphi


To replace string in delphi, we can use 'StringReplace' function. The pattern is
function StringReplace ( const SourceString, 
OldPattern, NewPattern : string; 
Flags : TReplaceFlags ) : string;

It replaces the first or all occurences of a substring 'OldPattern' in 'SourceString' with 'NewPattern' according to 'Flags' settings.
There are two Flags can be applied. It may be none, one, or both of these values:
rfReplaceAll  : Change all occurrences
rfIgnoreCase  : Ignore case when searching
 
Below is the example code:
var
  before, after : string;
begin
  // Try to replace all occurrences of a or A to THE
  before := 'It is a kind of fruit';
  after  := StringReplace(before, ' a ', ' THE ',
                          [rfReplaceAll, rfIgnoreCase]);
  ShowMessage('Before = '+before);
  ShowMessage('After  = '+after);
end;
It will output this alert
Before = It is a kind of fruit
After  = It is THE kind of fruit

Saturday, December 10, 2011

How to create trigger on mssql

In mssql we can create a trigger to get the orginal values in a separate table with the same structure to track changes on original table. It can be done using both trigger after insert, after update or after delete.
Below is scripts to create trigger in mssql :
Trigger insert
CREATE TRIGGER employee_aft_ins ON employee
AFTER INSERT 
AS
INSERT INTO employee_log
SELECT ID,FirstName,LastName FROM INSERTED
Trigger Update
CREATE TRIGGER employee_aft_upd ON employee
AFTER UPDATE
AS
INSERT INTO employee_log
SELECT ID,FirstName,LastName FROM DELETED
Trigger Delete
CREATE TRIGGER employee_aft_del ON employee
AFTER DELETE
AS
INSERT INTO employee_log
SELECT ID,FirstName,LastName FROM DELETED
Notes
Replace tables and fields name with your own
employee is the original table, while employee_log is table to save log history of original table

Friday, December 9, 2011

How to replace all spaces in url

Url now should be seo friendly as possible to make it indexed by google quickly. Therefore, many urls use the article title of which is of course could contain spaces. Then how to replace spaces with certain characters in the url ??.
The following script can be used :
$url = strtolower(str_replace(array('  ', ' '), '-', preg_replace('/[^a-zA-Z0-9 s]/', '', trim($string))));
Notes :
Those script using php
Replace '-' with any character as you wish
Those script convert all cases to lower

Thursday, December 8, 2011

How to make codeigniter without index.php

In codeigniter index.php will be included by default in the URL. We can remove it so that our URL should be like http://digilib.uad.ac.id/buku/Buku.
To do that just do the following steps:
  1. Open config.php in codeigniter application config directory
  2. replace $config['index_page'] = "index.php" with $config['index_page'] = ""
  3. Create a ".htaccess" file in the root of CodeIgniter directory
  4. write the following script:
    RewriteEngine on
    RewriteCond $1 !^(index\.php|resources|robots\.txt)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L,QSA] 
    

Wednesday, December 7, 2011

How to update some records in mssql

In certain conditions, we want to update some records, not all data. Suppose we want to update the first 100 data from a query. How to do it in MSSQL??.
The following query should be executed:
update top (100) table1 set field1 = 1
Notes
Make sure you replace "table1" with the actual table name.
And replace the field1, with your column names.

Tuesday, December 6, 2011

How to export query result in oracle

In may times, we often want to export the query results in the oracle into a text file with a specific format. In this blog we will discuss about how to export query results in the oracle into a text file.
To do so run the following script:
set head off 
spool c:\myoracle.txt
select field1||', '||field2||', '||field3 from my_table;
spool off
set head on
Notes :
This script will create a comma delimited file named: c:\myoracle.txt
Make sure you replace "my_table" with the actual table name.
And replace the field1, field2, with your column names.

Monday, December 5, 2011

How to Change the firewall scope in windows server 2003

Firewall is a software/hardware used to provide specific rules on a computer/server. The goal is to make our computer more secure from hacker attacks. In windows there is a built in firewall that can be set in such a way. By default the port is closed by a firewall, so that when we turn on the firewall, we must define the program/​​service that is allowed for access.

One program that is blocked by a firewall default is the file/printer sharing. When we turn on the firewall, then we can not share folders on our computer. In order to share we must add the File/Printer Sharing in Firewall exception.

By default the firewall exception is on the scope of subnet. So shared file can only be accessed on a computer in one subnet with our computers. To change the scope of the firewall do the following steps:
  1. Open windows firewall
  2. Click exception tab
  3. Click File/Printer sharing
  4. Click Edit
  5. Click Change Scope on every port
  6. Choose any computer or other choise as your need

Sunday, December 4, 2011

How to trim on mssql

Trim is a standard function which is used by many programming languages to remove the space character in a string. For example ' Hello world ', with trim function, it will be 'Hello world'.

In SQL Server, trim function is not provided by default. We need to do a certain trick to remove the spaces. we can use LTRIM and RTRIM function together.

Here's an example to remove spaces in SQL Server:
select LTRIM(RTRIM(' Hello world '))

Saturday, December 3, 2011

How to grant all user object privilege


In oracle, each user/schema has some objects. They can be tables, views, procedures, functions or packages. By default a user can not access other objects owned by other user, unless after the owner gives that user some objects privileges.

Granting objects privileges to other user in oracle can by done one by one. If a user has 100 objects for example, he must run a script 100 times to give the whole object. But there are tricks he can do to overcome it.

To give permissions all objects owned by a schema, perform the following steps:
  1. login as object owner
  2. run script below
    begin
    for i in (select object_name from user_objects where object_type in ('TABLE','VIEW'))
    LOOP
    execute immediate 'grant select on '|| i.object_name||' to bb';
    end loop;
    end;
    /
    

Friday, December 2, 2011

How to troubleshoot ‘cannot restore segment prot after reloc: Permission denied’

The error above occurs because the settings of selinux. To troubleshoot that problem, do the following:
  1. Go to System -> Administration -> Security Level and Firewall -> SELinux Tab
  2. Change "Enforce" to "Disabled"
  3. Alternatively you can edit selinux setting by editing file /etc/selinux/config

Thursday, December 1, 2011

How to edit fstab when at "Repair filesystem" prompt

Have you ever got an error in linux that caused by the errors on the filesystem??. If so, you would get "Repair filesystem" prompt appeared.

This post will discuss about how to troubleshoot linux when "Repair filesystem" prompt appears on RHEL 5. Here are the steps :
  1. Boot your system with Redhat Linux Disk1
  2. Go through the Linux Rescue process and you will get a hash prompt
  3. Type the command below
    # vi /mnt/sysimage/etc/fstab
    
  4. Save using wq
Don't Forget To Join Our Community
×
Widget