Programmatically Set VS Installer Project Version on Build Action - c#

I have a C# WPF application, which is written in Visual Studio 2017 (15.9.9) using .Net 4.7. The solution for the application contains two projects - the WPF Project itself and also a Microsoft VS Installer Project that creates a .msi file on the build action.
I have stored the version information for the application project and can return it using the following method
public static string GetVersion()
{
try
{
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
string version = fvi.FileVersion;
return $"Version {version}";
}
catch(Exception ex)
{
//send error notif to IT dept.
Alert_IT(ex, GetCurrentMethod(), false);
return "0";
}
}
I would like to use the result of this to set the the version information in the Setup project when I build the solution - at the moment it has to be manually entered into the properties of the setup project.
Since we are planning on using setup projects for all our applications, it would be really nice to only have to alter the version in one place for all our projects, ensuring that there are no inconsistencies.
Is it possible to set the version on a setup project programmatically? It would have to be done before the .msi is created.
If this is not possible, do you have any other suggestions as to how to achieve the desired outcome - that the version information for the application need only be set in one place before it is built?
I have seen the advice here, but did not find it specific enough to be helpful.

Related

Opening a solution with msbuildworkspace gives diagnostics errors without details

I am trying to analyse a solution with Roslyn, with MSBuildWorkspace.
The solution is a new solution, with 2 class library projects in them, one referencing the other.
They are created in Visual Studio 2017, .Net 4.6.2.
When I open the solution, I receive two generic errors in workspace.Diagnostics, both are :
Msbuild failed when processing the file 'PathToProject'
There is nothing more in the diagnostics or output window, to indicate WHY it failed to process the project file.
The code for opening the solution:
namespace RoslynAnalyse
{
class Program
{
static void Main(string[] args)
{
LocalAnalysis();
}
private static void LocalAnalysis()
{
var workspace = MSBuildWorkspace.Create();
var solution = workspace.OpenSolutionAsync(#"D:\Code\Roslyn\RoslynAnalyse\SolutionToAnalyse\SolutionToAnalyse.sln").Result;
var workspaceDiagnostics = workspace.Diagnostics;
}
}
}
The version of Microsoft.CodeAnalysis is 2.0.0.0.
Does anybody have any idea why MSBuild failed, how I can get more information ?
When MSBuildWorkspace fails to open a project or solution this way, it is almost always because the application using MSBuildWorkspace does not include the same binding redirects that msbuild.exe.config has in it.
MSBuild uses binding redirects to allow tasks (typically already compiled C# code using possibly different versions of msbuild API libraries) to all use the current msbuild API's. Otherwise, msbuild gets runtime load failures.
The solution is to add an app.config file to your project and copy the binding redirects (the assemblyBinding section of the msbuild.exe.config file) into your file.

TuesPechkin unable to load DLL 'wkhtmltox.dll'

I've been using TuesPechkin for some time now and today I went to update the nuget package to the new version 2.0.0+ and noticed that Factory.Create() no longer resolved, so I went to read on the GitHub the changes made and noticed it now expects the path to the dll?
IConverter converter =
new ThreadSafeConverter(
new PdfToolset(
new StaticDeployment(DLL_FOLDER_PATH)));
For the past few hours I've tried almost all the paths I can think of, "\bin", "\app_data", "\app_start", etc and I can't seem to find or figure out what it wants for the path and what dll?
I can see the TuesPechkin dll in my bin folder and it was the first path I tried, but I got the following error:
Additional information: Unable to load DLL 'wkhtmltox.dll': The
specified module could not be found. (Exception from HRESULT:
0x8007007E)
Where is that dll and now can I get it as the library doesn't seem to contain it, I tried installing the TuesPechkin.Wkhtmltox.Win32 package but the dll still is nowhere to be found. Also I am using this in a asp.net website project so I assume that using the following should work for obtaining the path, right?
var path = HttpContext.Current.Server.MapPath(#"~\bin\TuesPechkin.dll");
Further information: https://github.com/tuespetre/TuesPechkin/issues/57
The Tuespechkin has a zip file as a resource in the Win32 and Win64 embedded packages for the 'wkhtmltox.dll' file.
What it does when you use the Win32 or Win64 Embedded package is unzips the file and places it in the directory that you specify.
I have been putting a copy of the wkhtmltox dll at the root portion of my web app directory and pointing the DLL_FOLDER_PATH to it using the server physical path of my web app to get to it.
According to the author, you must set the converter in a static field for best results.
I do that, but set the converter to null when I am finished using it, and that seems to work.
Tuespechkin is wrapper for the wmkhtmlox dll file.
The original file is written in C++ and so will not automatically be usable in C# or VB.NET or any of the other managed code domains.
The Tuespechkin.dll file DOES NOT contain a copy of 'wkhtmltox.dll'. You either have to use one of the other embedded deployment modules or install a copy of the 'wkhtmltox.dll' in your web app after downloading it from the internet. That is what I do, and it seems to work just fine.
I am using Team Foundation Server, and attempts to compile code after using the Tuespechkin routines will fail the first time because the 'wkhtmltox.dll' file gets locked, but all you have to do is simply retry your build and it will go through.
I had issues with the 32-bit routine not working in a 64-bit environment and the 64-bit environment not being testable on localhost. I went with the workaround I came up with after examining the source code for Tuespechkin and the Win32 and Win64 embedded deployment packages.
It works well as long as you specify a url for the input rather than raw html.
The older package didn't render css very well.
If you are using a print.aspx routine, you can create the url for it as an offset from your main url.
I don't have the source code I am using with me at this point to offset to your base url for your web application, but it is simply an offshoot of HttpRequest.
You have to use the physical path to find the .dll, but you can use a web path for the print routine.
I hope this answers your question a bit.
If you are getting this error -> Could not load file or assembly 'TuesPechkin.Wkhtmltox.Win64' or one of its dependencies. An attempt was made to load a program with an incorrect format.
In Visual Studio Go to -
Tools -> Options -> Projects and Solutions -> Web Projects -> Use the 64 bit version of IIS Express for web sites and projects.
I installed TuesPechkin.Wkhtmltox.Win64 Nuget package and used the following code in a singleton:
public class PechkinPDFConvertor : IPDFConvertor
{
IConverter converter =
new ThreadSafeConverter(
new RemotingToolset<PdfToolset>(
new Win64EmbeddedDeployment(
new TempFolderDeployment())));
public byte[] Convert(string html)
{
// return PechkinSync.Convert(new GlobalConfig(), html);
return converter.Convert(new HtmlToPdfDocument(html));
}
}
The web application then has to be run in x64 otherwise you will get an error about trying to load an x64 assembly in an x86 environment. Presumably you have to choose x64 or x86 at design time and use the corresponding nuget package, it would be nicer to choose this in the web.config.
EDIT: The above code failed on one server with the exact same message as yours - it was due to having not installed VC++ 2013. So the new code is running x86 as follows
try
{
string path = Path.Combine(Path.GetTempPath(), "MyApp_PDF_32");
Converter = new ThreadSafeConverter(
new RemotingToolset<PdfToolset>(
new Win32EmbeddedDeployment(
new StaticDeployment(path))));
}
catch (Exception e)
{
if (e.Message.StartsWith("Unable to load DLL 'wkhtmltox.dll'"))
{
throw new InvalidOperationException(
"Ensure the prerequisite C++ 2013 Redistributable is installed", e);
}
else
throw;
}
If you do not want run the installer for wkhtmltox just to get the dll, you can do the following:
As #Timothy suggests, if you use the embedded version of wkhtmltox.dll from TuesPechkin, it will unzip it and place it in a temp directory. I copied this dll and referenced it with the StaticDeployment option without any issues.
To find the exact location, I just used Process Monitor (procmon.exe). For me it was C:\Windows\Temp\-169958574\8\0.12.2.1\wkhtmltox.dll
In my case, I am deploying on a 64-bit VPS then I got this error. I have solved the problem by installing the wkhtmltopdf that I downloaded from http://wkhtmltopdf.org/downloads.html. I chose the 32-bit installer.
In my case, I have solved the problem by installing the Wkhtmltox for win32 at https://www.nuget.org/packages/TuesPechkin.Wkhtmltox.Win32/
This error: Unable to load DLL 'wkhtmltox.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E) is returned in two situations:
1- Deploy dependency not installed:
For solve this, you can install nuget package "TuesPechkin.Wkhtmltox.Win64" and use this code (for WebApplications running in IIS):
IConverter converter =
new ThreadSafeConverter(
new RemotingToolset<PdfToolset>(
new Win64EmbeddedDeployment(
new TempFolderDeployment())));
// Keep the converter somewhere static, or as a singleton instance!
// Do NOT run the above code more than once in the application lifecycle!
byte[] result = converter.Convert(document);
In runtime this code will copy the dependency "wkhtmltox.dll" in a temporary directory like: "C:\Windows\Temp\1402166677\8\0.12.2.1". It's possible to get the destination of file using:
var deployment = new Win64EmbeddedDeployment(new TempFolderDeployment());
Console.WriteLine(deployment.Path);
2- Microsoft Visual C++ 2013 Redistributable not installed:
As described here:
https://github.com/tuespetre/TuesPechkin/issues/65#issuecomment-71266114, the Visual C++ 2013 Runtime is required.
The solution from README is:
You must have Visual C++ 2013 runtime installed to use these packages. Otherwise, you will need to download the MingW build of wkhtmltopdf and its dependencies from their website and use that with the library. https://github.com/tuespetre/TuesPechkin#wkhtmltoxdll
or, you can install the Microsoft Visual C++ 2013 Redistributable:
choco install msvisualcplusplus2013-redist
Here is AnyCpu version, also support iis-base or winform application
using TuesPechkin.Wkhtmltox.AnyCPU;
...
var converter = PDFHelper.Factory.GetConverter();
var result = converter.Convert(This.Document);
Reference : https://github.com/tloy1966/TuesPechkin
Installing the Visual C++ Redistributable for Visual Studio 2013 resolved the error for me.
https://www.microsoft.com/en-us/download/details.aspx?id=40784

How can I read WPF publish version number in code behind

I want to read and display WPF application publish version number in splash windows, In project properties in publish tab there is publish version, how can I get this and display it in WPF windows.
Thanks in advance
Access the assembly version using Assembly.GetExecutingAssembly() and display in UI
Assembly.GetExecutingAssembly().GetName().Version.ToString();
Add reference to System.Deployment library to your project and adjust this snippet to your code:
using System.Deployment.Application;
and
string version = null;
try
{
//// get deployment version
version = ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
}
catch (InvalidDeploymentException)
{
//// you cannot read publish version when app isn't installed
//// (e.g. during debug)
version = "not installed";
}
As stated in comment, you cannot obtain publish version during debug, so I suggest to handle InvalidDeploymentException.
Use GetEntryAssembly rather than GetExecutingAssembly to get the version from the current executable rather than from the currently-executing DLL, like so:
string version = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString();
string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
Console.WriteLine(version);

Programmatically retrieve version of an installed application

I want to programmatically retrieve the version of an installed application (which is currently running), of which I have the name of the running process. If possible, retrieving the install directory would also be appreciated, but that is optional.
I've searched at a lot of places, and some questions looked similar, but they do not give me what I ask for.
To be a bit more specific, right now I want to do this for Visual Studio i.e. I have a WPF app, which is running alongside Visual Studio & given that I know the process name for Visual Studio i.e. "devenv", how can I get the version information of Visual Studio installed on my machine, from the WPF app? This is just an example, don't assume anything particular to Visual Studio. In the general case, we'd have an app running, for which we know the Process name & want its installed version.
Can you please provide the C# code for doing this?
This is gonna be simple. All kind of system related information will be present in Registry. (i.e) If you open regedit, you may find various HKEY. Now, please navigate to the following location.
" HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall "
You can find many folders inside this location, in which the name of the folder will be encrypted. Those folders indicates the installed application in the current machine.
In each folder there will be many key and data pair of values. In that you can find DisplayName and DisplayVersion. So this DisplayVersion gives you the actual version of your application.
So, How to achieve this through code?
RegistryKey rKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
List<string> insApplication = new List<string>();
if (rKey != null && rKey.SubKeyCount > 0)
{
insApplication = rKey.GetSubKeyNames().ToList();
}
int i = 0;
string version = "";
foreach (string appName in insApplication)
{
RegistryKey finalKey = rKey.OpenSubKey(insApplication[i]);
string installedApp = finalKey.GetValue("DisplayName").ToString();
if (installedApp == "Google Chrome")
{
version = finalKey.GetValue("DisplayVersion").ToString();
return;
}
i++;
}
Process.GetProcessesByName("DevEnv")[0].Modules[0].FileVersionInfo
Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
This gets the version of the executing assembly.
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Public DTE As EnvDTE.DTE
Dim version As String
DTE = System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.9.0")
version = DTE.Version
MsgBox("The visual studio version is {0}", version)

Windows Setup: Dynamic Registry Keys/Values

A synopsis of my question:
Is it possible to use your own, custom variables (the way that you can use [TARGETDIR]) in the Registry screen of a Windows Setup project in VS2010? Specifically, I need to store my assembly's strong name and assembly version in the registry, in order to register a COM object on a machine without the installing user having admin rights.
I already tried using a custom action, and I'd rather not continue down that road if possible.
Here are the specifics, and what I've tried:
Recently, my employer started blindly removing all employees' admin rights from their machines.
I had created a COM-exposed C# class that I'd been using on a few of my workstations, which is no longer able to be registered, because I no longer have the appropriate permissions under HKEY_CLASSES_ROOT.
Through Googling, I found out how to register all of the appropriate keys under HKCU*, but now I'd like to implement this in my deployment project.
I understand how to use the Registry screen within Windows Setup, but there are custom keys/values that need to be stored (install folder, assembly strong name, version).
I could use a custom action, but ideally, I want Windows Setup to manage my registry settings, because (a) it's better than I am at automatically removing all the proper keys/values upon uninstall, (b) during the install, registry changes are transactional & rolled back upon install error, and (c) the logic for registry key install/removal/transactions is already written by Microsoft, and I won't have to rewrite it myself.
The project was in VS2008 until today, but I just upgraded it to VS2010, so perhaps something has changed between 2008 and 2010 that might allow this behavior.
So, rather than using a custom action, is there a better way to do this?
EDIT: I found this answer, which seems to suggest that you can access the Windows Install "Registry" table within your install project. I'm not sure how to do access it, though. In the past, I seem to recall that you could access the MSI databases from a special external tool (Orca), but I don't know if you can access these tables in your setup project.
EDIT 2: Ah, I may be on to something; perhaps a post-build event:
Use Orca to edit msi from command line?,
Examples of Database Queries Using SQL and Script,
WiRunSQL.vbs
* Run RegAsm twice - once with /codebase and once without; both times with the /regfile option. Then merge both files together (removing duplicates), and replace all HKCR references with HKCU\Software\Classes.
Yes, this can be done*.
First, create a Console executable that will be run as part of a post-build event of the Windows Setup project. This modifies the Registry table in the MSI file that has been built by VS2010.
Note: You must add a reference to "Microsoft Windows Installer Object Library" under COM, for the below code to compile.
using System;
using WindowsInstaller;
using System.Runtime.InteropServices;
using System.Reflection;
namespace Post_Setup_Scripting
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Incorrect args.");
return;
}
//arg 1 - path to MSI
string PathToMSI = args[0];
//arg 2 - path to assembly
string PathToAssembly = args[1];
Type InstallerType;
WindowsInstaller.Installer Installer;
InstallerType = Type.GetTypeFromProgID("WindowsInstaller.Installer");
Installer = (WindowsInstaller.Installer)Activator.CreateInstance(InstallerType);
Assembly Assembly = Assembly.LoadFrom(PathToAssembly);
string AssemblyStrongName = Assembly.GetName().FullName;
string AssemblyVersion = Assembly.GetName().Version.ToString();
string SQL = "SELECT `Key`, `Name`, `Value` FROM `Registry`";
WindowsInstaller.Database Db = Installer.OpenDatabase(PathToMSI, WindowsInstaller.MsiOpenDatabaseMode.msiOpenDatabaseModeDirect);
WindowsInstaller.View View = Db.OpenView(SQL);
View.Execute();
WindowsInstaller.Record Rec = View.Fetch();
while (Rec != null)
{
for (int c = 0; c <= Rec.FieldCount; c++)
{
string Column = Rec.get_StringData(c);
Column = Column.Replace("[AssemblyVersion]", AssemblyVersion);
Column = Column.Replace("[AssemblyStrongName]", AssemblyStrongName);
Rec.set_StringData(c, Column);
View.Modify(MsiViewModify.msiViewModifyReplace, Rec);
Console.Write("{0}\t", Column);
Db.Commit();
}
Console.WriteLine();
Rec = View.Fetch();
}
View.Close();
GC.Collect();
Marshal.FinalReleaseComObject(Installer);
Console.ReadLine();
}
}
}
The "variables" that we are going to use in the Windows Setup Registry screen get replaced in these lines of the above code; this could be adapted to any items that are necessary.
string Column = Rec.get_StringData(c);
Column = Column.Replace("[AssemblyVersion]", AssemblyVersion);
Column = Column.Replace("[AssemblyStrongName]", AssemblyStrongName);
Second, create a .reg file that contains the registry keys you want to create upon install. In the code above, we modify the MSI database in the post-build by replacing all instances of [AssemblyVersion] with the assembly version, and [AssemblyStrongName] with the assembly's strong name.
[HKEY_CURRENT_USER\Software\Classes\Record\{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\[AssemblyVersion]]
"Class"="MyClass.MyClass"
"Assembly"="[AssemblyStrongName]"
"RuntimeVersion"="v2.0.50727"
"CodeBase"="[TARGETDIR]MyClass.dll"
Third, import the .reg file into the Windows Setup registry screen in VS2010 by right-clicking "Registry On Target Machine", and clicking "Import".
Finally, call the post-build executable in the "PostBuildEvent" property of the setup project:
"C:\Path\To\Exe\Post-Setup Scripting.exe" [Path to MSI] [Path To DLL to extract strong name/version]
* This is a little different than using [TARGETDIR], because [TARGETDIR] gets resolved at install time, and these "variables" will get resolved at build time. For my solution, I needed to resolve at build time, because my version number increments with each build.

Categories