MongoDB Tutorial 2: Basic Window App

 

MongoDB Plugin
UniServer 6-Carbo.

MongoDB

Introduction

Our main application is a Windows interface for running MongoDB. Interestingly the real work for this application has already been covered. We have a set of functions that perform all the functionality we need.

A windows application is nothing more than a pretty user interface. One redeeming feature is providing user feedback. If it was not for this I would suggest stick with batch files and scripts.

Is creating a Windows application difficult and complex? Yes if you want to do it the hard way by compiling and using winapi directly. Alternatively WinBinder makes it a snip; all you need to know is a small amount of PHP.

Never reinvent the wheel use one of the many examples as a template. Check out these links for additional information:

This tutorial is provided with a working template see below.

Top

Window template

Template is located in folder z_mongo\UniServer\unicon\tray_menu_2 we renamed it to mongo_db.php

Content of this file shown below

<?php

chdir(dirname(__FILE__)); // Change wd to this files location

include "winbinder/winbinder.php";             // Location of WinBinder library

//=== Application name
define("APPNAME",   "MongoDB Control" );

//=== Button Text
define("START_DB_BTXT",       "Start MongoDB and Apache"); 
define("STOP_DB_BTXT",        "Stop MongoDB and Apache"); 
define("START_CLIENT_BTXT",   "Start Mongo Client"); 
define("RUN_PHPMOADMIN",      "Run phpMoAdmin"); 
define("OPEN_CMD_BTEXT",      "Open cmd Window"); 
define("HELP_INFO_BTXT",      "Help and Information"); 

//-- Constants ----------------------------------------------------------------

define('ID_DB_BUTTON',         1010);
define('ID_CLIENT_BUTTON',     1020);
define('ID_PHPMOADMIN_BUTTON', 1030);
define('ID_OPEN_CMD_BUTTON',   1040);
define('ID_HELP_BUTTON',       1050);

// Common variables

$win_mongo;             // Window
$statusbar_mongo;       // Status bar

//=== 1) Create main window ---------------------------------------------------
// create main window

define("CAPTION", APPNAME);             // Set caption to match application
if(wb_get_instance(CAPTION, TRUE))      // Is there an existing instance?
    die;                                // Yes: bring it to the front and quit

$win_mongo = wb_create_window(NULL, AppWindow, APPNAME, WBC_CENTER, WBC_CENTER, 207,230, 0);

//=== 2) Create controls for the main window ----------------------------------
wb_create_control($win_mongo, Frame, "Mongo",             5, 5, 190, 172, 0, 0, 0, 0);

wb_create_control($win_mongo, PushButton,      START_DB_BTXT, 15,  25, 170, 25, ID_DB_BUTTON, 0, 0, 0);
wb_create_control($win_mongo, PushButton,  START_CLIENT_BTXT, 15,  55, 170, 25, ID_CLIENT_BUTTON, 0, 0, 0);
wb_create_control($win_mongo, PushButton,     RUN_PHPMOADMIN, 15,  85, 170, 25, ID_PHPMOADMIN_BUTTON, 0, 0, 0);
wb_create_control($win_mongo, PushButton,     OPEN_CMD_BTEXT, 15, 115, 170, 25, ID_OPEN_CMD_BUTTON, 0, 0, 0);
wb_create_control($win_mongo, PushButton,     HELP_INFO_BTXT, 15, 145, 170, 25, ID_HELP_BUTTON, 0, 0, 0);

$statusbar_mongo = wb_create_control($win_mongo, StatusBar, " Displayed important information");

//=== 3) Assign handler function to the main window  --------------------------
  wb_set_handler($win_mongo, "process_mongo");
  wb_set_image($win_mongo, getcwd()."/images/utray.ico");  // Add logo   

//=== 5) Enter application loop -----------------------------------------------
wb_main_loop();   

//=== 4) Handler Function -----------------------------------------------------
function process_mongo($window, $id){
  global $win_mongo;
  global $statusbar_mongo;

    switch($id) {

        case 1010:
        case 1020:
            wb_message_box($window, "Button #$id was pressed.");
            break;

        case IDCLOSE:                         // The constant IDCLOSE is predefined
            wb_destroy_window($window);       // Destroy the window
            break;
     }
}

//------------------------------------------------------------------ END OF FILE

?>

Top

Overview

Collectively it looks complex however taking small chunks it really is simple:

  1. First line change-working directory.
  2. Define application name constant
  3. Define several constants to display button text
  4. Each button must have a unique number hence more constants
  5. Define some common variables
  • Section 1
  1. Check for another running instance we only want one active
  2. Create the window
  • Section 2
  1. Add a frame
  2. Add buttons to the window
  • Section 3
  1. Set an handler function to process requests to window.
  2. Add a logo appears top left of window.
  • Section 5
  1. Call main loop function keeps application alive
  • Section 4
  1. This is the handler function it processes all requests to the window.
  2. All button clicks are directed to this function.
  3. Buttons are identified by a unique number and intercepted using a switch statement.
  • Run template double click on
    Run_mongo_db.bat

Template produces the following:

 

Top

Includes

We are integrating this plugin into Uniform Server’s architecture. Gaining access to this requires several includes as follows add this to our template.

  • include_once "../main/includes/config.inc.php"; // US Control
  • include_once "../main/includes/functions.php"; // US Control
  • include_once "mongo_db_inc.php"; // Plugin

Top

Initialisation - Script start

Have servers moved

This may be first time servers are run or severs have been relocated (e.g moved to a USB memory stick or moved to different folder).

First thing a script must perform is to check if the servers have moved, if they have re-write all server absolute paths.

Just below the include section add the following:

//== Checked servers moved
run_location_tracker();   // Have servers moved if moved
                          // update configuration accordingly

Top

Configure server to run MongoDB

When this plugin is run for the first time it needs to configure the server to run MongoDB. PHP configuration files are updated to include the Mongo extension. Having done this a file is created indicating Mongo was installed.

Hence every time plugin is started file existence is checked and appropriate action taken.

Just below Server moved code add the following:

//== Configure server to run monoDB 
if(!file_exists(INSTALLED_TXT)){  // File not found 
  config_mongo();                 // Update PHP ini files
 
  //== Create installed file 
  $conf[] = "Php configured\n";
  $conf[] = "php_cli configured\n";

  $str1 = implode($conf);                 // Convert array to string
  file_put_contents(INSTALLED_TXT,$str1); // Save string to file
}

Top

New function config_mongo()

Add the following function to mongo_db_inc.php

//=== Config Mongo ============================================================
function config_mongo(){

  $str = 'extension=php_mongo.dll'; // String to find

   $file = file_get_contents(PHP_INI_1); // Read file
   if(!strpos($file, $str)) {            // Check for string
     $fh = fopen(PHP_INI_1, 'a');        // Not found 
     fwrite($fh, $str."\n");             // Add it to file
     fclose($fh);                        // Close file pointer
   }

   $file = file_get_contents(PHP_INI_2);
   if(!strpos($file, $str)) {
     $fh = fopen(PHP_INI_2, 'a');
     fwrite($fh, $str."\n");
     fclose($fh);
   }

   $file = file_get_contents(PHP_INI_3);
   if(!strpos($file, $str)) {
     $fh = fopen(PHP_INI_3, 'a');
     fwrite($fh, $str."\n");
   }

}
//======================================================== END Coonfig Mongo ===

Top

New paths

There are several new paths that require adding to mongo_db_inc.php as follows:

  • define("MONGO_PHP", "$mongo_base_f/UniServer/usr/local/php"); // PHP
  • define("INSTALLED_TXT", "$mongo_base_f/UniServer/usr/local/mongo/us_info/installed.txt"); // Dummy file
  • define("PHP_INI_1", MONGO_PHP."/php.ini"); //php main configuration
  • define("PHP_INI_2", MONGO_PHP."php.ini_delvelopment_nano"); //php dev configuration
  • define("PHP_INI_3", MONGO_PHP."/php.ini_production_nano"); //php pro configuration

Top

Initialisation - Window

When our application is run we have an opportunity to nag a user. We know the server must be shutdown before turning PC off; hence inform a new user of this fact. Allow users to disable nagging, this can be implemented by creating a file.

Add the following line to mongo_db_inc.php

define("NO_NAG_TXT", "$mongo_base_f/UniServer/usr/local/mongo/us_info/no_nag.txt");    // Dummy file

A user may have intentionally closed the application with server running. On resting the application check for server running and toggle button text accordingly.

Add the following function to end of mongo_db.php

//=== Initialise Main =========================================================
function mongo_init(){
  global $win_mongo;

  //=== Nag User
  //== Checkuser disabled nagging
  if(!file_exists(NO_NAG_TXT)){  // File not found 

   $str  = "Before turning your PC off \n";
   $str .= "Ensure you have closed MongoDB \n\n";

   $str .= "Failure to do will result in data loss\n";
   $str .= "Data from RAM needs to be written to disk.\n\n";

   $str .= "Display this alert next time you start MongoDB?";

   if(!wb_message_box($win_mongo, $str, "IMPORTANT", WBC_YESNO)){
     // User wants to disable nagging hence create file 
     //== Create or update a new redirect page 
       $no_nag[] = "To enable nagging\n";
       $no_nag[] = "Delete this file\n";

       $str_no_nag = implode($no_nag);            // Convert array to string
       file_put_contents(NO_NAG_TXT,$str_no_nag); // Save string to file
   } 
  }
  //=== Check mongo runnung
  if(mongodb_running()){  // MongoDB running
    wb_set_text(wb_get_control($win_mongo,    ID_DB_BUTTON),STOP_DB_BTXT);   // set button text
    wb_set_enabled(wb_get_control($win_mongo, ID_PHPMOADMIN_BUTTON), TRUE);  // Enable Admin button 
  }
  else{                   // MongoDB not running           
    wb_set_text(wb_get_control($win_mongo,    ID_DB_BUTTON),START_DB_BTXT);  // set button text
    wb_set_enabled(wb_get_control($win_mongo, ID_CLIENT_BUTTON), FALSE);     // Disable Client button 
    wb_set_enabled(wb_get_control($win_mongo, ID_PHPMOADMIN_BUTTON), FALSE); // Disable Admin button 
  }

}//=================================================== END Initialise Main ===

We need to call this function add the following line to end of section 3

  mongo_init();

Top

Test

  • Run Run_mongo_db.bat (See image on right)
  1. Note top button text start
  2. Client button is greyed out
  3. phpMoAdmin button is greyed out
  • Close window
  • Start MongoDB (alt_control\Run_start_mongo.bat)
  1. Note top button text changes to stop
  2. Client button is enabled
  3. phpMoAdmin button is enabled
  • Stop server (alt_control\Run_stop_mongo.bat)
  • Close window

 

Top

Summary

With a working window we need to add functionality to each button.

Net page covers lower two buttons.

Top