473,378 Members | 1,471 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

C# - Installer - Sample code to run batch file via custom action

Hi all,

Here's some work in progress that should allow you to run a batch file as a
custom action in a VS deployment project. Yup I know you can use js or wsh,
but the target may not have either.. Essentially it's just a wrapper for the
Process class and a command interpreter.

Warning, it only partly works. I had wanted to pass in

(a) The name of the batch file (through "BatchFileName"), and
(b) A set of arguements for the batch file (through "BatchFileArgs")

via the CustomActionData property exposed in the VS designer

eg.

/BatchFileName="[TARGETDIR]\InstallThirdParty.bat"

Unfortunately, I can't find a way to pass embedded double-quote characters
through BatchFileArgs. Passing embedded quotes is necessary when the
arguements represent paths with embedded spaces.. I'd love to know if anyone
has a workaround.

using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.IO;

namespace InstallHelper
{
[RunInstaller(true)]
public class BatchBootStrap : System.Configuration.Install.Installer
{
Process mCmdInterpreter = new Process();

public override void Install(IDictionary savedState)
{
Trace.WriteLine("InstallHelper.BatchBootStrap.Inst all - enter");
string BatchFileName = Context.Parameters["BatchFileName"];

try
{
base.Install(savedState);

Path.IsPathRooted(BatchFileName); // throws ArgumentException if
BatchFileName contains any InvalidPathCharacters

if (!File.Exists(BatchFileName))
throw new Exception(string.Format("Batch file \"{0}\", does not
exist", BatchFileName));

mCmdInterpreter.StartInfo.FileName =
Environment.GetEnvironmentVariable("ComSpec");

if (!File.Exists(mCmdInterpreter.StartInfo.FileName))
throw new Exception(string.Format("Command interpreter \"{0}\" not
present, probably non standard or corrupted OS installation",
mCmdInterpreter.StartInfo.FileName));

string BatchFileArgs = Context.Parameters["BatchFileArgs"];

// The ComSpec arguement format string supports space delimeted
double-quote framed args
// BatchFileArgs represents a space delimited list of arguements.
// Individual path / file name arguements that are passed via
BatchFileArgs must be "" framed if they contain spaces
// eg. BatchFileArgs could be the following '"C:\Test Dir\"
C:\TestDir2 123'
//

mCmdInterpreter.StartInfo.Arguments = string.Format("/c \"\"{0}\"
{1}\"", BatchFileName, BatchFileArgs);
mCmdInterpreter.StartInfo.UseShellExecute = false;
mCmdInterpreter.StartInfo.RedirectStandardOutput = true;
//mCmdInterpreter.StartInfo.RedirectStandardError = true;

mCmdInterpreter.Start();

Trace.WriteLine(string.Format("InstallHelper.Batch BootStrap.Install
- Running batch file \"{0}\"\n Args ==> {1}", BatchFileName, BatchFileArgs));
mCmdInterpreter.WaitForExit(); // blocking call

string StandardOutput = mCmdInterpreter.StandardOutput.ReadToEnd();
Trace.WriteLine(string.Format("InstallHelper.Batch BootStrap.Install
- Batch file complete, output was as follows..\n{0}", StandardOutput));

string StandardOutputLogFileName =
string.Format("{0}.{1:yyyy_MM_dd_a\\t_HH_mm_ss}.lo g", BatchFileName,
DateTime.Now);
Trace.WriteLine(string.Format("InstallHelper.Batch BootStrap.Install
- Trying to log output to \"{0}\"", StandardOutputLogFileName));

try
{
StreamWriter StandardOutputLog = new
StreamWriter(StandardOutputLogFileName);
StandardOutputLog.Write(StandardOutput);
StandardOutputLog.Flush();
StandardOutputLog.Close();
Trace.WriteLine(string.Format("{0}",
"InstallHelper.BatchBootStrap.Install - log written successfully"));
}
catch (Exception LogErr)
{
Trace.WriteLine(string.Format(
"InstallHelper.BatchBootStrap.Install - An exception occurred
whilst trying to log output to \"{0}\", {1}\n Check user priviledge and
quotas.",
StandardOutputLogFileName,
LogErr.Message));
}
}
catch (Exception Err)
{
string DetailedErrMessage = string.Format(
"InstallHelper.BatchBootStrap.Install - A fatal exception occurred
whilst trying to run batch file \"{0}\". {1}",
BatchFileName,
Err.Message);
Trace.WriteLine(DetailedErrMessage);
throw(new Exception(DetailedErrMessage, Err));
}
finally
{
Trace.WriteLine("InstallHelper.BatchBootStrap.Inst all - exit");
}
}

public BatchBootStrap() : base()
{
}
}
}

May 29 '06 #1
1 24238
"steve" <st***@discussions.microsoft.com> wrote in message
news:88**********************************@microsof t.com...
Hi all,

Here's some work in progress that should allow you to run a batch file as
a
custom action in a VS deployment project. Yup I know you can use js or
wsh,
but the target may not have either.. Essentially it's just a wrapper for
the
Process class and a command interpreter.

Warning, it only partly works. I had wanted to pass in

(a) The name of the batch file (through "BatchFileName"), and
(b) A set of arguements for the batch file (through "BatchFileArgs")

via the CustomActionData property exposed in the VS designer

eg.

/BatchFileName="[TARGETDIR]\InstallThirdParty.bat"

Unfortunately, I can't find a way to pass embedded double-quote characters
through BatchFileArgs. Passing embedded quotes is necessary when the
arguements represent paths with embedded spaces.. I'd love to know if
anyone
has a workaround.
<skip>
string BatchFileArgs = Context.Parameters["BatchFileArgs"];

// The ComSpec arguement format string supports space delimeted
double-quote framed args
// BatchFileArgs represents a space delimited list of arguements.
// Individual path / file name arguements that are passed via
BatchFileArgs must be "" framed if they contain spaces
// eg. BatchFileArgs could be the following '"C:\Test Dir\"
C:\TestDir2 123'
//

mCmdInterpreter.StartInfo.Arguments = string.Format("/c \"\"{0}\"
{1}\"", BatchFileName, BatchFileArgs);


why doing so? if parameter ( BatchFileArgs ) has value "C:\test 123" adding
more double-quotes?

You can detect if there are double quotes in the BatchFileArgs, an
appropriately preprocess it ( add or remove double quotes )
--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
May 29 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Arun Bhalla | last post by:
I'm working with VS.NET 2003 and .NET 1.1 (not SP1) on Windows XP SP1. My application is using the Windows Installer Bootstrap. (I may have also installed a module which detects requirements (.NET...
0
by: Arun Bhalla | last post by:
I'm having some inconsistency problems with my deployment project ("Setup") and its custom actions ("Installer"). I'm using Visual Studio .NET 2003 (.NET 1.1, no service pack) on Windows XPSP1. ...
2
by: MENTAT | last post by:
Hi, I am trying to create an installer for my web application. So I added a web setup project to my solution (I am using VS.NET 2003). Been playing around with it since then and it basically...
1
by: Craig | last post by:
I have added a 'Textboxes (A)' to my UI installer project along with a custom action to pass the value back to a class I've written to override the void Install function. As long as the text is...
1
by: BuddyWork | last post by:
Hello, When a particular user (has administrator rights) on a Windows 2000 Server SP4 tries to run any MSI's we get the message mentioned in the subject. If we logon with another user that has...
3
by: DC Gringo | last post by:
Hi, I'm trying to use a custom action to modify a database (rather than create one) using the VS.NET '03's help example called "Custom Action to Create Database During Installation". I've made...
3
by: Mark Assousa | last post by:
Hi, I'm having trouble finding the right news group for this posting so here goes... I am attempting to execute some special actions within an installation project for a standard .Net Windows...
4
by: Shiraz | last post by:
Hi I'm using Visual Studio Installer to make my installer, and have not as yet figured out a straightforward way to use it to set environmental variables. Amongst the various things I tried, I'm...
0
by: kplkumar | last post by:
Hi This is what we have, our MSI has custom actions which are .vbs which essentially calls a batch file that in turn calls .sql files to install the database. The vbs file has something like,...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.