Disable Wix Custom action on /quiet /silent - c#

In a WIX custom action, is there a way to detect whether the MSI was invoked with /silent or /quiet command line switches? Basically what I want is to not execute the custom action (since it shows a form) or handle it differently if these command line switches were passed but I am unable to find this out.
Is there a way to possibly detect it?

You can check the property UILevel and execute your CA based on your conditions.

I finally figured it out. Wix basically always sets the UILevel property to 2.0. It has its own property called WixBundleUILevel. Now important thing here is that prior to Wix 3.11 this WixBundleUILevel was an internal property and was not accessible to Bundle projects or MSI Custom Actions. So here is what I did
Defined a property in MSI called UI_LEVEL (important, make it all upper case)
In Bundle.wxs, right where I call MSIPackage, I set the UI_LEVEL property like so
<MsiPackage SourceFile="$(var.MsiPath)">
<MsiProperty Name="UI_LEVEL" Value="[WixBundleUILevel]" />
</MsiPackage>
Then finally in the custom action I check for this property like
int uiLevel;
if (int.TryParse(session["UI_LEVEL"], out uiLevel))
{
if (uiLevel == 4)
using (var form = new WhatsNew())
{
form.ShowDialog();
}
else
session.Log("Skipping What's new dialogue as UI Level is not 4");
}
else
{
session.Log("Couldnt figure out the UI level, so skipped the prompt");
}
And finally
here are the possible values of this f**ed up property
WixBundleUILevel Value Burn parameters
BOOTSTRAPPER_DISPLAY_FULL 4 (none)
BOOTSTRAPPER_DISPLAY_PASSIVE 3 /silent
BOOTSTRAPPER_DISPLAY_NONE 2 /quiet

Related

Use value dialog installation in windows service c#

We are develop a windows service for open a specific port.
Now this port can be custom for the user during the installation in a dialog.
I want know a possibility of capture this value and pass to the code of the service
if (myServer == null)
{
int port= int.Parse(ConfigurationManager.AppSettings["port1"]);
myServer = new NHttp.HttpServer
{
EndPoint = new System.Net.IPEndPoint(0, port)
};
}
myServer.Start();
I try using a value in app.config and editing this value in the installer:
public override void Install(System.Collections.IDictionary stateSaver)
{
string portServer= this.Context.Parameters["CTPUERTO"];
System.Configuration.ConfigurationManager.AppSettings.Set("port1", portServer);
base.Install(stateSaver);
}
CTPUERTO is the name of the textbox in the dialog install
You add the optional TextBoxes(A) dialog to your setup project and the user enters that text (in EDITA1 in the docs):
https://msdn.microsoft.com/en-us/library/e04k6f53(v=vs.100).aspx
Then in your custom action you'd add the parameter with something like:
/port1=[EDITA1]
in CustomActionData, then access it using the kind of code you showed, in an installer class.
These might be useful:
.net Setup Project: How to pass multiple CustomActionData fields
https://www.codeproject.com/Articles/12780/A-Setup-and-Deployment-project-that-passes-paramet
The main issue with this (because of the way VS setup projects work) is that you cannot validate it at the time it's entered. Custom actions in VS setup projects run after the UI and after everything is installed, so if your custom finds it's incorrect then you fail the whole install and roll back.

How to handle.NET user setting path changes with assembly info changes?

I've noticed that when changes are made to the assemblyinfo.cs the hash that is used to generate the user settings path is changed.
The screen grab shows the two directories that were created when I changed the copyright date from 2014 to 2015.
I don't imagine I will change other items in the assemblyinfo, but I'm pretty sure I will change the copyright if I do another release next year.
What's the best way to handle this?
Thanks in advance.
The ApplicationSettings class has an Upgrade method which will move the existing setting values to the new settings file.
What I have done previously is to have a boolean flag as a setting (named something like UpgradeRequired) which indicates if an upgrade to the settings is required. This is set to true as default.
When the application starts, check this flag and call the Upgrade() method if required (and then set the UpgradeRequired setting to false).
if (Settings.Default.UpgradeRequired)
{
Settings.Default.Upgrade();
Settings.Default.UpgradeRequired = false;
Settings.Default.Save();
}

Pass value from command line to Custom action-Burn

I am in a need to pass the value from command line to custom action.The custom action should get the value from command line and modify one file(app.config) during installation of EXE.I have the below code in custom action
if (Context.Parameters["ENV"] == "test") //Test environment
{
authEndPoint = "http://192.168.168.4/api/user_authentication/";
}
else if (Context.Parameters["ENV"] == " ") //Production environment
{
authEndPoint = "https://livesiteurl/api/user_authentication/";
}
I want to install the exe file like below
myapplication.exe env=test
I seen lot of sample to pass the value from command line to msi. How to pass the value from command line to CA and modify the app.config file.
There are better ways to do what you're trying to do here than use a custom action. Take a look at this for how use the WiXUtilExtension to modify the file, then create a property and reference it from the command line. If you still need/want to use a bootstrapper you can set that property you created with MsiProperty inside MsiPackage in the bundle.

Send Custom Action Data via Command Line for Visual Studio Installer

I have a Visual Studio Installer that has a custom UI with one text box recovering a value that is set to QUEUEDIRECTORY property. Then I have a custom action (an Installer class) that passes in that property value with this line /queuedir="[QUEUEDIRECTORY]" - and the installer works great.
Now, I need to send that value via the command-line so that this installer can be run by system administrators all across the organization. So, I tried the following command line statements but it just doesn't work.
msiexec /i Setup.msi QUEUEDIRECTORY="D:\temp"
Setup.msi QUEUEDIRECTORY="D:\temp"
Setup.msi queuedir="D:\temp"
msiexec /i Setup.msi queuedir="D:\temp"
Further, I can't seem to find anything online that doesn't feel like they hacked it because they just couldn't find the solution. I mean I've found some solutions where they are editing the MSI database and everything, but man that just doesn't seem like it's the right solution - especially since I'm using Visual Studio 2010 - Microsoft has surely made some enhancements since its initial release of this offering.
Here is one of the articles that appears would work but still really feels like a hack.
At any rate, I hope that you can help me out!
This is what I did to add command line only property values to my MSI in Visual Studio 2010. It's similar to the accepted answer, but less hacky. Create CommandLineSupport.js in setup project (.vdproj) directory, with the following code:
//This script adds command-line support for MSI installer
var msiOpenDatabaseModeTransact = 1;
if (WScript.Arguments.Length != 1)
{
WScript.StdErr.WriteLine(WScript.ScriptName + " file");
WScript.Quit(1);
}
WScript.Echo(WScript.Arguments(0));
var filespec = WScript.Arguments(0);
var installer = WScript.CreateObject("WindowsInstaller.Installer");
var database = installer.OpenDatabase(filespec, msiOpenDatabaseModeTransact);
var sql
var view
try
{
sql = "INSERT INTO `Property` (`Property`, `Value`) VALUES ('MYPROPERTY', 'MYPROPERTY=\"\"')";
view = database.OpenView(sql);
view.Execute();
view.Close();
database.Commit();
}
catch(e)
{
WScript.StdErr.WriteLine(e);
WScript.Quit(1);
}
Then click on your Deployment Project in Visual Studio to view the Properties of the project, and set the PostBuildEvent to this:
cscript.exe "$(ProjectDir)CommandLineSupport.js" "$(BuiltOuputPath)"
Then set up the Delopyment Project with a Custom Action. Click on the Primary Output to get to the Custom Action Properties, and set the CustomActionData field to /MYPROPERTY="[MYPROPERTY]"
You can then access that property in your Custom Action installer class like this:
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
string the_commandline_property_value = Context.Parameters["MYPROPERTY"].ToString();
}
In the end you can run the cmd. C:\>Setup.msi MYPROPERTY=VALUE
This doesn't require any messing about in Orca, or using any custom dialog controls like in the accepted answer. You don't have to modify the PostBuildEvent to have the correct .msi name either. Etc. Also can add as many properties as you wish like this:
INSERT INTO `Property` (`Property`, `Value`) VALUES ('MYPROPERTY', 'MYPROPERTY=\"\"'),('MYPROPERTY2', 'MYPROPERTY2=\"\"', ('MYPROPERTY3', 'MYPROPERTY3=\"\"')) ";
Have fun!
Alright, so I ended up going with the solution I linked to in the question. But let me put the script here for completeness. The first thing I needed to do was build a JS file that had the following code (I named it CommandLineSupport.js) and put it in the same directory as the .vdproj.
//This script adds command-line support for MSI build with Visual Studio 2008.
var msiOpenDatabaseModeTransact = 1;
if (WScript.Arguments.Length != 1)
{
WScript.StdErr.WriteLine(WScript.ScriptName + " file");
WScript.Quit(1);
}
WScript.Echo(WScript.Arguments(0));
var filespec = WScript.Arguments(0);
var installer = WScript.CreateObject("WindowsInstaller.Installer");
var database = installer.OpenDatabase(filespec, msiOpenDatabaseModeTransact);
var sql
var view
try
{
//Update InstallUISequence to support command-line parameters in interactive mode.
sql = "UPDATE InstallUISequence SET Condition = 'QUEUEDIRECTORY=\"\"' WHERE Action = 'CustomTextA_SetProperty_EDIT1'";
view = database.OpenView(sql);
view.Execute();
view.Close();
//Update InstallExecuteSequence to support command line in passive or quiet mode.
sql = "UPDATE InstallExecuteSequence SET Condition = 'QUEUEDIRECTORY=\"\"' WHERE Action = 'CustomTextA_SetProperty_EDIT1'";
view = database.OpenView(sql);
view.Execute();
view.Close();
database.Commit();
}
catch(e)
{
WScript.StdErr.WriteLine(e);
WScript.Quit(1);
}
You of course would need to ensure that you're replacing the right Action by opening the MSI in Orca and matching that up to the Property on the custom dialog you created.
Next, now that I had the JS file working, I needed to add a PostBuildEvent to the .vdproj and you can do that by clicking on the setup project in Visual Studio and hitting F4. Then find the PostBuildEvent property and click the elipses. In that PostBuildEvent place this code:
cscript "$(ProjectDir)CommandLineSupport.js" "$(BuildOutputPath)Setup.msi"
Making sure to replace Setup.msi with the name of your MSI file.
Though I still feel like it's a hack ... because it is ... it works and will do the job for now. It's a small enough project that it's really not a big deal.
This is an old thread, but there's a simpler, working solution that still seems hard to find, hence why I'm posting it here.
In my scenario we're working with VS2013 (Community Ed.) and VS 2013 Installer Project extension. Our installer project has a custom UI step collecting two user texts and a custom action bound to Install\Start step that receives those texts.
We were able to make this work from GUI setup wizard, but not from command line. In the end, following this workaround, we were able to make also command line work, without any MSI file Orca editing.
The gist of the thing was to set a value for all needed custom dialog properties directly from Visual Studio, and such value should be in the form [YOUR_DIALOG_PROPERTY_NAME]. Also, it seems like such "public" properties must be named in all caps.
Here's the final setup:
Custom dialog properties
Note e.g. Edit1Property and Edit1Value.
Custom action properties
Note as property key used later in code can be named in camel case.
Custom action code
string companyId = Context.Parameters["companyId"];
string companyApiKey = Context.Parameters["companyApiKey"];
Command line
> setup.exe COMPANYID="Some ID" COMPANYAPIKEY="Some KEY" /q /l mylog.txt
HTH

What is the most reliable way to create a custom event log and event source during the installation of a .Net Service

I am having difficulty reliably creating / removing event sources during the installation of my .Net Windows Service.
Here is the code from my ProjectInstaller class:
// Create Process Installer
ServiceProcessInstaller spi = new ServiceProcessInstaller();
spi.Account = ServiceAccount.LocalSystem;
// Create Service
ServiceInstaller si = new ServiceInstaller();
si.ServiceName = Facade.GetServiceName();
si.Description = "Processes ...";
si.DisplayName = "Auto Checkout";
si.StartType = ServiceStartMode.Automatic;
// Remove Event Source if already there
if (EventLog.SourceExists("AutoCheckout"))
EventLog.DeleteEventSource("AutoCheckout");
// Create Event Source and Event Log
EventLogInstaller log = new EventLogInstaller();
log.Source = "AutoCheckout";
log.Log = "AutoCheckoutLog";
Installers.AddRange(new Installer[] { spi, si, log });
The facade methods referenced just return the strings for the name of the log, service, etc.
This code works most of the time, but recently after installing I started getting my log entries showing up in the Application Log instead of the custom log. And the following errors are in the log as well:
The description for Event ID ( 0 ) in Source ( AutoCheckout ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details.
For some reason it either isn't properly removing the source during the uninstall or it isn't creating it during the install.
Any help with best practices here is appreciated.
Thanks!
In addition, here is a sample of how I am writing exceptions to the log:
// Write to Log
EventLog.WriteEntry(Facade.GetEventLogSource(), errorDetails, EventLogEntryType.Error, 99);
Regarding stephbu's answer: The recommended path is an installer script and installutil, or a Windows Setup routine.
I am using a Setup Project, which performs the installation of the service and sets up the log. Whether I use the installutil.exe or the windows setup project I believe they both call the same ProjectInstaller class I show above.
I see how the state of my test machine could be causing the error if the log isn't truly removed until rebooting. I will experiment more to see if that solves the issue.
Edit:
I'm interested in a sure fire way to register the source and the log name during the installation of the service. So if the service had previously been installed, it would remove the source, or reuse the source during subsequent installations.
I haven't yet had an opportunity to learn WiX to try that route.
The ServiceInstaller class automatically creates an EventLogInstaller and puts it inside its own Installers collection.
Try this code:
ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();
serviceProcessInstaller.Password = null;
serviceProcessInstaller.Username = null;
serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
// serviceInstaller
ServiceInstaller serviceInstaller = new ServiceInstaller();
serviceInstaller.ServiceName = "MyService";
serviceInstaller.DisplayName = "My Service";
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.Description = "My Service Description";
// kill the default event log installer
serviceInstaller.Installers.Clear();
// Create Event Source and Event Log
EventLogInstaller logInstaller = new EventLogInstaller();
logInstaller.Source = "MyService"; // use same as ServiceName
logInstaller.Log = "MyLog";
// Add all installers
this.Installers.AddRange(new Installer[] {
serviceProcessInstaller, serviceInstaller, logInstaller
});
Couple of things here
Creating Event Logs and Sources on the fly is pretty frowned upon. primarily because of the rights required to perform the action - you don't really want to bless your applications with that power.
Moreover if you delete an event log or source the entry is only truely deleted when the server reboots, so you can get into wierd states if you delete and recreate entries without bouncing the box. There are also a bunch of unwritten rules about naming conflicts due to the way the metadata is stored in the registry.
The recommended path is an installer script and installutil, or a Windows Setup routine.
The best recommendation would be to not use the Setup Project in Visual Studio. It has very severe limitations.
I had very good results with WiX
I have to agree with stephbu about the "weird states" that the event log gets into, I've run into that before. If I were to guess, some of your difficulties lie there.
However, the best way that I know of to do event logging in the application is actually with a TraceListener. You can configure them via the service's app.config:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlogtracelistener.aspx
There is a section near the middle of that page that describes how to use the EventLog property to specify the EventLog you wish to write to.
Hope that helps.
I also followed helb's suggestion, except that I basically used the standard designer generated classes (the default objects "ServiceProcessInstaller1" and "ServiceInstaller1"). I decided to post this since it is a slightly simpler version; and also because I am working in VB and people sometimes like to see the VB-way.
As tartheode said, you should not modify the designer-generated ProjectInstaller class in the ProjectInstaller.Designer.vb file, but you can modify the code in the ProjectInstaller.vb file. After creating a normal ProjectInstaller (using the standard 'Add Installer' mechanism), the only change I made was in the New() of the ProjectInstaller class. After the normal "InitializeComponent()" call, I inserted this code:
' remove the default event log installer
Me.ServiceInstaller1.Installers.Clear()
' Create an EventLogInstaller, and set the Event Source and Event Log
Dim logInstaller As New EventLogInstaller
logInstaller.Source = "MyServiceName"
logInstaller.Log = "MyCustomEventLogName"
' Add the event log installer
Me.ServiceInstaller1.Installers.Add(logInstaller)
This worked as expected, in that the installer did not create the Event Source in the Application log, but rather created in the new custom log file.
However, I had screwed around enough that I had a bit of a mess on one server. The problem with the custom logs is that if the event source name exists associated to the wrong log file (e.g. the 'Application' log instead of your new custom log), then the source name must first be deleted; then the machine rebooted; then the source can be created with association to the correct log. The Microsoft Help clearly states (in the EventLogInstaller class description):
The Install method throws an exception
if the Source property matches a
source name that is registered for a
different event log on the computer.
Therefore, I also have this function in my service, which is called when the service starts:
Private Function EventLogSourceNameExists() As Boolean
'ensures that the EventSource name exists, and that it is associated to the correct Log
Dim EventLog_SourceName As String = Utility.RetrieveAppSetting("EventLog_SourceName")
Dim EventLog_LogName As String = Utility.RetrieveAppSetting("EventLog_LogName")
Dim SourceExists As Boolean = EventLog.SourceExists(EventLog_SourceName)
If Not SourceExists Then
' Create the source, if it does not already exist.
' An event log source should not be created and immediately used.
' There is a latency time to enable the source, it should be created
' prior to executing the application that uses the source.
'So pass back a False to cause the service to terminate. User will have
'to re-start the application to make it work. This ought to happen only once on the
'machine on which the service is newly installed
EventLog.CreateEventSource(EventLog_SourceName, EventLog_LogName) 'create as a source for the SMRT event log
Else
'make sure the source is associated with the log file that we want
Dim el As New EventLog
el.Source = EventLog_SourceName
If el.Log <> EventLog_LogName Then
el.WriteEntry(String.Format("About to delete this source '{0}' from this log '{1}'. You may have to kill the service using Task Manageer. Then please reboot the computer; then restart the service two times more to ensure that this event source is created in the log {2}.", _
EventLog_SourceName, el.Log, EventLog_LogName))
EventLog.DeleteEventSource(EventLog_SourceName)
SourceExists = False 'force a close of service
End If
End If
Return SourceExists
End Function
If the function returns False, the service startup code simply stops the service. This function pretty much ensures that you will eventually get the correct Event Source name associated to the correct Event Log file. You may have to reboot the machine once; and you may have to try starting the service more than once.
I am having the same problems. In my case it seems that Windows installer is adding the event source which is of the same name as my service automatically and this seems to cause problems. Are you using the same name for the windows service and for the log source? Try changing it so that your event log source is called differently then the name of the service.
I just posted a solution to this over on MSDN forums which was to that I managed to get around this using a standard setup MSI project. What I did was to add code to the PreInstall and Committed events which meant I could keep everything else exactly as it was:
SortedList<string, string> eventSources = new SortedList<string, string>();
private void serviceProcessInstaller_BeforeInstall(object sender, InstallEventArgs e)
{
RemoveServiceEventLogs();
}
private void RemoveServiceEventLogs()
{
foreach (Installer installer in this.Installers)
if (installer is ServiceInstaller)
{
ServiceInstaller serviceInstaller = installer as ServiceInstaller;
if (EventLog.SourceExists(serviceInstaller.ServiceName))
{
eventSources.Add(serviceInstaller.ServiceName, EventLog.LogNameFromSourceName(serviceInstaller.ServiceName, Environment.MachineName));
EventLog.DeleteEventSource(serviceInstaller.ServiceName);
}
}
}
private void serviceProcessInstaller_Committed(object sender, InstallEventArgs e)
{
RemoveServiceEventLogs();
foreach (KeyValuePair<string, string> eventSource in eventSources)
{
if (EventLog.SourceExists(eventSource.Key))
EventLog.DeleteEventSource(eventSource.Key);
EventLog.CreateEventSource(eventSource.Key, eventSource.Value);
}
}
The code could be modified a bit further to only remove the event sources that didn't already exist or create them (though the logname would need to be stored somewhere against the installer) but since my application code actually creates the event sources as it runs then there's no point for me. If there are already events then there should already be an event source. To ensure that they are created, you can just automatically start the service.
I experienced some similar weird behaviour because I tried to register an event source with the same name as the service I was starting.
I notice that you also have the DisplayName set to the same name as your event Source.
On starting the service up, we found that Windows logged a "Service started successfully" entry in the Application log, with source as the DisplayName. This seemed to have the effect of registering Application Name with the application log.
In my event logger class I later tried to register Application Name as the source with a different event log, but when it came to adding new event log entries they always got added to the Application log.
I also got the "The description for Event ID ( 0 ) in Source" message several times.
As a work around I simply registered the message source with a slightly different name to the DisplayName, and it's worked ever since. It would be worth trying this if you haven't already.
The problem comes from installutil which by default registers an event source with your services name in the "Application" EventLog. I'm still looking for a way to stop it doing this crap. It would be really nice if one could influence the behaviour of installutil :(
Following helb's suggestion resolved the problem for me. Killing the default event log installer, at the point indicated in his example, prevented the installer from automatically registering my Windows Service under the Application Event log.
Far too much time was lost attempting to resolve this frustrating quirk. Thanks a million!
FWIW, I could not modify the code within my designer-generated ProjectInstaller class without causing VS to carp about the mods. I scrapped the designer-generated code and manually entered the class.
Adding an empty registry key to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\MY_CUSTOM_SOURCE_NAME_HERE seems to work fine.
An easy way to change the default behavior (that is, that the project installer creates an event log source with the name of your service in the application log) is to easily modify the constructor of the project installer as following:
[RunInstaller( true )]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
//Skip through all ServiceInstallers.
foreach( ServiceInstaller ThisInstaller in Installers.OfType<ServiceInstaller>() )
{
//Find the first default EventLogInstaller.
EventLogInstaller ThisLogInstaller = ThisInstaller.Installers.OfType<EventLogInstaller>().FirstOrDefault();
if( ThisLogInstaller == null )
continue;
//Modify the used log from "Application" to the same name as the source name. This creates a source in the "Applications and Services log" which separates your service logs from the default application log.
ThisLogInstaller.Log = ThisLogInstaller.Source;
}
}
}

Categories