Practical Web Programming

Tuesday, December 30, 2008

PHP: How to Dynamically Alternate the Table Row Background Color

In PHP, making the <table> row background color alternate dynamically is relatively easy. The key here is PHP's modulo (%) operator. Using the % operator inside a loop construct, you can reference every other row in an HTML <table>. See the example below.

Create the CSS rules.
.alt-color-1{
background-color:red;
}

.alt-color-2{
background-color:green;
}


Create the PHP script.
<?php
print "<table width='200' border='1' cellspacing='1' cellpadding='1'>";
for ($i = 0; $i < 10; $i++)
{
if (($i % 2) == 0)
{
$alt = "alt-color-1";
}
else
{
$alt = "alt-color-2";
}

print "<tr class='".$alt."'>";
print "<td>".$i."</td>";
print "<td>".$i."</td>";
print "</tr>";
}
print "</table>";
?>


Put it all together.
<html>
<head>
<title>Alternate Color in Table Rows</title>

<style>
.alt-color-1{
background-color:red;
}
.alt-color-2{
background-color:green;
}
</style>

</head>
<body>

<?php
print "<table width='200' border='1' cellspacing='1' cellpadding='1'>";

for ($i = 0; $i < 10; $i++)
{
if (($i % 2) == 0) //USE THE MODULO OPERATOR
{
$alt = "alt-color-1";
}
else
{
$alt = "alt-color-2";
}

print "<tr class='".$alt."'>";
print "<td>".$i."</td>";
print "<td>".$i."</td>";
print "</tr>";
}
print "</table>";
?>

</body>
</html>


After executing the PHP script, here's what the webpage will look.

PHP: How to Dynamically Alternate the Table Row Background Color

Friday, December 26, 2008

PHP: How to Display The Current Month in Calendar Style

Displaying the current month in a calendar style is very handy and user-friendly for a website, specially for a blog. Using a calendar-style navigation your visitors can easily navigate through your previous posts and articles.

Fortunately, in PHP, this seemingly difficult task in HTML is relatively easy. Just by using a nested For Loop and PHP's Date functions, use can build your own calendar.

Here's the simple source code.

<?php
$now = getdate(time());
$time = mktime(0,0,0, $now['mon'], 1, $now['year']);
$date = getdate($time);
$dayTotal = cal_days_in_month(0, $date['mon'], $date['year']);

print '<table><tr><td colspan="7"><strong>' . $date['month'] . '</strong></td></tr>';
for ($i = 0; $i < 6; $i++)
{
print '<tr>';
for ($j = 1; $j <= 7; $j++)
{
$dayNum = $j + $i*7 - $date['wday'];
print '<td';
if ($dayNum > 0 && $dayNum <= $dayTotal)
{
print ($dayNum == $now['mday']) ? ' style="background: #aaa;">' : '>';
print $dayNum;
}
else
{
print '>';
}
print '</td>';
}
print '</tr>';
if ($dayNum >= $dayTotal && $i != 6)
{
break;
}
}
print '</table>';
?>

Here's how the calendar will look like.


To make it fancier, all you have to do now is use CSS to add colors and styles.

Sunday, December 21, 2008

My First Ubuntu Machine, and I'm Loving it

My first encounter with Ubuntu was more than a year ago. Back then I was using Windows XP both at work and at home. By then, I tried installing it as a secondary boot in my XP desktop at home but it just wouldn't load after the installation so I didn't force it.

More than two weeks ago, I finally completed my desktop. It took me more than a month to build because I have to wait the parts (LCD monitor, casing, keyboard, mouse and power supply) that I bought from Amazon. I can say that it's worth the wait because this is my first Ubuntu machine and I'm loving it. I got Ubuntu 8.10 installed in it.



Though I am Windows user ever since, it wasn't difficult for to adjust to this new operating system. Like Windows, Ubuntu comes with softwares that you can use for your daily tasks. My problem with this OS is my printer is not working on it. Fortunately, I got a Macbook to print with. Other than that, I'm head over heels with it.

With this first taste of Linux, I think I will not go back to Windows if given a choice.

Saturday, December 20, 2008

PHP: Checking If Email is Valid with filter_var Function

In PHP 4, checking if an email is valid uses regular expressions. But with PHP 5, you can use the filter_var function. This function returns the filtered data, or false if the filter fails.

Here's the syntax.

mixed filter_var ( mixed $variable [, int $filter [, mixed $options ]] )

Where:
variable = Value to filter.
filter = ID of a filter to use. Defaults to FILTER_SANITIZE_STRING.
options = Associative array of options or bitwise disjunction of flags.


Here's how to use the function.

if (filter_var(trim($email), FILTER_VALIDATE_EMAIL))
{
echo $email . " is valid.";
}
else
{
echo $email . " is invalid.";
}

Friday, December 05, 2008

PHP: A Simple Function to Create an HTML Select Date Options

Here's a simple PHP function to create a select date options that you can use in your HTML forms to let users select a date. This is simple and easy to use. Below is the function definition.

//RETURN DATE OPTIONS IN HTML
function get_date_options($year = 0000, $month = 00, $day = 00)
{
$ret_val = "";

//ASSEMBLE MONTHS
$options = "<option value='00'>MM</option>";
for ($i = 1; $i < 13; $i++)
{
$attribute = "value='".$i."'";
if ($i == $month)
{
$attribute .= " selected ";
}
$options .= "<option ".$attribute.">".str_pad($i,2,0,STR_PAD_LEFT)."</option>";
}
$ret_val .= "<select name='month'>".$options."</select> / ";

//ASSEMBLE DAYS
$options = "<option value='00'>DD</option>";
for ($i = 1; $i < 32; $i++)
{
$attribute = "value='".$i."'";
if ($i == $day)
{
$attribute .= " selected ";
}
$options .= "<option ".$attribute.">".str_pad($i,2,0,STR_PAD_LEFT)."</option>";
}
$ret_val .= "<select name='day'>".$options."</select> / ";

//ASSEMBLE YEARS
$options = "<option value='0000'>YYYY</option>";
for ($i = 2008; $i < 2051; $i++)
{
$attribute = "value='".$i."'";
if ($i == $year)
{
$attribute .= " selected ";
}
$options .= "<option ".$attribute.">".$i."</option>";
}
$ret_val .= "<select name='year'>".$options."</select>";

return $ret_val;
}


Here's a simple way to use it.

Enter your birthday : <?php print get_date_options() ?>


And here's a way to use it to make default to a date.

Enter your birthday : <?php print get_date_options("2008", "12", "05") ?>

Tuesday, December 02, 2008

PHP: Simple String to Date / Date to String Conversion Functions

In PHP even a simple INSERT and UPDATE to the database, MySQL specially, can lead to bugs in DATETIME fields. Whenever I do database insertion, I run into this kind of problem. Instead of the actual date, the string "0000-00-00 00:00:00" appears. This string represents NULL in date.

To combat this problem, I created simple String to Date / Date to String conversion functions. Before inserting/updating date to a MySQL database, convert first the date using text_to_date_format. Then, when querying, use the date_to_text_format to make the date more human readable.


//FORMAT DATE TO STRING
function date_to_string_format($date)
{
if (strtotime($date))
{
return date("M. d, Y h:i A", strtotime($date));
}
else
{
return "";
}
}

//FORMAT STRING TO DATE
function string_to_date_format($date)
{
if (strtotime($date))
{
return date("Y-m-d H:i:s", strtotime($date));
}
else
{
return "0000-00-00 00:00:00";
}
}


Here's what your INSERT SQL statement should look like using the above function.


$sql = "INSERT INTO my_table (
my_id,
my_date
) VALUES (
1, ".
string_to_date_format($var_date).")";

Wednesday, November 12, 2008

How to Make a Cyber-Child

A little boy goes to his father and asks 'Daddy, how was I born?'

The father answers, 'Well, son, I guess one day you will need to find out anyway! Your Mom and I first got together in a chat room on Yahoo. Then I set up a date via e-mail with your Mom and we met at a cyber-cafe. We sneaked into a secluded room, where your mother agreed to a download from my hard drive. As soon as I was ready to upload, we discovered that neither one of us had used a firewall, and since it was too late to hit the delete button, nine months later a little Pop-Up appeared that said:

'You got Male!'

Friday, November 07, 2008

Lessons from the PHP Mail Function

Oh man, I got screwed.

Yesterday, I was testing the mail function that I wrote for the Helpdesk web application that I did. I was so sure the function works because I always receive email every time I submit a test ticket entry.

I wrote the function to send an email only to me when it is the development server and send to everybody else in our team when it's in the production. The human (or idiot :)) that I am, I miss to change the $to parameter of the mail function. So instead of only me receiving the email, our entire team for the whole US southern division received more than ten test emails. I only discovered the bug when my fellow developer called my attention that he keeps receiving a test email. Fortunately, those email all contains the title 'Test'.

Lesson learned? First, always test your application like you are in the production server. Had I not put 'Test' as the title, it would have been mistaken for a legit email. Second, don't think you already changed your source code somewhere, double check it, if not triple. Oftentimes, you are so sure you have it right, only to found out it's not.

Thursday, November 06, 2008

PHP: How to Print/Echo HTML Tags More Effeciently

PHP is very good at handling strings. But sometimes you have to help PHP do it's job more efficiently. In my recent web development job, I noticed that I always use PHP to print HTML tags. Here's an example of how I would do it before.


<?php
echo "<table>";
echo "<tr>";
echo "<td>"."How to print/echo HTML tags in PHP."."</td>";
echo "</tr>";
echo "</table>";
?>


Now, here's how I do it now which I think is more efficient and HTML readable.

<?php
echo "
<table
<tr>
<td>"."How to Print/Echo HTML tags in PHP More Effeciently"."</td>
</tr>
</table>
";
?>


Notice the difference? In the first PHP sourcecode, I use the echo five times, while in the second one, I use only once.

Using echo to print HTML tags is not expensive in terms of server resources, but if you're using it the way I did in the first example for all your pages and and you have thousands of users to your website, you'll see the difference.

Sunday, October 26, 2008

The Man Rules

Got this from a chain email, and I thought instead of passing this, I might as well post this in my blog. So here it is - The Man Rules.

These are our rules! Please note.. these are all numbered "1" ON PURPOSE!

1. Men are NOT mind readers.

1. Ask for what you want.
Let us be clear on this one:
Subtle hints do not work!
Strong hints do not work!
Obvious hints do not work!
Just say it!

1. Yes and No are perfectly acceptable answers to almost every question.

1. Come to us with a problem only if you want help solving it. That's what we do. Sympathy is what your girlfriends are for.

1. Anything we said 6 months ago is inadmissible in an argument. In fact, all comments become Null and void after 7 days.

1. If you think you're fat, you probably are. Don't ask us.

1. If something we said can be interpreted two ways and one of the ways makes you sad or angry, we meant the other one

1. You can either ask us to do something Or tell us how you want it done. Not both. If you already know best how to do it, just do it yourself.

1. Whenever possible, Please say whatever you have to say during commercials

1. Christopher Columbus did NOT need directions and neither do we.

1. ALL men see in only 16 colors, like Windows default settings. Peach, for example, is a fruit, not A color. Pumpkin is also a fruit. We have no idea what mauve is.

1. If it itches, it will be scratched. We do that.

1. If we ask what is wrong and you say "nothing," We will act like nothing's wrong. We know you are lying, but it is just not worth the hassle.

1. If you ask a question you don't want an answer to, Expect an answer you don't want to hear.

1. When we have to go somewhere, absolutely anything you wear is fine... Really .

1. You have enough clothes.

1. You have too many shoes.

1. I am in shape. Round IS a shape!

Saturday, October 11, 2008

Developers Definitely Need a Hug Sometimes

Friday, September 19, 2008

World's Natural Wonders Video, Made with iMovie

This is the first video I made with my MacBook. This one is made with iMovie which is included in Mac OS X. With iMovie making video is really easy. This video took me about 10-20 minutes to make. And what's cool about iMovie is you can upload it directly to YouTube. Check it out.

Monday, August 04, 2008

PHP: How to Display Errors Without Tweaking the Configuration File

Displaying errors in your PHP applications by tweaking the configuration file is sometimes troublesome, especially for most beginners. Luckily, you don't have to get your hand dirty to deal with it.

After installing MAMP (Mac, Apache, MySQL, PHP) in my MacBook, I had a hard time debugging my PHP codes as MAMP's default configuration do not allow showing of error.

In production environment, showing errors is a big mistake you can commit as your website is more vulnerable to hack attacks. But in development environment such as localhost, showing errors save you a lot of time in debugging.

Here's what I did.


ini_set('display_errors', 1);
error_reporting(E_ALL);


Put this two lines of codes in your index file and you'll see all the errors in your PHP codes will show off, if there are any (minus the links, of course).

Thursday, July 31, 2008

Ebook: Database Normalization Explained

If you're a programmer, aside from your favorite EDI and PL, database is one of your everyday companion. Almost all program these days uses a form of database, be it a flat file or RDBMS.

Being a good programmer, it's not enough that you only know the DML and DDL statements. You should also know and master the art of Database Normalization. Database normalization techniques is essential in order to achieve a high performance database design for your programs. If your database design doesn't conform to at least the Third Normal Form, you will have a hard time getting the data you want and it will be harder to achieve a high performance and scalable application.

Finally, there's an e-book that could give you the right knowledge about Database Normalization. This e-book shows you that normalization is a far too easy approach, and it is richly documented with graphical Entity Relationship and Server Diagram examples.

This knowledge-packed e-book is a great resource for DBAs and programmers.

Click here to get a copy of the Database Normalization Ebook.

Friday, February 29, 2008

PHP: How to Get the Current Server Date and Time

Adding date and time to your website gives it an impression of being fresh and updated regularly. In PHP, getting the current server date and time is a no brainer using the getdate() function.

To add date and time, see the PHP script below.

<html>
<head>
<title>DATE and TIME</title>
</head>

<body>
<?php
$date_array = getdate();
print "Server Date : $date_array[month] $date_array[mday], $date_array[year].<BR>";
print "Server Time : $date_array[hours]:$date_array[minutes]:$date_array[seconds]<BR>";
?>
</body>
</html>

Wednesday, February 27, 2008

Types of Looping Construct in Visual Basic

A loop is a sequence of instructions that is continually repeated until a certain condition is reached. It is a fundamental programming idea that is commonly used in writing programs. Without looping in a programming language, hundreds to thousands of repeated computer instructions would be time consuming, if not impossible to perform.

Here are the four types of looping construct in Visual Basic.

For Loop example
Private Sub ForLoop()
Dim intX As Integer

'-->INCREMENTING
For intX = 0 To 10
MsgBox "For Loop #" & intX, vbInformation, _
"Visual Basic Looping"
Next

'-->DECREMENTING
For intX = 10 To 0 Step -1
MsgBox "For Loop Step -1 #" & intX, vbInformation, _
"Visual Basic Looping"
Next
End Sub


Do While Loop example
Private Sub DoWhileLoop()
Dim intX As Integer

intX = 0
Do While intX < 10
MsgBox "Do While Loop #" & intX, vbInformation, _
"Visual Basic Looping"
intX = intX + 1
Loop
End Sub


While Wend Loop example
Private Sub WhileWendLoop()
Dim intX As Integer

intX = 0
While intX < 10
MsgBox "While Wend Loop #" & intX, vbInformation, _
"Visual Basic Looping"
intX = intX + 1
Wend
End Sub


Do Loop Example
Private Sub DoLoop()
Dim intX As Integer

intX = 0
Do
MsgBox "Do Loop #" & intX, vbInformation, _
"Visual Basic Looping"
intX = intX + 1
Loop While intX < 10
End Sub

Tuesday, February 26, 2008

PHP: How To Redirect To Another Website

Redirecting to another website in PHP is very simple and straightforward. Just by using the PHP header function and the the URL where to you want to redirect as a parameter, you can accomplish this task.

Here's the example below.
<html>

<header>
<title>PHP Redirection</title>
</header>

<body>

<?php
$url= "http://www.joelbadinas.com/";

/* Redirect browser */
header("Location: $url");

/* Make sure that code below does not
get executed when we redirect. */
exit;
?>

</body>

</html>


To use this script, just copy and paste it to your favorite PHP/HTML text editor, save it with a .php extension and put it in you web server. When you run it, you will be redirected to this blog.

Enjoy, and comments are welcome. (^_^)

Monday, February 25, 2008

How to Get The RGB of a Color Value in Visual Basic

This functions will returns the red, blue and green value of a color value.


'-->RETURNS THE RED COLOR VALUE
Private Function Red(ByVal Color As Long) As Integer
Red = Color Mod &H100
End Function

'-->RETURNS THE GREEN COLOR VALUE
Private Function Green(ByVal Color As Long) As Integer
Green = (Color \ &H100) Mod &H100
End Function

'-->RETURNS THE BLUE COLOR VALUE
Private Function Blue(ByVal Color As Long) As Integer
Blue = (Color \ &H10000) Mod &H100
End Function


Here's how to use this functions (see the image above for the result):

Private Sub Command1_Click()
MsgBox "Red: " & Red(Me.BackColor) & "," & vbNewLine & _
"Blue: " & Blue(Me.BackColor) & "," & vbNewLine & _
"Green: " & Green(Me.BackColor), _
vbInformation, "Form RGB Color"
End Sub

Thursday, February 21, 2008

How to Full Format Date in Visual Basic

This function shows how to full format date in Visual Basic 6.

Here's how to call the function: MsgBox FullFormatDate("02/24/1978")
The result will be: Friday, 24th Mar 1978

Public Function FullFormatDate(ByVal strDate As String) As String
Dim strDay As String

strDay = Format(strDate, "DD")
Select Case strDay
Case 1, 21, 31
strDay = Format(strDay, "#0") & "st"
Case 2, 22
strDay = Format(strDay, "#0") & "nd"
Case 3, 23
strDay = Format(strDay, "#0") & "rd"
Case Else
strDay = Format(strDay, "#0") & "th"
End Select

FullFormatDate = Format(strDate, "DDDD, ") & strDay & _
Format(strDate, " MMM YYYY")
End Function

Monday, February 11, 2008

Get Free Hosting Services at Tribuhost

Tribuhost is a website that offers free hosting services. At present, it is hosting two of my websites, Free Funny Jokes Collections and Online Recipe Collections, and so far, I am contented with there services. The support is fast and very helpful. Here's what Tribuhost offers:

- 250 MB disk space
- 6 GB Monthly transfer
- 5 MySQL databases
- 5 Add-on domains
- 5 Sub domains
- Vista Panel
- Automatic installer (29 scripts)
- Php 5
- FTP account
- File manager (browser upload)
- Web mail
- POP email accounts
- and more...

When you sign-up, you get a sub domain (ex: you.tribuhost.com) and you can create your website immediately. Also, a 468x60 banner ad is placed at the bottom of your website to cover the free hosting services - which I think is too little compared to the good service you get.

Sunday, February 10, 2008

Yahoo to Reject Microsoft's Plans to Buy the Internet Giant


Yesterday, reports came out the Yahoo plans to reject Microsoft's plans to buy the internet giant Yahoo.

Last February 1, Microsoft announced that it made an unsolicited offer to buy Yahoo for $44.6 billion, both in terms of cash and stocks. This is Microsoft's move to counter Google's an unstoppable superior status in the web.

The $44.6 billion bid, according to Yahoo's board, is way too low compared to it's current value.

Count the Forms Loaded in a Visual Basic Project

Sometimes you want to count the forms loaded in your Visual Basic project during runtime.


This simple and ready to use function will return the number of forms loaded in a project.

Public Function FormCount() As Long
Dim frmForm As Form
For Each frmForm In Forms
FormCount = FormCount + 1
Next
End Function


To use, just call the function like this.

MsgBox "# of forms loaded: " & FormCount

Saturday, February 09, 2008

My JoelBadinas.com Domain Is Not Working at the Moment

If you guys are wondering why joelbadinas.com is not working at the moment, it's because I am having issues with my registrar. For the meantime, this blog can be access via kabalweg.blogspot.com.

I'm already working to get my previous domain to work, unfortunately, it may take days before it will be back to normal. So please bear with me for the meantime.

Thursday, February 07, 2008

How to Flash a Minimized Form in the Taskbar Using API in Visual Basic

Here's a simple function to to flash a minimized form in the taskbar. It uses the FlashWindow API function and is written in Visual Basic

'-->API DECLARATION
Public Declare Function FlashWindow Lib "user32" (ByVal hWnd As Long, _
ByVal bInvert As Long) As Long

'-->THIS SUB WILL FLASH THE MINIMIZED FORM IN THE TASKBAR
Public Sub FlashForm(lngHandle As Long, _
Optional intCount As Integer = 1)
Dim intX As Integer

For intX = 0 To intCount
Call FlashWindow(lngHandle, True)
Next
End Sub

Wednesday, February 06, 2008

Free Online Recipes

Get free recipes at Free Online Recipes. This site features hundreds of free and practical yet mouth-watering recipes for homemakers, hobbyists and food enthusiasts or anybody who likes to cook. You can choose from several different recipe categories.

If you are a homemaker who don't know what dish to cook next for you family, a kitchen hobbyist who want to serve unique meals everyday, or just someone who would like to experiment something in the kitchen, this site is for you.

Drag PictureBox at Runtime in Visual Basic

The source codes below shows how you can drag a picturebox at runtime. To test this, copy and paste code to the declaration section of a form with a picturebox on it.

Private dblX As Double, dblY As Double
Private bolMove As Boolean

Private Sub cmdClose_Click()
Unload Me
End Sub

Private Sub Picture1_MouseDown(Button As Integer, _
Shift As Integer, _
X As Single, Y As Single)
If Button = 1 And Not bolMove Then
bolMove = True
dblX = X
dblY = Y
End If
End Sub

Private Sub Picture1_MouseMove(Button As Integer, _
Shift As Integer, _
X As Single, Y As Single)
Dim tmpy As Integer
Dim tmpx As Integer

If bolMove Then
If dblY > Y Then 'scroll up
tmpy = (dblY - Y) '* 100
Me.Picture1.Top = Me.Picture1.Top - tmpy
Else 'scroll down
tmpy = (Y - dblY) '* 100
Me.Picture1.Top = Me.Picture1.Top + tmpy
End If
If dblX > X Then 'scroll right
tmpx = (dblX - X) '* 100
Me.Picture1.Left = Me.Picture1.Left - tmpx
Else 'scroll left
tmpx = (X - dblX) '* 100
Me.Picture1.Left = Me.Picture1.Left + tmpx
End If
End If
End Sub

Private Sub Picture1_MouseUp(Button As Integer, _
Shift As Integer, _
X As Single, Y As Single)
bolMove = False
End Sub

Tuesday, February 05, 2008

Oracle PL/SQL Basics: A Simple Tutorial on Oracle PL/SQL

1. Using SQL-Plus

SQL-Plus is a query command line utility which has some powerful formatting capabilities.

Basic SQL-Plus Command
;                     Command line terminator
/ Execute the current batch of commands
SET SERVEROUTPUT ON Allow messages from PL-SQL to be displayed
SHOW ERRORS Show errors from last batch
EDIT Run editor, and load buffer
CLEAR BUFFER Clear buffer commands
& Prompt for value
@ Run commands in @filename


Prompt for process id, and kill
alter system kill session 'Victim';


Run commands in tables.sql
@tables.sql;


2. Creating a stored procedure

Below is a simple stored procedure which deletes an invoice.
Note:
- variable declaration placement
- the syntax for comments is /* --- */, or --
- ALL select statements must have an into statement for the result set. Oracle stored procedures must use "out" variables to return results to client programs.
- the declaration of INV_ID1 uses the column def as a prototype

CREATE OR REPLACE PROCEDURE PROC_DELETE_INVOICE(USERID1 VARCHAR2,
INV_ID1 INVOICE.INV_ID%TYPE) AS INV_COUNT NUMBER;
BEGIN
INV_COUNT := 0;
/* check if invoice exists */
SELECT COUNT(*) INTO INV_COUNT
FROM INVOICE WHERE INV_ID = INV_ID1;
IF INV_COUNT > 0 THEN
DELETE FROM INVOICE WHERE INV_ID = INV_ID1;
COMMIT;
END IF;
END;


3. Displaying output

All SELECT statements in PL-SQL must have an INTO clause; therefore another method is needed to display output to the console.

DBMS_OUTPUT.PUT_LINE('TEST OUTPUT');
salary := 24000;
dbms_output.put_line(salary);


4. Output variables

Output variables are used to return data to another procedure, or to an external application which has invoked the stored procedure.

Sample procedure header using output variables
TYPE INV_ARRAY IS TABLE OF NUMBER(8) INDEX BY BINARY_INTEGER;

CREATE OR REPLACE PROCEDURE PROC_GET_INV_NOS(
USERID1 IN VARCHAR2,
INV_IDS OUT INV_ARRAY)
AS . . .


5. Arrays and structures

Arrays and structures are implemented thought the use of "tables" and
"records" in PL-SQL.

Example of a simple record type
TYPE INVOICE_REC_TYPE IS RECORD(INV_ID   INVOICE.INV_ID%TYPE,
INV_DT INVOICE.INV_DT%TYPE);


Array declaration
TYPE NAME_TABLE_TYPE IS TABLE OF VARCHAR2(20) 
INDEX BY BINARY_INTEGER;
NAME_TABLE NAME_TABLE_TYPE;


Array subscripting
I := I + 1;
NAME_TABLE(I) := 'JSMITH';


6. Conditionals

Sample formats of conditional branching are given below:

IF statement
IF 'condition' THEN 'statement' ;


IF .. END IF statement
IF 'condition' THEN
'statements' ;
END IF;


IF .. ELSIF .. END IF statement
IF 'condition' THEN
'statements';
ELSIF 'condition' THEN
'statements';
END IF;


Sample statement, note the pipes for concatenation
IF (COUNT1 = 0) AND (COUNT2 > 0) THEN
RETMSG := 'Security attributes have not been assigned,
' || 'you are restricted.';
ELSE
RETMSG := 'You are OK';
END IF;


7. Looping

WHILE (I <>/* put command here */
I = I + 1;
END LOOP;


8. Packages

A package is a construct which bounds related procedures and functions together. Variables declared in the declaration section of a package can be shared among the procedures/functions in the body of the package.

Package
CREATE OR REPLACE PACKAGE INVPACK IS
/* function */
FUNCTION COUNTINV(SALESREP IN VARCHAR2) RETURN INTEGER;
/* procedure */
PROCEDURE PURGEINV(INV_ID IN INTEGER);
END INVPACK;


Package body
CREATE OR REPLACE PACKAGE BODY INVPACK IS
COUNT1 NUMBER;

/* function */
FUNCTION COUNTINV(SALESREP IN VARCHAR2) RETURN INTEGER IS
BEGIN
SELECT COUNT(*) INTO COUNT1
FROM INVOICE
WHERE SALES_REP_ID = SALESREP;

RETURN COUNT1;
END COUNTINV;

/* procedure */
PROCEDURE PURGEINV(INV_ID1 IN INTEGER) IS
BEGIN
DELETE FROM INVOICE WHERE INV_ID = INV_ID1;
END PURGEINV;
END INVPACK;


9. Cursors

Sample #1: This example depicts dbase-style row processing.
PROCEDURE PROC_SCAN_INVOICES(EXPIRE_DT IN DATE) IS
CURSOR INVOICE_CUR IS SELECT INV_ID, INV_DT FROM INVOICE;

TYPE INVOICE_REC_TYPE IS RECORD(INV_ID INVOICE.INV_ID%TYPE,
INV_DT INVOICE.INV_DT%TYPE);

INVOICE_REC INVOICE_REC_TYPE;
BEGIN
FOR INVOICE_REC1 IN INVOICE_CUR LOOP
IF INVOICE_REC.INV_DT <> EXPIRE_DT THEN
DELETE FROM INVOICE WHERE INV_ID = INV_REC.INV_ID;
DBMS_OUTPUT.PUT_LINE('INVOICE DELETETED:');
DBMS_OUTPUT.PUT_LINE(INV_REC.INV_ID);
END IF;
END LOOP;
END PROC_SCAN_INVOICES;


Sample #2: This example is a more traditional "fetch" approach.
PROCEDURE UPDATE_LOAD_CENTER_WORK_ORDER(
REC_NO IN MASTERTABLE.RECORDNUMBER%TYPE,
LCID IN MASTERTABLE.LC_NUMBER%TYPE,
WO_NO IN MASTERTABLE.WO_NUMBER%TYPE,
TRS_NO IN MASTERTABLE.TRS_NUMBER%TYPE) IS

CURSOR CURMAXID IS
SELECT MAX(RECORDNUMBER) + 1 FROM AMFM.GIS_LCWOMASTER;
NEXTRECNO MASTERTABLE.RECORDNUMBER%TYPE;

BEGIN
IF REC_NO = 0 THEN
OPEN CURMAXID;
FETCH CURMAXID
INTO NEXTRECNO;
CLOSE CURMAXID;
IF NEXTRECNO IS NULL THEN
NEXTRECNO := 1;
END IF;

INSERT INTO AMFM.GIS_LCWOMASTER A
(RECORDNUMBER, LC_NUMBER, WO_NUMBER, TRS_NUMBER, DATE_ENCODED)
VALUES
(NEXTRECNO, LCID, WO_NO, TRS_NO, SYSDATE);
ELSE
UPDATE AMFM.GIS_LCWOMASTER
SET LC_NUMBER = LCID, WO_NUMBER = WO_NO, TRS_NUMBER = TRS_NO
WHERE RECORDNUMBER = REC_NO;
END IF;
END UPDATE_LOAD_CENTER_WORK_ORDER;


Sample #3: This example returns a cursor. Note: Execute this two sample separately.
/* package declaration */
CREATE OR REPLACE PACKAGE load_center_pkg IS
TYPE refCursor IS REF CURSOR;

PROCEDURE get_all_transformers(pCursor OUT refCursor);
END load_center_pkg;

/* package body declaration */
CREATE OR REPLACE PACKAGE BODY load_center_pkg IS
PROCEDURE GET_ALL_TRANSFORMERS(PCURSOR OUT REFCURSOR) IS
BEGIN
OPEN PCURSOR FOR
SELECT A.XFORMER_ID,
A.PRIVATE_OWN,
A.PHASE, A.BRAND
FROM TRANSFORMER_MAST A;
END GET_ALL_TRANSFORMERS;
END load_center_pkg;


10. Exception Handling

The following block could appear at the end of a stored procedure:

EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('End of data !!);
WHEN OTHERS THEN
BEGIN
DBMS_OUTPUT.PUT_LINE('OTHER CONDITION OCCURRED !');
END;

Sunday, February 03, 2008

Gauss - Jordan Reduction Source Codes in C/C++

This program will process the matrix entered by the user to Reduced-Row Echelon Form. This method is known as Gauss-Jordan Reduction. I made this as a Midterm Project in Numerical Analysis.

NOTE: This is a complete and running C/C++ program.

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <ctype.h>
#include <conio.h>
#include <string.h>
#define PAUSE 10000

/*++++++++++++++ FUNCTION DECLARATION ++++++++++++++++++++++++*/
void Main_Screen();
void Dimension();
void Enter_To_The_Matrix();
void About_The_Matrix();
void The_Programmer();
void Help_Topics();
void ProcessMatrix(float Matrix[10][10],int row,int col);
void SwapRow(float Matrix[10][10],int R1,int R2,int col);
void MultiplyRow(float Matrix[10][10],int R1,int R2,int col);
void MultiplyAddRow(float Matrix[10][10],int R1,int R2,int col);
void centerY(char *text,int y,int fore,int back);
void centerX(char text[],int x1,int y1,int fore,int back);
void box1(int x1,int y1,int x2,int y2,int fore);
void wall1(int x1,int y1,int x2,int y2,int fore,int back);
void shadow(int x1,int y1,int x2,int y2,int fore,int back);

/*++++++++++++++ GLOBAL VARIABLES ++++++++++++++++++++++++++++*/
char ans, buffer[10], rowBuf[10], colBuf[10];
int x, y, z, X, Y, Z, check1,check2;
float matrix[10][10], InputBuf, row, col, num;

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

/*########### S T A R T of M A I N #########################*/
void main()
{
while(1 == 1)
{
Main_Screen();
ans=0;
while(ans!='1' && ans!='2' && ans!='3')
{
ans = getch();
}
switch(ans)
{
case 49: Dimension(); break;
case 50: About_The_Matrix(); break;
case 51: exit(0);
}
}
}

void Dimension()
{
shadow(20,10,66,20,8,0); wall1(18,9,64,19,3,3);
box1(18,10,63,17,8); box1(28,12,52,16,8);
centerY(" I n s i d e t h ‚ M … t r i x ",10,15,4);
centerY("Dimension",12,0,3);
while(1 == 1)
{
centerY(" x ",14,14,1);
gotoxy(37,14); gets(rowBuf); row = atof(rowBuf);
gotoxy(43,14); gets(colBuf); col = atof(colBuf);
gotoxy(44,14);
if(row > 0 && row < 6 && col > 1 && col < 7 )
{
break;
}
}
Enter_To_The_Matrix();
}

void Enter_To_The_Matrix()
{
char label[]="ABCDE";
ans=0;
while(ans != 'N')
{
shadow(10,4,76,24,8,0); wall1(8,3,74,23,7,7); box1(8,4,73,21,8);
box1(10,10,47,20,9); box1(48,6,71,20,1);
centerY(" I n s i d e t h ‚ M … t i x ",4,10,4);
centerX("Gauss-Jordan Reduction", 60,6,14,1);
centerX("Enter elements :", 19,9,0,7);
for(x=0 ; x<row ; x++)
{
for(y=0,z=0 ; y<col ; y++,z=z+6)
{
if(y < col-1)
{
textattr(14+(4<<4));
gotoxy(12+z,11); cprintf(" %c ",label[y]);
}
while(1 == 1)
{
centerX(" ",30,9,14,1);
gotoxy(29,9); gets(buffer);
InputBuf = atof(buffer);
if(InputBuf < 100 && InputBuf > -100)
{
break;
}
}
if(y == col-1)
{
label[y] = ' ';
}
matrix[x][y] = InputBuf; textattr(0+(7<<4));
gotoxy(12+z,13+x); cprintf("%.0f%c",matrix[x][y],label[y]);
}
}
ProcessMatrix(matrix,row,col);
centerX("Again? (Y/N)", 15,22,1,7);
ans=0;
while(ans != 'Y' && ans != 'N' && ans != 27)
{
ans = toupper(getch());
}
if(ans == 'N')
{
return;
}
if(ans == 'Y')
{
Dimension();
}
if(ans == 27)
{
return;
}
}
}

void ProcessMatrix(float Matrix[10][10],int row,int col)
{
char label[]="ABCDE";
X=0;Y=0;Z=1;
while(X<row)
{
for(x=X;x<row;x++)
{
if(Matrix[x][Y] == 1)
{
SwapRow(Matrix,x,Y,col);
}
}
if(Matrix[X][Y] == 0)
{
for(x=X;x<row-1;x++)
{
if(Matrix[x][Y] != 0)
{
SwapRow(Matrix,x,Y,col);
}
}
}
MultiplyRow(Matrix,X,Y,col);
for(y=Z;y<row;y++)
{
MultiplyAddRow(Matrix,y,Y,col);
}
X++;Y++;Z++;
}
for(Z=1;Z<6;Z++)
{
X=0;Y=Z;
while(X<row)
{
MultiplyAddRow(Matrix,X,Y,col);
X++;Y++;
}
}
for(y=0;y<col-1;y++)
{
check1=0;
if(y==col-2)
{
for(x=0;x<col;x++)
{
if(Matrix[row-1][x]==0)
{
check1++;
}
}
}
check2=0;
if(check1==col && row<col)
{
check2=1;
centerX("Ä> Has infinitely many solution!",29,19,4,7);
}
if(col>=row+2)
{
check2=1;
centerX("Ä> No possible solution! ",29,19,4,7);
}
}
for(y=0,z=0;y<col-1;y++,z=z+2)
{
textattr(15+(4<<4));
gotoxy(50,9+z); cprintf(" %c ",label[y]);
textattr(8+(7<<4));
gotoxy(54,9+z); cprintf("=");
if(check2==0)
{
textattr(0+(7<<4));
gotoxy(56,9+z); cprintf(" %.1f ",Matrix[y][col-1]);
}
}
for(x=0;x<row;x++)
{
for(y=0,z=0;y<col;y++,z=z+6)
{
textattr(0+(7<<4));
gotoxy(12+z,13+x); cprintf(" ");
gotoxy(12+z,13+x); cprintf("%.1f",Matrix[x][y]);
}
}
}

void SwapRow(float Matrix[10][10],int R1,int R2,int col)
{
float buffer[10];
for(x = 0; x < col; x++)
{
buffer[x] = Matrix[R1][x];
Matrix[R1][x] = Matrix[R2][x];
matrix[R2][x] = buffer[x];
}
}

void MultiplyRow(float Matrix[10][10],int R1,int R2,int col)
{
if(Matrix[R1][R2] == 0)
{
return;
}
num = (1 / Matrix[R1][R2]);

for(x = 0; x < col; x++)
{
Matrix[R1][x] = Matrix[R1][x] * num;
}
}

void MultiplyAddRow(float Matrix[10][10],int R1,int R2,int col)
{
float buffer[10];
num = Matrix[R1][R2];
if(num!=0)
{
num = num*(-1);
}
for(x = 0; x < col; x++)
{
buffer[x] = Matrix[R2][x];
buffer[x] = buffer[x] * num;
Matrix[R1][x] = Matrix[R1][x] + buffer[x];
}
}

void About_The_Matrix()
{
while(1 == 1)
{
shadow(14,6,72,20,8,0); wall1(12,5,70,19,3,3);
box1(12,6,69,18,8); shadow(18,9,68,18,8,0); wall1(16,8,66,17,4,4);
centerY(" A B O U T t h ‚ M … t r i x ",6,15,4);
centerX(" 1 ", 30,10,14,9);
centerX(" 2 ", 51,10,14,9);
centerX(" 3 ", 40,13,14,9);
centerX("The Programmers", 30,11,15,4);
centerX("Help Topics", 51,11,15,4);
centerX("Return To Main Menu", 40,14,15,4);
ans=0;
while(ans != '1' && ans != '2' && ans != '3'&& ans != 27)
{
ans = toupper(getch());
}
switch(ans)
{
case 49: The_Programmer(); break;
case 50: Help_Topics(); break;
case 51: return;
case 27: return;
}
}
}

void The_Programmer()
{
while(1 == 1)
{
shadow(10,4,76,24,8,0); wall1(8,3,74,23,7,7); box1(8,4,73,21,8);
centerY(" T h e P r o g r a m m e r s ",4,10,4);
centerY("Joel Badinas",8,0,7);
centerY("Michelle Claridad",9,0,7);
centerY("Dan Virgel Ratilla",10,0,7);
centerY("Frederick Jhun Layno",11,0,7);
centerY("ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ ",13,6,7);
centerY("The programmers are 3rd year students of",15,0,7);
centerY("the University of Southeastern Philippines taking up",16,0,7);
centerY("Bachelor of Science in Computer Science.",17,0,7);
centerX("<Esc> to cancel", 16,22,1,7);
while(ans != 27)
{
ans = getch();
}
if(ans == 27)
{
return;
}
}
}

void Help_Topics()
{
while(1 == 1)
{
shadow(10,4,76,24,8,0); wall1(8,3,74,23,7,7); box1(8,4,73,21,8);
centerY(" H e l p T o p i c s ",4,10,4);
centerX("This program will process the matrix entered by the user ",41,8,0,7);
centerX("to Reduced-Row Echelon Form(R.R.E.F.). This method is ",41,9,0,7);
centerX("known as Gauss-Jordan Reduction. The program will display ",41,10,0,7);
centerX("the result of the operation or the value corresponding the",41,11,0,7);
centerX("letter. ",41,12,0,7);

centerX("Please be guided that the dimension of the matrix the ",41,14,0,7);
centerX("program will accept must have a minimum of '1 x 2' and ",41,15,0,7);
centerX("a maximum of '5 x 6'. Also, the value of each element ",41,16,0,7);
centerX("should not be greater than '100'. ",41,17,0,7);

centerX("<Esc> to cancel", 16,22,1,7);
while(ans != 27)
{
ans = getch();
}
if(ans == 27)
{
return;
}
}
}

void Main_Screen()
{
textattr(1+(1<<4));
clrscr(); box1(1,1,80,24,7);
centerY("th‚ M…trix",2,10,1);
centerY(" Copyright(c) 2002 ",3,14,1);
centerY(" A Midterm Project in Numerical Analysis ",4,15,1);
centerY(" Submitted on February 2002 ",5,15,1);
textattr(13+(1<<4));
gotoxy(12,9); cprintf(" Û Û Üß ");
gotoxy(12,10); cprintf(" ÜÜÛÜ ÛÜÜÜ ÜÜÜÜ ");
gotoxy(12,11); cprintf(" Û Û Û ÛÜÜÛ ");
gotoxy(12,12); cprintf(" ÛÛ ÛÛ Û ÛÜÜÜ ");
gotoxy(12,13); cprintf("ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿");
textattr(10+(1<<4));
gotoxy(29,8); cprintf(" ÛÛÛÜ ÜÛÛÛ Ü ÛÛ ");
gotoxy(29,9); cprintf(" ÛÛÛÛÛ ÛÛÛÛÛ ß ßßÛÛßß ");
gotoxy(29,10); cprintf(" ÛÛÛ Û Û ÛÛÛ ßßßßÜ ÛÛ Û Üßß Ü ÛÜ ÜÛ ");
gotoxy(29,11); cprintf(" ÛÛÛ ÛÛÛ ÛÛÛ ÜßßßÛ ÛÛ Ûß Û ßÛÜÜÛß ");
gotoxy(29,12); cprintf(" ÛÛÛ ß ÛÛÛ Þ Û ÛÛ Û Û ÛÛ ");
gotoxy(29,13); cprintf(" ÛÛÛ ÛÛÛ ßÜÜßÛ ÛÛ Û Û ÜÛßßÛÜ ");
gotoxy(28,14); cprintf("ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄßßÄÄÄÄßßÄ ");
textattr(12+(1<<4));
gotoxy(57,8); cprintf(" Ü ");
gotoxy(57,9); cprintf("ßÜß");
centerY(" G A U S S - J O R D A N R E D U C T I O N ",15,4,2);
wall1(5,17,77,24,7,1);
wall1(10,18,30,22,4,4); wall1(32,18,50,22,4,4); wall1(52,18,72,22,4,4);
shadow(12,19,32,23,8,0); shadow(34,19,52,23,8,0); shadow(54,19,74,23,8,0);
centerX(" 1 ", 20,19,14,9);
centerX(" 2 ", 41,19,14,9);
centerX(" 3 ", 62,19,14,9);
centerX(" E N T E R ", 20,20,15,4);
centerX(" A B O U T ", 41,20,15,4);
centerX(" Q U I T ", 62,20,15,4);
centerX("Type number to select", 12,25,14,1);
centerX("D rkm…n", 76,25,3,1);
}

/*################ E N D ##################################*/




/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void centerX(char text[],int x1,int y1,int fore,int back)
{
int x;
textattr(fore+(back<<4));
x = (x1 - ((x1-x1)/2)) - (strlen(text)/2);
gotoxy(x,y1); cprintf("%s",text);
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void centerY(char *text,int y,int fore,int back)
{
textattr(fore+(back<<4));
gotoxy(40-strlen(text)/2,y);cprintf("%s",text);
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void box1(int x1,int y1,int x2,int y2,int fore)
{
int i; textcolor(fore);
for(i=x1;i<x2;i++) {
gotoxy(i,y1);cprintf("Ä");
gotoxy(i,y2);cprintf("Ä"); }
for(i=y1;i<y2;i++) {
gotoxy(x1,i);cprintf("³");
gotoxy(x2,i);cprintf("³"); }
gotoxy(x1,y1);cprintf("Ú");
gotoxy(x2,y1);cprintf("¿");
gotoxy(x1,y2);cprintf("À");
gotoxy(x2,y2);cprintf("Ù");
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void wall1(int x1,int y1,int x2,int y2,int fore,int back)
{
int i,j;
for(j = y1; j < y2; j++) {
for(i = x1;i < x2; i++) {
gotoxy(i,j); textattr(fore+(back<<4)); cprintf("°");} }
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void shadow(int x1,int y1,int x2,int y2,int fore,int back)
{
int i,j;
for(j = y1; j < y2; j++) {
for(i = x1;i < x2; i++) {
if(i+2 >= x2 || j+1 >= y2) {
gotoxy(i,j); textattr(fore+(back<<4)); cprintf("°"); } } }
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/


/*+++++++++++++ E X C E S S +++++++++++++++++++++++++++++++*/
/*X=0;Y=1;
while(X<row)
{
MultiplyAddRow(Matrix,X,Y,col);
X++;Y++;
}
X=0;Y=2;
while(X<row)
{
MultiplyAddRow(Matrix,X,Y,col);
X++;Y++;
}

X=0;Y=3;
while(X<row)
{
MultiplyAddRow(Matrix,X,Y,col);
X++;Y++;
}*/
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

Thursday, January 31, 2008

How to Get the File Information Using API in Visual Basic

This function takes a passed filename as an argument and returns the description of that file. For example, if you pass the filename "c:\windows\sys.com" to the function, it will return the string "MS-DOS Application". If the file doesn'texist, it will return a blank type information.

NOTE: To see the result, copy and paste the code below in the
declaration section of a form.

'Constants declaration
Const SHGFI_DISPLAYNAME = &H200
Const SHGFI_TYPENAME = &H400
Const MAX_PATH = 260
Private Type SHFILEINFO
hIcon As Long ' out: icon
iIcon As Long ' out: icon index
dwAttributes As Long ' out: SFGAO_ flags
szDisplayName As String * MAX_PATH ' out: display name (or path)
szTypeName As String * 80 ' out: type name
End Type

'API declaration
Private Declare Function SHGetFileInfo Lib "shell32.dll" Alias _
"SHGetFileInfoA" (ByVal pszPath As String, _
ByVal dwFileAttributes As Long, _
psfi As SHFILEINFO, ByVal cbFileInfo As Long, _
ByVal uFlags As Long) As Long

'Gets the information of the file passed to it
Private Function GetFileInfo(strFileName) As SHFILEINFO
Dim lngRetVal As Long
Dim fileInfo As SHFILEINFO

lngRetVal = SHGetFileInfo(strFileName, 0, fileInfo, Len(fileInfo), _
SHGFI_DISPLAYNAME Or SHGFI_TYPENAME)
GetFileInfo = fileInfo
End Function

'This fucntion is used to strip al the unnecessary chr$(0)'s
Private Function StripTerminator(sInput As String) As String
Dim ZeroPos As Integer
'Search the position of the first chr$(0)
ZeroPos = InStr(1, sInput, vbNullChar)
If ZeroPos > 0 Then
StripTerminator = Left$(sInput, ZeroPos - 1)
Else
StripTerminator = sInput
End If
End Function

Private Sub Form_Load()
Dim fileInfo As SHFILEINFO

fileInfo = GetFileInfo("c:\autoexec.bat")
MsgBox "Displayname: " & StripTerminator(fileInfo.szDisplayName) & _
vbNewLine & _
"Typename: " & StripTerminator(fileInfo.szTypeName)
End Sub

Tuesday, January 29, 2008

Cut, Copy, Paste and Delete Using the Clipboard Object Source Codes in Visual Basic

Are you having difficulty in doing Cut, Copy, Paste and Delete of texts routines in Visual Basic? Well, settle down now.

This source codes shows the CUT, COPY, PASTE and DELETE routines using the Clipboard object. This source codes assumes that you have four commandbutton controls (EditCut, EditCopy, EditPaste and EditDelete) in your Visual Basic project

Private Sub EditCut_Click()
'Clear the contents of the Clipboard.
Clipboard.Clear
'Copy selected text to Clipboard.
Clipboard.SetText Screen.ActiveControl.SelText
'Delete selected text.
Screen.ActiveControl.SelText = ""
End Sub

Private Sub EditCopy_Click()
'Clear the contents of the Clipboard.
Clipboard.Clear
'Copy selected text to Clipboard.
Clipboard.SetText Screen.ActiveControl.SelText
End Sub

Private Sub EditPaste_Click()
'Place text from Clipboard into active control.
Screen.ActiveControl.SelText = Clipboard.GetText()
End Sub

Private Sub EditDelete_Click()
'Delete selected text.
Screen.ActiveControl.SelText = ""
End Sub

Monday, January 28, 2008

How to Handle Control Arrays with Index Holes in Between in Visual Basic

Here's simple tutorial on how you can handle control arrays with index holes in between.

Control array is one of the best feature of Visual Basic. However, this can cause runtime errors if you are not careful, especially if they have missing elements or index in between.

To handle control arrays with sequence index, you can use this method.

Dim intX as integer
For intX = Text1.LBound to Text1.UBound
MsgBox Text1(intX).Text
Next


However, if they have holes in between them (Ex: Text1(0), Text1(1), Text1(3), Text1(4)), the above method spits an error. To avoid that situation, treat the array like a collection as below.

Dim txt as TextBox
For Each txt In Text1
MsgBox txt.Text
Next txt


That's it. Tamed control arrays. (^_^)

Sunday, January 27, 2008

Oracle DDL Basics: A Simple Tutorial on Oracle Data Definition Language

Here's a simple tutorial on Oracle Data Definition Language. I always make this handy at the office as I sometimes forget some of the basis of the Oracle DDL.

1. Data Type.

Type                Storage     Range/Length
----------------- ---------- --------------
NUMBER 16 40 digit floating point
FLOAT 16 40 digit floating point
SMALLINT 16 40 digit floating point
NUMBER(a,b) varies a digits, b precision
FLOAT(a,b) varies a digits, b precision
DECIMAL 16 40 digit
INTEGER 16 40 digits
INTEGER(a) varies a digits
CHAR(a) a a=(1-255)
VARCHAR(a) varies 1 - 255
VARCHAR2(a) varies 1 - 2000
DATE 8 1/1/4217BC - 12/31/4712AD
LONG varies 0 - 2 GB
LONG RAW varies 0 - 2 GB
LONG VARCHAR varies 0 - 2 GB
BLOB varies 0 - 4 GB
CLOB varies 0 - 4 GB
NCLOB varies 0 - 4 GB
BFILE ?? ??
ROWID 8 n/a


* Long datatypes are discouraged in Oracle 8.
Note that are long and blob datatypes are incompatible.

2. Creating a Table.

PCTFREE = Amount of space to leave in block during insert operations. Allows room for records to grow within the same area.
PCUSED = The threshold at which the block is placed back on the free block list.
INITIAL/NEXT = The initial disk allocated, and the next extent size.
LOGGING = Indicates whether operations are written to the redo logs.

CREATE TABLE EMPLOYEE (
EMP_ID NUMBER(8),
LNAME VARCHAR2(30),
FNAME VARCHAR2(15),
HIRE_DT DATE,
SALARY NUMBER(8,2) )

PCTFREE 20
PCTUSED 50
STORAGE (INITIAL 200K NEXT 200K PCTINCREASE 0 MAXEXTENTS 50 )
TABLESPACE ts01 LOGGING;


3. Creating indexes

CREATE UNIQUE INDEX EMP_IDX ON EMPLOYEE (EMP_ID);


/* index create - table has sorted data */
CREATE UNIQUE INDEX IDX_INVOICE_ITEMS   ON INVOICE_ITEMS
(INVOICE_ID,YEAR,FREQ_CODE,FREQ_NUMBER,FIELD_NUMBER,RECORD_SEQ)
TABLESPACE TS_07
NOLOGGING
NOSORT;


/* create index - constraint */
ALTER TABLE  INVOICE_FORMAT
ADD CONSTRAINT PK_INVOICE_FORMAT PRIMARY KEY(INVOICE_ID)
USING INDEX TABLESPACE PROD_IDX_01;


/* Get index information */
SELECT A.COLUMN_NAME,
A.COLUMN_POSITION,
A.INDEX_NAME,
B.UNIQUENESS
FROM USER_IND_COLUMNS A,
USER_INDEXES B
WHERE A.INDEX_NAME = B.INDEX_NAME AND
A.TABLE_NAME = 'IDX_INVOICE_ITEMS'
ORDER BY A.INDEX_NAME, A.COLUMN_POSITION;


/* create bitmap index - table is fairly static, and has less than 1000 distinct values in the indexed column */
CREATE BITMAP INDEX BIX_INVOICE_ARCHIVE
ON INVOICE_ARCHIVE (SALES_ID)
TABLESPACE PROD_IDX_01;


4. Creating constraints

/* primary key constraint */
ALTER TABLE EMPLOYEE (
CONSTRAINT EMP_PK
PRIMARY KEY (EMP_ID));


ALTER TABLE  REPORT_FORMAT
ADD CONSTRAINT PK_REPORT_FORMAT PRIMARY KEY(REPORT_ID)
USING INDEX TABLESPACE PROD_IDX_01;


/* foreign key constraint */
ALTER TABLE EMPLOYEE ADD (
CONSTRAINT EMP_LOC_ASSIGN_FK
FOREIGN KEY (EMP_ID,
LOC_CD)
REFERENCES LOC_REGISTRY (
EMP_ID,
LOC_CD));


5. Creating and using a sequence.

/* create a sequence for employee ids */
CREATE SEQUENCE EMP_ID_SEQ
INCREMENT BY 1
NOMINVALUE
NOMAXVALUE
NOCYCLE
CACHE 20
NOORDER ;


/ * use the next emp id, and increment the sequence */
INSERT INTO EMPLOYEE(EMP_ID, LNAME, FNAME)
VALUES (EMP_ID_SEQ.NEXTVAL, 'SMITH', 'JIM');


/* get the current value of the sequence */
INSERT INTO EMPLOYEE(EMP_ID, LNAME, FNAME)
VALUES (EMP_ID_SEQ.CURRVAL, 'SMITH', 'JIM');


6. Creating triggers.

The example below illustrates versioning of the EMP_RESUME table, which contains a blob field.

CREATE OR REPLACE TRIGGER EMP_RES_INS_TR
AFTER INSERT ON EMP_RES
FOR EACH ROW
DECLARE
VER1 NUMBER ;
EBLOB BLOB ;
VBLOB BLOB ;
BEGIN
EBLOB := EMPTY_BLOB();

SELECT (COUNT(*) + 1) INTO VER1
FROM VEMP_RES
WHERE EMP_ID =:NEW.EMP_ID ;

VBLOB := :NEW.RESUME ;

INSERT INTO VEMP_RES
( EMP_ID, DOC_URL,
A_USERID, D_MODIFIED, VER_NO, RESUME)
VALUES (
:NEW.EMP_ID, :NEW.DOC_URL,
USER, SYSDATE, VER1, EBLOB ) ;

SELECT RESUME
INTO EBLOB
FROM VEMP_RES
WHERE EMP_ID =:NEW.EMP_ID AND
VER_NO = VER1
FOR UPDATE ;

UPDATE VEMP_RES
SET RESUME = VBLOB
WHERE EMP_ID =:NEW.EMP_ID AND
VER_NO = VER1 ;
END;



7. Renaming a table.

RENAME EMPLOYEE TO MANAGER;


8. Synonyms and Database Links.

/* Synonym Creation */
GRANT SELECT ON USER5.COMPANY TO USER6 ;
CREATE SYNONYM USER6.COMPANY5 FOR USER5.COMPANY;


/* Database Link */
CREATE DATABASE LINK ARCHIVE_DATA CONNECT TO
USER5 IDENTIFIED BY TIGER USING 'SERVER5';


/* user within this system can now reference tables using ARCHIVE_DATA.tablename */

9. Changing a column's type or name.

/*Change Type*/
ALTER TABLE CORPORATION MODIFY (COMPANY_NM VARCHAR2(100));


ALTER TABLE employee MODIFY(last_name varchar2(40));


/*Change Name*/
ALTER TABLE EMPLOYEE RENAME COLUMN LAST_NAME TO LNAME;


10. Moving a table.

ALTER TABLE COMPANY MOVE
STORAGE (
INITIAL 200K
NEXT 200K
PCTINCREASE 0
MAXEXTENTS 50 )
TABLESPACE TS_01;


11. Partitioned Tables.

Table partitioning is the best feature ever added to the Oracle RDBMS.
Chunks of data can be appended, replaced, or purged very easily when
using table partitioning. When you have more than 20 million rows in a
non-static table, partitioning is recommended. We found that bitmap
indexes work better than standard indexes on partitioned tables.

/*Add a partition*/
ALTER TABLE PHONE_DATA ADD PARTITION
p2004JUL VALUES (200407) TABLESPACE TS01 ;


/*Populate a partition, replaces existing data, if it exists*/
ALTER TABLE PHONE_DATA EXCHANGE PARTITION
p2004JUL WITH TABLE TMP_SWITCH_DATA ;


/*Move a partition*/
ALTER TABLE PHONE_DATA MOVE PARTITION 
P2004JUL TABLESPACE TS01 NOLOGGING;


/*Truncate a partition*/
ALTER TABLE PHONE_DATA TRUNCATE PARTITION;


/*Drop a partition*/
ALTER TABLE PHONE_DATA DROP PARTITION p2004JUL 
update global indexes;


/*Get partition information*/
SET PAGESIZE 0
SET LINESIZE 120
SELECT TABLE_NAME, PARTITION_NAME, BLOCKS, TABLESPACE_NAME
FROM USER_TAB_PARTITIONS
ORDER BY TABLE_NAME, PARTITION_NAME;


/*Create a local partition index*/
CREATE BITMAP INDEX BIX_PHONE_DATA ON PHONE_DATA
(PERIOD_KEY)
TABLESPACE TS02
LOCAL;


/*Rebuild*/
ALTER TABLE PHONE_DATA MODIFY PARTITION
p2004JUL REBUILD UNUSABLE LOCAL INDEXES;

Saturday, January 26, 2008

Wishful Thinking

How I wish I could go on a cruises vacation like cruisecheap.com is offering. My last vacation was far from being comfortable. I had to go on a 24-hour trip via bus. The waiting and the long bus trip will just drain your energy away.

Well, maybe if my online business picked up, then I'll be able to afford to travel via plane back and forth everytime I go home for a vacation and avoid wasting my vacation time on a bus. And maybe I'll go on a cruise vacation with my wife, who knows. (^_^)

How to Easily Clear the Texts in Textbox or Combobox in Visual Basic

Ever done a program wherein you have to clear all the texts in textboxes and/comboboxes every time you need to input something? If you reference each control by it's name and then clearing the text one by one, that will result to more lines of codes. And in programming, more lines of codes means more complications.

Good thing is, you don't have to write several lines of source codes, the function below will do just that.

This visual basic function will clear texts any control with text property or a list-index property in the form.

Public Sub ClearAllControls(frmForm As Form)
Dim ctlControl As Object
On Error Resume Next
For Each ctlControl In frmForm.Controls
ctlControl.Text = ""
ctlControl.LISTINDEX = -1
DoEvents
Next ctlControl
End Sub

Wednesday, January 23, 2008

A Payroll System Source Codes in C/C++

I wrote this Payroll System in C/C++ for our final project requirement in college. It uses array of structure to save the employees information. Check it out.

#include<stdio.h>
#include<process.h>
#include<ctype.h>
#include<string.h>
#include<dos.h>
#include<conio.h>
#define PAUSE 10000

void addEmp();
void viewEmp();
void addDed();
void viewDed();
void exitSys();
void linefill(int start);

struct employee{
char code[10];
char fname[15];
char lname[15];
char mname[5];
char sex[10];
char status[15];
char ded_name1[15];
char ded_name2[15];
char ded_name3[15];
float grossPay;
float netPay;
float tax;
float ded_n1;
float ded_n2;
float ded_n3;
}empRec[50];

char ch,ID[10];
int x,cntrX,idCheck;

void main()
{
int start=16,end=20;
textattr(9+(1<<4)); clrscr(); cntrX=0;
while(1 == 1)
{
window(1,1,80,25);
linefill(start); textattr(10+(1<<4));
gotoxy(20,3); cprintf("Ûßßß Ü ÛßßÛ ÜÜÜÜ Û ");
gotoxy(20,4); cprintf("ÛÛßß Ü ÛÛ Û ÜÜÜÛ ÛÛ ");
gotoxy(20,5); cprintf("ÛÛ Û ÛÛ Û ÛÜÜÛ ÛÛÜÜ");
textattr(6+(1<<4));
gotoxy(42,3); cprintf("Üßßßß Û Û Üßßßß");
gotoxy(42,4); cprintf(" ßßßÜ ßÛß ßßßÜ");
gotoxy(42,5); cprintf("ßßßß ß ßßßß ");
textattr(15+(1<<4));
gotoxy(60,3); cprintf("TM ");
gotoxy(23,7); cprintf(" Final Project ");
gotoxy(23,8); cprintf(" by: Joel Badinas ");
gotoxy(23,9); cprintf(" October 2001 ");
textattr(2+(4<<4));
gotoxy(29,14); cprintf(" >> M A I N M E N U << ");
textattr(2+(1<<4));
gotoxy(25,15); cprintf("ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ");
gotoxy(33,16); printf("Add new employee");
gotoxy(33,17); printf("View employee");
gotoxy(33,18); printf("Add deduction");
gotoxy(33,19); printf("View deduction");
gotoxy(33,20); printf("Quit");
gotoxy(25,21); cprintf("ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ");
textattr(14+(1<<4));
gotoxy(2,25); cprintf("FiNaLSYS Ver 1.0");
gotoxy(63,25); cprintf("Copyright(c) 2001");
ch=getch();
if(ch==72)
{
textbackground(1); textcolor(9);
gotoxy(31,start); cprintf(" ");
start = start -1;
if(start < 16)
{
start = end;
}
textbackground(1); textcolor(9);
gotoxy(31,start+1); cprintf(" ");
linefill(start);
}
if(ch==80)
{
textbackground(1); textcolor(9);
gotoxy(31,start); cprintf(" ");
start = start + 1;
if(start > 20)
{
start = 16;
}
textbackground(1); textcolor(9);
gotoxy(31,start-1); cprintf(" ");
linefill(start);
}
if(ch == 13)
{
if(start == 16)
{
addEmp(); textattr(9+(1<<4));
window(1,1,80,24); clrscr();
}
if(start == 17)
{
viewEmp(); textattr(9+(1<<4));
window(1,1,80,24); clrscr();
}
if(start == 18)
{
addDed(); textattr(9+(1<<4));
window(1,1,80,24); clrscr();
}
if(start == 19)
{
viewDed(); textattr(9+(1<<4));
window(1,1,80,24); clrscr();
}
if(start == 20)
{
exitSys(); exit(0);
}
}
}
}

void addEmp()
{
float pay1;
char name1[15],name2[15],name3[5],name4[10],name5[15];
ch=0;
while(ch != 'N')
{
window(8,4,72,22);
textattr(2+(0<<4)); clrscr(); textattr(7+(0<<4));
while(1 == 1)
{
idCheck=0;
gotoxy(6,3); cprintf("Enter code : "); scanf("%s",&ID);
for(x=0;x<cntrX+1;x++)
{
if(strcmp(empRec[x].code,ID)==0)
{
idCheck=1;
}
}
if(idCheck==1)
{
gotoxy(23,3); printf(" ");
gotoxy(2,19); cprintf("Code no. already exist! ");
delay(PAUSE);
gotoxy(2,19); printf(" ");
}
else
{
break;
}
}
gotoxy(6,8); cprintf("Last Name : ");
gotoxy(6,9); cprintf("First Name : ");
gotoxy(6,10); cprintf("Middle Initial : ");
gotoxy(6,11); cprintf("Sex : ");
gotoxy(6,12); cprintf("Status : ");
gotoxy(6,13); cprintf("Monthly Pay : ");

gotoxy(23,8); scanf("%s",&name1);
gotoxy(23,9); scanf("%s",&name2);
gotoxy(23,10); scanf("%s",&name3);
gotoxy(23,11); scanf("%s",&name4);
gotoxy(23,12); scanf("%s",&name5);
gotoxy(23,13); scanf("%f",&pay1);
gotoxy(2,19); cprintf("Save this entry? (Y/N) ");
ch=0;
while(ch != 'Y'&& ch != 'N')
{
ch=toupper(getch());
}
if(ch=='Y')
{
cntrX++;
strcpy(empRec[cntrX].code,ID);
strcpy(empRec[cntrX].fname,name1);
strcpy(empRec[cntrX].lname,name2);
strcpy(empRec[cntrX].mname,name3);
strcpy(empRec[cntrX].sex,name4);
strcpy(empRec[cntrX].status,name5);
empRec[cntrX].grossPay = pay1;
empRec[cntrX].tax = (.12)*pay1;
empRec[cntrX].netPay = empRec[cntrX].grossPay-empRec[cntrX].tax;
gotoxy(2,19); cprintf("Saving entry... ");
delay(PAUSE);
}
else
{
gotoxy(2,19); cprintf("Saving cancelled... ");
delay(PAUSE);
}
gotoxy(2,19); cprintf("Save entry again? (Y/N) ");
ch=0;
while(ch != 'Y'&& ch != 'N')
{
ch=toupper(getch());
}
}
}

void viewEmp()
{
ch=0;
while(ch != 'N')
{
idCheck=0;
window(8,4,72,22);
textattr(2+(0<<4)); clrscr(); textattr(7+(0<<4));
gotoxy(6,3); cprintf("Enter code : "); scanf("%s",&ID);
for(x=0;x<cntrX+1;x++)
{
if(strcmp(ID,empRec[x].code)==0)
{
gotoxy(6,8); cprintf("Last Name : ");
gotoxy(6,9); cprintf("First Name : ");
gotoxy(6,10); cprintf("Middle Initial : ");
gotoxy(6,11); cprintf("Sex : ");
gotoxy(6,12); cprintf("Status : ");
gotoxy(6,13); cprintf("Net Pay : ");

gotoxy(23,8); printf("%s",empRec[x].fname);
gotoxy(23,9); printf("%s",empRec[x].lname);
gotoxy(23,10); printf("%s",empRec[x].mname);
gotoxy(23,11); printf("%s",empRec[x].sex);
gotoxy(23,12); printf("%s",empRec[x].status);
gotoxy(23,13); printf("%.2f",empRec[x].netPay);
idCheck=1; break;
}
}
if(idCheck==0)
{
gotoxy(2,19); cprintf("Employee record not found... ");
delay(PAUSE);
}
gotoxy(2,19); cprintf("View employee again? (Y/N) ");
ch=0;
while(ch != 'Y'&& ch != 'N')
{
ch=toupper(getch());
}
}
}

void addDed()
{
char nameded1[15],nameded2[15],nameded3[15];
float amount1,amount2,amount3;
ch=0;
while(ch != 'N')
{
window(8,4,72,22); idCheck=0;
textattr(2+(0<<4)); clrscr(); textattr(7+(0<<4));
gotoxy(3,2); cprintf("Enter code : "); scanf("%s",&ID);
for(x=0;x<cntrX+1;x++)
{
if(strcmp(ID,empRec[x].code)==0)
{
idCheck=1;
gotoxy(3,6); cprintf("Name : ");
gotoxy(3,7); cprintf("Monthly Pay : ");
gotoxy(46,6); cprintf("Sex : ");
gotoxy(46,7); cprintf("Status : ");

gotoxy(17,6); printf("%s %s %s",empRec[x].fname,empRec[x].lname,empRec[x].mname);
gotoxy(17,7); printf("%.2f",empRec[x].grossPay);
gotoxy(55,6); printf("%s",empRec[x].sex);
gotoxy(55,7); printf("%s",empRec[x].status);

gotoxy(16,10); cprintf(" Type of Deduction ³ Amount");
gotoxy(16,11); cprintf("ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ");
gotoxy(17,12); cprintf("1)"); gotoxy(36,12); cprintf("³");
gotoxy(17,13); cprintf("2)"); gotoxy(36,13); cprintf("³");
gotoxy(17,14); cprintf("3)"); gotoxy(36,14); cprintf("³");

gotoxy(20,12); scanf("%s",&nameded1);
gotoxy(39,12); scanf("%f",&amount1);

gotoxy(20,13); scanf("%s",&nameded2);
gotoxy(39,13); scanf("%f",&amount2);

gotoxy(20,14); scanf("%s",&nameded3);
gotoxy(39,14); scanf("%f",&amount3);

gotoxy(2,19); cprintf("Save this entry? (Y/N) ");
ch=0;
while(ch != 'Y'&& ch != 'N')
{
ch=toupper(getch());
}
if(ch == 'Y')
{
for(x=0;x<cntrX+1;x++)
{
strcpy(empRec[x].ded_name1,nameded1);
strcpy(empRec[x].ded_name2,nameded2);
strcpy(empRec[x].ded_name3,nameded3);
empRec[x].ded_n1 = amount1;
empRec[x].ded_n2 = amount2;
empRec[x].ded_n3 = amount3;
empRec[x].netPay = empRec[x].grossPay-empRec[x].tax-amount1-amount2-amount3;
}
gotoxy(2,19); cprintf("Saving entry... ");
delay(PAUSE); break;
}
else
{
gotoxy(2,19); cprintf("Saving cancelled... ");
delay(PAUSE); break;
}
}
}
if(idCheck==0)
{
gotoxy(2,19); cprintf("Employee record not found... ");
delay(PAUSE);
}
gotoxy(2,19); cprintf("Add deduction again? (Y/N) ");
ch=0;
while(ch != 'Y'&& ch != 'N')
{
ch=toupper(getch());
}
}
}

void viewDed()
{
ch=0;
while(ch != 'N')
{
window(8,4,72,22); idCheck=0;
textattr(2+(0<<4)); clrscr(); textattr(7+(0<<4));
gotoxy(3,2); cprintf("Enter code : "); scanf("%s",&ID);
for(x=0;x<cntrX+1;x++)
{
if(strcmp(ID,empRec[x].code)==0)
{
idCheck=1;
gotoxy(3,5); cprintf("Name : ");
gotoxy(3,6); cprintf("Monthly Pay : ");
gotoxy(46,5); cprintf("Sex : ");
gotoxy(46,6); cprintf("Status : ");

gotoxy(17,5); printf("%s %s %s",empRec[x].fname,empRec[x].lname,empRec[x].mname);
gotoxy(17,6); printf("%.2f",empRec[x].grossPay);
gotoxy(55,5); printf("%s",empRec[x].sex);
gotoxy(55,6); printf("%s",empRec[x].status);

gotoxy(16,9); cprintf(" Type of Deduction ³ Amount");
gotoxy(16,10); cprintf("ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ");
gotoxy(17,11); cprintf("1)");
gotoxy(17,12); cprintf("2)");
gotoxy(17,13); cprintf("3)");
gotoxy(17,14); cprintf("4)");
gotoxy(36,11); cprintf("³");
gotoxy(36,12); cprintf("³");
gotoxy(36,13); cprintf("³");
gotoxy(36,14); cprintf("³");
gotoxy(36,16); cprintf("³");
gotoxy(16,15); cprintf("ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ");

gotoxy(20,11); printf("Salary Tax");
gotoxy(20,12); printf("%s",empRec[x].ded_name1);
gotoxy(20,13); printf("%s",empRec[x].ded_name2);
gotoxy(20,14); printf("%s",empRec[x].ded_name3);
gotoxy(20,16); printf("Net Pay");

gotoxy(39,11); printf("%.2f",empRec[x].tax );
gotoxy(39,12); printf("%.2f",empRec[x].ded_n1 );
gotoxy(39,13); printf("%.2f",empRec[x].ded_n2 );
gotoxy(39,14); printf("%.2f",empRec[x].ded_n3 );
gotoxy(39,16); printf("%.2f",empRec[x].netPay);
}
}
if(idCheck==0)
{
gotoxy(2,19); cprintf("Employee record not found... ");
delay(PAUSE);
}
gotoxy(2,19); cprintf("View deduction again? (Y/N) ");
ch=0;
while(ch != 'Y'&& ch != 'N')
{
ch=toupper(getch());
}
}
}

void linefill(int start)
{
textattr(0+(7<<4));
gotoxy(31,start); cprintf(" ");
}

void exitSys()
{
window(8,4,72,22);
textattr(7+(0<<4)); clrscr();
gotoxy(16,10); printf("Please wait while system exits... ");
delay(PAUSE);
}

Tuesday, January 15, 2008

I'm on a Vacation Leave

This blog will become idle for about a week as I take my much awaited vacation leave from work.

I'll be going to my hometown, Gen. MacArthur, E. Samar, to attend the anniversary of Nanay when she was taken by the Lord.

I will be back early next week to post more programming source codes and tutorials and pictures of our hometown.

Until then...

Automatically Search ListBox Using API in Visual Basic

Using API, this codes automatically searches the listbox for whatever you type in the textbox.

To use this codes, add a ListBox, named List1 and a TextBox, named Text1 into your project and copy and paste the codes to your project.

Private Declare Function SendMessage Lib "user32" _
Alias "SendMessageA" (ByVal hwnd As Long, _
ByVal wMsg As Long, ByVal wParam As Integer, _
ByVal lParam As Any) As Long

Const LB_FINDSTRING = &H18F

Private Sub Form_Load()
With List1
.AddItem "Computer"
.AddItem "Screen"
.AddItem "Modem"
.AddItem "Printer"
.AddItem "Scanner"
.AddItem "Sound Blaster"
.AddItem "Keyboard"
.AddItem "CD-Rom"
.AddItem "Mouse"
End With
End Sub

Private Sub Text1_Change()
Index = SendMessage(List1.hwnd, LB_FINDSTRING, -1, _
ByVal CStr(Text1.Text))
If Index < 0 Then Exit Sub
List1.ListIndex = Index
Text1.Text = List1.List(Index)
End Sub

Saturday, January 12, 2008

How to Make Context Menu (Pop up) Using API in Visual Basic

This is a very good example on how to make context menu or pop-up menu using API.

Context menu (pop up menu) is useful for your program, specially if it's heavy in graphic. A program with context menu far more user-friendly than one which has not.

In my case at work, are program usually deals with map (autoCAD maps), so context menu is very important. Fortunately, Visual Basic 6 has APIs to do just that.

Copy and paste the source codes below into your VB project and you're ready to go.

Private Enum BTN_STYLE
MF_CHECKED = &H8&
MF_APPEND = &H100&
TPM_LEFTALIGN = &H0&
MF_DISABLED = &H2&
MF_GRAYED = &H1&
MF_SEPARATOR = &H800&
MF_STRING = &H0&
TPM_RETURNCMD = &H100&
TPM_RIGHTBUTTON = &H2&
End Enum

Private Type POINTAPI
X As Long
Y As Long
End Type

Private Declare Function CreatePopupMenu Lib "user32" () As Long
Private Declare Function TrackPopupMenuEx Lib "user32" (ByVal hMenu As Long, _
ByVal wFlags As Long, ByVal X As Long, ByVal Y As Long, _
ByVal HWnd As Long, ByVal lptpm As Any) As Long
Private Declare Function AppendMenu Lib "user32" Alias "AppendMenuA" _
(ByVal hMenu As Long, _
ByVal wFlags As BTN_STYLE, ByVal wIDNewItem As Long, _
ByVal lpNewItem As Any) As Long
Private Declare Function DestroyMenu Lib "user32" (ByVal hMenu As Long) As Long
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Dim hMenu As Long

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, _
X As Single, Y As Single)
Dim Pt As POINTAPI
Dim ret As BTN_STYLE

If Button = vbRightButton Then
hMenu = CreatePopupMenu()
AppendMenu hMenu, MF_STRING, 1, "New"
AppendMenu hMenu, MF_STRING, 2, "Open"
AppendMenu hMenu, MF_SEPARATOR, -1, "Add"
AppendMenu hMenu, MF_STRING, 3, "Exit"
GetCursorPos Pt
ret = TrackPopupMenuEx(hMenu, TPM_LEFTALIGN Or TPM_RETURNCMD, _
Pt.X, Pt.Y, Me.HWnd, ByVal 0&)
DestroyMenu hMenu

If ret = 1 Then
MsgBox "New"
ElseIf ret = 2 Then
MsgBox "Open"
ElseIf ret = 3 Then
MsgBox "Exit"
End If
End If
End Sub

Friday, January 11, 2008

10 Type Of Girls in the IT World

Do you have women in your IT department? See if she belongs to any of the list below.

1. HARD DISK GIRLS: she remembers everything, and FOREVER.

2. RAM GIRLS: she forgets about you the moment you turn her off.

3. WINDOW GIRLS: everyone knows that she can't do a thing right, but no one can live without her.

4. SCREENSAVER GIRLS: She is good for nothing but at least she is fun.

5. INTERNET GIRLS: Difficult to access.

6. SERVER GIRLS: Always busy when you need her.

7. MULTIMEDIA GIRLS: She makes horrible things look beautiful.

8. CD-ROM GIRLS: She is always faster and faster.

9. EMAIL GIRLS: For every ten things she says, eight are nonsense .

10. VIRUS GIRLS: Also known as "wife'' when you are not expecting her, she comes, install herself and uses all your resources. If you try to uninstall her, you will lose something, if you don't try to uninstall her, you will lose everything...

Have you ever come across with this types of girls at your workplace? Well. I'm lucky enough, there's no girl in our team (gay maybe). It would have been more difficult. (^_^)

See also:
Top 25 explanations by programmers

Thursday, January 10, 2008

Accessing MySQL Database Using PHP

Accessing MySQL database is one of the best uses of PHP. In fact, the PHP's support for MySQL has been included since the first public usable version of the language. PHP and MySQL are like blood-brother, as some programmers say.

This PHP source code shows how to access a MySQL database and display the result. This example assumes the you're running PHP and MySQL in your local PC. If you don't have PHP and MySQL, you can download the XAMPP installer. XAMPP is an easy to install Apache distribution containing MySQL, PHP and Perl. I use this a lot.

In your MySQL, create a database named "company" and a table named "employee". See the SQL DDL below.
create table employee(
id smallint(5),
name varchar(35),
email varchar(35));


Connect to database, where;

"localhost" is you database server
"un" is the username defined in your database
"pw" is the password for the username

$db = mysql_connect("localhost", "un", "pw") or
die("Cannot connect to the database");


Select the database

mysql_select_db("company");


Set up the SQL statement and query the employee table

$result = mysql_query("SELECT id, name, email FROM employee") or
die(mysql_error());


Loop & display the resultset

while($rows = mysql_fetch_assoc($result))
{
echo "<b>ID</b>".$rows["id"]."<br>";
echo "<b>Name</b>".$rows["name"]."<br>";
echo "<b>Email</b>".$rows["email"]."<br><br>";
}


Summing it all up

<?php
$db = mysql_connect("localhost", "un", "pw") or
die("Cannot connect to the database");
mysql_select_db("company");

$result = mysql_query("SELECT id, name, email FROM employee") or
die(mysql_error());

while($rows = mysql_fetch_assoc($result))
{
echo "<b>ID</b>".$rows["id"]."<br>";
echo "<b>Name</b>".$rows["name"]."<br>";
echo "<b>Email</b>".$rows["email"]."<br><br>";
}
?>


Note: You can use print instead of echo.

Tuesday, January 08, 2008

PHP Basics: A Simple Tutorial on PHP

I'm a self-teach PHP developer, and being one, I know how self-teach programmer who likes to have grapple the basics of PHP, need to have a good, yet simple tutorial on the language.

I made this PHP tutorial as simple as possible for you to grapple the basics of the PHP programming language. You can also use this as a good reference of the basics of PHP. So I suggest you bookmark this post and come back here whenever you need. You are most welcome. (^_^)

1. Basic Syntax

A PHP scripting block always starts with <?php and ends with ?>. It can be placed anywhere in the document.

You can also use the shorthand symbol, <? and end with ?>, on servers with shorthand support enabled

However, it is recommended that you use the standard form (<?php) rather than the shorthand form (<?) for maximum compatibility,

Example:

<?php
echo "Hello World";
?>


2. Comments

Use // sign to make a single-line comment or /* and */ signs to make a large comment block.

Example;

<?php
//This is a comment

/*
This is
a comment
block
*/
?>


3. Variables

In php, variables start with a $ sign symbol. Variables may contain strings, numbers, or arrays but should start with a letter.

Rule:
* A variable name must start with a letter or an underscore "_"
* A variable name can only contain alpha-numeric characters and
underscores (a-Z, 0-9, and _ )
* A variable name should not contain spaces. If a variable name should be more
than one word, it should be separated with underscore ($my_string),
or with capitalization ($myString)


Valid: $a, $name, $name1
Invalid: $3, $3name

Example

<?php
$text="Hello World";
echo $text;
?>


4. Operators

Arithmetic Operators

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (division remainder)
++ Increment
-- Decrement


Assignment Operators

Operator Example The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y


Comparison Operators

Operator Description
== is equal to
!= is not equal
> is greater than
< is less than
>= is greater than or equal to
<= is less than or equal to


Logical Operators

Operator Description
&& and
|| or
! not


5. Conditional Statements

if...statement

<?php
$d=date("D");
if ($d=="Fri")
{
echo "Have a nice weekend!";
}
?>


The If...Else Statement

<?php
$d=date("D");
if ($d=="Fri")
{
echo "Have a nice weekend!";
}
else
{
echo "Have a nice day!";
}
?>


The ElseIf Statement

<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>


The Switch Statement

<?php
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>


6. Arrays

Indexed Array

$names = array("Babyrose", "Kabalweg");

or

$names[0] = "Babyrose";
$names[1] = "Kabalweg";


Associative Arrays

$age = array("Babyrose"=>27, "Kabalweg"=>28);
$ages["Babyrose"] = "27";
$ages["Kabalweg"] = "28";


Multidimensional Arrays

$families = array
(
"Badinas"=>array
(
"Joel",
"Kabaleg"
),
"Aranas"=>array
(
"Rosalina",
"Babyrose"
)
);


7. Looping

while loop

<?php
$x=1;
while($x<=10)
{
echo "The number is " . $x . "<br />";
$x++;
}
?>


do...while loop

<?php
$x=1;
do
{
echo "The number is " . $x . "<br />";
$x++;
}
while ($x<10);
?>


for loop

<?php
for ($x=1; $x<=10; $x++)
{
echo "The number is " . $x . "<br />";
}
?>


foreach loop

<?php
$arr=array("one", "two", "three", "four", "five");
foreach ($arr as $value)
{
echo "Value: " . $value . "<br />";
}
?>
</pre>


8. Functions

Simple

<?php
function sayMyName()
{
echo "You are Joel Badinas";
}
?>


Parameterized

<?php
function sayMyName($name)
{
echo "You are ".$name;
}
?>


Returning Values

<?php
function sayMyName()
{
$name = "You are Joel Badinas";
Return $name;
}
?>

Monday, January 07, 2008

Bill Gates Will Resign from Microsoft

If you still haven't heard of it, Bill Gates will retire as Chief Software Architect and Chairman of Microsoft this coming July 2008. He will be working part-time for Microsoft while working full-time for the foundation he and his wife Melinda founded. He announced his resignation last week in a press conference.

As of July 2008, Gates will transition from his day-to-day role as Chief Software Architect and Chairman of Microsoft to just being the Chairman. Chief Technical Officer Ray Ozzie will immediately assume the title of Chief Software Architect and begin working side by side with Gates on all technical architecture and product oversight responsibilities while Chief Technical Officer Craig Mundie will immediately take the new title of Chief Research and Strategy Officer.

"I don't know what it's going to feel like not to come in every day and work 10 hours," Gates said. "I have a sense of what it's like to do foundation work because I've squeezed that in part time, but I think it will probably take me a while, just like six years ago when I switched off from CEO. It might take me a year and a half to get used to my role. That's a little bit of an unknown now and because I've got two years, I don't even really want to go there now, because I'll figure it out when I get there."

Sunday, January 06, 2008

Warning for RealPlayer 11 Users, You are Vulnerable to Hacker Attack

If you a RealPlayer user, this is for you.

Experts in the field of internet security issued a warning saying that RealPlayer is vulnerable exploitation. The flaw of the recent version of the product, the RealPlayer 11, could allow hackers to remotely control a PC if successfully exploited.

This security flaw was discovered by Evgeny Legerov, of Russian security firm GLEG.

Webuser reports:
As yet unpatched by Real Networks, the vulnerability "is caused due to an unspecified error and can be exploited to cause a buffer overflow," according to an advisory from a separate security company, Secunia.

Secunia also warned surfers not to open untrusted media files or browse unfamiliar websites, rating the vulnerability "highly critical".

How to Check if Email Address is Valid in PHP

If your website is accepting email address as input, it is always wise to check of it's validity as some users, especially spammers, have a habit of inputing garbage text in email fields. If you don't check it, you end up saving invalid email.

The PHP funtion below checks for the validity of the email address passed to it.

PHP function
function isValidEmail($address)
{
return preg_match("/^[a-z0-9._\-]+[@]([a-z0-9\-]+[.])+([a-z]{2,4})\$/i",
$address);
}


Using the function
if(!isValidEmail($_POST["email_address"]))
echo "Please input a valid email address.";
else
echo "Your email is valid";

New Year's Resolution from the Adsense Blog

Still at a lost this New Year? Well, if you're an Adsense publisher, the Adsense Blog listed some New Year's resolution you could choose from. Although a little late, it's worth the try. (^_^)

1. Turn my custom channels into ad placements, complete with descriptive details to attract placement-targeting advertisers.

2. Regularly check my sites for compliance with the AdSense program policies.

3. Keep my address and tax info up to date so that my payments are accurate and timely. (And sign up for EFT if it's available to me!)

4. Place more of my ad units above the fold and on my homepage for increased visibility -- and advertiser appeal.

5. Share my AdSense expertise with other publishers in the AdSense Help Forum.

6. Opt in to text and image ads to make the most of the available ad inventory for my content.

7. Use the Manage Ads feature to experiment with removing the borders from my ad units.

8. View the Payments Demo and payments schedule with rapt attention so I'll always know when to expect my next payment.

Recent Post