Translate

How to create a Windows Service to run scripts using C# | Part 2

How to create a Windows Service to run scripts using C# | Part 2
Now that PHPWinService is complete, we need to move on to next steps. Let's take a look at task.bat(last article we promised you, we will take a look at service manual installation/uninstalltion process, before that let's take a look at the batch process and php script).


task.bat

Fire up your favourite text editor and create a file call "task.bat". Add below code to the file and save the file to root of C: drive.
@echo off
cd\
set path=c:\xampp\php;
cd "c:\"
php win.php
exit
I won’t be going into in-depth detail about the specifics involved in creating a batch file, and will only explain so very briefly.

Fundamentally, you can imagine a batch file as the same as that of working with command-line, although with a minor difference; during runtime the batch file will convert all its entries into a series of executables for command-line.

For this, you have to initially prompt the batch file as to whether it is code is enabled for display or vice versa – and this is correspondingly done so from the very first line. In the 2nd line, we will CD into the root i.e. the C: driver (most commonplace for Windows). In the 3rd line we set up a PHP compiler as a temporary environmental variable in order to run win.php file from command line. Finally, the 4th and 5th lines are for accessing the win.php file, while the very last line is to exit the command line and shut the batch file once the task is complete.

win.php

$hostname = "MYSQL_HOST_NAME";
$username = "MYSQL_USERNAME";
$password = "MYSQL_PASSWORD";
    
try{
     
  $pdo = new PDO("mysql:host=$hostname;
   dbname=phpwinservice",$username,$password);
  
}catch(PDOException $e){
  
  echo $e->getMessage();
}
 
$params = array(':id' => '1');
$sth = $pdo->prepare
 ("INSERT INTO win(id) VALUES(:id)");
$sth->execute($params);
The above code is very simple and straightforward – it is a PHP script that connects to the local MYSQL phpwinservice database and inserts "1" to win table every time win.php call.

Below is the simple SQL for creating databases and win tables:
CREATE DATABASE phpwinservice;

USE phpwinservice;

CREATE TABLE win(

  uid TINYINT NOT NULL AUTO_INCREMENT,
  id TINYINT NOT NULL DEFAULT NULL 
   COMMENT 'PHPWinService',
  PRIMARY KEY(uid)
)
COMMENT='win service data table'
COLLATE='utf8_unicode_ci'
ENGINE=MyISAM;

Related post -
How to create a Windows Service to run scripts using C# | Part 1
How to create a Windows Service to run scripts using C# | Part 3
How to create a setup wrapper with Microsoft Visual Studio

No comments:

Post a Comment

Nerdcore is a free tutorial website about latest technological development, designing and programming. Nerdcore have tuts for all skill levels in web, desktop and mobile application development. Tuts and courses we provided are carefully crafted by expert developers and designers from www.waan.it