Analytics


Google

Wednesday, February 25, 2009

List for Unix Commands (Solaris and AIX)

There is a page which provides a nice guide on Solaris here. Here is a sample info:

df -n (or fstyp device) show type of file system (ufs/vxfs)
fuser and pfiles open files
prtconf -V OBP level
pgrep, pkill, prstat -a process info and manipulation
logins -p|-d local users without passwords | duplicate uids
mpstat, prtdiag, psrinfo -v processor information and more
traceroute since Solaris 7
troff -man man.1 | dpost | lp print old style man pages
sgml2roff lpfilter.1m | troff -man | dpost | lp print sgml (new) man pages
fstyp -v list superblock including minfree %
tput nice screen output
what, ldd, strings information about binaries
ctrl-V in vi insert control character
ftp> get README | more
ufsdump 0f - /filesystem | (cd /mnt; ufsrestore rf -); rm /mnt/restoresymtable dump restore pipe
echo \007 get bell to ring
comm common (non-common) lines from two files
pkgchk -lp /usr/bin/ls which package does ls belong to?
df -oi -F ufs free inodes
icheck -b blockno filesystem block to file mapping
dircmp, rsync, filesync compare directories, sync utilities
nohup /var/tmp/myscript.ksh > /var/tmp/myscript.out & for things which have to complete (no risk of terminal being logged out)
netstat -pn arp like output when name services are down
pwdx, pldd, ptree and more in /usr/proc/bin
uname -X basic system information - one item on each line (useful for scripts)
read read a line
listusers another way of listing users
tcopy copy tape
nfsstat -m (or check /etc/rmtab) current nfs mount
clear_locks clear nfs locks
df -h, du -h, ls -lh since Solaris 9 - output in powers of 1024

There is also another site which allows you to search various commands within different operating system. Unfortunately, you need to know the key word to search.

Here is another reference useful for Solaris.

This one is not as good but have some information I did not see above.

Here is a quick Reference for AIX.

A similar list for AIX so there might some overlap here.

Alternatively, you can refer to the AIX 4.3 reference book here.

Another good source for AIX information is from IBM's own System Magazine.

Finally, here is a chart of the various commands in different Unix platforms:

Saturday, February 14, 2009

Getting your virtual path

Sometimes we need to obtain the virtual path to our page to pass into 3rd party applications. This can easily be done in asp.net by using

Request.ApplicationPath

However, if you are using asp classic, you will need some additional more coding. This is one way of doing it:

dim vUrl, arrStr, vStr
dim loopCnt
vUrl = Request.ServerVariables("PATH_INFO")
arrStr = Split(vUrl, "/")
vStr = "/"

for loopCnt = 0 to UBound(arrStr) - 1
if Len(vStr) > 1 then
vStr = vStr & "/"
End If
vStr = vStr & arrStr(loopCnt)
Next

Monday, January 19, 2009

Top 25 Programming Errors

I found the following article in my mail and thought it was important to be aware of this as a programmer.

Original Article

Article that referred me to that article

Thursday, January 15, 2009

Free DVD Burner software

I am currently working on a HP Compaq notebook which comes with a DVD drive and is running on Windows XP. However, the software that comes with the computer does not seem to work.

I know Windows XP itself is able to burn data to disk however, when I tried to do that apparently it only knows how to burn on CD only and not DVD. Which got me searching - since I wanted to stay legal but did not want to pay any money.

I came across the following article which refers to some very nice DVD burning freeware together with a review. Basically it recommended two software after reviewing a few:
  • infrarecorder from sourceforge which was pretty need because it has a distribution where you just unzip and use - no installation required.
  • imgburn which has some very nice reviews on a few other sites I visited.

Saturday, January 10, 2009

ASP and ASP.Net can't find Oracle

This is from Microsoft Q225084, link also to the following post. Copied here to simplify my reference and not meant to plagiarize. No offense intended.


This article outlines some of the common steps to take when you troubleshoot a problem with a connection to an Oracle Database from an Active Server Pages (ASP) application. Some of the more common error messages are:


Microsoft OLE DB Provider for ODBC Drivers error '80004005' [Oracle][ODBC][Ora]ORA-12154: TNS:Could not resolve service name /vdir/filename.asp, line xxx.


-and-


The Oracle(tm) client and networking components were not found. These components are supplied by Oracle Corporation and are part of the Oracle Version 7.3 (or greater) client software installation.

You will be unable to use this driver until these components have been installed.

=============================


The following is a list of general steps to take when you investigate a connectivity problem between ASP and an Oracle database.
  • First verify that you can connect to Oracle and retrieve data using Oracle's SQL Plus utility (a command line-based query utility). If you cannot connect from this tool, then you either have a bad installation or configuration of the Oracle client components or you did not correctly use the SQL Net Easy Config or Oracle Net8 Easy Config utility to create an alias for the Oracle server. You must work with your Oracle database administrator to make sure that the necessary Oracle components have been installed and are configured correctly.
  • If the Oracle client was recently installed on the Internet Information Server (IIS) computer, make sure that the computer has been rebooted at least once. In some cases after installation, the Oracle component SQL Plus works fine, but connectivity from IIS does not work until you reboot the computer.
  • Look for multiple copies of the OCIW32.dll file on the IIS server. There should only be one copy of this .dll file on the computer, and it should be in the \Bin subfolder of the Oracle home folder. If you find other copies, rename these with a .bak extension and then retest connectivity. You may want to restart the IIS services after renaming any additional copies of the .dll file that you found.
  • Make sure that you are running the recommended versions of the Oracle components.
  • For more information on how to obtain and install these patches, work with your database administrator or contact Oracle Technical Support. (Microsoft Technical Support does not support the configuration of these Oracle components.
  • Check to make sure that the Oracle client components are installed locally on the IIS server. While it is possible to get other applications to work without the Oracle components installed locally, this causes problems when you work with ASP applications. Microsoft recommends that these components be installed on the IIS server; other custom configurations are not supported.
  • Look at the system environment variables on the IIS computer and check the PATH variable. If there are any remote share names or mapped drives that point to locations that contain Oracle components, remove them. You must reboot the computer in order for any changes that you make to take effect.
  • Look again at the system environment variables on the IIS computer and check the PATH variable. Make sure that the \Bin folder in the Oracle home directory is included as part of the PATH environment variable. With a default installation, this is the Orant\Bin folder. Again, you must reboot the computer for the changes that you make to take effect.
  • Try to connect with both the Microsoft ODBC for Oracle driver and the Microsoft OLEDB Provider for Oracle. Here are sample connection string syntax for each of these:
'Microsoft OLEDB Provider for Oracle
"Provider=MSDAORA.1;Data Source=Your_TNSNames_Alias;User ID=User;Password=Password"

'Microsoft ODBC for Oracle DSN-Less
"Provider=MSDASQL;DRIVER={Microsoft ODBC for ORACLE};UID=User;PWD=Password;Server=Your_TNSNames_Alias"

'Microsoft ODBC for Oracle using a DSN
"DSN=Your_DSN_Name;UID=User;PWD=Password"

  • Disable SQL*Net Authentication. To do this, edit the SQLNET.ora file. This configuration file is usually stored in the Network\Admin subfolder of the Oracle home folder. Add the following lines to this file:
SQLNET.AUTHENTICATION_SERVICES = (none)
SQLNET.AUTHENTICATION = (none)

Restart the IIS service after you make these changes.
  • Add the IUSR_machine name account and the IWAM_machine name account to the Oracle home folder. Give both accounts full control.

To do this, right-click on the Oracle home folder in Windows Explorer. Click Properties, and then click the Security tab. Add the appropriate accounts and then give them full control. Restart your computer.
The third-party products that are discussed in this article are manufactured by companies that are independent of Microsoft. Microsoft makes no warranty, implied or otherwise, regarding the performance or reliability of these products.

Microsoft provides third-party contact information to help you find technical support. This contact information may change without notice. Microsoft does not guarantee the accuracy of this third-party contact information.

Tuesday, January 6, 2009

Captcha

Captcha are images that are used to deter automated registration and is a way to check to see if it is a person or a program submitting the comment/registration.

It is not really necessary to perform the programming yourself since there are a lot of free tools/components that you can use.

Some of my favorites are:
  1. CodeProject
  2. Free Captcha - but not sure how it will impact the performance since it needs to talk to the provider.
One thing to be aware is how the captcha images appear. The following website shows some of those to avoid.

Other things to be aware of captcha are:
  1. There are now more sophisticated tools to defeat the captchas.
  2. More and more users are getting upset and turn off by captchas so it may cause you to lose your main customers.

Thursday, December 25, 2008

Shell Scripting on Unix

Ideally to learn how to do scripting, we need to have a unix environment to try out the scripts and this can be easily done by setting up Linux or Open Solaris on your computer. However, what happens if you don't have a spare computer to do that?

You could use a live CD. Problem with that is you need to reconfigure it each time which is troublesome. Alternatively, you can setup Cygwin. There are two version - Cygwin which is purely command prompt and Cygwin/X which provides a X Windows environment.

Given that you can then use the various tutorials on Internet to learn scripts like bash:

Linux Config org
Bash Programming How To
Advanced Bash Tutorial

Alternatively, you can use perl, php or even java to automate your unix scripts.

Monday, December 22, 2008

Free Charting Libraries

When writing program, we have an option to either write everything ourselves or to use/leverage on utilities/libraries that are already written. This is especially true when it comes to charting.

When using asp classic, you can use the mschart control that comes with MS Office. However, that requires that you install MS Office on your webserver. Also, I found the library quite difficult to work with.

The following are some popular opensource/freeware libraries you can use:

For Java, you can use jfreechart.
For .Net, you can use zedgraph. I saw a good article on this on this web page, which is in fact how I found this library.

Alternatively, you can use paid software, our previous software was chartfx and then we started working on Netchart.

Netchart is good in that it can be used for different platforms because it uses webservices and provides libraries for java, asp etc. Only thing it is requires a server to serve the webservices.

Some additional libraries that I found are:

Open Flash Chart
Fusion Chart Free A good sample code on how to use Fusion Chart Free using .net is found here.
Some additional java script charting components are found here.

Friday, December 19, 2008

Can't find table in stored function, procedure or package in Oracle

This is a strange problem:

We have rights to select a table and can select in normal sql statement. However, when we write a stored procedure or function (with or without a package), we encounter an error that says table not found.

The one solution we found was to grant that account select any table rights. Once granted, we can compile and use the stored procedure/package. However, the problem with doing that is the account can also select any table in any schema in that instance.

I found the following solution thanks to a support from the community forum:

Note:388774.1


Applies to:
Oracle Server - Enterprise Edition - Version: 9.2.0.1 to 10.2.0.3
This problem can occur on any platform.
Symptoms
When SYSTEM user grants select on a table to another user with SQL*Plus , it works fine: SYSTEM user has the GRANT ANY OBJECT PRIVILEGE system privilege .

SQL> CONNECT system/xxx
Connected.
SQL> grant SELECT, INSERT, UPDATE, DELETE on SCOTT.TEST TO X;
Grant succeeded.
1. Under 10g, when this statement is in a stored procedure, it returns "ORA-1031 - insufficient privilege".
2. Under 9i, it returns "ORA-00942: table or view does not exist "

SQL> CREATE OR REPLACE PROCEDURE system.def_grant_test
IS
cursor_handle INTEGER;
BEGIN
cursor_handle := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cursor_handle, 'GRANT SELECT, INSERT, UPDATE, DELETE on SCOTT.TEST TO X', dbms_sql.native );
DBMS_SQL.CLOSE_CURSOR(cursor_handle);
END;
/


Procedure created.
SQL 9i> exec system.def_grant_test
BEGIN system.def_grant_test; END;
*
ERROR at line 1:
ORA-00942: table or view does not exist
ORA-06512: at "SYS.DBMS_SYS_SQL", line 826
ORA-06512: at "SYS.DBMS_SQL", line 39
ORA-06512: at "SYSTEM.DEF_GRANT_TEST", line 6
ORA-06512: at line 1
SQL 10g> exec system.def_grant_test
BEGIN system.def_grant_test; END;

*
ERROR at line 1:
ORA-01031: insufficient privileges
ORA-06512: at "SYS.DBMS_SYS_SQL", line 906
ORA-06512: at "SYS.DBMS_SQL", line 39
ORA-06512: at "SYSTEM.DEF_GRANT_TEST", line 6
ORA-06512: at line 1
Cause
Generally an invokers's called procedure executes using the caller's privileges and all unqualified objects are resolved in the schema of the caller.
The privileges of the invoker are checked during runtime only for
DML statements ('insert', 'update','delete', 'update')
dynamic sql statements ('execute immediate' and 'open for using')
cursor statements ('open' and 'open for update')
DDL statements ('lock table')
parsed SQL statements using dbms_sql.parse
Solution
To implement the solution, please execute the following steps:

1. Create the procedure defined as an invoker's right procedure , with AUTHID CURRENT_USER clause:

SQL> CREATE OR REPLACE PROCEDURE system.inv_grant_test authid current_user
IS
cursor_handle INTEGER;
BEGIN
cursor_handle := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cursor_handle, 'GRANT SELECT, INSERT, UPDATE, DELETE on SCOTT.TEST TO X', dbms_sql.native );
DBMS_SQL.CLOSE_CURSOR(cursor_handle);
END;
/


Procedure created.
SQL> exec system.inv_grant_test
PL/SQL procedure successfully completed.
SQL> select * from dba_tab_privs where table_name='TEST' and grantee='X';

GRANTEE OWNER TABLE_NAME GRANTOR PRIVILEGE GRA HIE

-------- -------- ---------- -------- ---------- --- ---
X SCOTT TEST SCOTT INSERT NO NO
X SCOTT TEST SCOTT DELETE NO NO
X SCOTT TEST SCOTT SELECT NO NO
X SCOTT TEST SCOTT UPDATE NO NO

Wednesday, December 17, 2008

Java Enterprise Edition (JEE) servers

Two of the most renown JEE servers are JBoss (now under RedHat) and GlassFish (from Sun).

However, if your company is primarily using Weblogic at the corp level and you want to have a development environment, you can download it here, it comes with a free developer license (which allows up to 5 ip addresses) to perform your test and development.

Maybe it is due to my lack of knowledge of the server. I was unable to successfully create my own project using the easy start. The project was created using the wizard but failed to start. Also, I noted that the weblogic server (10.3 still uses Java 1.4 instead of Java 1.5 or Java 1.6) as used by the JBoss and Glassfish. Also, there was no easy way to start the server by itself.

I tried JBoss, starting and stopping is very simple. I have yet to try out Glassfish.

JBoss 4.2.x is JEE 5 able but not certified. JBoss 5.0 is JEE 5 certified. Glassfish and Weblogic also support JEE 5. All three servers are supported by NetBeans.

Tuesday, December 16, 2008

m.www.yahoo.com

I recently received a complaint from a colleague that she is not able to get to the yahoo website:

http://www.yahoo.com

instead she was redirected to the following website:

http://m.www.yahoo.com

The first reaction from our helpdesk was that there could be a possible spyware on her computer. Mostly because others who type the following address were redirected to the following page:

http://www.yahoo.com/?nm=1

A quick search in Google quickly revealed that she was directed to a new interface which yahoo is testing. The frustrating part is the users are picked at random and are not given a choice to revert back.

The fix is to clear the cookie and the cache in her browser. Also her feedback was that she did not really like the new interface, she preferred the old one because:
  1. To her it was prettier with the pictures that changes according to season. Like right now there is the Christmas greeting.
  2. Everything is with one click.
I read comments from other sites and a lot of them did not like it either, even though Yahoo was trying to emulate Google's cleaner interface. I guess that is a lesson to be learned. One your user base is used to an interface, you should not just change it; otherwise you risk angering your loyal customers!!!

Sunday, December 14, 2008

Compiling .Net programs with Nant

Nant is the .Net Version of Ant. It is capable of doing a lot of things as indicaed in the task reference here. However, for the purpose of this article, I am going to focus how to use it to either compile an .net assembly either to .exe or .dll.

In my previous article, I provided an example how we can write a program without using Visual Studio. Assuming you have written your program, you could use the command line vbc (for Visual Basic compiler) and csc (C# compiler) to compile. However, it is tedious if the program references a lot of libraries or there are multiple source file.

To compile using Nant, first step is to download NANT. The home page is found here. Download and unzip the zip file. Assuming you downloaded Nant 8.5, you can unzip everything to c:\nant-0.85. When unzipping, just say use the folder in the zip file then unzip it to c:\. It will automatically create a folder tree c:\nant-0.85\...

Next, create a build file:

Here is an example for compiling .exe:

<?xml version="1.0"?>
<project name="FileLimAlert" default="build" basedir=".">
<property name="debug" value="true" unless="${property::exists('debug')}" />
<property name="verbose" value="true" />
<target name="clean" description="remove all generated files">
<delete file="FileLimAlert.exe" failonerror="false" />
<delete file="FileLimAlert.pdb" failonerror="false" />
</target>
<target name="build" description="compiles the source code">
<vbc target="exe" output="FileLimAlert.exe" debug="${debug}">
<sources>
<include name="FileLimAlert.vb" />
</sources>
<references>
<include name="System.dll" />
<include name="System.Web.dll" />
<include name="System.Web.Services.dll" />
<include name="System.XML.dll" />
</references>
</vbc>
</target>
</project>


Here is a sample to compile code behind (into .dll) - assuming this is called newLdaplogin.build.xml:

<?xml version="1.0"?>
<project name="newLDAPLogin" default="build" basedir=".">
<property name="debug" value="true" unless="${property::exists('debug')}" />
<property name="verbose" value="true" />
<target name="clean" description="remove all generated files">
<delete file="bin\newLDAPLogin.dll" failonerror="false" />
<delete file="bin\newLDAPLogin.pdb" failonerror="false" />
</target>
<target name="build" description="compiles the source code">
<vbc target="library" output="bin\newLDAPLogin.dll" debug="${debug}">
<sources>
<include name="newLDAPLogin.aspx.vb" />
</sources>
<references>
<include name="System.dll" />
<include name="System.Web.dll" />
<include name="System.Data.dll" />
</references>
</vbc>
</target>
</project>


Note
  1. The target build will instruct nant what to do. In the above example to use VBC to compile either.
  2. In the first example above, the vbc target is to exe and the second one is to library.
  3. The references section within the target are for the libraries your program is referencing.
  4. The sources section within the target are for all the source code.
  5. As shown above, each section can include multiple includes, so you could have multiple source code compiling into either an exe or a dll.
  6. Clean basically instruct nant what are the files to delete.
To compile, just type (if you are building for Framework 1.1):

c:\nant-0.85\bin\nant -buildfile:newLdaplogin.build.xml -t:net-1.1

The output will look something like this:

NAnt 0.85 (Build 0.85.2478.0; release; 10/14/2006)
Copyright (C) 2001-2006 Gerry Shaw
http://nant.sourceforge.net

Buildfile: file:///C:/project/vbUtils/clsldap.build.xml
Target framework: Microsoft .NET Framework 1.1
Target(s) specified: build


build:

[vbc] Compiling 1 files to 'C:\project\vbUtils\bin\
newLDAPLogin'.

BUILD SUCCEEDED

Total time: 3.7 seconds.


If you want to build for framework 2.0 then change -t:net-1.1 to -t:net-2.0.

The build will detect is a recompilation is necessary and will not compile if the assembly is already up to date. Each version of nant will have a list of framework that is supported.

The latest version 0.86-Beta 1 supports the following framework:

FrameworkTargetRuntime
.NET Framework 1.0**
.NET Framework 1.1**
.NET Framework 2.0**
.NET Framework 3.5**
.NET Compact Framework 1.0*
.NET Compact Framework 2.0*
Mono 1.0 Profile**
Mono 2.0 Profile**
Mono 3.5 Profile**
Moonlight 2.0*
Shared Source CLI 1.0*
Silverlight 2.0*

You can check the version supported by looking into the nant.exe.config file.

Friday, December 5, 2008

Removing standby or logout from Windows XP shutdown menu

Obtained the following from here - Have not verified:


HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ACPI\Parameters
Click in the right pane and create a new REG_DWORD value.
Give it the name Attributes
Set the value to 00000070

After reboot, Standby is unavailable.

********************************

to remove logoff :-

Start the Registry Editor (go to Start, Run and type Regedt32). Find the key

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer]
create a new dword called NoLogOff and give it a value of 1

the above can be done on the hklu part of the registry if it is just for a particular user.

Monday, December 1, 2008

Oracle Hints

Every so often, when you have an application which is working fine and suddenly the applications slows down for no apparent reason. I have seen this on many occasions and found that majority of the time is somehow Oracle decided the fastest way to perform my sql query is to do a full table scan on some huge tables because the database has many extends.

In those situations, I use hints to "advice" Oracle to use the index for example:

select /*+ index(e iempmaster) */ empno, title, extension from empmaster e where empno = 'XXX123';

Note the the hints starts with /*+, it needs a space immediately after that prior to the hint. Index is not the only options there are many other hints such as hash etc. You can find reference to the rest in the following sites:

http://www.psoug.org/reference/hints.html
http://www.dba-oracle.com/t_sql_hints_tuning.htm

To test if your hint is working or not, perform an explain plan without the hint and run the explain plan with the hint. You should see the difference. You can perform explain plan from the sqlplus (dos prompt) or use SQL Developer, there is a button for execute Explain plan. However, to do that you need to have a table called plan_table with the following structure:

Column Name Data type
STATEMENT_ID VARCHAR2(30 BYTE)
TIMESTAMP DATE
REMARKS VARCHAR2(80 BYTE)
OPERATION VARCHAR2(30 BYTE)
OPTIONS VARCHAR2(30 BYTE)
OBJECT_NODE VARCHAR2(128 BYTE)
OBJECT_OWNER VARCHAR2(30 BYTE)
OBJECT_NAME VARCHAR2(30 BYTE)
OBJECT_INSTANCE NUMBER
OBJECT_TYPE VARCHAR2(30 BYTE)
OPTIMIZER VARCHAR2(255 BYTE)
SEARCH_COLUMNS NUMBER
ID NUMBER
PARENT_ID NUMBER
POSITION NUMBER
COST NUMBER
CARDINALITY NUMBER
BYTES NUMBER
OTHER_TAG VARCHAR2(255 BYTE)
PARTITION_START VARCHAR2(255 BYTE)
PARTITION_STOP VARCHAR2(255 BYTE)
PARTITION_ID NUMBER
OTHER LONG
DISTRIBUTION VARCHAR2(30 BYTE)

Monday, November 24, 2008

Accessing LDAP using Java

The easiest way to access LDAP in Java is to use JNDI (Java Naming and Directory Interface).

A good example on how to do that can be obtained from Sun website. Snippet is as follows:


In the LDAP, authentication information is supplied in the "bind" operation. In LDAP v2, a client initiates a connection with the LDAP server by sending the server a "bind" operation that contains the authentication information.

In the LDAP v3, this operation serves the same purpose, but it is optional. A client that sends an LDAP request without doing a "bind" is treated as an anonymous client (see the Anonymous Authentication section for details). In the LDAP v3, the "bind" operation may be sent at any time, possibly more than once, during the connection. A client can send a "bind" request in the middle of a connection to change its identity. If the request is successful, then all outstanding requests that use the old identity on the connection are discarded and the connection is associated with the new identity.

The authentication information supplied in the "bind" operation depends on the authentication mechanism that the client chooses. See the next section for a discussion of the authentication mechanism.

Authenticating to the LDAP by Using the JNDI
In the JNDI, authentication information is specified in environment properties. When you create an initial context by using the InitialDirContext(in the API reference documentation) class (or its superclass or subclass), you supply a set of environment properties, some of which might contain authentication information. You can use the following environment properties to specify the authentication information.

* Context.SECURITY_AUTHENTICATION(in the API reference documentation) ("java.naming.security.authentication").
Specifies the authentication mechanism to use. For the Sun LDAP service provider, this can be one of the following strings: "none", "simple", sasl_mech, where sasl_mech is a space-separated list of SASL mechanism names. See the next section for a description of these strings.
* Context.SECURITY_PRINCIPAL(in the API reference documentation) ("java.naming.security.principal").
Specifies the name of the user/program doing the authentication and depends on the value of the Context.SECURITY_AUTHENTICATION property. See the next few sections in this lesson for details and examples.
* Context.SECURITY_CREDENTIALS(in the API reference documentation) ("java.naming.security.credentials").
Specifies the credentials of the user/program doing the authentication and depends on the value of the Context.SECURITY_AUTHENTICATION property. See the next few sections in this lesson for details and examples.

When the initial context is created, the underlying LDAP service provider extracts the authentication information from these environment properties and uses the LDAP "bind" operation to pass them to the server.

The following example shows how, by using a simple clear-text password, a client authenticates to an LDAP server.

// Set up the environment for creating the initial context
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

// Authenticate as S. User and password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial");
env.put(Context.SECURITY_CREDENTIALS, "mysecret");

// Create the initial context
DirContext ctx = new InitialDirContext(env);

// ... do something useful with ctx

Using Different Authentication Information for a Context
If you want to use different authentication information for an existing context, then you can use Context.addToEnvironment()(in the API reference documentation) and Context.removeFromEnvironment()(in the API reference documentation) to update the environment properties that contain the authentication information. Subsequent invocations of methods on the context will use the new authentication information to communicate with the server.

The following example shows how the authentication information of a context is changed to "none" after the context has been created.

// Authenticate as S. User and the password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial");
env.put(Context.SECURITY_CREDENTIALS, "mysecret");

// Create the initial context
DirContext ctx = new InitialDirContext(env);

// ... do something useful with ctx

// Change to using no authentication
ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "none");

// ... do something useful with ctx

Authentication Failures
Authentication can fail for a number of reasons. For example, if you supply incorrect authentication information, such as an incorrect password or principal name, then an AuthenticationException(in the API reference documentation) is thrown.

Here's an example that is a variation of the previous example. This time, an incorrect password causes the authentication to fail.

// Authenticate as S. User and give an incorrect password
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial");
env.put(Context.SECURITY_CREDENTIALS, "notmysecret");

This produces the following output.

javax.naming.AuthenticationException: [LDAP: Invalid Credentials]
at java.lang.Throwable.(Compiled Code)
at java.lang.Exception.(Compiled Code)
...

Because different servers support different authentication mechanisms, you might request an authentication mechanism that the server does not support. In this case, an AuthenticationNotSupportedException(in the API reference documentation) will be thrown.

Here's an example that is a variation of the previous example. This time, an unsupported authentication mechanism ("custom") causes the authentication to fail.

// Authenticate as S. User and the password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "custom");
env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial");
env.put(Context.SECURITY_CREDENTIALS, "mysecret");

This produces the following output.

javax.naming.AuthenticationNotSupportedException: Unsupported value for java.naming.security.authentication property.
at java.lang.Throwable.(Compiled Code)
at java.lang.Exception.(Compiled Code)
at javax.naming.NamingException.(Compiled Code)
...

Wednesday, November 19, 2008

Understanding J2EE Programming

I have bought many books on J2ee programming and I found a lot of times the concept is very difficult to grasp - especially for a person who is from .Net programming background.

However, I found so far the best explanation to help understand the concept is from theserverside web site. The provide some complete books on the subject in PDF format for free download. One of them is Mastering EJB.

If you are interested in the subject, this is an excellent place to start. However, the book may be a little outdated but I believe most of the concepts on the stateful and stateless beans are still explained nicely in the book. There is also a more uptodate version of it (again free download of the complete pdf) - Mastering Enterprise JavaBean 3.

One of the problems I have with J2EE, is they keep adding other framework like Struts, JavaFaces, Hibernate etc. The above book does not cover those.

Saturday, November 15, 2008

Rich experience programming on the Web

I read a pretty good review on the launch of Java 1.6u10 release. In one of the comments, there is a reference to Interactive Pulp which provides samples of how to write very nice applets which rivals Flash - link is here.

Also, I see that Microsoft is coming with similar competition to Flash called SilverLight. The installation is only 4 Mbytes.

Monday, November 10, 2008

Too Many Open Cursors

Occasionally, you may find your program encountering "Too Many Open Cursor" when using Oracle.

You may be able to resolve this by:
  1. Closing any open resultset.
  2. Dispose any database adapter after use.
  3. Disposing your database command object after use (either oleDBCommand or OracleCommand) whether or not it is a prepared statement or not.

What sometimes happen is after you create a database command within your subroutine and then you perform a query a cursor is opened. We sometimes assume that when we exit the routine, the GC (garbage collector) will automatically close the open cursors and dispose of the objects that are no longer used. However, I found out that it does not always happen. In an environment where you perform a lot of query or update, the system may not know that it can reuse the existing open cursor and will open new cursors during each iteration or call and sooner or later will hit the limit.

This applies whether you are using .Net framework or Java.

I have found this has helped me avoid the "Too Many Open Cursors" issue in both environment.

Saturday, November 8, 2008

Compiling invalid Oracle Object

If you use a lot of packages, stored functions and procedures, they may sometimes become invalid if an object it depends on is changed. We have encountered in a few occasions, our application will hang as a result. To address this, we are using a script (shown below) and schedule it to run once an hour to recompile any invalid objects it encounters.

This is a script is obtained from another blog but was modified so that it will continue to compile the rest even if it encounters error (in case, there are procedures that are in the schema that is still being edited and will not compile correctly, so other invalid object (but compilable) will still get compiled ).
rem -----------------------------------------------------------------------
rem Filename:   cmpall2.sql
rem Purpose:    Compile all invalid database objects
rem             Run this script after each database upgrade or whenever
rem             required.
rem Notes:      If the dependencies between objects are complicated, you can
rem             end up re-compiling it many times, as recompiling some
rem             invalidates others. This script uses dyamic SQL, and
rem             recompile objects based on reverse dependency order.
rem Date:       24-Sep-1998
rem Author:     Fiona Lindsay <f_lindsay@hotmail.com>
rem -----------------------------------------------------------------------

set serveroutput on size 1000000

declare
   sql_statement varchar2(200);
   cursor_id     number;
   ret_val       number;
begin

   dbms_output.put_line(chr(0));
   dbms_output.put_line('Re-compilation of Invalid Objects');
   dbms_output.put_line('---------------------------------');
   dbms_output.put_line(chr(0));

   for invalid in (select object_type, object_name
                   from   user_objects o
                   where  o.status       = 'INVALID'
                     and  o.object_type in ('PACKAGE', 'PACKAGE BODY',
                                            'FUNCTION',
                                            'PROCEDURE', 'TRIGGER',
                                            'VIEW')
                   order  by o.object_type) loop

      begin
       if invalid.object_type = 'PACKAGE BODY' then
          sql_statement := 'alter package '||invalid.object_name||
                           ' compile body';
       else
          sql_statement := 'alter '||invalid.object_type||' '||
                           invalid.object_name||' compile';
       end if;
 
       /* now parse and execute the alter table statement */
       cursor_id := dbms_sql.open_cursor;
       dbms_sql.parse(cursor_id, sql_statement, dbms_sql.native);
       ret_val := dbms_sql.execute(cursor_id);
       dbms_sql.close_cursor(cursor_id);
 
       dbms_output.put_line(rpad(initcap(invalid.object_type)||' '||
                                invalid.object_name, 32)||' : compiled');
      EXCEPTION
          When others then
             dbms_output.put_line('Error in '|| invalid.object_name || ' - Continuing');
      end;
   end loop;

end;
/
EXIT

To use the above script, just copy into a text file and save it as comp_obj.sql. You can then use a batch file to run it as follows:

sqlplus scott/tiger@orcl @comp_obj >> comp_obj.log

Wednesday, November 5, 2008

Review Google Chrome Browser

I realize that there are many reviews of Chrome already but I am approaching this as a programmer blogger.

Things I like about Chrome:
  • It is fast.
  • In some cases where I get timeout with either IE or Firefox, the page still gets rendered in Chrome.
  • The incognito page is often handy when you want to do research and don't want to leave any trail on the PC of where you have been.
  • You can open a set of book marks in a new window (similar functionality available in firefox).
Things I don't like about Chrome:

  • When you perform compose in Blogger, it encloses the subsequent paragraph between <div> </div> tag. Both IE and Firefox does not add these extra tags.
  • It does not have an option to undo close tab which you may have accidentally closed (this is available in FireFox - haven't noticed it in IE7 - not sure if it is there or not).
  • If you want to have properly aligned table, you can enter your information into Excel and then paste in into the compose screen in Firefox and the data will align correctly. See examples below.
  • Assuming you have your photos in Flickr, you can switch to view source and search for <img src="http://farm When you do that in Firefox, it will highlight and select the text for you. In Chrome, the text is selected but not highlighted. (I do this because I upload my images to flickr and then display them in my blogs).
Pasting from Excel into Blogger compose screen:

This is how the excel looks like:


Using Firefox:

Date Mileage time
1-Jan-08 10 1 hr
2-Jan-08 5 0.5 hr



Using IE:

Date
Mileage
time
1-Jan-08
10
1 hr
2-Jan-08
5
0.5 hr

Using Chrome:


Date Mileage time 1-Jan-08 10 1 hr 2-Jan-08 5 0.5 hr