Linking to an Ms-Access Data Source using Visual C++ 2008 Windows Forms Application

1.Create an Ms-Access database file using the following fields and data types:



2. Name your table as “tblApps” no quotes. Add appropriate record values for instance:



3. Name your Access database file as “dbICons” no quotes and save it in My documents. Make sure to close Ms-Access before you start Visual C++ 2008, otherwise you’ll get an “Already in use” error in the database connection part.

4. Click Start>All Programs>Microsoft C++ 2008 Express Edition.

5. Click File>New>Project>Select CLR from the Visual C++ Project Types tree view>Select Windows Forms Application from the Visual Studio installed templates pane>Enter your desired project name then click Ok.

6. Design your form as follows:



7. Just use the suggested control names above so that you will not get lost later on in this tutorial. To name a control, just select the control and change its name property value in the properties window.

8. At this moment we will now specify the name of our database that we wanted to connect to. To do that, click the Tools menu and select Connect to database:



9. Select Microsoft Access Database File (OLE DB) as a data source value then locate dbIcons and assign it as a Database filename value.



10. Click the oledbDataAdapter control from the general category of the toolbox and drag it to your form. There instances wherein the oledbdataadapter is not shown, to show it, click Tools>Choose Toolbox items>type “ole” not quotes in the filter textbox> then check everything that starts with “ole” then click the Ok button.

11. Once you have added an oledataadapter control, the data adapter configuration wizard will then come into view. If you noticed the table that you have connected previously (using step 8-9) is selected as a default value of the “what data connection should the data adapter use?” listbox. If not then click the listbox button then select “dbIcons” then click the Next button.



12. In the Choose a command type window, select the Use SQL statement radio button then click Next.

13. In the Generate SQL statement window, type “SELECT * FROM tblApps” no quotes in the blank pane then click Next>Finish.

14. Right-click>OleDbDataAdapter form the component tab>generate dataset>Ok.



15. Double-click your form then add the following in the Form_load event.
//Populates the dataset
this->oleDbDataAdapter1->Fill(this->dataSet11,"tblApps");
16. This will fill our dataset with record values from our database.

17. Bind the fieldname to an appropriate control using the following syntax:

this->objectname->databindings->add(gcnew Binding(“Property”, datasetname,”Tablename.fieldname”);

Add it below the oledbdataadapter.fill line. Your code should now look like this:

private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
//Populates the dataset
this->oleDbDataAdapter1->Fill(this->dataSet11,"tblApps");
//bind idlabel to the numappid fieldname
this->idlabel->DataBindings->Add(gcnew Binding("Text",this->dataSet11,"tblApps.numappid"));
//bind desclabel to the chrappdesc fieldname
this->desclabel->DataBindings->Add(gcnew Binding("Text",this->dataSet11,"tblApps.chrappdesc"));
//bind appPictureBox to the chriconurl fieldname
this->apppictureBox->DataBindings->Add(gcnew Binding("ImageLocation",this->dataSet11,"tblApps.chriconurl"));
}

18. Click the run icon to start debugging, you should see the following outputs:

A simple “Hello World” program in BlueJ

1. Click Start>All Programs>BlueJ>BlueJ.
The BlueJ Environment will then come into view.

2. Click the Project menu>New project. In the Look in Listbox, select My documents> Enter “Example” (no quotes) in the Folder Name textbox then click Create.

3. Click the New Class button>Type “Hello” (no quotes) in the Class Name textbox> Ensure that Class is selected in the class type radio buttons then click OK.



A class icon with a caption “Hello” will then appear in the BlueJ workarea.



4.Double click the Hello class icon, the following source code window will then appear:



Before creating our “Hello World” program, let us first dissect the pre-made code bit by bit. If you noticed, I’ve enabled line numbers by clicking Options>Preferences>Display line numbers, for discussion purposes.

Line 8: Is the class declaration section. It simply tells the BlueJ compiler the name of our class and to create class file based on it.
Line 9: Indicates the beginning of our class.
Line 10-12: Is the instance variable declaration section. This is where we declare the variables that will be needed in our application.
Line 16-20: Is the variable initialization section. This is where we initialize the values of our variables.
Line 28-32: Is the method declaration section. This is where we specify the actions that our application is capable of performing.
Line 34: Simply specifies the end of our class.

5. Now that we’ve understood (somehow) Blue’s code structure, let us now make our hello world program. Go to the instance variable declaration section (Line 10-12) and change “private int x;” to “private String strtext;” no quotes. The reason why we are declaring a string variable instead of the default integer variable is because we will be storing text i.e. “Hello World” to this variable in the variable initialization section.



6. Go to the variable initialization section (Line 16 to 20) and assign a “Hello World” value to our previously declared variable. This can be done by erasing ‘x=0;’ and changing it to ‘strtext=”Hello World”;’.



7. Go to the method declaration section (Line 28-32). Since we will not be accepting a numeric value from other methods nor we will be passing numeric value, change :



To



8. Your code will now look like this:

/**
* Write a description of class Hello here.
* 
* @author (your name) 
* @version (a version number or a date)
*/
public class Hello
{
// instance variables - replace the example below with your own
private String strtext;

/**
* Constructor for objects of class Hello
*/
public Hello()
{
// initialise instance variables
strtext="Hello World";
}

/**
* An example of a method - replace this comment with your own
* 
* @param  y   a sample parameter for a method
* @return     the sum of x and y 
*/
public void sampleMethod()
{
//clears the previous outputs
System.out.println("\u000c");
//retrieves the value of the strtext variable and display it on the screen.
System.out.println(strtext);
}
}
9. Click the compile button to convert your Bluej source code into bytecode.

10. Click the Close Button.

11. Create an Object based on your Hello class by right-clicking the Hello class icon>new Hello.



12. Right-click the name of the Hello object>Click your method i.e., sampleMethod.



13. You should now see an output similar to the following:



Google has recently deindexed all co.cc domain extensions names. You can see the details of that here http://www.theinquirer.net/inquirer/news/2092882/security-experts-claim-googles-cocc-ban-inefficient. www.aprogguide.co.cc will be transferring to blogspot for good in one week time.

Creating a Hit Points (HP) Indicator in DarkGDK

HP indicators are normally used in Adventure games to show the character’s present HP level. There are several ways to create an HP level indicator in DarkGDK but the easiest way (I guess) is to create a sprite sheet with three or more columns and with different HP numbers per column. For instance, three HP’s on the first column, two on the second and one on the last. If a character dies, display the appropriate column relative to the character’s HP level. This method can also be used to specify the remaining number of bullets left or the character’s current energy level. If you are confused, follow these steps:

1. Start Microsoft Visual 2008 C++ Express Edition.

2. Click File>New Project>Select the Wizards Project type>Select Dark GDK-2d Game from the Visual Studio installed templates.

3. Click View>Solution Explorer. Double-click main.cpp. The following should then appear:
// Dark GDK - The Game Creators - www.thegamecreators.com

// the wizard has created a very simple 2D project that uses Dark GDK
// it can be used as a starting point in making your own 2D games

// whenever using Dark GDK you must ensure you include the header file
#include "DarkGDK.h"

// the main entry point for the application is this function
void DarkGDK ( void )
{
// in this application a backdrop is loaded and then several
// animated sprites are displayed on screen

// when starting a Dark GDK program it is useful to set global
// application properties, we begin by turning the sync rate on,
// this means we control when the screen is updated, we also set
// the maximum rate to 60 which means the maximum frame rate will
// be set at 60 frames per second
dbSyncOn   ( );
dbSyncRate ( 60 );

// a call is made to this function so we can stop the GDK from
// responding to the escape key, we can then add in some code in our
// main loop so we can control what happens when the escape key is pressed
dbDisableEscapeKey ( );

// now we will set the random seed value to the timer, this will
// help us to get more random values each time we run the program
dbRandomize ( dbTimer ( ) );

// we are going to display a backdrop for the scene, to do this
// we load our image and give it an ID number of 1, this particular
// image is of a sky at night with stars
dbLoadImage ( "backdrop.bmp", 1 );

// the next step is to create a sprite that uses this image, this
// is achieved by calling dbSprite and passing in a value of 1 for the
// sprites ID, 0 for the X coordinate, 0 for the Y coordinates and a
// value of 1 for the image
dbSprite ( 1, 0, 0, 1 );

// next we will load in some animated sprites, before doing this
// we need to adjust the image color key, by using this function we
// can make a specific color be transparent, in our case we want this
// to be bright pink
dbSetImageColorKey ( 255, 0, 255 );

// in this loop we're going to create some animated sprites, the image
// we load contains frames of animation for an asteroid
for ( int i = 2; i < 30; i++ )
 {
  // create an animated sprite and give it the ID number from the
  // variable i, next is the filename, now we come to how many frames
  // across and down, in our case this is 4, finally we come to the image
  // ID that the sprite will use, again we use i
  dbCreateAnimatedSprite ( i, "sprite.bmp", 4, 4, i );

  // position our sprite at a random location
  dbSprite ( i, dbRnd ( 640 ), -dbRnd ( 1500 ), i );
 }

 // now we come to our main loop, we call LoopGDK so some internal
 // work can be carried out by the GDK
 while ( LoopGDK ( ) )
 {
  // run a loop through all our sprites
  for ( int i = 2; i < 30; i++ )
  {
   // move the sprite down and play its animation
   // moving from frame 1 to 16 with a delay of 60 ms
   dbMoveSprite ( i, -2 );
   dbPlaySprite ( i, 1, 16, 60 );

   // check the position of the sprite, if it has gone off scren
   // then reposition it back to the top
   if ( dbSpriteY ( i ) > 500 )
dbSprite ( i, dbRnd ( 640 ), -dbRnd ( 1500 ), i );
}

// here we check if the escape key has been pressed, when it has
// we will break out of the loop
if ( dbEscapeKey ( ) )
break;

// here we make a call to update the contents of the screen
dbSync ( );
}

// when the user presses escape the code will break out to this location
// and we can free up any previously allocated resources

// delete all the sprites
for ( int i = 1; i < 30; i++ )
  dbDeleteSprite ( i );

 // delete the backdrop image
 dbDeleteImage ( 1 );

 // and now everything is ready to return back to Windows
 return;
}
4. Since we intend to make our sample application from the scratch, delete all the pre-made codes, except the following:
// Dark GDK - The Game Creators - www.thegamecreators.com
#include "DarkGDK.h"

// the main entry point for the application is this function
void DarkGDK ( void )
{
 
 dbSyncOn   ( );
 dbSyncRate ( 60 );

 
 while ( LoopGDK ( ) )
 {
  

  // here we make a call to update the contents of the screen
  dbSync ( );
 }

}
5. Make a spritesheet using gimp or photoshop. In this example we will be using the following image: 6. Later on we will be dividing this image into three columns. If you noticed if we divide this image into three divisions each divisions we will have different number of HP’s. 7. Copy this image from whatever location you have saved it. In this example, I have saved it on my desktop so all I need to do is go to the desktop. Select the file “hplevel.bmp”. Then press CTRL + C to copy it.
8. Switch to Micorsoft Visual C++ 2008 DarkGDK to view our game again then click the Open File icon from the formatting toolbar. 9. This causes the Open File dialog box to appear. Click on the empty pane>Press Ctrl + V to paste our “hplevel.bmp” file. 10. The next thing that you’ll need to do is to load this image into the computer’s memory, and divide it into three columns. We can do so by using the dbCreateAnimatedSprite command. Click the cancel button from the open dialog box to close it. This causes our code window to appear. Enter the ff. after the dbSyncRate(60); line.
//divides the image into 3 columns
dbCreateAnimatedSprite(1,"hplevel.bmp",3,1,1);
11. If you run your application now, it will just display a blue screen. To display your animated sprite,use the dbSprite command. Enter the following code after the dbCreateAnimatedSprite line.
//displays our animated sprite
dbSprite(1,0,0,1);
12. Press Ctrl+ F5 to test our application again. If you noticed the first column of our animated sprite is shown together with a white background. To clear the white background, use the dbSetImageColorKey command. Enter the following before the dbCreateAnimated line:
//clears the white background
dbSetImageColorKey(255,255,255);
13. Your code should now look like this:
// Dark GDK - The Game Creators - www.thegamecreators.com
#include "DarkGDK.h"

// the main entry point for the application is this function
void DarkGDK ( void )
{

dbSyncOn   ( );
dbSyncRate ( 60 );
//clears the white background
dbSetImageColorKey(dbRgb(255,255,255));
//divides the image into 3 columns
dbCreateAnimatedSprite(1,"hplevel.bmp",3,1,1);
//displays our animated sprite
dbSprite(1,0,0,1);



while ( LoopGDK ( ) )
{


// here we make a call to update the contents of the screen
dbSync ( );
}

}
14. The next thing that we want to do is to subtract the number of HP’s everytime the space key is pressed. Of course you can replace this with more advanced algorithms such as when your player dies or when a shot is fired, etc. But for the sake of simplicity, lets just go with the space key(hehehe). 15. Declare an integer variable named intspritesheetcols just below #include "DarkGDK.h" line and assign a a default value 1. 16. Enter the following after the while ( LoopGDK ( ) ){
//you can replace dbSpaceKey with  "if a player dies" or "if a gun is fired" algorithms
if (dbSpaceKey())
{
//increment the value of intspritesheetcols by 1
//if you recall we've initially assigned a starting value 1 to
//our intspritesheetcols variable. If you press the
//the space key for the first time it will be incremented by 1
intspritesheetcols=intspritesheetcols + 1;
//displays the spritesheet division relative to the specified
//intspritesheetcols value. The first time you press the space key
//intspritescols will have a value to causing the second column
//of our spritesheet to be displayed
dbSetSpriteFrame(1,intspritesheetcols);
//displays our sprite
dbSprite(1,0,0,1);
}
//if the number of columns exceeds 3
//you can display your game over screen here but in this case let's
//just exit the game
if(intspritesheetcols>3)
{
return;
}
17. Your whole code should now look like this:
// Dark GDK - The Game Creators - www.thegamecreators.com
#include "DarkGDK.h"
int intspritesheetcols=1;
// the main entry point for the application is this function
void DarkGDK ( void )
{

dbSyncOn   ( );
dbSyncRate(5);
//clears the white background
dbSetImageColorKey(255,255,255);
//divides the image into 3 columns
dbCreateAnimatedSprite(1,"hplevel.bmp",3,1,1);
//displays our animated sprite
dbSprite(1,0,0,1);

while ( LoopGDK ( ) )
{
//you can replace dbSpaceKey with  "if a player dies" or "if a gun is fired" algorithms
if (dbSpaceKey())
{
//increment the value of intspritesheetcols by 1
//if you recall we've initially assigned a starting value 1 to
//our intspritesheetcols variable. If you press the
//the space key for the first time it will be incremented by 1
intspritesheetcols=intspritesheetcols + 1;
//displays the spritesheet division relative to the specified
//intspritesheetcols value. The first time you press the space key
//intspritescols will have a value to causing the second column
//of our spritesheet to be displayed
dbSetSpriteFrame(1,intspritesheetcols);
//displays our sprite
dbSprite(1,0,0,1);
}
//if the number of columns exceeds 3
//you can display your game over screen here but in this case let's
//just exit the game
if(intspritesheetcols>3)
{
return;
}
// here we make a call to update the contents of the screen
dbSync ( );
}

}
18. Press CTRL + F5 to run your application. You should now see an output similar to the following:
19. That’s all.

Blender 2.5 Beta Boids Particle System

Boids particle system is used to emulate the movements of animals moving in clusters or groups. To create a simple boids simulation in Blender 3d 2.5 Beta, follow these steps:

1. Start Blender by clicking on Start>All Programs>Blender Foundation>Blender>Blender.

2. Press Esc to get rid of the Splash screen then select the default cube by right-clicking it.



3. Click the particles button in the Properties View (formerly known as Buttons Window).



4. Click the + (add particles) button.



5. Blender will automatically create a particle system named “ParticleSystem”. Locate the Physics category by scrolling the scrollbar down> Then click the boids button.



6. At this point you can press Alt+A to test our animation.If you noticed, our simulation does not would do that much because what we have done so far is to create the cube object as a source or emitter of our boids particles.

7. The next thing that we need to do is to add an object that will serve as destination or goal of our boids particles. To do that, position the 3d cursor a few blender units away from our cube object.



8. Press Shift + A>Mesh>Icosphere.



9. You can add any object you want as a destination of our boids particles but in this case we’ve used an icosphere as our goal object(no reason in particular). Select the icosphere by right-clicking on it>Click the Physics button from the Properties View.



10. Locate the Force Field category. Select Magnetic from the type listbox.



11. Select your cube object by right-clicking on it>Click the particles button> Locate the Boid Brain Category>Click the +(Add Rule) button>Select Goal.



12. Click the Goal object textbox> Select icosphere.



13. Press Alt+A to test your animation. If you noticed our boids particles seemed to be moving in the direction of our destination object (icosphere). Unfortunately it does not actually reached the icosphere because it dies after 50 frames. To increase the boids life, right-click the cube object>Click the Particles button. In the emission category, change its Lifetime value to 999.000.



14. You can change whatever particles lifetime value you like just make sure that it is identical to the ending frame of our animation. To change the ending frame of our animation, locate the End option in the timeline then change it to 999.



15. Press Alt + A to test your animation. You should now see an output similar to the following.

Display Record Values from Two Tables in ASP.net Visual Web Developer Express Edition

To display data from two tables in ASP.net, we’ll need two tables with one or more identical fields. One field should act as a primary key on one table and the other should act as a foreign key or normal key on the other table. For the sake of example, let’s make two tables tblStudents and tblBooks using the following structures:

a. tblStudents
Column NameData Type
chrstudidnchar(10)
chrstudfnamenchar(20
chrstudlnamnchar(20)

b. tblBooks

Column NameData Type
chrbookidnchar(10)
chrtitlenchar(30
chrauthornchar(30)
chrstudidnchar(10)

1. Start Visual Web Developer Express Edition.

2. Click File>New Website>Select Asp.net website from Visual Studio Installed Templates options>Click Ok.

3. Click View>Solution Explorer>Right-click App_Data from the solution Explorer>Add New Item>Select SQL Server Database from Visual Studio Installed templates options>Accept the default database.mdf name>Click Add.



4. The Database Explorer panel will then come into view. To create a new table>Right-click Tables from the database explorer panel>Select Add new table.



Enter the following column names, use chrstudid as a primary key:



5. Click the close(x) button when done. You will be prompted if you wanted to saves changes to the table, just Click the Yes button>Enter “tblStudents” in the Enter a name for the table textbox>Click Ok.

6. Click the + icon beside the Tables node in the database Explorer>Right-click tblStudents>Click Show Table Data.



Enter the following values:




7. Right-click Tables from the Database Explorer again then Select Add New Table.



Enter the following Column names using chrbookid as a primary key:





8. Click the close(x) button when done. You will be prompted if you wanted to saves changes to the table, just Click the Yes button>Enter “tblBooks” in the Enter a name for the table textbox>Click Ok.

9. Click the + icon beside the Tables node in the database Explorer>Right-click tblBooks>Click Show Table Data.



Enter the following values:



10. Click View Solution Explorer > Double-Click Default.aspx> Double-click the design button>Expand the Data category of the toolbox>Click and drag a SqlDataSource control to the Outline Designer window.



11. Click the configure data source link>Select Database.Mdf from the “Which data connection should your application use to connect to the database?” listbox>Next.


12. Click the Specify a custom SQL statement or stored procedure radio button>Next.

13. Click the SELECT tab then enter the following SQL statements in the SQL Statement textarea:



14. This statement retrieves the values of our specified column names from both tables. If you noticed, we’ve added tblStudents dot chrstudid to specify that the values should be retrieve from the tblStudents table since tblBooks table also has chrstudid.Moreover, we’ve added INNER JOIN to join our tables using a common field
due to the fact that chrbookid, chrtitle, and chrauthor exists on the other table.


15. Click next. You can click the test query button to preview the result then click the finish button.

16. Click a grid view control from the data category of the toolbox then drag it onto the Outline Designer. Select the name of your SQLDataSource from the gridview’s Choose Data Source List Box.



16. Press CTRL + F5 to test your application.

17. You should now see an output similar to the following screenshot:

Example 18: Race to Ten Text-Based Game

Problem: Make a simple Race to Ten text-based game. The details of the game is shown in the following screenshot:



Code:
// Learn more about F# at http://fsharp.net
open System
//change the console title
System.Console.Title<-"Race to Ten"
//adds the foreground and background color
System.Console.ForegroundColor<-ConsoleColor.DarkBlue
System.Console.BackgroundColor<-ConsoleColor.Gray
//clears the screen. This is to apply the background color once the
//console application is loaded
System.Console.Clear()
//display the game title screen
printfn "\t\t\t\tRace to Ten"
printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue..."
System.Console.ReadLine()|>ignore
System.Console.Clear()
//display the game description screen
printfn "Instructions:"
printfn "In this game, each player(you vs. the computer) enters a number between 1 to 3"
printfn "The previously inputted number will be added to the present number"
printfn "The first player to enter a number that adds up to 10 wins the game"
printfn "Press Esc to quit the game"
printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue..."

let mutable userkey=System.Console.ReadLine()
System.Console.Clear()
//declares our variables
let rndnum=new Random()
let mutable intsum=0
let mutable intusernum=0
let mutable intremain=0
//loop while sum is not equal to 10 and 
//the spacebar key has been pressed
while (intsum < 10 ) do
//computer generates a number
        printfn "\n\nAI's turn..."
        let intainum=rndnum.Next(1,3)
        printfn "AI num: %d" intainum
//accumulates the number to the
//value of sum
        intsum<-intsum + intainum
        printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue...Esc to quit"
        System.Console.ReadLine()|>ignore
System.Console.Clear()
//display how many numbers more to go
//before 10
intremain<-intsum-10  
        printfn "%d more to go!" intremain
 //if the sum is equal to 10 
 //display "computer wins"
        if intsum>=10 then  
System.Console.Clear()
//reset the value of sum so that 
//the game will loop again
//remove intsum<-0 if you want the
 //game to end after one game
            printfn "Computer Wins!" 
            intsum<-0
            printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue...Esc to quit"
            System.Console.ReadLine()|>ignore
System.Console.Clear()          
//otherwise ask for a number         
printfn "\n\nYour turn:" 
intusernum<-(int)(System.Console.ReadLine())
 //if the number exceeds 3 then
 //ask for a number again
        if intusernum>3 then
printfn "Number must be between 1 to 3"
printfn "You turn:"
intusernum<-(int)(System.Console.ReadLine())
            intsum<-intsum + intusernum
            System.Console.Clear()
//accumulates the inputted number to the value of sum
        intsum<-intsum + intusernum 
        intremain<-intsum-10  
        printfn "%d more to go!" intremain
        if intsum>=10 then
System.Console.Clear()
printfn "You Win!"
intsum<-0
            printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue...Esc to quit"
            System.Console.ReadLine()|>ignore
System.Console.Clear()

Example#17(Array.Iter)

Problem: Make a console application that will convert the following singular nouns to plural. Use Array.Iter:

1. ally
2. army
3. baby
4. lady
5. navy

// Learn more about F# at http://fsharp.net
open System
//change the console title
System.Console.Title<-"Convert to Plural"
//adds the foreground and background color
System.Console.ForegroundColor<-ConsoleColor.Blue
System.Console.BackgroundColor<-ConsoleColor.White
//clears the screen. This is to apply the background color once the
//console application is loaded
System.Console.Clear()
//assigns the singular nouns to our array variable singularnouns
let singularnouns=[|"ally";"army";"baby";"lady";"navy"|]
printfn "Singular words:"
//iterates through the values of our singularnouns array variable
singularnouns|>Array.iter(fun singularwords->printfn "%s" singularwords)
printfn "Plural words:"
//iterates through the values of our singularnouns array variable
//replace the word in each array element from "y" to "ies"
singularnouns|>Array.iter(fun pluralnouns->
let pluralwords= pluralnouns.Replace("y","ies")
printfn "%s" pluralwords)

This will display the following output:

Visual F# 100 Examples: Example Number 16(Search a Record Value)

Problem: Make a Windows Forms Application that will allow the user to search a record value from a database file.

// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Data
open System.Drawing
open System.Data.OleDb
//creates a font
let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)  
//creates a connection object
let oleconn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
  Data Source=C:\Documents and Settings\Station03\My Documents\dbEmployee.mdb")
 //creates an OleDbDataAdapter
let dataadpter = new System.Data.OleDb.OleDbDataAdapter("Select * from tblEmployee", oleconn)
//generates a dataset
let dataset11 = new DataSet()
//fills the dataset with recod values
dataadpter.Fill(dataset11,"tblEmployee")|>ignore
//creates a form
let dataform = new Form(Text="Search a Record Value",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(400, 360),StartPosition=FormStartPosition.CenterScreen)
//creates our controls
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(300, 320)) 
let searchbutton=new Button(Text="Search", Location=new System.Drawing.Point(220, 320))  
let label1=new Label(Text="Enter the employee number:",Location=new System.Drawing.Point(0, 10),AutoSize=true)
let label2=new Label(Text="Empno:",Location=new System.Drawing.Point(0, 50),AutoSize=true)
let label3=new Label(Text="Firstname:",Location=new System.Drawing.Point(0,100),AutoSize=true)
let label4=new Label(Text="Lastname:",Location=new System.Drawing.Point(0,150),AutoSize=true)
let empnotext=new TextBox(Location=new System.Drawing.Point(200,10))
let emplabel=new Label(Location=new System.Drawing.Point(100,50),BorderStyle=BorderStyle.FixedSingle)
let fnamelabel=new Label(Location=new System.Drawing.Point(100,100),BorderStyle=BorderStyle.FixedSingle)
let lnamelabel=new Label(Location=new System.Drawing.Point(100,150),BorderStyle=BorderStyle.FixedSingle)
//creates a datagrid
let datagrid = new DataGridView(ColumnHeadersHeightSizeMode=DataGridViewColumnHeadersHeightSizeMode.AutoSize,Size=new System.Drawing.Size(300, 120),Location=new System.Drawing.Point(10, 180))
//creates a grid control colums
let chrempnocol=new DataGridViewTextBoxColumn()
let chrfnamecol=new DataGridViewTextBoxColumn()
let chrlnamecol=new DataGridViewTextBoxColumn()
//adds the columns into our datagrid
datagrid.Columns.Add(chrempnocol)|>ignore
datagrid.Columns.Add(chrfnamecol)|>ignore
datagrid.Columns.Add(chrlnamecol)|>ignore
datagrid.DataSource <- dataset11.Tables.["tblEmployee"]
//assingns the font to our form
dataform.Font<-ffont
//links our fieldname to each grid
//and change its header text
chrempnocol.DataPropertyName<-"chrempno"
chrempnocol.HeaderText<-"Employee No."
chrfnamecol.DataPropertyName<-"chrfname"
chrfnamecol.HeaderText<-"First Name"
chrlnamecol.DataPropertyName<-"chrlname"
chrlnamecol.HeaderText<-"Last Name"
//add the datagrid to our form
dataform.Controls.Add(datagrid)
//adds the controls to our form
dataform.Controls.Add(exitbutton)
dataform.Controls.Add(searchbutton)
dataform.Controls.Add(label1)
dataform.Controls.Add(label2)
dataform.Controls.Add(label3)
dataform.Controls.Add(label4)
dataform.Controls.Add(empnotext)
dataform.Controls.Add(emplabel)
dataform.Controls.Add(fnamelabel)
dataform.Controls.Add(lnamelabel)
//binds the fieldnames to our label
emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(0))
fnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(1))
lnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(2))
searchbutton.Click.Add(fun search->  
                    //handles the row index number               
                    let mutable introws=0
                    //determines if the record has been found or not
                    let mutable blnfound=false   
                    //handles the total number of records                
                    let mutable inttotrec=Convert.ToInt32(dataset11.Tables.["tblEmployee"].Rows.Count)
                    //handles the data inputted by the user
                    let strtext=Convert.ToString(empnotext.Text)
                    //while no match is found and the end of the file has not been reached
                    while((blnfound=false) && (introws<=inttotrec-1)) do
                         let strempnum=Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(introws).Item(0))
                         //compare the data inputted in the textbox to the employee number in our table
                         //if they are equal, display the match record
                         if strtext.ToUpper()=strempnum.ToUpper() then
                            blnfound<-true
                            emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(introws).Item(0))
                            fnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(introws).Item(1))
                            lnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(introws).Item(2)) 
                         //compare to the next record while no match is found
                         introws<-introws + 1    
                    //if no match is found, display this      
                    if blnfound=false then
                        MessageBox.Show("Record not found.","Search a Record Value",MessageBoxButtons.OK,MessageBoxIcon.Information)|>ignore)                       
//when the exit button is clicked
exitbutton.Click.Add(fun exit->
//close the form and dataconnection
                    dataform.Close()
                    oleconn.Close()) 
//executes our application
Application.Run(dataform)

Since Visual F# is very particular with the code indention, I posted below the screenshot of our code in the while loop section.



Here's what it should look like if you click the run icon:

Visual F# 100 Examples: Example 14 and 15(Pattern Matching)

Pattern matching/match with statement is similar to the switch selection statement in other programming languages. The following examples demonstrate how to use it:


Problem: Make an application that will asks a letter and displays its equivalent U. S. military phonetic alphabet.
//use F# library
open System
//change the CLI title
System.Console.Title<-"Display Military Phoenitic Alphabet"
//adds color to our console application
System.Console.ForegroundColor<-ConsoleColor.Blue
//asks the user to enter a letter
printfn "Enter a letter:"
//convert the input to character and convert it to uppercase letter
//this is just for comparison purpose
let chrletter=Char.ToUpper(Convert.ToChar(System.Console.ReadLine()))
//clear the screen   
System.Console.Clear()
//match the value of chrletter to the ff. values
match chrletter with
//if the value of chrletter is a or A display Alpha
| 'A' ->printfn "Alpha"
//if the value of chrletter is b or B display Bravo
| 'B' ->printfn "Bravo"
//if the value of chrletter is c or C display Charlie
| 'C' ->printfn "Charlie"
//if the value of chrletter is d or D display Delta
| 'D' ->printfn "Delta"
//if the value of chrletter is e or E display Echo
| 'E'->printfn "Echo"
//if the value of chrletter is f or F display Foxtrot
| 'F'->printfn "FoxTrot"
//if the value of chrletter is g or G display Golf
| 'G'->printfn "Golf"
//if the value of chrletter is h or H display Hotel
| 'H'->printfn "Hotel"
//if the value of chrletter is i or I display India
| 'I'->printfn "India"
//if the value of chrletter is j or J display Juliet
| 'J'->printfn "Juliet"
//if the value of chrletter is k or K display Kilo
| 'K'->printfn "Kilo"
//if the value of chrletter is l or L display Lima
| 'L'->printfn "Lima"
//if the value of chrletter m or M display Mike
| 'M'->printfn "Mike"
//if the value of chrletter is n or N display November
| 'N'->printfn "November"
//if the value of chrletter is o or O display Oscar
| 'O'->printfn "Oscar"
//if the value of chrletter is p or P display Papa
| 'P'->printfn "Papa"
//if the value of chrletter is q or Q display Quebec
| 'Q'->printfn "Quebec"
//if the value of chrletter is r or R display Romeo
| 'R'->printfn "Romeo"
//if the value of chrletter is s or S display Sierra
| 'S'->printfn "Sierra"
//if the value of chrletter is t or T display Tango
| 'T'->printfn "Tango"
//if the value of chrletter is u or U display Uniform
| 'U'->printfn "Uniform"
//if the value of chrletter is v or V display Victor
| 'V'->printfn "Victor"
//if the value of chrletter is w or W display Whiskey
| 'W'->printfn "Whiskey"
//if the value of chrletter is x or X display X-Ray
| 'X'->printfn "X-Ray"
//if the value of chrletter is y or Y display Yankee
| 'Y'->printfn "Yankee"
//if the value of chrletter is z or Z display Zulu
| 'Z'->printfn "Zulu"
//otherwise
| _ ->printfn "Invalid input"
The last statement |_ is similar to the
default statement in other programming languages Switch conditional structure. It is automatically executed when no pattern match is found. Don't forget to add it at the end of every match with statement otherwise you will get an “Incomplete pattern matches on this expression” error.


Problem: Make an application that will ask the month number and display the corresponding month name and the number of days in it. Use pattern matching.

//use F# library
open System
//change the CLI title
System.Console.Title<-"Display Month Name"
//adds color to our console application
System.Console.ForegroundColor<-ConsoleColor.Blue
System.Console.BackgroundColor<-ConsoleColor.White
//asks the user to enter a month number
printfn "Enter a month number(1-12):"
let intmonth=Convert.ToInt32(System.Console.ReadLine())
//clear the screen   
System.Console.Clear()
//match the value of intmonth to the ff. values
match intmonth with
//if the value of intmonth is 1 display January
| 1 ->printfn "January(31 days)"
//if the value of intmonth is 2 display February
| 2 ->printfn "Febrary(28/29 days)"
//if the value of intmonth is 3 display March 
| 3 ->printfn "March(31 days)"
//if the value of intmonth is 4 display April
| 4 ->printfn "April(30 days)"
//if the value of intmonth is 5 display May
| 5 ->printfn "May(31 days)"
//if the value of intmonth is 6 display June
| 6 ->printfn "June(30 days)"
//if the value of intmonth is 7 display July
| 7 ->printfn "July(31 days)"
//if the value of intmonth is 8 display August
| 8 ->printfn "August(31 days)"
//if the value of intmonth is 9 display September
| 9 ->printfn "September(30 days)"
//if the value of intmonth is 10 display October
| 10 ->printfn "October(31 days)"
//if the value of intmonth is 11 display November
| 11 ->printfn "November(30 days)"
//if the value of intmonth is 12 display December
| 12->printfn "December(31 days)"
//otherwise
| _ ->printfn "Invalid input"

That's all for now my Visual F# friends. Ciao!

Visual F# 100 Examples: Example 12 and 13

This is the continuation of our planned 100 Visual F# examples. By the way, the bugs in examples number 7 to 11 had been fixed. My apologies, I should’nt have written those without using Visual F# compiler:)


Problem: Make a console application that will asks the user to enter the day that he was born and display his character or future based on the famous nursery rhyme written in England, “Monday’s Child”.

open System
//changes the console application title
System.Console.Title<-"Tell the Future"
//adds foreground color
System.Console.ForegroundColor<-ConsoleColor.Cyan
printfn "What day were you born?"
let strday=System.Console.ReadLine()
//clears the screen
System.Console.Clear()
//converts the inputs to lowercase then compare it our
//specified values
if strday.ToLower()="monday" then
    printfn "Monday's child is fair of face"
else if strday.ToLower()="tuesday" then
    printfn "Tuesday's child is full of grace"
else if strday.ToLower()="wednesday" then
    printfn "Wednesday's child is full of woe"
else if strday.ToLower()="thursday" then
    printfn "Thurdays's child has far to go"
else if strday.ToLower()="friday" then
    printfn "Friday's child is loving and giving"
else if strday.ToLower()="saturday" then
    printfn "Saturday's child works hard for a living"
else if strday.ToLower()="sunday" then
    printfn "Sunday's child is bonny and blithe and good and gay"
else
    printfn "Invalid input"
Problem: Develop a console application that will asks the wind speed in kilometer per hour(kph) and display its equivalent Philippine Storm Signal number.
open System
//changes the console application title
System.Console.Title<-"Determine Storm Signal Number"
//adds foreground color
System.Console.ForegroundColor<-ConsoleColor.Cyan
printfn "Enter wind speed(kph):"
let intspeed=Convert.ToInt32(System.Console.ReadLine())
//clears the screen
System.Console.Clear()
//if the wind speed ranges from 30 to 60
if intspeed>=30 && intspeed<=60 then
    printfn "Storm signal number 1"
//if the wind speed ranges from 61 to 100
else if intspeed>60 && intspeed<=100 then
    printfn "Storm signal number 2"
//if the wind speed ranges from 101 to 185
else if intspeed>100 && intspeed<=185 then
    printfn "Storm signal number 3"
//if the wind speed is greater than 185
else if intspeed>185 then
printfn "Storm signal number 4"
else 
printfn "Invalid input"

Visual F# 100 Examples: Example 11

Problem: Make a simple crack the treasure chest console application game.

// Learn more about F# at http://fsharp.net

open System
//change the title to Crack the Safe
System.Console.Title<-"Crack the Safe"
//change the foreground color to green
Console.ForegroundColor<-ConsoleColor.Green
//dislay the game title screen
printfn "\t\t\t Crack the Safe"
printfn "\t\t\t Press enter to continue..."
//waits for a keypress from the user
System.Console.ReadLine()|>ignore
//Game action sequence
printfn "\t\t\t You have found a legendary treasure chest"
printfn "\t\t\t believed to contain the rarest gem on Earth"
printfn "\t\t\t Press enter to continue... "
//waits for a keypress from the user
System.Console.ReadLine()|>ignore

printfn "\t\t\t this chest can be opened only by"
printfn "\t\t\t entering a mysterious 4-digit key code"
printfn "\t\t\t Press enter to continue..."
//waits for a keypress from the user
System.Console.ReadLine()|>ignore

let random=new Random()
let intkeycode=Convert.ToInt32(random.Next(1000,9999))

printfn "\t\t\tEnter the keycode:"
let intusercode= Convert.ToInt32(Console.ReadLine())
//if usercode is equal to the computer generated code then
if intusercode=intkeycode then
//display a congratulatory message
    printfn "\t\t\Congrats You have opened the treasure chest."

//otherwise 
else
    printfn "\t\t\tInvalid Code"

printfn "\t\t\tPress enter to continue... "
System.Console.ReadLine()|>ignore
printfn "\t\t\tGame Over"

Visual F# 100 Examples: Example 8 to 10

Problem: Make a console application that will accept five numbers and display the sum.
open System
//change the title to Add Five Numbers
System.Console.Title<-"Add Five Numbers "
//change the foreground color to cyan
Console.ForegroundColor<-ConsoleColor.Cyan
printfn "\t\t\tEnter the first number:"
let intnum1=Convert.ToInt32(System.Console.ReadLine())
printfn "\t\t\tEnter the second number:"
let intnum2=Convert.ToInt32(System.Console.ReadLine())
printfn "\t\t\tEnter the third number:"
let intnum3=Convert.ToInt32(System.Console.ReadLine())
printfn "\t\t\tEnter the fourth number:"
let intnum4=Convert.ToInt32(System.Console.ReadLine())
printfn "\t\t\tEnter the fifth number:"
let intnum5=Convert.ToInt32(System.Console.ReadLine())
let  intsum=intnum1+ intnum2 + intnum3 + intnum4 + intnum5
printfn "\t\t\tThe sum is:%i" intsum

Problem: Make a console application that will ask the power transmitted and power received then display the power loss value.
open System
//change the title to Calculate Power Loss
System.Console.Title<-"Calculate Power Loss "
//change the foreground color to cyan
Console.ForegroundColor<-ConsoleColor.Cyan
printfn "\t\t\t\tPower transmitted:"
let dblpowertrans=Convert.ToDouble(System.Console.ReadLine())
printfn "\t\t\tPower recieved:"
let dblpowerrec=Convert.ToDouble(System.Console.ReadLine())
let dblpowerloss= dblpowertrans/ dblpowerrec
printfn "\t\t\t Power loss:%f " dblpowerloss

Problem: Develop a console application that will ask the base value and height value then display the volume of a pyramid.
open System
//change the title to Volume of a Pyramid
System.Console.Title<-" Volume of a Pyramid"
//change the foreground color to cyan
Console.ForegroundColor<-ConsoleColor.Cyan
printfn "\t\t\tBase value:"
let dblbase=Convert.ToDouble(System.Console.ReadLine())
printfn "\t\t\tHeight value:"
let dblheight=Convert.ToDouble(System.Console.ReadLine())
let  dblvolume=(dblbase*dblheight)/3.0
printfn "\t\t\tVolume of a pyramid:%f" dblvolume

Visual F# 100 Examples: Example Number 7

So far I have been sharing to you guys some examples of Window Based application in Visual F#. This time, for variation sake lets make some console application:

Problem: Make a simple console application mind reader game.
open System
//change the title to Simple Mind Reader Game
System.Console.Title<-"Simple Mind Reader Game"
//change the foreground color to cyan
Console.ForegroundColor<-ConsoleColor.Cyan
//dislay the game title screen
printfn "\t\t\t Mind Reader Game"
printfn "\t\t\tPress enter to continue..."
//waits for a keypress from the user
System.Console.ReadLine()|>ignore
System.Console.Clear()
//the following does the game action sequence
printfn "\t\t\t Think of a five-digit number that has five unique numbers(Eg. 12345)"
printfn "\t\t\tPress enter to continue..."
System.Console.ReadLine()|>ignore
System.Console.Clear()

printfn "\t\t\t Reverse the numbers then subtract the smaller number from the larger number(Eg.54321- 12345)"
printfn "\t\t\tPress enter to continue..."
System.Console.ReadLine()|>ignore
System.Console.Clear()

printfn "\t\t\t Add 10000 to the difference"
printfn "\t\t\t Press enter to continue..."
System.Console.ReadLine()|>ignore
System.Console.Clear()

printfn "\t\t\tVisualize the sum while I try to read your mind."
printfn "\t\t\tPress enter to continue..."
System.Console.ReadLine()|>ignore
System.Console.Clear()

printfn "\t\t\tThe sum is…"
printfn "\t\t\tPress enter to continue..."
System.Console.ReadLine()|>ignore
System.Console.Clear()

printfn "\t\t\tThe sum is…"
printfn "\t\t\tPress enter to continue..."
System.Console.ReadLine()|>ignore
System.Console.Clear()

printfn "\t\t\tThe sum is…"
printfn "\t\t\tPress enter to continue..."
System.Console.ReadLine()|>ignore
System.Console.Clear()

printfn "\t\t\t51976"