Monday, March 23, 2009

Boot Your Own Hello World Application

In this blog I am going to teach u how to write Assembly x86 code. (Execute it by) Booting it from a USB drive or floppy drive and run it!...

1. Custom Master Boot code.
2. The Boot Signature.
3. Windows Xp Master Boot Code.
4. Tools to write into the boot sector.
5. Hello World Boot code.
6. Bios Settings.
7. Assembly translation


Custom Master Boot code

The first 512 bytes of memory in any secondary storage device is the The Master boot code. My aim is to let u write directly into the master boot record.


The Boot Signature (55AAh)


The value 55AA in hex at last Memory location of the boot sector ie. 01FE(value 55) and 01FF(value AA) in Absolute Sector 0(Cylinder 0, Head 0, Sector 1) Represents the boot signature.. All bootable boot enabled devices must have a boot signature.


Windows Xp Master Boot Code


Absolute Sector 0 (Cylinder 0, Head 0, Sector 1)

0 1 2 3 4 5 6 7 8 9 A B C D E F
0000 33 C0 8E D0 BC 00 7C FB 50 07 50 1F FC BE 1B 7C 3.....|.P.P....|
0010 BF 1B 06 50 57 B9 E5 01 F3 A4 CB BD BE 07 B1 04 ...PW...........
0020 38 6E 00 7C 09 75 13 83 C5 10 E2 F4 CD 18 8B F5 8n.|.u..........
0030 83 C6 10 49 74 19 38 2C 74 F6 A0 B5 07 B4 07 8B ...It.8,t.......
0040 F0 AC 3C 00 74 FC BB 07 00 B4 0E CD 10 EB F2 88 ..<.t...........
0050 4E 10 E8 46 00 73 2A FE 46 10 80 7E 04 0B 74 0B N..F.s*.F..~..t.
0060 80 7E 04 0C 74 05 A0 B6 07 75 D2 80 46 02 06 83 .~..t....u..F...
0070 46 08 06 83 56 0A 00 E8 21 00 73 05 A0 B6 07 EB F...V...!.s.....
0080 BC 81 3E FE 7D 55 AA 74 0B 80 7E 10 00 74 C8 A0 ..>.}U.t..~..t..
00A0 00 B4 08 CD 13 72 23 8A C1 24 3F 98 8A DE 8A FC .....r#..$?.....
00B0 43 F7 E3 8B D1 86 D6 B1 06 D2 EE 42 F7 E2 39 56 C..........B..9V
00C0 0A 77 23 72 05 39 46 08 73 1C B8 01 02 BB 00 7C .w#r.9F.s......|
00D0 8B 4E 02 8B 56 00 CD 13 73 51 4F 74 4E 32 E4 8A .N..V...sQOtN2..
00E0 56 00 CD 13 EB E4 8A 56 00 60 BB AA 55 B4 41 CD V......V.`..U.A.
00F0 13 72 36 81 FB 55 AA 75 30 F6 C1 01 74 2B 61 60 .r6..U.u0...t+a`
0100 6A 00 6A 00 FF 76 0A FF 76 08 6A 00 68 00 7C 6A j.j..v..v.j.h.|j
0110 01 6A 10 B4 42 8B F4 CD 13 61 61 73 0E 4F 74 0B .j..B....aas.Ot.
0120 32 E4 8A 56 00 CD 13 EB D6 61 F9 C3 49 6E 76 61 2..V.....a..Inva
0130 6C 69 64 20 70 61 72 74 69 74 69 6F 6E 20 74 61 lid partition ta
0140 62 6C 65 00 45 72 72 6F 72 20 6C 6F 61 64 69 6E ble.Error loadin
0150 67 20 6F 70 65 72 61 74 69 6E 67 20 73 79 73 74 g operating syst
0160 65 6D 00 4D 69 73 73 69 6E 67 20 6F 70 65 72 61 em.Missing opera
0170 74 69 6E 67 20 73 79 73 74 65 6D 00 00 00 00 00 ting system.....
0180 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
0190 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
01A0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
01B0 00 00 00 00 00 2C 44 63 B5 EB 31 E0 00 00 80 01 .....,Dc..1.....
01C0 01 00 07 FE BF 82 3F 00 00 00 84 9E 9D 00 00 00 ......?.........
01D0 81 83 05 FE FF FF C3 9E 9D 00 FE F2 0A 04 00 00 ................
01E0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
01F0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 55 AA ..............U.


Tools to write into the boot sector.

The trick here is to write into the physical disk and not just Partitioned/Formatted drives.
To write into the boot sector I Recommend Hexworkshop .Its a hex editor with total access to all writable drives (cd writing not supported for obvious reasons).Especial recommend for USB boot sector writing.

Hello World Boot code.

Open hexworkshop. Next from Disk Menu(in the main menu)Click Open Drive. Important In the open'd Dialog box choose the "Physical Disk" from the select menu. One of the displayed disks will be ur USB Disk Choose and click Ok. Warning! hex Workshop Can Destroy Data on ur Hard disk or usb and even cause windows to stop booting if not used correctly.

The code:

Absolute Sector 0 (Cylinder 0, Head 0, Sector 1)
0 1 2 3 4 5 6 7 8 9 A B C D E F
00000000 31 C0 8E D0 66 BC 00 7C FB 66 B8 C0 07 8E D8 90 1...f..|.f......
00000010 B4 00 B0 00 CD 10 B0 00 B4 05 CD 10 B5 00 B1 07 ................
00000020 B4 01 CD 10 B6 09 B2 09 B7 00 B4 02 CD 10 8C D8 ................
00000030 8E C0 B4 13 B0 00 B7 00 B3 0F B9 0C 00 B6 09 B2 ................
00000040 09 BD 50 00 CD 10 B7 00 B4 08 CD 10 EB FE CD 19 ..P.............
00000050 68 65 6C 6C 6F 20 77 6F 72 6C 64 21 90 90 90 90 hello world!....
00000060 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
00000070 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
00000080 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
000000A0 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
000000B0 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
000000C0 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
000000D0 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
000000E0 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
000000F0 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
00000100 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
00000110 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
00000120 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
00000130 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
00000140 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
00000150 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
00000160 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
00000170 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
00000180 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
00000190 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
000001A0 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
000001B0 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
000001C0 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
000001D0 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
000001E0 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ................
000001F0 90 90 90 90 90 90 90 90 90 90 90 90 90 90 55 AA ..............U.

Easy TO copy version:
31 C0 8E D0 66 BC 00 7C FB 66 B8 C0 07 8E D8 90
B4 00 B0 00 CD 10 B0 00 B4 05 CD 10 B5 00 B1 07
B4 01 CD 10 B6 09 B2 09 B7 00 B4 02 CD 10 8C D8
8E C0 B4 13 B0 00 B7 00 B3 0F B9 0C 00 B6 09 B2
09 BD 50 00 CD 10 B7 00 B4 08 CD 10 EB FE CD 19
68 65 6C 6C 6F 20 77 6F 72 6C 64 21 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
90 90 90 90 90 90 90 90 90 90 90 90 90 90 55 AA


Bios Settings.

boot the computer by setting the first boot device as the usb flash drive.to do this u need to hit del key before windows loads up. go to the boot menu set the first boot device as the device in which u have ur bootsector code. save and exit bios setup. Don't exit without saving if u want the settings to be saved.Warning! can cause windows to stop booting if not done correctly.Maybe even fry ur chip if u mess around too much.


Assembly translation



cli
xor ax,ax
mov ss,ax
mov esp,66FB7C00h
mov ax,07C0h
mov ds,ax
nop
mov ah,00h
mov al,00h
int 10h
mov al,00h
mov ah,05h
int 10h
mov ch,00h
mov cl,07h
mov ah,01h
int 10h
mov dh,09h
mov dl,09h
mov bh,00h
mov ah,02h
int 10h
mov ax,ds
mov es,ax
mov ah,13h
mov al,00h
mov bh,00h
mov bl,0Fh
mov cx,000ch
mov dh,09h
mov dl,09h
mov bp,offset txt ; error prone cause it can point to 150
                  ; insted of 50 might have to correct that

int 10h
mov bh,00h
mov ah,08h
int 10h
loop:
jmp short loop
int 19h
txt:
db 'hello world!'





Nbasm is a Good tool to Tanslate each of these code line to get its x86 binary equilvalant.



Saturday, March 21, 2009

Format Numbers

//Format to number like this 10, 7.5, 0, 2.33
function formatNumber(amount) {
var i = parseFloat(amount);
if(isNaN(i)) { i = 0.00; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
s = minus + s;
return s;
}

//Format to currency like this 0.00, 10.00, 7.50, 2.33
function formatCurrency(amount) {
var i = parseFloat(amount);
if(isNaN(i)) { i = 0.00; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if(s.indexOf('.') < 0) { s += '.00'; }
if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
s = minus + s;
return s;
}

Thursday, March 19, 2009

C Program Handling Mouse

#include <iostream.h>
#include <dos.h>
#include <conio.h>

void showm()
{
_AX = 1;
geninterrupt(0x33);
}

unsigned x = 0,y= 0, button;

void updatestatus()
{
_AX = 3;
geninterrupt(0x33);
x = _CX;
y = _DX;
button = _BX;
}

void main()
{
clrscr();

_setcursortype(_NOCURSOR);

showm();

while(!kbhit())
{
updatestatus();

textcolor(GREEN);
gotoxy(5,2);cprintf("X = %0.2d", (x / 8 +1));
gotoxy(5,3);cprintf("Y = %0.2d", (y / 8 + 1));
gotoxy(5,4);cprintf("Button = %d", button);

}

}

Tuesday, March 17, 2009

C Program Selection Sort

// Program for Selection Sort

#include <iostream.h>
#include <conio.h>



//----------------------------------------------------------------------

void Selectionsort ( int array[] , int UB )
{
for ( int i = 0 ; i <= UB ; i++ )
for ( int j=i+1 ; j<=UB ; j++ )
{
if ( array [i] > array [j] )
{
int temp = array [i] ;
array [i] = array[j] ;
array [j] = temp ;

}
}
}


void Showarray ( int array[] , int UB )
{
gotoxy ( 1,2 ) ;
cout << "\n" ;

for ( int i = 0 ; i <= UB ; i++ )
{
cout << array [i] << endl ;
}

}

//----------------------------------------------------------------------

void main ()
{
clrscr ();

int array [10] = { 42 , 23 , 74 , 11 , 65 , 58 , 94 , 36 , 99 , 87 };

Selectionsort ( array , 9 ) ;

Showarray ( array , 9 ) ;

getch ();

}

Monday, March 16, 2009

C Program Quick Sort

// Program for Quick Sort

#include <iostream.h>
#include <conio.h>

enum Boolean { False , True } ;

//-------------------------------------------------------------------

void Quicksort ( int array[] , int LB , int UB )
{
Boolean Flag = True ;
int i , j , Keyval , temp ;

if ( LB < UB )
{
i = LB , j = UB+1 ;

Keyval = array [ LB ] ;

while ( Flag == True )
{

i++ ;
while ( array[i] < Keyval )
i++ ;

j--;
while ( array[j] > Keyval )
j--;

if ( i < j )
{
temp = array[i] ;
array[i] = array[j];
array[j] = temp ;
}
else
Flag = False ;

}

temp = array [ LB ] ;
array [ LB ] = array [ j ] ;
array [ j ] = temp ;

Quicksort ( array , LB , j-1 ) ;
Quicksort ( array , j+1 , UB ) ;

}

return ;
}


void Showarray ( int array[] , int UB )
{
gotoxy ( 1,2 ) ;
cout << "\n" ;

for ( int i = 0 ; i < UB ; i++ )
{
cout << array [i] << endl ;
}

}

//-------------------------------------------------------------------

void main ()
{
clrscr ();

int array [10] = { 42 , 23 , 74 , 11 , 65 , 58 , 94 , 36 , 99 , 87 };

Quicksort ( array , 0, 9 ) ;

Showarray ( array , 10 ) ;


getch();
}

Sunday, March 15, 2009

C Program Merge Sort

// Program for Merge Sort
//For Merge sort two arrays or record files to be Merged must be in Order

#include <iostream.h>
#include <conio.h>

//----------------------------------------------------------------------

void Bubblesort ( int array[] , int UB )
{
for ( int i = 0 ; i <= UB ; i++ )
for ( int j=0 ; j<=UB-1 ; j++ )
{
if ( array [j] > array [j+1] )
{
int temp = array [j] ;
array [j] = array[j+1] ;
array [j+1] = temp ;

}
}
}


//-------------------------------------------------------------------

void Mergesort ( int a[] , int b[] , int c[] , int n1 , int n2 , int n3 )
{
int alimit , blimit , climit ;
int apoint , bpoint , cpoint ;


alimit = n1 - 1 ;
blimit = n2 - 1 ;
climit = n3 - 1 ;

apoint = 0 ;
bpoint = 0 ;

for ( cpoint = 0 ; apoint <= alimit && bpoint <= blimit ; cpoint++ )
{
if ( a[apoint] < b[bpoint] )
c[cpoint] = a[apoint++] ;
else
c[cpoint] = b[bpoint++] ;

}

while ( apoint <= alimit && cpoint <= climit )
c[cpoint++] = a[apoint++];

while ( bpoint <= blimit && cpoint <= climit )
c[cpoint++] = b[bpoint++];


}


void Showarray ( int array[] , int UB )
{
gotoxy ( 1,2 ) ;
cout << "\n" ;

for ( int i = 0 ; i < UB ; i++ )
{
cout << array [i] << endl ;
}

}

//-------------------------------------------------------------------

void main ()
{
clrscr ();

int array1 [5] = { 42 , 23 , 74 , 11 , 65 };
int array2 [5] = { 58 , 94 , 36 , 99 , 87 };
int array3 [10] ;

Bubblesort ( array1 , 4 ) ;
Bubblesort ( array2 , 4 ) ;


Mergesort ( array1 , array2 , array3 , 5 , 5 , 10 ) ;


Showarray ( array3 , 10 ) ;


getch ();
}

Hello World OS Boot loader

Simply stating, it is an Operating System that does nothing but displays a simple message "Hello World". The source code is written in assembly language (NASM), and can be booted from a floppy disk.

The reader must be familiar with all the OS terminology and boot loader mechanism along with a minimal knowledge of a 16 bit Assembly language and working knowledge with NASM (freely downloadable) and the MSDOS program name Debug.Exe.

Write the boot loader code:

;**************************************************
; Hello World OS Boot loader
; Designed by Arnav
; http://pendorasoft.byethost15.com/
;**************************************************

[BITS 16]
[ORG 0x0000]

; code located at 0000:7C00, adjust segment registers
cli
mov ax, 0x07C0
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax

; create stack
mov ax, 0x0000
mov ss, ax
mov sp, 0xFFFF
sti

; post message
mov si,msgHello
call DisplayMessage
mov si, msgEnd
call DisplayMessage
hlt


; Display Message
DisplayMessage:
lodsb ; load next character
or al, al ; test for NUL character
jz .DONE
mov ah, 0x0E ; BIOS teletype
mov bh, 0x00 ; display page 0
mov bl, 0x07 ; text attribute
int 0x10 ; invoke BIOS
jmp DisplayMessage
.DONE:
ret

; data section
msgHello db 0x0D, 0x0A, "Hello World", 0x0D, 0x0A, 0x00
msgEnd db 0x0D, 0x0A, "That's all folks!!!", 0x0D, 0x0A, 0x00

;ASM Signature
TIMES 510-($-$$) DB 0
DW 0xAA55


Save the above code in a file, say boot.asm.

Next we have to generate a RAW Binary code file for the above code. So I used NASM. Assuming that NASM is in the system path, we write the following at the COMMAND prompt:
D:\>NASM boot.asm -o boot.bin -f bin

Next we need a floppy disk from which we will boot the OS. So place a floppy disk in the A Drive and before continuing, please backup any data that may be on the floppy Disk, because we would require to format the floppy in this step:
D:\>format a: /q

I have quick formatted the disk to save a lot of time, but full format will also do.
Now we need to copy our OS binary to the floppy disk. So we use the Debug.Exe program as follows:
D:\>debug boot.bin
-W 100 0 0 1
-Q
D:\>


On issuing the -W option in debug program, the binary is RAW written to the boot sector of the floppy disk after which we quit the debug application.
So we are done with our OS. Now restart the system and boot from the floppy disk. We will see the following output on the screen:

Hello World

That's all folks!!!

And then the computer halts as it now receives the HLT instruction.

Points of Interest:
The first point to note here is that this is not a real OS but a kernel boot-loader. And thus the activities I can do here are limited to 512 kb (1 sector). So my code size does not exceed 512 kb which includes the data section.

Apart from that, I guess the code itself is self explanatory. The only tricky part to note is that the loader always tries to search for the Signature 0xAA55 in the boot loader to mark it as valid for loading. So at the end of the 510 byte of my code (and data) space, the extra 2 bytes are provided for the 2 byte signature for the loader to verify my code as valid.

Problems:
The only problem in this OS is that after the OS is copied to the floppy disk, Windows or MSDOS starts thinking that the floppy is not formatted and then onwards, every time I try updating the code above, I have to first format the floppy and then copy the boot sector binary (boot.bin).
Solution:
A legitimate boot sector is supposed to contain information about the disk format starting at address $7C02 (the first two bytes should be a short branch)

Tuesday, March 10, 2009

C Program Dynamic Memory Allocation

#include <iostream.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>

// Dynamic Memory Allocation

//--------------------------------------------------------------------------

class student
{

private:

int rno ;
char name [25] ;


public:

student ()
{
rno = 0 ;
strcmp ( name , "N.A" ) ;
}

void getinfo ()
{
gotoxy ( 10 , 5 ) ;
cout << "Enter Roll No .................... : " ;
cin >> rno ;

gotoxy ( 10 , 7 ) ;
cout << "Enter Name ....................... : " ;
gets ( name ) ;
}

void showinfo ( int row )
{
gotoxy ( 5 , row ) ;
cout << rno ;

gotoxy ( 25 , row ) ;
cout << name ;
}

};

//#define max 500

//-----------------------------------------------------------------------

void main ()
{

clrscr () ;

student *ptr ;

char ch = 0 ;
int counter = 0 ;

while ( ch !='n' && ch !='N' )
{
clrscr () ;

gotoxy ( 10 , 3 ) ;
cout << "Record No : " << ( counter + 1 ) ;

ptr = new student ;
ptr -> getinfo () ;

counter ++ ;
ptr=ptr+1;
gotoxy ( 10 , 23 ) ; cout << "Do you want to enter [Y/N] : " ;
ch = getch () ;
}

clrscr () ;

for ( int i = 0 ; i < counter ; i++ )
{
ptr -> showinfo ( 5 + i ) ;
ptr =ptr-1 ;
}

getch () ;

}

C Program Check Disk (CHKDSK)

#include <iostream.h>
#include <dos.h>
#include <dir.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
//--------------------------------------------------------------------


void chkdsk ( )
{
dfree fdisk ;
int disk = getdisk() ;
getdfree( disk+1 , &fdisk ) ;

cout << endl ;
cout << "Information for Disk Drive : " ;
cout << ( ( (disk+1) == 3 ) > "C:" :
( (disk+1) == 4 ) > "D:" :
( (disk+1) == 5 ) > "E:" :
"" );
int x, y ;
cout << endl ;
cout << endl ;
x = wherex() , y = wherey() ;

gotoxy ( x+10 , y ) ;
cout <<"Total Clusters .......... : " ;
cout << (long)fdisk.df_total << endl; /* Total clusters */
cout << endl ;

x = wherex() , y = wherey() ;
gotoxy ( x+10 , y ) ;
cout <<"Sector Per Cluster ...... : " ;
cout << (long)fdisk.df_sclus << endl; /* Sectors per cluster */
cout << endl ;

x = wherex() , y = wherey() ;
gotoxy ( x+10 , y ) ;
cout <<"Bytes Per Sector ........ : " ;
cout << (long)fdisk.df_bsec << endl; /* Bytes per sector */
cout << endl ;

x = wherex() , y = wherey() ;
gotoxy ( x+10 , y ) ;
cout <<"Total Disk Size ......... : " ;
cout << (long)fdisk.df_total*(long)fdisk.df_sclus*(long)fdisk.df_bsec ;
cout << " Bytes Available";
cout << endl ;
cout << endl ;
cout << endl ;

x = wherex() , y = wherey() ;
gotoxy ( x+10 , y ) ;
cout <<"Total Clusters Free ..... : " ;
cout << (long)fdisk.df_avail << endl; /* Available clusters */
cout << endl ;

x = wherex() , y = wherey() ;
gotoxy ( x+10 , y ) ;
cout <<"Total Free Space ........ : " ;
cout << (long)fdisk.df_avail*(long)fdisk.df_sclus*(long)fdisk.df_bsec ;
cout << " Bytes Available";


}

//***********************************

void chkdsk ( char *arg )
{
char driveletter[1];

strncpy ( driveletter , arg , 1 ) ;
driveletter[1] = '\0' ;

int disk = 0 ;
if ( strcmpi ( driveletter , "C" ) == 0 )
{
disk = 3 ;
}
else
if ( strcmpi ( driveletter , "D" ) == 0 )
{
disk = 4 ;
}
else
{
cout << driveletter ;
exit(0);
}


dfree fdisk ;
getdfree( disk , &fdisk ) ;

cout << endl ;
cout << "Information for Disk Drive : " ;
cout << ( ( (disk) == 3 ) > "C:" :
( (disk) == 4 ) > "D:" :
( (disk) == 5 ) > "E:" :
"" );
int x, y ;
cout << endl ;
cout << endl ;
x = wherex() , y = wherey() ;

gotoxy ( x+10 , y ) ;
cout <<"Total Clusters .......... : " ;
cout << (long)fdisk.df_total << endl; /* Total clusters */
cout << endl ;

x = wherex() , y = wherey() ;
gotoxy ( x+10 , y ) ;
cout <<"Sector Per Cluster ...... : " ;
cout << (long)fdisk.df_sclus << endl; /* Sectors per cluster */
cout << endl ;

x = wherex() , y = wherey() ;
gotoxy ( x+10 , y ) ;
cout <<"Bytes Per Sector ........ : " ;
cout << (long)fdisk.df_bsec << endl; /* Bytes per sector */
cout << endl ;

x = wherex() , y = wherey() ;
gotoxy ( x+10 , y ) ;
cout <<"Total Disk Size ......... : " ;
cout << (long)fdisk.df_total*(long)fdisk.df_sclus*(long)fdisk.df_bsec ;
cout << " Bytes Available";
cout << endl ;
cout << endl ;
cout << endl ;

x = wherex() , y = wherey() ;
gotoxy ( x+10 , y ) ;
cout <<"Total Clusters Free ..... : " ;
cout << (long)fdisk.df_avail << endl; /* Available clusters */
cout << endl ;

x = wherex() , y = wherey() ;
gotoxy ( x+10 , y ) ;
cout <<"Total Free Space ........ : " ;
cout << (long)fdisk.df_avail*(long)fdisk.df_sclus*(long)fdisk.df_bsec ;
cout << " Bytes Available";


}

//--------------------------------------------------------------------

void main ( int argc , char *args[] )
{

if ( argc == 1 )
chkdsk ();
else
if ( argc == 2 )
chkdsk ( args[1] ) ;
else
cout << "Incorrect Synatx.";

}

C Program Bubble Sort

// Program for Bubble Sort

#include <iostream.h>
#include <conio.h>

//----------------------------------------------------------------------

void Bubblesort ( int array[] , int UB )
{
for ( int i = 0 ; i <= UB ; i++ )
for ( int j=0 ; j<=UB-1 ; j++ )
{
if ( array [j] > array [j+1] )
{
int temp = array [j] ;
array [j] = array[j+1] ;
array [j+1] = temp ;

}
}
}


void Showarray ( int array[] , int UB )
{
gotoxy ( 1,2 ) ;
cout << "\n" ;

for ( int i = 0 ; i <= UB ; i++ )
{
cout << array [i] << endl ;
}

}

//----------------------------------------------------------------------

void main ()
{
clrscr ();

int array [10] = { 42 , 23 , 74 , 11 , 65 , 58 , 94 , 36 , 99 , 87 };

Bubblesort ( array , 9 ) ;

Showarray ( array , 9 ) ;

getch ();

}

C Program Arrays

Eample 1:
#include <iostream.h>
#include <stdio.h>
#include <conio.h>

void main() {

clrscr();

char chart [5][5] = { '0' , '0' , '0' , '0 ', '0' ,
'0' , '0' , '0' , '0' , '0' ,
'0' , '0' , '0' , '0' , '0' ,
'0' , '0' , '0' , '0' , '0' ,
'0' , '0' , '0' , '0' , '0' } ;

char ch[4] = { 'a' , 'b' , 'c' , 'd' } ;

cout << chart << endl ;

cout << ch ;

getch();

}


Eample 2:
#include <iostream.h>
#include <conio.h>

void main() {
clrscr();

int a[10] = {25,65,98,36,21,47,85,85,96,41};

int temp;

for(int i = 0;i<=9; i++)
{
for(int j=1;j<=9;j++)
if(a[i]>a[i+j]) {
temp=a[i];
a[i]=a[i+j];
a[i+j]=temp;
}

}
int *ptr = a;

for(i=1;i<=10;i++) {
cout<<*ptr<<endl;
ptr++;
}

getch();
}


Eample 3:
#include <iostream.h>
#include <conio.h>
#include <stdlib.h>
void main() {

clrscr();

char ac[10]={0,0,0,0,0,0,0,0,0,0},x=0,a=0;

gotoxy(10,10);cout<<"Enter Your Roll.No";

while(a!=13) {

a=getch();

if(a>=48&&a<=57&&x<10) {
cout<<(char)a;
ac[x]=a;
x++;
}

}

gotoxy(12,12);
for(int i=0;i<10;i++)
cout<<ac[i];

getch();

}

C Program with Arguments

There are number of executable programs we have which take paramenters on command line and do some task. Like Del command of DOS takes name of a directory or file to delete that. If we want to create our own command line programs which take parameters to perform some task, we can do as follows:

#include <iostream.h>
#include <conio.h>

void main ( int argc , char *args[] )
{

cout << " Number Of Arguments : " << argc << endl ;
for ( int i=0 ; i<argc ; i++ )
{
cout << "arg["<<i<<"]: "<<args[i] << endl ;
}

}

How this works, we know that the main() method is the gateway to a C/C++ program, as this is a method, and methods can have parameters. We difined a main method with parameters.

Thursday, March 5, 2009

Change User Profile Folder Location in Vista

Here is how we can move user profile location.  Please note that we want all of the profiles moved, included Public and Default, so some of these steps can be skipped if you do not want that:

  1. Make sure you have a complete backup of your system!

  2. Copy the original Default Profile directory to the new location (e.g. from C:\Users\Default to D:\Users\Default).

  3. Copy the original Public Profile directory to the new location (e.g. from C:\Users\Public to D:\Users\Public).

  4. Navigate to 
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList.

  5. Change the value of the Default key to the new user profile location (e.g. D:\Users\Default).

  6. Change the value of the Public key to the new user profile location (e.g. D:\Users\Public).

  7. Change the value of the ProfilesDirectory to the new user profile location (e.g. D:\Users).

  8. At this point, you need to restart and log back in as a different user that has never logged in before and therefore does not have a profile created.  In my case, the Administrator user had never logged in before so I enabled it so that Administrator could log in and used that.  You can enable Administrator login by loading Computer Management and then go to User Accounts, edit the properties for Administrator, and then uncheck Disable Login.

  9. After logging in for the first time with the new user account, you will see “Creating Desktop” and other things like that while Windows is creating your profile.  Note that the new profile should be created in the new location.

  10. After logging in, try to close as many applications as possible.  This will prevent most files from being locked so that you cannot copy them.

  11. Copy the entire original user profiles folder from the original location to the new location (e.g. C:\Users\* to D:\Users\).  (See next step after copy starts).

  12. There are a few things to note during this copy.  There were thousands of .TMP files that were locked and would not copy.  I just skipped these files.  I held down Alt-S so that I could see all of the skipped files and make sure that there were only .TMP files being skipped.  Yes, this took a little while, but at least I was confident that I got all of my files copied.  This process could probably be made easier using the command prompt or powershell.

  13. If, in your case, there are some files that will not copy, you can run procexp.exe, which is file provided by sysinternals.  Then do a Find Handle and search for part of the filename.  procexp will tell you which programs are locking the file.  As long as you closed as many programs as you could, though, this should not happen.

  14. Find and download a program that will do a Search & Replace on the registry.  I will not suggest one because I did not find one single program that worked perfectly.  I ended up downloading a few different freeware applications and using all of them.

  15. Using the Registry Search & Replace program, do a search for the original user profile folder and replace it with the new user profile folder (e.g. search for “C:\Users” and replace with “D:\Users”.  Note that some of the applications I used would only change values and not key names.  However, the keys that needed to be chagned were all related to MuiCache.  I do not know if these actually need to be updated.  I did just to make sure.

  16. Log out.  Log back in with the same user.  Repeat step 14 until there is nothing left to replace.  The reason for this step is that on logout, some programs seem to update the registry using the old user profile path.

  17. Run regedit.exe and do a search for the original user profile path and make sure it does not exist.  The reason for this step is because (as noted in step 13), I did not trust any of the Registry Search & Replace programs I used.  I ended up needing to update about a dozen of the keys and values manually, since the search & replace missed them.

  18. So that you can easily find programs that do not use the registry and hard-coded profile paths, rename your original profile folder (e.g. rename C:\Users to C:\~Users).

  19. Log out. Log back in as your usual user.  Everything should be working correctly except for programs that use a “hardcoded” user profile location.

  20. There are two easy methods that can be used to find programs that use a “hardcoded” profile location and are still looking for the original user profile path.  You can use the procexp.exe trick mentioned above and search for handles in the original profile location.  You can also monitor the oringal profile location to see if any new folders or files were created.  For example, in my case, FolderShare created some folders and files in the directory C:\Users\MyUsername\AppData\Local\FolderShare\.  So, I updated the FolderShare settings to point to the different path and then deleted the C:\Users directory (note that C:\~Users still existed as a backup).

  21. Since you are now confident that all of your data has been moved (right??????), you can deleted the backup of the original user profile location (e.g. C:\~Users).

NTFS symbolic link

An NTFS symbolic link (symlink) is a file-system object in the NTFS filesystem that points to another file system object. The object being pointed to is called the target. Symbolic links should be transparent to users; the links appear as normal files or directories, and can be acted upon by the user or application in exactly the same manner. Symbolic links are designed to aid in migration and application compatibility with POSIX operating systems, and were introduced with the modifications made to the NTFS file system with Windows Vista.

Unlike a NTFS junction point (available since Windows 2000), a symbolic link can also point to a file or remote SMB network path. Additionally, the NTFS symbolic link implementation provides full support for cross-filesystem links. However, the functionality enabling cross-host symbolic links requires that the remote system also support them, which effectively limits their support to Windows Vista and later Windows operating systems.

Symbolic links can point to non existent targets because operating system does not check to see if the target exists.

Restrictions:
The default security settings in Windows Vista disallow non-elevated administrators and all non-administrators from creating symbolic links. This behavior can be changed in the Local Security Policy management console (under: Security Settings\Local Policies\User Rights Assignment\Create symbolic links). It can be worked around by starting cmd.exe with Run as administrator option or the runas command.

Since Windows Vista Home does not have the Local Security Policy Management Console, the command line utility ntrights.exe from the Windows Server 2003 Resource Kit Tools can be used to grant rights to symbolic link creation.

Syntax:
The mklink command is used to create a symbolic link. It has the following command line syntax:

mklink [[/D] | [/H] | [/J]] link target

/D – Creates a directory symbolic link. Default is a file symbolic link.
/H – Creates a hard link instead of a symbolic link.
/J – Creates a Directory Junction.
link – Specifies the new symbolic link name.
target – Specifies the path (relative or absolute) that the new link refers to.
Just like ordinary files and folders, del and rmdir can be used to delete the symbolic links to files and directories respectively.

To delete symbolic link to a file, the following command line syntax can be used:

del filename

filename – Specifies the name of the file/symbolic link to be deleted
To delete symbolic link to a folder, the following command line syntax can be used:

rmdir directoryname

directoryname – Specifies the name of the folder/symbolic link to be deleted

Windows Vista – Missing CD/DVD-Rom drive

A problem lot of people got after upgrading or installing Vista, i myself had this issue and got the solution from different forums. The one that work for me is as follows:

Follwoing key in the registry has the solution to this problem:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E965-E325-11­CE-BFC1-08002BE10318}

1. Click on the start menu.
2. If this is a Vista machine in the search box type in “regedit” without the quotation marks.
3. Maximize the HKEY_LOCAL_MACHINE and then go ahead and browse until you reach the key shown above.
4. In the right panel you’ll see “UpperFilter” and “LowerFilter”, you want to click on each “filter” key and hit delete. Click yes when it asks to confirm if you wish to delete the key.
5. Restart Windows.

And thats all the drives should show normally after your system starts up.

Wednesday, March 4, 2009

Make Height Of Two Table Cell Equal

<script>
function makesame()
{
var tbl1=document.getElementById("table1")
var tbl2=document.getElementById("table2")

if(tbl1.offsetHeight>tbl2.offsetHeight)
{
tbl2.height=tbl1.offsetHeight+'px';
}
else
{
tbl1.height=tbl2.offsetHeight+'px';
}
}
</script>

Tuesday, March 3, 2009

ASP.Net Print Posted Values

Create two web forms, one name posting.aspx and another is posted.aspx, on the posing.aspx place different web controls like text boxes, dropdown list, etc
When finished, open the source view of posting.aspx and set the action property of the form tag to "posted.aspx", this will direct the page to post values to the posted.aspx page. Dont forget to place a submit button on posting.aspx page, so we click to post the values.

Posting.aspx page:
(a). Here you will add all user input controls
(b). place a submit button
(c). Set action property of the form to "posted.aspx"
(d). Set method property of the form to either post of get

Posted.aspx:
Now create the posted.aspx page and simply place the below code in the source of posted.aspx page.

<%For Each skey As String In Me.Request.Form.Keys%>
<%sKey%>=<%Request.Form.Get(sKey)%>
<%Next %>

This code will print out all the posted parameters with the name and values.
Only those parameters will be posted for which value is set or entered by the user.
Now click submit and see the result, you will find list of parameters with there values.

Monday, March 2, 2009

Vista Shorcut Keys

These are not all the shortcuts, Vista has tons of usefull shortcuts, under are the mostly used and liked by users, as follows:

[Win]+[Tab]
Flip 3D, new feature in Vista.

[Win]+[Space]
Shows the sidebar holding Gadgets.

[Ctrl]+[Win]+[Tab]
Flip 3D, but you do not need to hold the keys, just press the combination once and the 3D Flip will remain active, now you can use Up/Down arrow keys to navigate windows.

[Win]+[E]
This opens the file explorer, mostly opens the my computer where all drives are visible.

[Win]+[R]
This opens the traditional run command dialogue box.

[Win]+[T]
Tabs between running applications on the taskbar, also a small thumbnail of the application window is shown just above the focus.

[Win]+[G]
pushes focus to the the sidebar the focus and when you press this key combination again it tabs between the gadgets on the sidebar.

[Win]+[M]
This is also a traditional shortcut, this minimizes all windows and shows the desktop.

[Shift]+[Win]+[M]
Undoes the minimize windows

[Win]+[Number]
Press the Win key and then choose a number of the applications that are in the quick launch task bar. An example the third icon on the taskbar (starting from left) is IE so to run IE press Win-3 and it will launch IE.

[Win]+[U]
This will open Ease of Access Center, here all accessibility features are available.

[Win]+[F]
This opens the search window, here vista users can enjoy the fast searching feature.

[Win]+[L]
This is another traditional shortcut, it is used to lock you computer so no one else access it when you are away.

[Ctrl]+[Shift]+[Esc]
Press this combination to open task manager, here all running programs can be seen, performace of CPU and memory consumption can be checked.

Sunday, March 1, 2009

Loading External Javascript Files

Static:
<script src="/includes/scripts/test.js" type="text/javascript"></script>

Dynamically Static Way:
<script type="text/javascript">
function staticLoadScript(url)
{
document.write('<script src="', url, '" type="text/JavaScript"><\/script>');
}
staticLoadScript("/includes/scripts/test.js");
</script>

Dynamically DHTML Way:
<script type="text/javascript">
function dhtmlLoadScript(url)
{
var e = document.createElement("script");
e.src = url;
e.type="text/javascript";
document.getElementsByTagName("head")[0].appendChild(e);
}
onload = function()
{
dhtmlLoadScript("/includes/scripts/test.js");
}
</script>

Reference: http://www.ecma-international.org/publications/standards/Ecma-262.htm

Javascript include from ASP.NET server control

In ASP.NET 2.0 the Page object has a Header property - which contains a Controls collection. This is good news since it makes it possible to (easily) inject a <script type="text/javascript" src="whatever"> into the <head></head> section of the resulting HTML page.

You can - for example from the code of your custom server control - add a htmlgeneric control to the containing page header control like this:

string sInclude = "~/specialincludes/blabla.js";
sInclude = ResolveUrl( sInclude );
HtmlGenericControl Include = new HtmlGenericControl("script");
Include.Attributes.Add("type", "text/javascript");
Include.Attributes.Add("src", sInclude);
this.Page.Header.Controls.Add(Include);
and that would make the resulting html code look like this:

<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" src="/thesite/specialincludes/blabla.js">
</script>
<head>

Track SQL Dependencies

--PAYROLL.dbo.PAY_GETPAYLIST dependents on

EXEC sp_depends @objname = N'PAY_GETPAYLIST' ;

--dependent on PAYROLL.dbo.PAY_GETPAYLIST

EXEC sp_MSdependencies N'dbo.PAY_GETPAYLIST', null, 1315327

--PAYROLL.dbo.PAY_GETPAYLIST dependents on

--oType =1 (Scalar Function), oType =8 (Table)

EXEC sp_MSdependencies N'dbo.PAY_GETPAYLIST', null, 1053183

-- SYS COMMENTS

SELECT distinct so.name

FROM syscomments sc

INNER JOIN sysobjects so ON sc.id = so.id

WHERE charindex('PAY_GETPAYLIST', text) > 0

--INFORMATION_SCHEMA.ROUTINES

SELECT routine_name, routine_type

FROM INFORMATION_SCHEMA.ROUTINES

WHERE ROUTINE_DEFINITION LIKE '%PAY_GETPAYLIST%'

IIS Worker Process and Application Pooling

Web server?
IIS (Internet Information Service) running on a software port like 80 for Http and 443 for Https or any other port set bt the administrator, it can host more than one web site and each web site can hold more than one web application. Web server provides application pooling and hanldes all web request from the internet and forward it to respective web site's application pool for processing and response. IIS can host classic asp applications, asp.net applications, php applications, etc.

Application Pooling?
The Windows IIS web server, has application pools where different web applications or web sites can be pooled. When we say pooled it means it is loaded in the process, so the web requests are processed. Why pooling? becuase the application will handle multiple web requests, the application is loaded once, and remains in the pool for quite some time to process subsequent requests and when remains idel for too long it is unloded. The pooling helps better manage server resources, so the CPU and Memory is not consumed uselessly. An application pool can hold more than one web application, and IIS can have more than one application pools. Application pools it self is comprehensive topic and it provides many things to tune your web application performace.

Worker Process?
As we discussed above, application pooling is done in IIS, Worker Process is actually a program that executes in the system memory for a specific application pool, if we have three application pools and the pools are active than we will have three process running it the system memory, these are the processes which handle the requests and send response. The "w3wp.exe" program can be easily found in the task manager, this is the program running behind the application pool.
We can define more than one worker process in an application pool, by default we have one worker process in an application pool, this means there is only one queue for my web requests, so ten request will execute one at a time.
If i increase the number to 2, so now my application pool has 2 worker process, this means there are two queues for my web requests, so ten request will execute two at a time. Ofcourse the CPU time will be divied between the two worker processes, this means to many worker processes will cut down the overall response time if i have a moderate server, therefore it depends upon the hardware of the server that how many worker processes it can hold.