Thursday, 26 April 2007

JavaScript: How to tell if any form fields have been modified

The following function can be used to determine if a form passed as parameter has been modified, returning true or false respectively. You may use it on submit events in order to avoid unnecessary post actions or like I do in other page links in order to warn the user of pending changes.

I have tested this with Firefox 2.0.0.3, but will post results for other browsers as well.

    /**
     * Check if a form has changed
     */    
    function formModified(aForm)
    {                
        for (var i=0; i < aForm.elements.length; i++) {
            // get the form current element
            var curElement = aForm.elements[i];
            // get the current element type            
            var myType = curElement.type;
            // assume that the form is modified
            var valueChanged = true;
            
            if (myType == 'checkbox' || myType == 'radio') {
                // if both the checked state and the DefaultCheck state are equal
                if (curElement.checked == curElement.defaultChecked) {
                    valueChanged = false
                }                     
            } else if (myType == 'hidden' || myType == 'password' || myType == 'text' || myType == 'textarea') {
                // if the current text is the same as the default text i.e. the original in the
                // HTML Document
                if (curElement.value == curElement.defaultValue) {
                    valueChanged = false
                }
            } else if (myType == 'select-one' || myType == 'select-multiple') {
                for (var j=0;  j < curElement.options.length; j++) {
                    if (curElement.options[j].selected && curElement.options[j].defaultSelected) {
                        valueChanged = false
                    }
                }
            } else
                // unhandled type assume no change
                valueChanged = false;
                    
            // the previously checked element has changed
            if (valueChanged)
                return true;
        }

        // all elements have their default value
        return false;
    }

In order to warn the user of pending changes you would have to write something like :

    /**
     *  returns true if a user can leave a page based on wheither the
     *  aform parameter is committed.
     */
    function canLeavePage(aForm)
    {
        // if no changes were made in the form
        if (formModified(aForm) == false)
            return true;

        // else ask user
        return confirm('Form data have been modified.\n' +
                       ' Are you sure you want to leave this page ?') ;
    }

To use this in your Web page, name your form with something like myForm or InputForm and place anywhere in the page a link like :

              <a href="myPage.php"
                onclick="return canLeavePage(InputForm);"/>
                <img src="images/exit.png"
                    border="0"
                    align="middle"
                    hspace="2"
                    vspace="2"
                    title="Exit"/>
                </a>

Enjoy!

Monday, 23 April 2007

PHP: Directory Listing

Here is a snipper I use to get the contents of a directory. I have many times searched the WEB -- and my files -- for similar functionality so I thought I might put it here to save me the the next searches. The PHP manual for opendir that contains similar code can be found here.

/**
 * returns an associative array containing the file list of the $directory parameter
 * $fileList[$file_name]contains the size of the file or 0 if file_name is a irectory
 */
function fileList($disrectory)
{
   $files = array();
   if (!is_dir($directory))
      return $files;

   if (false == ($d = @opendir($directory)))
     return NULL;

   while (false != ($f = readdir($d))) {
      $fullName = "$directory/$f";
      $files[$f] = is_file($fullName) ? filesize($fullName) : 0;
   }
   closedir($d);

   return $files;
}

Tuesday, 17 April 2007

SAP via Delphi Re-executing the same SAP function

After running the examples from BAPI / RFC with Delphi, I run into the following problem: Each time the Button2Click function was called the grid would show the results already displayed plus any data returned from SAP after the current call. A little bit of debugging showed that the table returned from the SAPFunctions object in statement Table := Funct.tables.item('DATA'), was the one that would not get initialized prior to Funct.call(). Aa I have no clues regarding the available methods of the table or the SAPFunctions object that would allow me to clear the table data before each call, I ended up rewriting the example performing the following changes.

  1. Create one connection object and retain it throughout the entire program session during FormCreate.
  2. Create and destroy a SAPFunctions object at each invocation of the ExecuteButtonClick() function. The way the table returned always has new data returned from SAP. This has been the only way I could avoid the problem of not initializing the returned table. Since I use similar code to perform data transfers between SAP and an other Oracle database at user defined intervals , this optin was more or less a one way.
The actual code of the get cost centers example now looks like this :
unit MainUni;

interface

uses
 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
 Dialogs, OleCtrls, SAPLogonCtrl_TLB, Grids,
 StdCtrls, ComCtrls, ExtCtrls, Buttons;

type
 TFormMain = class(TForm)
   PanelLogin: TPanel;
   StatusBar: TStatusBar;
   ButtonExec: TButton;
   Grid: TStringGrid;
   SAPLogonControl: TSAPLogonControl;
   BitBtnClose: TBitBtn;
   procedure ButtonExecClick(Sender: TObject);
   procedure FormCreate(Sender: TObject);
 private
   { Private declarations }
   Table, Funct, Connection : VARIANT ;
 public
   { Public declarations }
 end;

var
 FormMain: TFormMain;

implementation
{$R *.dfm}

Uses
  SAPFunctionsOCX_TLB;

procedure TFormMain.FormCreate(Sender: TObject);
  begin
     (* create a new connection object to be used
      * for all sessions
      *)
     Connection                  := SAPLogonControl.newConnection;
     Connection.System           := 'R3Q';
     Connection.Client           := '100';
     Connection.ApplicationServer:= 'sapqa_prd.shelman.int';
     Connection.SystemNumber     := '00';
     Connection.Language         := 'EN' ;
  end;

procedure TFormMain.ButtonExecClick(Sender: TObject);
  var
     txt : String;
     r : integer;
     SAPFunctions: TSAPFunctions;
  begin
     SAPFunctions := nil;

     // parameter "true" = SilentLogOn
     if Connection.LogOn(0, false) = true then
        try
           (* Create a new SAPFunctions obejct and
            * assign the existing connection to it
            *)
           SAPFunctions := TSAPFunctions.Create(Self);
           SAPFunctions.Connection := Connection;

           Funct := SAPFunctions.add('RFC_READ_TABLE');
           Funct.exports('QUERY_TABLE').value := 'CSKT';

           // attempt to call
           if not Funct.call then
              // called failed display the error in the statusbar
              StatusBar.SimpleText := Funct.Exception
           else begin
              // Call is successfull display returned data
              Table := Funct.tables.item('DATA');
              grid.rowCount := Table.rowcount + 1;
              grid.cells[0,0] := 'RecNo';
              grid.cells[1,0] := 'Client';
              grid.cells[2,0] := 'CostCent-No';
              grid.cells[3,0] := 'CostCent-Des.';
              for r := 1 to grid.rowCount -1 do begin
                 txt := Table.value(r,1);
                 grid.cells[0,r] := IntToStr(r);
                 grid.cells[1,r] := copy(txt,0,3);
                 grid.cells[2,r] := copy(txt,9,10);
                 grid.cells[3,r] := copy(txt,27,20);
              end;
           end;
        finally
           // close connection
           Connection.LogOff;
           // get rid of the SAPFunctions Object
           SAPFunctions.Free;
        end
     else
        StatusBar.SimpleText := 'Unable to login';
  end;

end.

Wednesday, 11 April 2007

BAPI / RFC with Delphi 6

A sad story with a happy end.

I wanted to write a small application that would update some Oracle tables based on data read from SAP using Delphi 6. Very soon I realized that it all came down to installing the various ActiveX components required for Delphi to connect to SAP, be able to execute functions and read the returned results.

And this is where the sad part of the story begins. Looking around at various sources I could find some instructions explaining how to perform the required installation but none of them seemed to be accurate enough or straightforward enough in order to produce the desired results. In my opinion the problem occurs because our German colleagues who provided the "how-to's" tried to translate the menus from their German Delphi to English and that caused the misunderstanding. Additionally, while following the directions provided I also run into compilations errors increasing my frustration. The following article provides my how to install SAP ActiveX controls on Delphi 6 and I hope to make it as clear as possible.

I have to admit that I owe everything to the guy who wrote and maintained the BAPI/RFC Programming with Delphi Page and to my good friend Marilena who found the page for me. The page has enough examples required in order for the average Delphi programmer to understand how to program the necessary communication. An other page that gives information regarding the pre-installation steps is this one found at SDN.

So here is the list of the steps I followed in order to install SAP ActiveX controls on my version of Delphi 6 If you are using Delphi 2006 then it you might beter have a look here.

  1. Create an additional package page to host the new components.
    1. Right click on the Delphi palette → Properties → Click the Add button.
    2. Type a name for the new page SAP will do just fine
    3. Use the Move Up and Move Down buttons to position the page at the correct position. Caution : Since the page will initially be empty it will not appear on the Delphi palette.
  2. Create an additional directory to hold the units for the new controls. In my case I created : C:\Program Files\Borland\Delphi6\Imports\SAPControls\.
  3. Go to main menu Component → Import ActiveX Control
    1. Select the SAP Logon Control Version 1.1 (wdtlog.OCX). The displayed class name should be TSAPLogonControl
    2. Select SAP as the Palette Page
    3. Change the directory of the unit file name to the new path created in the previous step.
    4. Click install. The first time select to create a new package, name it SAPControls and put it the path we are already using. The controls we will install next will be added to the package as well.
    5. Perform the same steps this time installing the TSAPBapiControl class from SAP BABPI Control Version 1.2
  4. Go to main menu Project → Import Type Library.
    1. Select SAP Remote Function Call Controll (Version 5.0). This will provide you with the TSAPFunctions, TFunction, TParameter, TExports, TImports, TStructure clases
    2. Click install and choose the SAPCOntrols package created previously.
  5. Press compile to compile the project. At this point I got many errors, but I will show you how to resolve them.
Many errors appear in functions with code like the following :
procedure TStructure.Set_Value(index: OleVariant; Param2: OleVariant);
 begin
   DefaultInterface.Set_Value(index) := Param2;
 end;
This should be corrected like this :
procedure TStructure.Set_Value(index: OleVariant; Param2: OleVariant);
 begin
   // DefaultInterface.Set_Value(index) := Param2;
   DefaultInterface.Value[index] := Param2;
 end;
The general error pattern is that there are unknown identifiers for functions of the form Set_XXX(i). These should be changed to indexed properties like XXX[i] Additionally I have had many functions not returning a value. The worst part is that the Delphi complier did not issue any warnings for some of them, so I had to look at each one separately. The worst case was the NewConnection method of the TSAPLogonControl class. The generated code was
function  TSAPLogonControl.NewConnection: IDispatch;
 begin
   DefaultInterface.NewConnection;
 end;
and it had to be corrected to
function  TSAPLogonControl.NewConnection: IDispatch;
 begin
   // had to add Result :=
   Result := DefaultInterface.NewConnection;
 end;
Failure to correct this results to all new Connections being returned null afterwards, making connections to R3 practically impossible. After you correct all the functions with warnings, you should be finished. Just press "Install" on the package dialog and you 're done The examples in BAPI RFC with Delphi page are good and they may get you started immediately. If I ever get any examples of my own I will post them in this page for future reference.

Saturday, 31 March 2007

Linux: How many songs do I have

I have always wanted to know the exact number of music files that I own. Of course Amarok appears to have the correct answer, still I always wanted to write something like that
#!/bin/bash
# Count the music files starting form MUSIC_BASE
# Thanassis Bakalidis
# 31-03-2007

# This is the directory containing all my music
MUSIC_BASE=/mnt/Culture/My\ Mjavascript:void(0)usic
# Add more music file extentions here
MUSIC_EXTENTIONS="mp3 wma ogg flac"

echo Base directory is $MUSIC_BASE

TOTAL_FILES=0
for ext in $MUSIC_EXTENTIONS
 do 
   echo ""
   echo Saerching for $ext  files
   current=`find "$MUSIC_BASE" -type f -name "*.$ext" -print | wc -l`
   echo Located $current $ext files
   TOTAL_FILES=`expr $TOTAL_FILES + $current`
done

echo ""
echo A total of $TOTAL_FILES music files were accounted.
exit

Wednesday, 28 March 2007

ABAP: Check if a day ix a holiday

Here is some sample code that allows you to determine if a date passed as parameter is a holiday or a weekend day.

FORM check_if_holiday
                USING
                  value(fact_cal) LIKE scal-fcalid
                  value(holiday_cal) LIKE scal-hcalid
                  a_date TYPE d.
  FIELD-SYMBOLS :
     TYPE casdayattr.

  DATA
    days_attr_tbl TYPE STANDARD TABLE OF casdayattr.

* get the attributes for the specified day 
  CALL FUNCTION 'DAY_ATTRIBUTES_GET'
   EXPORTING
     factory_calendar                 = fact_cal      " default 'GR'
     holiday_calendar                 = holiday_cal   " default 'GR'
     date_from                        = a_date
     date_to                          = a_date
     language                         = sy-langu
*   IMPORTING
*     YEAR_OF_VALID_FROM               =
*     YEAR_OF_VALID_TO                 =
*     RETURNCODE                       =
    TABLES
      day_attributes                   = days_attr_tbl
   EXCEPTIONS
     factory_calendar_not_found       = 1
     holiday_calendar_not_found       = 2
     date_has_invalid_format          = 3
     date_inconsistency               = 4
     OTHERS                           = 5.
  IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
            WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
  ENDIF.

  READ TABLE days_attr_tbl INDEX 1 ASSIGNING <day_attr>.

  IF NOT <day_attr>-holiday_id IS INITIAL.
    MESSAGE w888(sabapdocu) WITH a_date text-e05  <day_attr>-txt_long.
  ENDIF.

  IF <day_attr>-weekday = '6' OR  <day_attr>-weekday = '7'.
    MESSAGE w888(sabapdocu) WITH a_date text-e06 -weekday_l.
  ENDIF.
ENDFORM.                    " check_if_holiday

The parameters fact_cal and holiday_cal are two letter country code representations, so in my case, they may be hard coded to the value 'GR'.

A practical way to use the above would be :

On the screen flow logic

PROCESS AFTER INPUT.
 ...
    FIELD input_date
      MODULE input_date_changed ON REQUEST.

On the actual code

MODULE input_date_changed INPUT.
  PERFORM check_if_holiday USING 'GR' 'GR' input_date.
ENDMODULE.

Update source for Mozilla Products on openSUSE

I have always wondered why there were no updates for the SuSE provided Firefox. Looking a bit more carefully at the openSUSE site, I realized that in order to get updates for Firefox, SeaMonkey and Thunderbird, you need to add an additional YaST source.

The base directory for all Mozilla related products on SuSE Linux is http://software.opensuse.org/download/mozilla/.

You can add the correct path for your Linux distribution from there.

For example the openSUSE 10.2 the source URL is http://software.opensuse.org/download/mozilla/openSUSE_10.2/.

As far as I am concerned, there are more good news as I realised that the base address also offers versions for SLES9 and SLES10.

Wednesday, 21 March 2007

Linux: A simple backup script

Here is the script I use for backing up my home directory onto the hard drive an other machine (mounted using samba). The script can be configured by changing the values of the top variables

#!/bin/bash
# Script to back up my home directory
# Created 21-03-2007
# Thanassis Bakalidis

BKP_FILE="/mnt/KomUsers/bakalidi/LinuxBackups/my_home.tar.bz2"
BKP_ROOT="/home/thanassis"
LOG_FILE="/home/thanassis/backup_output.txt"
EXCLUDE_FILES_FILE="/home/thanassis/.files_to_exclude"
ERROR_FILE="/home/thanassis/backup_errors.txt"

EXCLUDE_DIRS="/home/thanassis/mp3 /home/thanassis/java"

# remove file if existing
if [ -f $EXCLUDE_FILES_FILE ]; then
 rm $EXCLUDE_FILES_FILE
fi

# get a list of all file patterns that do not need be backed up
for path in $EXCLUDE_DIRS
do
 echo $path/\* >> $EXCLUDE_FILES_FILE
done

# finally append the log file in the list of excluded files
echo $LOG_FILE >> $EXCLUDE_FILES_FILE
echo $EXCLUDE_FILES_FILE >> $EXCLUDE_FILES_FILE

# start the log File
echo Backup of $BKP_ROOT Starting at `date` > $LOG_FILE

# after creating the list of files to be excluded perform the actual backup
/bin/tar -jcvf $BKP_FILE -X $EXCLUDE_FILES_FILE --exclude-caches  $BKP_ROOT  1>> $LOG_FILE 2>$ERROR_FILE

# mark the end time stamp on the log file and exit
echo Backup of $BKP_ROOT finished at  `date` >> $LOG_FILE
exit 0

It is true that one could directly edit the $EXCLUDE_FILES_FILE and add the patterns of the files that should not be backed up. Personally, I prefer the approach shown above, because that way I keep all my information regarding backups in one place and thus have less configuration files to worry about-- Of course there is always more than one way to do things right.

Finally I have added the following in my crontab config :

thanassis@lxbakalidis:~> crontab -l
# DO NOT EDIT THIS FILE - edit the master and reinstall.
# (/tmp/crontab.XXXXhnhNTc installed on Wed Mar 21 11:52:39 2007)
# (Cron version V5.0 -- $Id: crontab.c,v 1.12 2004/01/23 18:56:42 vixie Exp $)
30 18 * * * /home/thanassis/bin/tarbackup.sh

The /mnt/KomUsers speciffied as target in script file directory points to the users folder of a Windows 2003 server on my local area network. The company administrator runs tape backup jobs at exactly 19:00 everyday, so starting my backup at 18:30 allows me to keep a copy of my data every day in a separate tape following the day, week, month company schedule.

Linux: How to mount Windows Shares with Samba at startup

This posting applies for SuSE systems only. If you are using Red Hat or any of its clones like CentOS or OEL for example, then information required for mounting windows shares at startup can be found at this very neat and precise article at the CentOS Wiki website.

Install the samba-client package. After installation you end up with a directory named /etc/samba.

thanassis@lxbakalidis:~> rpm -q samba-client
samba-client-3.0.23d-19.2

Create the mount points for the new directories. Mine are at /mnt

Add appropriate entries inside the file named smbfstab located inside /etc/samba.

The entries in /etc/samba/smbfstab must have the following form :

//my_windows_pc/my_share  /mnt/my_dir  cifs   username=windows_user,
password=win_pasword,uid=thanassis,gid=dba,file_mode=0644,dir_mode=0755,
iocharset=iso8859-7

Note that the the above statement should be placed in a single line. You need one sutch line per mount point. It is also a good idea to use case sensitive references to windows shares especially if mounting drives from Windows NT.

Next, use the iocharset addition only if your Linux machine is not configured for UTF-8.

Reboot

Sunday, 18 March 2007

Linux: How to use iptables in order to deny access to speciffic IP's

Eventually I had to deal with that as well. Somebody trying to start DOS attacks on my site. Asking the experts revealed th at the safest way to deal such cases is to use iptables. The command works on the kernel level for any kind of access to your entire web space. To get things started let's suppose that the offending IP address is 192.167.250.1. To block out this address completely enter the following as root.

iptables -A INPUT -s 192.167.250.1 -j DROP

Naturally attacks do not come from just one IP. Their usual sources are entire ISP address blocks so it is much better to block out the entire IP range. The correct syntax for this command is :

iptables -A INPUT -s 192.167.250.0/24 -j DROP

Listing all active iptables rules is performed by the following command.

iptables -L

I will update this post with more info as soon as I 've learned more. For the moment here is a link for more info on the subject

Monday, 12 March 2007

Sending mail using Java Mail

In addition to the previous article, I shall provide here a slightly changed version of Sudhir Ancha's code as presented in his Sending Email From Your Application Using Java Mail article at javacomerice.com.

The only notable difference is the Charset = .. addition to the setContent() method of the message class, that allows sending the message using the iso8859-7 Greek character set.

package utils.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


/**
 * @class SendMail
 * Encapsulates a simple mail sending using a specific SMTP Server
 */
public class SendMail {
    // put you server here
    public static final String SMTP_HOST = "smtp.mydomain.com";

    public void post(String to, // recipient for the message
        String subject,         // subject
        String message,         // actual mesage text
        String from)            // address of sender
        throws MessagingException 
    {

        String[] recipients = new String[1];
        recipients[0] = to;

        postToMany(recipients, subject, message, from);
    }

    public void postToMany( String[] recipients, // list of recipients for the message
        String subject, // subject
        String message, // actual mesage text
        String from) // address of sender
        throws MessagingException 
    {
        boolean debug = false;

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST);

        // create some properties and get the default Session
        Session session = Session.getDefaultInstance(props, null);
        session.setDebug(debug);

        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) 
            addressTo[i] = new InternetAddress(recipients[i]);
        
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Content-type: text/html; charset=utf-8\r\n
        // Optional : You can also set your custom headers in the Email if you Want
        // msg.addHeader("Content-type", "text/html; charset=utf-8");

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain; Charset=iso8859-7");
        Transport.send(msg);
    }

    private static final String emailMsgTxt = "Δοκιμαστικό μύνημα σταλμένο από Java.";
    private static final String emailSubjectTxt = "EMail from Java";
    private static final String emailFromAddress = "me@mydomain.gr";
    private static final String[] emailList = {
            "he@hisdomain.com",
            "she@herdomain.gr" 
    };
    

    public static void main(String[] args) throws Exception 
    {
        SendMail smtpMailSender = new SendMail();
        smtpMailSender.post("me@mydomain.om", emailSubjectTxt, emailMsgTxt,
                            emailFromAddress);
        System.out.println("Sucessfully Sent mail to All Users");
    }
}

Send email from PHP

Here is some sample code I came across over the net. It demonstrates two things:

One how to send email using PHP the second one is how to change the mail headers in order to send Unicode UTF-8 mail.

<?php
   $from = 'me@mydomain.com';
   $to = 'you@yourdomain.com';
   $subject = 'Sending Unicode e-mail';
   $message = '
            <p>
               Hello!
            </p>
            <p> 
                This message contains and displays unicode characters like 
                the Greek Α, Γ and Ω
             </p>';
    $header = "Content-type: text/html; charset=utf-8\r\nFrom: $from\r\nReply-to: $from";
 
    if ( mail($to, $subject, $message, $header) ) 
        echo "Email sent to $to!";
    else
        echo "Error occurred while sending email to $to!";

?>

Remember that for the mail function to work correctly the SMTP Server must be correctly specified in PHP.ini.

I will come back with more precise info as soon as I have completed my tests

Thursday, 8 March 2007

Installation of SAP JCo on an Oracle IAS 10.1.3.x on Linux

1) Unpack sapjco to /opt/SAP/SAPJCo.

2) Create the following symbolic links in $ORACLE_HOME/lib

oracle@barbara:~> ln -sf /opt/SAP/SAPJCo/librfccm.so $ORACLE_HOME/lib/librfccm.so
oracle@barbara:~> ln -sf /opt/SAP/SAPJCo/libsapjcorfc.so $ORACLE_HOME/lib/libsapjcorfc.so
3) Create an additional OC4J instance to host SAP enabled Java apps.
oracle@barbara:~> createinstance -instanceName OC4J_SAP
Creating OC4J instance "OC4J_SAP"...
Set OC4J administrator's password for "OC4J_SAP" (password text will not be displayed as it is entered)
Enter password:
Confirm password:
The password for OC4J administrator "oc4jadmin" has been set.
New OC4J instance "OC4J_SAP" has been created.
oracle@lachesis:~>

4) Navigate to the instance home page. Start the new instance and then click on the administration tab and select the Shared libraries.

5) Click on the Create button at the bottom of the page.

5.1) On the Create shared library attributes page enter SAPJCo for the library name and the corresponding SAPJCo version (eg 2.1.6) for the version. Click next

5.2) The following page is entitled “Create Shared Library: Add Archives”. Click on the Add button and insert the /opt/SAP/SAPJCo/sapjco.jar file. Click next

5.3) The final step is the page entitled “Create Shared Library: Import Shared Libraries”. You do not need any adjustments here. Just click finish.

... and that does it.

Monday, 26 February 2007

Automatic configuration of SQL Plus on start-up

This is something I picked up from Oracle PL/SQL Programming by Steven Fewerstein and Bill Prybil.

When you start sqlplus the program reads configuration data from two files:
  • $ORACLE_HOME/sqlplus/admin/glogin.sql
  • ./login.sql
Since starting sqlplus from a directory that always contains an appropriate login.sql file isn't always possible, Bill recommends editing the glogin.sql. This is what the last lines my glogin sql look like :
-- Additional Settings by Bill Prybil
SET LINESIZE 132
SET PAGESIZE 999

-- Change the editor to vi if you don't do that sqlplus will use the editor from the $EDITOR
-- environment variable 
DEFINE _EDITOR = /usr/bin/vim

-- Format columns commonly retrieved from data dictionary
COLUMN segment_name FORMAT A30 WORD_WRAPP
COLUMN object_name FORMAT A30 WORD_WRAPP

-- set the sql prompt
SET SQLPROMPT "_USER'@'_CONNECT_IDENTIFIER >"

Selecting af:tableSelectOne by clicking anywhere in the table row

Just picked it up from the Oracle Java Developer Newsletter. It's sure worth it. By the way I just added Veniamin Goldin's Blog to my Oracle Links. He offers lots of goodies and unlike many others his tips tricks and examples are ready to be used

Friday, 16 February 2007

ABAP Transalation of text elements created when implementing user-exits

When you create text elements during implementation of a SAP user exit then — for reasons beyond my understanding — these texts are not directly translatable. So when you try to user the goto translation menu SAP pops up the dialog that allows you to choose the "from" and "to" languages but when you press ok, then you get an error message of the form "Please use transaction SE63.

Following is the exact list of actions that should be followed (Thanks Marilena)

  1. Open the Function Module containing the user-exit using either SE80 or SE37.
  2. From the program main menu use Goto → Text Elements → Text Symbols
  3. Copy the program name that is displayed on the top of the screen just above the texts table
  4. Goto transaction SE63.
  5. From the program main menu click Translation → Short Texts → ABAP → Program Texts
  6. Paste into the field marked Program name the text you copied from step 3.
  7. Select source and target languages
  8. Press the big button labeled Edit

Thursday, 15 February 2007

Linux: Format and examples of the crontab command

Whatever there is to find out about crontab is right there in the man pages. Paul Vixie explains everything crystal clear. Here are the main points to remember.

The cron(8) daemon examines cron entries once every minute.

Display of the user's crontab file is performed by crontab -l while editing is done with the -e switch. (Make sure that the EDITOR environment variable is set to your favorite editor program)

cronatb entries are date time fields followed by the command to be executed at that time. The time and date fields are:

field allowed values
minute 0-59
hour 0-23
day of month 1-31
month 1-12 (or names, see below)
day of week 0-7 (0 or 7 is Sun, or use names)

A field may be an asterisk (*), which always stands for ``first-last''.

Ranges of numbers are allowed. Ranges are two numbers separated with a hyphen. The specified range is inclusive. For example, 8-11 for an ``hours'' entry specifies execution at hours 8, 9, 10 and 11.

Lists are allowed. A list is a set of numbers (or ranges) separated by commas. Examples: ``1,2,5,9'', ``0-4,8-12''.

Step values can be used in conjunction with ranges. Following a range with ``/'' specifies skips of the number's value through the range. For example, ``0-23/2'' can be used in the hours field to specify command execution every other hour (the alternative in the V7 standard is ``0,2,4,6,8,10,12,14,16,18,20,22''). Steps are also permitted after an asterisk, so if you want to say ``every two hours'', just use ``*/2''.

Names can also be used for the ``month'' and ``day of week'' fields. Use the first three letters of the particular day or month (case doesn't matter). Ranges or lists of names are not allowed.


EXAMPLE CRON FILE

# use /bin/sh to run commands, no matter what /etc/passwd says
SHELL=/bin/sh
# mail any output to `paul', no matter whose crontab this is
MAILTO=paul
#
# run five minutes after midnight, every day
5 0 * * *       $HOME/bin/daily.job >> $HOME/tmp/out 2>&1
# run at 2:15pm on the first of every month -- output mailed to paul
15 14 1 * *     $HOME/bin/monthly
# run at 10 pm on weekdays, annoy Joe
0 22 * * 1-5   mail -s "It's 10pm" joe%Joe,%%Where are your kids?%
23 0-23/2 * * * echo "run 23 minutes after midn, 2am, 4am ..., everyday"
5 4 * * sun     echo "run at 5 after 4 every sunday"

Finally here is my DB Server crontab which backs up the entire database every day at 6:00pm and backups up the archive logs at past 35 every two hours.


oracle@poulcheria:~> crontab -l
# DO NOT EDIT THIS FILE - edit the master and reinstall.
# (/tmp/crontab.21301 installed on Fri Feb  2 09:45:47 2007)
# (Cron version -- $Id: crontab.c,v 2.13 1994/01/17 03:20:37 vixie Exp $)
0 18 * * * /home/oracle/backup_jobs/perform_backup
35 */2 * * * /home/oracle/backup_jobs/perform_archlog_backup

PHP Redirecting to a relative URL

This comes directly from the PHP Manual, but I thought I might keep it here as a reference.

Note: HTTP/1.1 requires an absolute URI as argument to » Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself:
<?php

/* 
 * Redirect to a different page in the current directory that was requested 
 */
$host  = $_SERVER['HTTP_HOST'];
$uri  = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';  // change accordingly

header("Location: http://$host$uri/$extra");
exit;

PHP Destroying the current session completely

Here is a code snipper I got out from Janet Valade's PHP & MySQL Visual Blueprint book and this is what I use it to implement logout pages
session_start();
$_SESSION = array();
if (isset($_COOKIE['PHPSESSID']))
    setcookie('PHPSESSID', '', time() - 42000, '/');
session_destroy();

$return_url = 'login.php';
header("Location: http://".$_SERVER['HTTP_HOST']
                      .dirname($_SERVER['PHP_SELF'])
                      ."/".$return_url);
exit;

Saturday, 10 February 2007

Linux: Changing file and dirctory permisions for an entire directory tree

Suppose you have a directory named /mydir and you need to change the permissions on all the files for the entire directory tree. Using a command like chmod -R 644 * might get you into trouble since this may change execute (i.e. traversal) access even for existing directories.

A friend from Germany (thanks Antoni) gave me the fhis solution :

First the files

find /mydir -type f -exec chmod 0644 {} \;

... and then the directories

find /mydir -type d -exec chmod 0755 {} \;

Note: The previous commands reset the file permissions completely. If you want to just add read access, while preserving the rest, you might prefer a u+r or g+r command line to chmod as in the following example which adds read and execute access to /mydir and all it's subdirectories.

find /mydir -type d -exec chmod u+rx {} \;

By the way, since I have lately found to need this more and more - as I move data to and from USB sticks -- I created a simple script that given a directory gives all files permissions 0644 and all directories 0755

#!/bin/bash
# File resetPerms.sh

if [ -d $1 ]
then
  echo Reseting file and directory access on $1
  find $1 -type f -exec chmod 0644 {} \;
  find $1 -type d -exec chmod 0755 {} \;
fi