Thursday 10 October 2013

Windows and Linux..... a better Server and a better Desktop

It's a very common discussion comparing Windows and Linux. As windows is favorable to everyone using desktop PC but till now Linux is more suitable as using as a server than windows. Through linux is slowly growing popularity in Desktop version as in Ubuntu, but still windows is still the better one as a desktop version than linux, more user interactivity, easy to install device driver and software, to say specifically linux is a better OS for software engineers.
But.... but but .. when it's comes question of using server version, undoubtedly linux seems to be the best. You can runa machine running linux server for days and months without even restarting without any problems, while windows needs to upgrade itself every weeks so on. It's needed restarting the OS and these upgrade makes the server slow day by day, but linux, continue it for months without any maintenance, restarting. So don't you think it's better to have a server with linux version than windows.
I generally saw students have a fascination of installing desktop version of linux on their machine and getting bored a few days after. They used to get frustrated with package installations, tired of fetching dependency rpms and a few days after they are happy to wipe out the linux version and continue with windows. So for students this is a message that linux is not a fascinating stufff or nor does it server purpose of some gaming stuff, it's in a clean way a stuff that requires a bit of learning to depth and a little patience and then you will find how interesting it is. Tell me one think.... if you are a programmer and you think that the features you see in your desktop version needs to be just as you want it to be... in Windows!!!! never never never. But in linux just take the source code of any package which generally comes in tar format. Modify it as per your wish (until you use it commercially), compile it and GET SET GO..... Windows also give you this privilege but in API format and you don't know what the hell is inside it. All the distros of linux  you see is derived from some basic version of linux, modifying the source code and get your own DISTROS.
So guys if are fascinated with linux boost your fascination to OBSESSION and you will find the secret of this OS, otherwise if you are having  some business needs to maintain a huge data on your server, my suggestion is to use linux server version, believe me it will rock, but but but don't get excited with it, it's better to provide your employee  a desktop with windows version.

thanks to Eli Etherton for information on Using linux as server.



Monday 7 October 2013

How to change the case of letter of the content of a file in bash shell

Suppose there is a file named file1.txt which contains
----
Hello World
This is a simple command
------

Now the command will be like this
$cat file1.txt | while read line; do; echo $line | tr "a-z" "A-Z"; done

Now what happens here
first cat prints the content of the file which instead of going to stdout goes as input to the next
command through the PIPE ( | ). Here we runs a loop which reads one line at a time it gets as
input from file1.txt, and again PIPED to another command tr which is a translation command
converting each character from small case ("a-z") to upper ("A-Z"). while loop runs until last line
of the file is reached.

Output is

----
hELLO wORLD
tHIS IS A SIMPLE COMMAND
------

Glob expressions in Shell Scripting in Linux

1. If you are a regular user of MS Dos you might know the use of wild cards.
The same is applicable in Linux shell know as GLOB Expression

like if you write this syntax

for name in d??

this will find all the file names in your current directory with 3 characters
starting with d and then any 2 characters like doc,dol...

In the same way if we write

for name in *d??
this will show all file name ending with d following any 2 characters
just like extension name, doc,div etc.

2. a. Regular expression in enclose characters
    m[0123456789]x
    it may be any name starting with m followed by digits and ending
    with x
    this can be made short by using m[0-9]x.
  
  The same thing can be done with alphabets
   [0-9][a-z].  This expression will take anything starting with digits and ending with
   alphabets in small case. eg. 98ab but not ab98 or 98AB.

   Negation
   Condition can be negated like m[!0-9]x will take anything starting with    m, any non numeric     
  characters, ending with x,  eg. xyzABCx
  or [0-9][!a-z] will read anything starting with numbers and ending with
  anything not alphabets in small case. eg. 79XYZ.

  In case you want alphabets with both lower case and upper case then you write [a-zA-Z]
  You can also provide range of alphabets or numbers. Like [d-jF-N] will validated any string
  starting with lower case alphabets between d and j and upper case alphabets between F and N.
  The same is with  numbers. [5-9] will validate anything between 5 and 9. 234 is wrong.
 
  All this expression given above only works if files with such pattern exists otherwise it will
  return the expression itself

  Say if you write for name in [a-z]123, this will print the name of file starting with alphabets
  but ending with 123 (may be extension name), but if file with such pattern does not exists it
  will return just the expression [a-z]123.

Friday 4 October 2013

Navigating through the arguments of a shell script while executing

 How to get access to the arguments we pass while executing a shell script  
   In the shell script myscript.sh we write
  
   #!bin/bash
  
   while [ -n "$1" ]
   do
     echo "$1"
     shift
   done
  
   output of the shell script when its argument are like this
  
   myscript.sh first comes nation then family
  
   first
   comes
   nation
   then
   family
  
   shift actually takes the next argument from $1 to $2 then to $3 and so on.
   -n "$1" checks whether the value is non zero. When there is no more argument
   -n "$1" return false and the loop end.
  
   You can also write the condition like this.
  
   while [ ! -z "$1" ]
  
   -z check whether the value of "$1" is zero so when there is argument -z "$1" returns false
   so when it is prefixed by ! its return true.
  
   Using for loop instead of while loop
  
   As $1, $2, $3 returns consecutive arguments, $@ return all the arguments in a sentence separated
   by space so if write a for loop like this
  
   for arg in "$@" - here arg takes one word from the sentence $@ for each iteration
   The full script is like this
  
   for arg in "$@"
   do
   echo "$@"
   done

Thursday 3 October 2013

How to check whether a file is a shell script file (.sh) or not

   As we know that the first line of a shell script file contains #!bin/bash,
   so we will check whether a file contains the text bin/bash
  
   Arguments of a shell script file is identified as $1,$2,$2....
   $1 is the name of the executing script file itself, and arguments of
   the script files are $2,$3 ....
  
   So lets us write a shell script file isscript.sh
  
   #!bin/bash
  
   if grep "bin/bash" "$1"
   then
    echo "File is a shell script file"
   else
    echo "File is not a shell script file"
   fi
  
   now suppose we want to see whether a file named abc.sh is a
   shell script file or not
  
   so we run the isscript file like this
   $./isscript.sh abc.sh
  
   Now the shell script takes abc.sh as argument $1
   grep "bin/bash" "$1" checks whether the pattern "bin/bash"
   exists in the shell script abc.sh, if exists then command
   echo "File is a shell script file" is executed otherwise
   echo "File is not a shell script file" is executed.
  
  
  

How to create a bash script

   A shell script file should conventionally have an extension .sh

   The first line of your script file should be #!/bin/bash, this line actually tells
   the OS that the script is a bash script.

   A simple script file example

   open a script file say file1.sh with vi. vi file1.sh

   #!/bin/bash
   echo "Hello World, this is what I got in my home directory
   ls /home/subhroneel

   save the file and quit vi.

   set executable permission to file1.sh

   $chmod u+x file1.sh

   run the script just as written below

   $./file1.sh

   output is:  
   Hello World
   Listing of /home/subhroneel directory
   Music Video Ebooks  

Wednesday 2 October 2013

Basic Linux Bash command

1. Pathname
To types of pathname are there, Relative pathname and Abosolute pathname

Relative pathname does not begins with /, it is always relative to the present working directory.
Suppose your present working directory is /home/myuser, so if you type
$ pwd ($ is the prompt, you type pwd), it will display /home/myuser, this is the absolute path.
Now if you type cd games, then games here is relative to /home/myuser and your present directory changes to /home/myuser/games. IF you have type cd /home/myuser/games the
same thing happened but in this case you have given absolute path.

2. ls
Lists the contents of the current working directory
(pwd - "Print Working Directory" To see the current working directory)

ls -a
List all files including the files with Dot prefix

ls -l

List name of files with details like permission,date time (created/modified)

Commands can be combined
Say you want to list all files with details you type
ls -a -l or ls -al
This joining can be only done for Short options
for long options like -all you cannot join to options
(example ls -al)

Long and short options can be mixed.
ls --all -l

3.  . and .. (dot and dotdot) directory
    Every directory (even empty) contains two directory in it. One is . (dot) and another is .. (dotdot)
    . (dot) directory is actually the shortcut to the current working directory and .. (dotdot) is a     shortcut to the parent working directory. For example if you type cd .. (you present directory is   /home/myuser/games) you will navigate to /home/myuser.
   For example if you type ls ../ (your pwd is /home/myuser/games) it will list all files and   directories in  myuser folder.

4. rm  - Commands used to delete a file.
   
    Command is - rm filename.extensionname
     rm file1.txt

     rm does not remove directory but you can remove list of files in a directory by this command
     rm -r directoryname.  (-r recursive method)
     rm -r Music.  This command will remove all the files in the directory Music.

     You cannot remove files with rm if you do not have write permission on the files.

     
5. cp - Copies files / directory from source to destination

    cp file1.txt file2.txt
    cp /home/myuser/Music/a.txt /home/myuser/a.txt

    cp can also copy directories and sub directories in a recirsive manner.

    cp -r dir1 dir2.  This copies all contents of dir1 including files and subdirectories to dir2.

6. mv - Moves files / directories from source to destination
    mv oldfilename.txt newfilename.txt (this is similar to renaming a file).
    mv /home/myuser/Music/olddir /home/myuser/newdir

7. cat,tac and less command
     cat file1.txt prints the content of the file
     cat file1.txt file2.txt file3.txt displays content of all the three files concatenated.
   
     tac file1.txt prints the content of the file in reverse order.
   
     less file1.txt displays contents of the file pagewise.

8.  file command Gives information about the file type
      file file1.bmp  Bitmap image

9.  find command searches the entire directories/subdirectories starting from the source           directory specified for a certain file/ directory specified. Wildcard can be used.
    
      find / -name "*.txt" searches all files with extension txt starting from /

10. locate command does the same as find but build an index before searching which makes the           search more faster.
      locate abc.txt
      locate command cannot be used to search a newly created file until it is indexed, in that case          you have to use the find command.

11. chmod
      syntax is - chmod permissions filename
      chmod u+x file1.sh. Set/Adds executable (x) permission to current user (u) (u+x).
      chmod u-x file1.sh.  Unset/removes executable (x) permission to current user (u) (u-x).
      chmod go-rwx file1.sh Unset/removes read,write,executing permission from the group (g) the
      user belongs to and all others (o). So with this permission only user has the rights. Rights are
      revoked from everybody else.

12. gzip and gunzip
     
      gzip  compreses a file 
      gzip file1.txt  this command compress the file file1.txt to file1.txt.gz
     
      gunzip file1.txt.gz this command uncompress the file file1.txt.gz to file1.txt
     
      gzip works best for text files.
      gzip is not an archiver, it's a compressor. Archiver archives multiple files to a single file like winrar or winzip,
      but gzip compresses only a single file.
      To archive files you need to use tar command.

13. tar archive a directory containing multiple files
     create
     tar -cvf Musicbkup.tar /home/myuser/Music, c is to create the archive, v is for verbose mode       
     (prints all the files names to be archived), f is for target tar filename (Musicbkup.tar),
     if you mention f option you need to give the output archivename.
   
     tar -czvf Musicbkup.tar.gz /home/myuser/Music, z is added to the options -cvf to compress the archived file.
       
     extract
     tar -xvf Musicbkup.tar, extract all files from the archive.

     tar -xzvf Musicbkup.tar.gz, extract and uncompress all files from the compressed .gz.

     tar -xzvf Musicbkup.tar.gz actually perform two commands into one. First its gunzip
     Musicbkup.tar.gz into Musicbkup.tar and then extract all files from Musicbkup.tar.
   
14. head and tail commands
    head -n 10 file1.txt prints the first 10 lines of the file file1.txt, option n being the number of lines.
    head does the same thing as less commands but less commands prints page by pagee but head
    commands prints the desired number of lines.
   
    tail -n 10 file1.txt prints the last 10 lines of the file file1.txt, option n being the number of lines.
   
15. du command prints the amount of space a specified diretory use in the disk.
    du -sh Desktop if s option is not given then du command prints size information of all the subdirectories under
    specified directories, s option summarizes all the information and only shows the space occupied by it. h option
    gives the size information in MB or GB instead of bytes, if you do not provide h option result will come into byte units.

16. grep command searches for pattern in the content of a file specified.
    grep sun file1.txt searches for pattern sun output can be like this sun,sunny,sundry,prasun.
   
17. history command list all the previous commands you have typed. Up and down arrow browse through history in lifo method.
    when you type any command the commands stored into the memory but when you end terminal session all commands are appended
    into a file automatically. Now when you are into one session and you want to see the command history on another terminal
    session, it will not show because it is not written onto disk yet. You can type history -a which flushes the memory and
    append current history in the file and you can see those commands when you type history from other terminal session.
   
18. export command to set environment variable on your current session
    export VAR_NAME=value general convension is to set the variable in upper case.
    export ORACLE_HOME=u01/oracle/app/db_1
    unset VAR_NAME - command to unset the environment variable is
    unset ORACLE_HOME
   
19. vi / vim editor vi or vim editor is a text editor which can be used to create file, edit contents of the file.
    command is vi filename or vim filename
    some commands in insert mode
    'i' turn insert mode on by moving the cursor to the next cursor location
    'a' turn insert mode keeping the cursor where it is.
    'i' to insert text or to say to turn the editor to insert mode
    'esc' to turn off the insert mode and enter to command mode
   
    this commands works when not in command mode
    'h' move the cursor to the left.
    'k' move the cursor up.
    'l' move the cursor to the right.
    'j' move the cursor down.
    'b' move one word left.
    'w' move one word right.
    'x' delete one character right (del).
    'X' delete one character left (backspace).
    'V' Highlight / Salect a complete line.
    'j' to hightlight the line following the selected line downwards.
    'y' (yank) to copy a selected line / paragraph.
    'p' paste a copied line / paragraph on top of the copied section.
    'P' paste a copied line / paragraph below the copied section.
    'd' delete a selected line / paragraph.
    :w writes changes to disk / save the file.
    :q quits vim.
    :wq writes changes to disk and then quit vim.
    :q! discard changes to file and then quit vim.
   
19. env - a command to see all the environment variable set in the current session.   

20. sort  this command sorts lines in a file in alphabetical order.
    sort file1.txt

Tuesday 1 October 2013

A Simple PC Diagnostic Tool Project

This is a simple PC Diagnostic Tool project developed using windows management service class library in Visual Basic 6.0.
.
Download the project


How to search windows component using Windows API in Visual Basic 6.0

Download Source Code

Option Explicit
Private Declare Function RemoveMenu Lib "user32" (ByVal hMenu As Long, ByVal nPosition As Long, ByVal wFlags As Long) As Long
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function GetMenu Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function GetSubMenu Lib "user32" (ByVal hMenu As Long, ByVal nPos As Long) As Long
Private Declare Function GetMenuItemID Lib "user32" (ByVal hMenu As Long, ByVal nPos As Long) As Long
Private Declare Function GetActiveWindow Lib "user32" () As Long
Private Declare Function GetMenuItemCount Lib "user32" _
(ByVal hMenu As Long) As Long
Private Declare Function GetSystemMenu Lib "user32" (ByVal hwnd As Long, ByVal bRevert As Long) As Long
Private Declare Function GetMenuItemInfo Lib "user32" _
Alias "GetMenuItemInfoA" (ByVal hMenu As Long, _
ByVal un As Long, ByVal b As Boolean, _
lpMenuItemInfo As MENUITEMINFO) As Boolean

Const MF_BYPOSITION = &H400&
Const MF_REMOVE = &H1000&

Private Const MIIM_ID = &H2
Private Const MIIM_TYPE = &H10
Private Const MFT_STRING = &H0&

Private Type MENUITEMINFO
    cbSize As Long
    fMask As Long
    fType As Long
    fState As Long
    wID As Long
    hSubMenu As Long
    hbmpChecked As Long
    hbmpUnchecked As Long
    dwItemData As Long
    dwTypeData As String
    cch As Long
End Type

Dim taskBarhWnd As Long, notifyTrayhWnd As Long, rebarWindow As Long, toolbarWindow As Long, quickLaunchWindow As Long, startBtnWindow As Long
Dim ppthWnd As Long, ribbonhWnd As Long, panehWnd As Long, deskhWnd As Long, vbhWnd As Long, vbmainMenuhWnd As Long, vbaWindowhWnd As Long, ExplorerhWnd As Long

Private Sub Command1_Click(Index As Integer)
    Select Case Index
    Case 0
        taskBarhWnd = FindWindow("Shell_TrayWnd", vbNullString)
        notifyTrayhWnd = FindWindowEx(taskBarhWnd, 0&, "TrayNotifyWnd", vbNullString)
        Call ShowWindow(notifyTrayhWnd, show_Chk(Index).Value)
    Case 1
        taskBarhWnd = FindWindow("Shell_TrayWnd", vbNullString)
        'toolbarWindow = FindWindow("RebarWindow32", "")
        rebarWindow = FindWindowEx(taskBarhWnd, 0&, "RebarWindow32", "")
        Call ShowWindow(rebarWindow, show_Chk(Index).Value)
    Case 2
        taskBarhWnd = FindWindow("Shell_TrayWnd", vbNullString)
        'toolbarWindow = FindWindow("RebarWindow32", "")
        quickLaunchWindow = FindWindowEx(FindWindowEx(taskBarhWnd, 0&, "RebarWindow32", ""), 0&, "ToolbarWindow32", "Quick Launch")
        Call ShowWindow(quickLaunchWindow, show_Chk(Index).Value)
    Case 3
        taskBarhWnd = FindWindow("Shell_TrayWnd", vbNullString)
        startBtnWindow = FindWindowEx(taskBarhWnd, 0&, "button", "start")
        Call ShowWindow(startBtnWindow, show_Chk(Index).Value)
    Case 4
        taskBarhWnd = FindWindow("Shell_TrayWnd", vbNullString)
        'toolbarWindow = FindWindow("RebarWindow32", "")
        quickLaunchWindow = FindWindowEx(FindWindowEx(taskBarhWnd, 0&, "RebarWindow32", ""), 0&, "ToolbarWindow32", "Quick Launch")
        toolbarWindow = FindWindowEx(FindWindowEx(taskBarhWnd, 0&, "RebarWindow32", ""), quickLaunchWindow, "ToolbarWindow32", "Running Applications")
        Call ShowWindow(toolbarWindow, show_Chk(Index).Value)
    Case 5
        ppthWnd = FindWindow("PP12FrameClass", vbNullString)
        'panehWnd = FindWindowEx(ppthWnd, 0&, "paneClassDC", "Slide")
        Call ShowWindow(ppthWnd, show_Chk(Index).Value)
    Case 6
        ppthWnd = FindWindow("PP11FrameClass", vbNullString)
        'panehWnd = FindWindowEx(ppthWnd, 0&, "paneClassDC", "Slide")
        Call ShowWindow(ppthWnd, show_Chk(Index).Value)
    Case 7
        vbhWnd = FindWindow("wndclass_desked_gsk", vbNullString)
        'panehWnd = FindWindowEx(ppthWnd, 0&, "paneClassDC", "Slide")
        Call ShowWindow(vbhWnd, show_Chk(Index).Value)
    Case 8
        vbhWnd = FindWindow("wndclass_desked_gsk", vbNullString)
        vbmainMenuhWnd = FindWindowEx(FindWindowEx(vbhWnd, 0&, "MsoCommandBarDock", "MsoDockTop"), 0&, "MsoCommandBar", "Menu Bar")
        'panehWnd = FindWindowEx(ppthWnd, 0&, "paneClassDC", "Slide")
        Call ShowWindow(vbmainMenuhWnd, show_Chk(Index).Value)
    Case 9
        vbhWnd = FindWindow("wndclass_desked_gsk", vbNullString)
        vbaWindowhWnd = FindWindowEx(FindWindowEx(vbhWnd, 0&, "MDIClient", ""), 0&, "VbaWindow", "Form1 (Code)")
        'panehWnd = FindWindowEx(ppthWnd, 0&, "paneClassDC", "Slide")
        Call ShowWindow(vbaWindowhWnd, show_Chk(Index).Value)
    Case 10
        ExplorerhWnd = FindWindow("CabinetWClass", "My Computer")
       ' vbaWindowhWnd = FindWindowEx(FindWindowEx(vbhWnd, 0&, "MDIClient", ""), 0&, "#32770(Dialog)", "Display Properties")
        'panehWnd = FindWindowEx(ppthWnd, 0&, "paneClassDC", "Slide")
        Call ShowWindow(FindWindow("CabinetWClass", "My Computer"), show_Chk(Index).Value)
        Call ShowWindow(FindWindow("ExploreWClass", "My Computer"), show_Chk(Index).Value)
    End Select
End Sub

Private Sub Text1_LostFocus()
    Timer1.Enabled = False
End Sub

Private Sub Text1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
    If Button = vbRightButton Then
        Timer1.Enabled = True
        Timer1.Interval = 10
    End If
End Sub

Private Sub Text1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
    If Button = vbRightButton Then Timer1.Enabled = False
End Sub

Private Sub Timer1_Timer()
    Dim hMenu As Long, hSubMenu As Long, hID As Long, ExtraSubMenu As Long
'    'hMenu = GetActiveWindow
    hMenu = GetMenu(Me.hwnd)
'
    If GetMenuItemCount(hMenu) > 0 Then
        RemoveMenu hMenu, 0, MF_BYPOSITION Or MF_REMOVE
        RemoveMenu hMenu, 1, MF_BYPOSITION Or MF_REMOVE
    End If
'    Debug.Print hMenu
    hSubMenu = GetSubMenu(hMenu, 0)
   
    Debug.Print hSubMenu
    Call ShowWindow(hSubMenu, 0)
End Sub

A usercontrol example to build an Analog clock in Visual Basic 6.0

Download Source Code

Option Explicit
Private Type POINTAPI
    x As Double
    y As Double
End Type
Private oHrCenter As POINTAPI, oHrEnd As POINTAPI
Private oMinCenter As POINTAPI, oMinEnd As POINTAPI
Private oSecCenter As POINTAPI, oSecEnd As POINTAPI
Private m_Hour As Integer
Private m_Minute As Integer
Private m_Second As Integer
Private m_Radius As Double
Private Const PIE = 3.14159265358979

Private Sub Timer1_Timer()
    Call UserControl_Resize
End Sub

Private Sub UserControl_Initialize()
    UserControl.ScaleMode = vbPixels
End Sub

Private Sub DrawClock()
    UserControl.Cls
    m_Hour = VBA.hour(VBA.Now)
    m_Minute = VBA.Minute(VBA.Now)
    m_Second = VBA.second(VBA.Now)
    Call SetHour((m_Hour Mod 12))
    Call SetMinute(m_Minute)
    Call SetSecond(m_Second)
    Debug.Print (m_Second) & " : " & GetAngle(m_Second * 6)
    UserControl.Circle (oHrCenter.x, oHrCenter.y), m_Radius, RGB(255, 255, 255)
    UserControl.DrawWidth = 2    UserControl.Line (oHrCenter.x, oHrCenter.y)-(oHrEnd.x, oHrEnd.y)
    UserControl.DrawWidth = 1
    UserControl.Line (oMinCenter.x, oMinCenter.y)-(oMinEnd.x, oMinEnd.y)
    UserControl.Line (oSecCenter.x, oSecCenter.y)-(oSecEnd.x, oSecEnd.y)
End Sub

Private Sub UserControl_ReadProperties(PropBag As PropertyBag)
    If UserControl.Ambient.UserMode = True Then
        Timer1.Enabled = True
        Timer1.Interval = 1000
    End If
End Sub

Private Sub UserControl_Resize()
    UserControl.Height = UserControl.Width
    m_Radius = UserControl.ScaleWidth / 2 - 1
    DrawClock
End Sub

Public Sub SetHour(hour As Integer)
    oHrCenter.x = UserControl.ScaleWidth / 2
    oHrCenter.y = UserControl.ScaleHeight / 2
    oHrEnd.x = (m_Radius - 10) * XValue(hour * 30) + oHrCenter.x
    oHrEnd.y = (m_Radius - 10) * YValue(hour * 30) + oHrCenter.y
End Sub

Public Sub SetMinute(min As Integer)
    oMinCenter.x = UserControl.ScaleWidth / 2
    oMinCenter.y = UserControl.ScaleHeight / 2
    oMinEnd.x = (m_Radius - 5) * XValue(min * 6) + oMinCenter.x
    oMinEnd.y = (m_Radius - 5) * YValue(min * 6) + oMinCenter.y
End Sub

Public Sub SetSecond(second As Integer)
    oSecCenter.x = UserControl.ScaleWidth / 2
    oSecCenter.y = UserControl.ScaleHeight / 2
    oSecEnd.x = (m_Radius) * XValue(second * 6) + oSecCenter.x
    oSecEnd.y = (m_Radius) * YValue(second * 6) + oSecCenter.y
 '   Debug.Print (second * 6)

End Sub

Private Function GetAngle(ang As Double) As Double
'    If ang > 0 And ang <= 90 Then
'      GetAngle = 90 - ang
'    Else
        GetAngle = (450 - ang)
'    End If
End Function

Private Function YValue(ByVal angle As Double) As Double
  Select Case angle
    Case 0 To 90, 360 To 450
      YValue = -Math.Sin(GetAngle(angle) * 2 * PIE / 360)
    Case 90 To 180
      YValue = -Math.Sin(GetAngle(angle) * 2 * PIE / 360)
    Case 180 To 270
      YValue = -Math.Sin(GetAngle(angle) * 2 * PIE / 360)
    Case 270 To 360
      YValue = -Math.Sin(GetAngle(angle) * 2 * PIE / 360)
  End Select
End Function

Private Function XValue(ByVal angle As Double) As Double
  Select Case (angle)
    Case 0 To 90, 360 To 450
      XValue = Math.Cos(GetAngle(angle) * 2 * PIE / 360)
    Case 90 To 180
      XValue = Math.Cos(GetAngle(angle) * 2 * PIE / 360)
    Case 180 To 270
      XValue = Math.Cos(GetAngle(angle) * 2 * PIE / 360)
    Case 270 To 360
      XValue = Math.Cos(GetAngle(angle) * 2 * PIE / 360)
  End Select
End Function

How to browse folder using Windows API

Download Source Code

option explicit

Private Type BrowseInfo
     hwndOwner As Long
     pIDLRoot As Long
     pszDisplayName As Long
     lpszTitle As Long
     ulFlags As Long
     lpfnCallback As Long
     lParam As Long
     iImage As Long
End Type
Private Declare Sub CoTaskMemFree Lib "ole32.dll" (ByVal hMem As Long)
Private Declare Function lstrcat Lib "kernel32" Alias "lstrcatA" (ByVal lpString1 As String, ByVal lpString2 As String) As Long
Private Declare Function SHBrowseForFolder Lib "shell32" (lpbi As BrowseInfo) As Long
Private Declare Function SHGetPathFromIDList Lib "shell32" (ByVal pidList As Long, ByVal lpBuffer As String) As Long
Private Declare Function getTempPathAPI Lib "kernel32" Alias "GetTempPathA" (ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Private Declare Function GetFullPathName Lib "kernel32" Alias "GetFullPathNameA" (ByVal lpFileName As String, ByVal nBufferLength As Long, ByVal lpBuffer As String, ByVal lpFilePart As String) As Long
Private Const MAX_PATH = 1024

Private Sub Command1_Click()
  Dim b As BrowseInfo
  MsgBox BrowseForFolder(0, "Browse", "c:\")
End Sub

Public Function BrowseForFolder(hwndOwner As Long, sPrompt As String, ByVal StartLocation As String) As String
    'Declare variables to be used
     Dim iNull As Integer
     Dim lpIDList As Long
     Dim lResult As Long
     Dim sPath As String
     Dim BI As BrowseInfo
    'Initialise Type variables
     With BI
        .hwndOwner = hwndOwner
        .lpszTitle = lstrcat(sPrompt, "")
        .ulFlags = BIF_RETURNONLYFSDIRS
        .lpfnCallback = getFunctionLong
        .lParam = lstrcat(StartLocation, "")
     End With
    'Call the browse for folder API
     lpIDList = SHBrowseForFolder(BI)
    'Get the resulting string path
     If lpIDList Then
        sPath = String$(MAX_PATH, Chr$(0))
        lResult = SHGetPathFromIDList(lpIDList, sPath)
        Call CoTaskMemFree(lpIDList)
        iNull = InStr(sPath, vbNullChar)
        If iNull Then sPath = Left$(sPath, iNull - 1)
     End If
    'If cancelled, set sPath = ""
     BrowseForFolder = sPath
End Function

Sunday 29 September 2013

Retrieve Data from Oracle Database with ADODB using ASP

<!DOCTYPE html>
<html>
<body>
<%
set con=Server.CreateObject("ADODB.Connection")
con.Open("Provider=MSDAORA.1;user id=provide user name;password=provide password;datasource=service name in TNSNAMES.ORA file")

set rs = Server.CreateObject("ADODB.recordset")
rs.Open "select filed1,filed2.... from tablename", con

%>

<table border="1" width="100%">
<%do until rs.EOF%>
    <tr>
    <%for each orec in rs.Fields%>
       <td><%Response.Write(
orec.value)%></td>
    <%next
    rs.MoveNext%>

    </tr>
<%loop
rs.close
con.close
%>

</table>
</body>
</html>

Add dynamically values to a combo list in Oracle D2k Forms

-- first  method using creategroupfromquery function creating a recordgroup dynamically
declare
myrec RECORDGROUP;
begin
if not id_null(myrec) then
   delete_group(myrec);
end if;
  myrec := CREATEGROUPFROMQUERY('otmp','select  decode(emp_grade,'S','Staff', 'W', 'Worker','') ,emp_grade from employee_master');

if poplatre_group(myrec) =0 then
    clear_list('control.combolist1');
    populate_list('control.combolist1',myrec);   
end if; 
end;

--second method, using a explicit cursor and add to list using add_list_element

declare
cursor rec is  select  decode(emp_grade,'S','Staff', 'W', 'Worker','') emp_grade_desc ,emp_grade from employee_master;
reccount  number:=0;
clear_list('control.combolist1');
begin
 for o in rec loop
   add_list_element('control.combolist1',reccount,o.emp_grade_desc,o.emp_grade);
   reccount :=reccount +1;
 end loop;
end;

Creating an inilne view in SQL,PL/SQL

Here is an example of an inline view SQL.
Lets take for example three tables/

1. tbl_withdrawdeposit
    memb_id  -- reference to p_k to tbl_member_master
    trans_date  --Date of transaction
    amount       -- Amount of transaction
    transaction_type -- Type of Transaction ('W'-withgdrawal, 'D' - deposit
 2. tbl_loansvr
    memb_id  -- reference to p_k to tbl_member_master
    trans_date  --Date of transaction
    amount       -- Amount of transaction
    transaction_type -- Type of Transaction ('W'-withgdrawal, 'D' - deposit

3. tbl_member_master
    member_id   member_id primary key
    member_name  --name of the member
    acc_no              -- account number of the member

 we are going to write an inline view that will show the name,account number of all the member who
 have deposited amount/ returned loan amount more than 1,00,00,00 in the year 2012


select A.acc_no,member_name from
(
(select a.acc_no,a.member_name,nvl(b.amount,0) amount
 from tbl_member_master a,tbl_loansvr b
 where b.memb_id = a.memb_id
 and to_char(trans_date,'rrrr'')='2012'
 and trans_type='D'

union
(
select a.acc_no,a.member_name,nvl(b.amount,0) amount
 from tbl_member_master a,tbl_withdrawdeposit b
 where b.memb_id = a.memb_id
 and to_char(trans_date,'rrrr'')='2012'

)  tbl_all

group by tbl_all.acc_no,tbl_all.member_name
having sum(tbl_all.amount)>1000000

We have created an inline view by union of two tabl and selected acc_no and member_name from
that view naming it tbl_all. Added summed up amount to having clause, grouping by acc_no and member_name, (iline view can contain record from both the table for a single member.).


Wednesday 25 September 2013

How to load a picture from resource file (.res) in Visual Basic

option explicit
Private Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long)
Private Declare Function CreateStreamOnHGlobal Lib "ole32" (ByVal hGlobal As Long, ByVal fDeleteOnRelease As Long, ppstm As Any) As Long
Private Declare Function GlobalAlloc Lib "kernel32" (ByVal uFlags As Long, ByVal dwBytes As Long) As Long
Private Declare Function GlobalLock Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Function GlobalUnlock Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Function OleLoadPicture Lib "olepro32" (pStream As Any, ByVal lSize As Long, ByVal fRunmode As Long, riid As Any, ppvObj As Any) As Long

Private Function SetImageFromResource(Optional ByRef PB As Object = Nothing, _
                                Optional ByVal RID As String = "") As IPictureDisp
    Dim bImage() As Byte
    bImage() = LoadResData(RID, "CUSTOM")
    Set SetImageFromResource = ArrayToPicture(bImage(), 0, UBound(bImage) + 1)
    If Not PB Is Nothing Then
        If PB.Picture <> SetImageFromResource Then
            PB.Picture = SetImageFromResource
        End If
    End If
    Erase bImage
End Function

Private Function ArrayToPicture(inArray() As Byte, Offset As Long, size As Long) As IPicture
    Dim o_hMem As Long
    Dim o_lpMem As Long
    Dim aGUID(0 To 3) As Long
    Dim IIStream As IUnknown

    aGUID(0) = &H7BF80980    ' GUID for stdPicture
    aGUID(1) = &H101ABF32
    aGUID(2) = &HAA00BB8B
    aGUID(3) = &HAB0C3000

    o_hMem = GlobalAlloc(&H2&, size)
    If Not o_hMem = 0& Then
        o_lpMem = GlobalLock(o_hMem)
        If Not o_lpMem = 0& Then
            CopyMemory ByVal o_lpMem, inArray(Offset), size
            Call GlobalUnlock(o_hMem)
            If CreateStreamOnHGlobal(o_hMem, 1&, IIStream) = 0& Then
                Call OleLoadPicture(ByVal ObjPtr(IIStream), 0&, 0&, aGUID(0), ArrayToPicture)
            End If
        End If
    End If

End Function

Search entire XML tree with recursive method XML DOM, Visual Basic 6.0


Private function SearchXMLNode(xmlNode as Object,nodeName as string) as Object
  dim ochild,ochild1
  for each ochild in xmlNode.childNodes
     if  vba.lcase$(ochild.nodename) = vba.lcase$(nodeName) then           set SearchXMLNode =  ochild
           exit function
     end if
     SearchXMLNode = SearchXMLNode(ochild)
     if not SearchXMLNode is nothing then exit function
  next ochild
End Function

Reading an excel file using Microsoft excel object in Visual Basic.

option explicit
Private exc as Object
Private wb as Object
Private ws as Object

Private sub ImportExcelData(excelFileName as String)
    if exc is nothing then
       set exc = CreateObject("Excel.Application")
   end if
   if exc is nothing then
        call msgbox("Failed to load excel application")
        exit sub
   end if
   set wb = exc.Workbook.Open(excelFileName)
   if wb is nothing then
        call msgbox("Failed to open excel file")
        exit sub
   end if

' please note that this program is for file without password, open file with password will be on the
 ' next blog
  set ws = wb.Sheets("sheet1")

   if ws is nothing then
        call msgbox("Failed to load worksheet")
        exit sub
   end if
   dim r as long
   r=1
   while not ws.Range("A" & r ":A" & r).value<> ""
      debug.print  ws.Range("A" & r ":A" & r).value
      r=r+1
   wend
   wb.close true
   set wb=nothing
   exc.quit
   set exc=nothing
End Sub

How to use Split Function in Visual Basic 6.0

Split function in VB 6.0 actually splits a string based on delimiter provided and returns it into an
array.

Suppose there is a string like this "Ram#23#Male#M.G.Road"
Now if we split this string with delimiter # into a variant array name arr the result will be
arr(0)="Ram"
arr(1)="23"
arr(0)="Male"
arr(0)="M.G.Road"

Here is the program written into a function

private sub SplitString(strTxt as string,delimiter as string)
  dim var
  dim i as integer
  var = VBA.Split(strTxt,delimiter)
   for i=lbound(var) to ubound(var)
       debug.print var(i)
   next i
end sub

'In form load event the function is called with 2 parameters, a string and a delimiter #
private sub Form_Load()
  call splitstring( "Ram#23#Male#M.G.Road","#")
end sub

Using Minus query in SQL.

(select * from employee_salary)
minus
(select * from employee_salary where to_date(pay_month_year,'mm/rrrr')<='01-dec-2012)

Just look into the above query.

Sql in the first line returns all the records.
Now i apply minus with the secong query which returns all the records where pay_month_year is less
than equal to december-2012. So the result will be all the records where pay_month_year starting from january-2013. (please note that pay_month_year is in the format mm/rrrr i.e. 12/2012.

Lets take another example.

(select * from employee_salary)
minus
(select * from employee_salary where gross_pay>=20000)

second query returns all the records whose gross_pay is greater than 20000, and first query returns
all the records so result of the query will return all the records where gross_pay is less than 20000.

How to extract day, month and year from a date field in SQL Server database sql query.

Here is a method to extract day, month and year from date field in sql server sql database.

Say their is a table named employee_attendance with field attn_date

we will get the day , month and year separately from the date field

Here is the SQL statement

select emp_id,substring(conver(char,attn_date,103),1,2) dy,
          substring(conver(char,attn_date,103),4,2) mon,
          substring(conver(char,attn_date,103),7,4) yr
          from employee_attendance
          order by emp_id

Now look into the sql statement where day, month and year is extracted.

Lets start with day  substring(conver(char,attn_date,103),1,2)

convert function with third parameter 103 convert date to dd/mm/yyyy
format, so 19th april 2013 is converted to 19/04/2013 and char converts the date to string, because if
we do not convert character to string then we cannot use substring function onto it. substring function
actually extract the pattern from the date string.

substring('19/04/2013',1,2) --> 19
substring('19/04/2013',4,2) --> 94
substring('19/04/2013',7,4) --> 2013


Using case statement in sql query on SQLServer database.

Say there is a table employee_master and we are going to use 5 fields

emp_code, emp_name, emp_sex, emp_grade and emp_category

last three fields
i.   emp_sex have value 'M' and 'F' (need to output 'Male' for 'M' and 'Female' for 'F')
ii.  emp_grade have value 'S' and 'W' (need to output 'Staff' for 'S' and 'Worker' for 'W')
iii. emp_category have value 'P' and 'T' (need to output 'Permanent' for 'P' and 'Temporary' for 'T')

Now this is the select statement using case statement

select emp_code,
          emp_name,
          (case when emp_sex='M' then 'Male' else case when emp_sex='F' then 'Female' else '' end end)
          as emp_sex,
          (case when emp_grade='S' then 'Staff' else case when emp_grade='W' then 'Worker' else '' end
          end)    as emp_grade,
          (case when emp_category='P' then 'Permanent' else case when emp_category='T' then
          'Temporary' else '' end) as emp_category
          from employee_master
          order by emp_code

       Now look into the case statement. For every case statement there is another nested case
       statement. "case when condition then value else (another nested case statement on the else part)
       end"

       I this way we can write multiple case statement just like next if else statement.
      
        end)    as emp_grade,
       



Oracle PL/SQL cursor example


--A Procedure ProcCur is created
create or replace procedure ProcCur is

--A cursor is declared selecting 2 fields from employee_master emp_code and emp_name
cursor rec is select emp_code,emp_name from employee_master
              where emp_grade='S'
              order by emp_code;
-- 2 variables are declared of filed type emp_code and emp_name
ecode employee_master.emp_code%type;
ename employee_master.emp_name%type;
begin

-- add this  statement otherwise  ORU-10027: buffer overflow will rise
  dbms_output.enable(1000000);

-- cursor opened
  open rec;

-- column header printed
  dbms_output.put_line(lpad('Code',10,' ')||lpad('Name',60,' '));

-- loop started
  loop

--   current record fetched into ecode and ename. remember that number of fields in the cursor should
--   be equal to number of variables on which records are fetched.
    fetch rec into ecode,ename;

--  exit the loop if when no more records are fetched
    exit when rec%NOTFOUND;

-- fetched values printed
    dbms_output.put_line(lpad(ecode,10,' ')||lpad(ename,60,' '));

-- end of loop
  end loop;

--end of procedure
end TestProc;

-------------------------------------------------------------------------------------------------------------------------
-- Alternate method using for loop, this is the easiest and shortest wa.
-------------------------------------------------------------------------------------------------------------------------

--A Procedure ProcCur is created
create or replace procedure ProcCur is

begin

-- add this  statement otherwise  ORU-10027: buffer overflow will rise
  dbms_output.enable(1000000);

-- column header printed
  dbms_output.put_line(lpad('Code',10,' ')||lpad('Name',60,' '));

-- loop started
  for rec in (select emp_code,emp_name from employee_master
              where emp_grade='S'
              order by emp_code)

  loop

-- fetched values printed
    dbms_output.put_line(lpad(rec.emp_code,10,' ')||lpad(rec.emp_name,60,' '));

-- end of loop
  end loop;

--end of procedure
end TestProc;

Tuesday 24 September 2013

How to create a dynamic combolist and add data from the database in HTML, Javascript

<html>
<head>
<script>
function myFunction()
{
var con = new ActiveXObject('ADODB.Connection');
var rs = new ActiveXObject('ADODB.Recordset');
con.ConnectionString="Provider=MSDAORA.1;User ID=hr_man;Password=hr_man;Data Source=ORCL;Persist Security Info=False";
con.Open();
rs.Open("select emp_id,emp_name from employee_master order by emp_name").value,con);
var s="<select>";
while(!rs.EOF)
{
s+="<option value='" + rs.Fields("emp_id").Value + "'>" +   rs.Fields("emp_name").Value  + "</option>";
rs.MoveNext();
}
s+-"</select> ";
rs.Close();
con.close;
document.getElementById("comboDiv").innerHTML=s;
}
</script>
</head>
<body>
<div id="comboDiv">
</div>
</body>
 </html>

Monday 23 September 2013

How to Connect to Oracle and retrieve data using ActiveX object in Javascript

<html>
<head>
<script>
function myFunction()
{
var con = new ActiveXObject('ADODB.Connection');
var rs = new ActiveXObject('ADODB.Recordset');
con.ConnectionString="Provider=MSDAORA.1;User ID=hr_man;Password=hr_man;Data Source=ORCL;Persist Security Info=False";
con.Open();
rs.Open(document.getElementById("sqlTxt").value,con);
var s="<table><tr>";
for(var i=0;i<rs.Fields.count;i++)
s+="<td>" + rs.Fields(i).Name + "</td>";
s+="</tr> <tr>";
while(!rs.EOF)
{
for(var i=0;i<rs.Fields.count;i++)
s+="<td>" + rs.Fields(i).Value + "</td>";
rs.MoveNext();
}
s+-"</tr></table>";
rs.Close();
con.close;
document.getElementById("outputSection").innerHTML=s;
}
</script>
</head>
<body>
<div id="inputSection">
<textArea id="sqlTxt"></textArea>
<input type="Button" id="btn" value="Execute" onclick="myFunction();"/>
</div>
<div id="outputSection">
</div>
</body>
 </html>

Sunday 22 September 2013

How to invoke Microsoft Common dialog box dynamically using createobject

option explicit

private function OpenDialog() as String
  dim dlg as object
  on error goto  OpenDialog_Error
  set dlg=CreateObject("MSCOMDlg.Commondialog")
  if dlg is nothing then exit sub
  dlg.Filter="All Files (*.*)|*.*"
  dlg.CancelError=True
  dlg.ShowOpen
  OpenDialog=dlg.FileName
 exit sub
OpenDialog_Error:
end sub

private sub Form_Load()
    dim fileName as string
    fileName=OpenDialog()
end sub

Create XML with XML Document Object

option explicit
private xmlObj as Object  ' xml object
private xmlHead as object  ' xml node
private xmlNode as object  ' xml node
private xmlChildNode as object ' xml nodePrivate sub CreateXML
   set xmlObj = CreateObject("MSXML2.DOMDocument") ' dynamic xmlobject created
   if xmlObj is nothing then  ' if failed then exit procedure
        exit sub
  end if
  set xmlHead = xmlObj.createElement("Parent")  'first xml node created , head node
  set xmlNode = xmlObj.createElement("Child1")  ' xmlnode created, first child of head
  cal xmlHead.appenChild(xmlNode) ' set to child of head
  set xmlChildNode= xmlObj.createElement("Child1ofChild1")  ' xmlnode created
  call xmlNode.AppendChild(xmlChildNode)  ' set to first child of the first child of head
  set xmlChildNode= xmlObj.createElement("Child2ofChild1")  ' xmlnode created
  call xmlNode.AppendChild(xmlChildNode) ' set to second child of the first child of head
  set xmlNode = xmlObj.createElement("Child2") ' xmlnode created, second child of head
  call xmlHead.appenChild(xmlNode)  ' set to child of head
   set xmlChildNode= xmlObj.createElement("Child1ofChild2")  ' xmlnode created
  call xmlNode.AppendChild(xmlChildNode) ' set to first child of the second child of head
  set xmlChildNode= xmlObj.createElement("Child2ofChild2")   ' xmlnode created
  call xmlNode.AppendChild(xmlChildNode) ' set to second child of the second child of head
 debug.print xmlHead.documentElement.xml
 set xmlnode=nothing
set xmlchildnode=nothing
set xmlobj=nothing
End Sub

A simple subclassing example

Module Code
option explicit
Private Const GWL_WNDPROC = (-4)
Private Const WM_LBUTTONUP = &H202
Private Const WM_MOUSEMOVE = &H200
Private Declare Function SetWindowLong Lib "User32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
private originalHandler as long

'Window hooked with Customized function Winproc returning the original handle 
public sub SubClassWindow(handle as long)
   oldWindowHandler = SetWindowLong(handler, GWL_WNDPROC, AddressOf WinProc)
End Sub

'Window restore to it's original Windows procedire
public sub UnSubClass(handle as long)
   call setWindowsLong(handler,, GWL_WNDPROC, oldWindowHandler)
End Sub

'Customized Windows function

private sub WinProc(ByVal hWnd As Long, ByVal MSG As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
   select case MSG
      ' If user released it's left mouse button
       Case WM_LBUTTONUP
             debug.print "Left Button Up"
       ' If user moved it's mouse
       Case WM_MOUSEMOVE
            debug.print "Mouse Moving"
   End select
  ' Original windows procedure invoked, this is necessary other wise program will crash
  WinProc = CallWindowProc(OldHandler, hWnd, MSG, wParam, lParam)
End Sub

Validate email with Regxp (regular expression) in Visual Basic 6.0

option explicit
private Function IsValidEmail(ByVal emailStr As String) As Boolean
   
    ' if email is blank then return
    If VBA.Len(VBA.Trim$(emailStr)) = 0 Then
        IsValidEmail = False
        Exit Function
    End If
  
   
    Dim regex  As  Object
    Dim cMatch  As  Object ' For MatchCollection

    Set regex = CreateObject("VBScript.RegExp")  ' Object created with VBscript.RegExp class.

    regex.MultiLine = False ' email is a single line expression therefore multiline is set to false

    regex.IgnoreCase = False  ' Case sensitive checking is set to true

    regex.Pattern = "\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b" ' regular expression pattern

    Set cMatch = regex.Execute(emailStr)
   
    IsValidEmail = Not (cMatch.Count = 0) ' If no matches found then email is invalid

    ' first item of  collection cMatch return length of the email is it is not equal to the length of meail email is invalid.
    If IsValidEmail Then IsValidEmail = IIf(VBA.Len(cMatch.Item(0)) = VBA.Len(emailStr), True, False)
    'Release memory
    Set cMatch = Nothing
    Set regex = Nothing
End Function

Private sub Form_Load()
    if not IsValidEmail("subhroneelganguly@gmail.com")  then
        msgbox "Email not valid"
   else
      msgbox "Email valid"
    end if
End Sub

How to get list of all files and folders starting from a specific path - Visual Basic 6.0

option explicit
private fs as Object     ' declared for filesystem object
private flds as Object    ' declared for main folder object
private fld as Object    ' declared for folder object
private fl as Object      ' declared for file object

private sub ListFolderAndFiles(pathname as String)
   create file system object
   set fs=CreateObject("Scripting.FileSystemObject")

   'exit if fails to create file system object
   if fs is nothing then exit sub

  ' exit is folder does not exists in the pathname
  if not fs.isFolderExists(pathname) then
      msgbox "Ivalid path or folder name"
      exit sub
  end if
 
   ' Set the folder object from the specified path
   set flds=fs.GetFolder(pathName)
  
   ' exit if failed to create folder object
   if not flds is nothing then exit sub

  ' enumerate through all folders in the parent folder
   for each fld in flds.Folder
     ' enumerate through all files in the folder
       for each fl in fld.Files
           ' add filename along with it's containing folder name  in the listbox
           call list1.AddItem(fld.Name & "-" & fl.Name)
       next fl
   next fld
 
   'release object from memory
   set flds=nothing
   set fl=nothing
   set fs=nothing
End Sub

Private Sub Form_Load()
     ' Calling procedure
     call ListFolderAndFiles("c:\MyLibrary")End Sub

How to enable, disable controls in your form in Visual Basic 6.0

' procedure will take parameters as following
  form object, enable or disable flag, types of controls to be enabled or disabled

option explicit
Private sub EnableDisableControls(frm as Object,flag as Boolean,ParamArray arg() as Variant)
   dim ctl
'   loop starts to fetch all controls in the form object
   for each ctl in frm.Controls
        dim i as integer
  'inner loop starts to navigate through arg from lower bound to upperbound for all the typename parameters passed by in the procedure

        for i=lbound(arg) to ubound(arg)
'typename return control type name, if it matches with the typename send in the argument then ctl.enabled state is set to flag value.
            if vba.lcase(vba.typename(ctl)) = vba.lcase(arg(i)) then
                 ctl.Enabled = flag
                 doevents
           end if
        next i
   next ctl
End Sub

Writing a simple Text Validation function in Visual Basic 6.0 IDE

option explicit
' Enum created for validation type
private enum enumValidation
   numericOnly
   alphabetOnly
end enum

private sub ValidateText(ctl as object,byref keyascii as integer,e as enumValidation)
   ' parameter ctl is a by reference to text object, keyascii is the ascii key code value pressed by  user send as byref so that we can modify the value, e is the validation type

          ' if the validation is not met type then keyascii is set to 0 which will prevent the value of the key pressed by user to be printered in the textbox

   select case e
      case numericOnly
        if not isNumeric(keyascii) then               keyascii=0
        end if
       case textOnly
        if  not (keyascii>=65 and keyascii<=90) or (keyascii>=97 and keyascii<=122)  then
               keyascii=0
        end if
        end select        
End Sub

private sub Text1_Keypress(KeyAscii as Integer)
    call ValidateText(text1,Keyascii,alphabetOnly)
End Sub

How to use extendable parameter list in functions using paramarray in Visual Basic 6.0

' This program will call a function which can take as many parameters as possible. Parameters not predefined.

option explicit

private sub PrintName(ParamArray arg() As Variant) ' argument is of type variant (can store any type of value) paramarray, function can be called with arguments which is flexible.

   dim i as integer
   for i=lbound(arg) to ubound(arg)
     ' lbound is the lower bound of the array and ubound is the upper bound of the array
       debug.print arg(i)
   next i
End Sub

How to get the list of all the controls in a form in Visual Basic 6.0

'This program will retrieve all the controls in the form and the name of the controls and their type in a list box.

option explicit
private ctl as object

private sub Form_Load()
   for each ctl in Me.Controls
      ' this listbox will contain name and types of all the controls including itself.
       list1.Additem ctl.Name & "," & vba.typename(ctl)
       doevents
   next ctl   
End Sub

How to get computer name using windows API in Visual Basic 6.0

' Platform : any windows OS
' Developing platform visual basic 6.0 (Visual Studio 6.0 IDE)
 '------------------------------------------------------------------------------------------------------------------
option explicit
' GetComputerName is a windows API to retrieve computer name
Private ComputerName as String
Private strBuffer As String
Private lngBufSize As Long
Private lngStatus As Long
private computername as string

Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Private sub Form_Load()

' before passing strBuffer as by reference to "GetComputerName" function, size need to be allocated for strBuffer which is assigned lngBufSize

    lngBufSize = 255  

    strBuffer = String$(lngBufSize, " ") ' Memory allocated for strBuffer

 ' lngStatus returns status for success or failure. return any non zero value for success. computer name is set in the strBuffer string and length of the string is assigned in lngBuffsize, i.e. if  computer name is "subhroneel" then strbuffer is set with "subhroneel" and lngBuffSize is set with 10

    lngStatus = GetComputerName(strBuffer, lngBufSize)

    If lngStatus <> 0 Then
        ' extra allocated space is truncated
        computername = Left(strBuffer, lngBufSize)
    End If

End Sub

How to get list of field names of a table using activex dataobject in VB6

Database used : Oracle 11g
Client used : Oracle Net8 client
Application developed in Visual Basic 6.0

We are going to print the output in a multiline textbox
'---------------------------------------------------------------------------------------------------------------------
' Declaration
option explicit
private con as ADODB.Connection
private rs as ADODB.Recordset

private sub Form_Load()
  set con = new ADODB.Connection
  if not con is nothing then exit sub

  con.ConnectionString="Provided=MSDAORA.1;user id=hr_db;password=hr_db;Datasource=ORA"  ' Datasource is the service name configure in TNSNAMES.ora file.

 con.Open

 rs.Open "select * from employee_master",con,adOpenDynamic
dim fld

text1.Text="List of field names in the table employee_master : "
if not rs.EOF
   for each fld in rs.Fields
     text1.text = text1.text & fld.Name & "," & vbcrlf
   next fld
end if
rs.close
con.close
set rs=nothing
set con=nothing
end sub

Saturday 4 May 2013

A simple program to compare to string whether they are equal or not

#include"stdio.h"
#include"conio.h"
#include"malloc.h"
int main()
{
char *firstString =(char*)malloc(100);
char *secondString =(char*)malloc(100);
void readString(char *);
void printString(char *);
int stringCompare(char *,char *);
int result;
clrscr();
printf("\nEnter First String : ");
readString(firstString);
printf("\nEnter Second String : ");
readString(secondString);
result=stringCompare(firstString,secondString);
if(result!=0)
printf("\nString are not equal");
else
printf("\nStrings are equal");
getch();
return 1;
}

//Function readString

void readString(char *s)
{
while((*s=getchar())!='\n')  // Read until user press enter key
*s++;
*s=NULL;
}


//Function printString

void printString(char *s)
{
while(*s!=NULL)
putchar(*s++);
}


//Compare to string and returns 0 if they are equal else return 1
int stringCompare(char *first,char *second)
{
while(*first&&*second)
if(*first++!=*second++)
return 1;
return 0;
}

A Simple pointer example to Read String and Print the string

#include"stdio.h"
#include"conio.h"
#include"alloc.h"

int main()
{

char *s=(char*)malloc(100); // Declaring pointer variable to char
                            // data type and dynamically allocating memory
void readString(char *);     // Prototype for readString
void printString(char *);   // Prototype for printString
clrscr();
printf("\nEnter your name : ");
readString(s);
printf("\nYour name is ");
printString(s);
getch();
return 1;

}

//Function readString

void readString(char *s)
{
while((*s=getchar())!='\n')  // Read until user press enter key
*s++;
*s=NULL;
}


//Function printString

void printString(char *s)
{
while(*s!=NULL)
putchar(*s++);
}

How to print the nth number of a Fibonacci series by recursive method in C programming

#include"stdio.h"
#include"conio.h"
void main()
{
int num;
long fibo(int);
void printFiboSeries(int);
clrscr();
printf("\nEnter number : ");
scanf("%d",&num);
printFiboSeries(num);
getch();
}
long fibo(int n)
{
if(n<=2)
return 1;
return fibo(n-1) + fibo(n-2);
}

void printFiboSeries(int n)
{
if(n<1 br="">return;
printFiboSeries(n-1);
printf("%d ",fibo(n)); // printf is called when all function call of printFiboSeries is popped up from
                                   // the stack
}

Suppose input variable is 5 then the result should be 5

                                                            fibo(5)          
                               fibo(4)                      +                    f ibo(3)
           fibo(3)             +         f ibo(2)      +        fibo(2)        +     fibo(1)
fibo(2)   +   fibo(1)     +              1           +             1            +        1
   1         +       1          +              1           +             1            +        1         =  5