How can I read WPF publish version number in code behind - c#

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);

Related

Programmatically Set VS Installer Project Version on Build Action

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.

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

Environment.SpecialFolder.ProgramFiles returns the wrong directory

I am working on a C# project and I am using the following code
string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
However, when I look at the rootPath its set to C:\Program Files (x86).
Why would do it this as there is an Environment.SpecialFolder.ProgramFilesX86 which I would have thought would have returned the above.
Thanks for any help you can provide
If your project is currently targeting the x86 platform, both of those enum values will return the Program Files(x86) directory.
Change the target platform for your project to x64, and SpecialFolder.ProgramFiles should return the Program Files directory instead.
I have a scenario where i could not change the target of the executing assembly. So i use this method to get always the x64 (also when running in 32bit):
var programFilesX64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)
.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion")?.GetValue("ProgramFilesDir");

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)

Tesseract 3 (OCR) - .NET Wrapper

http://code.google.com/p/tesseractdotnet/
I am having a problem getting Tesseract to work in my Visual Studio 2010 projects. I have tried console and winforms and both have the same outcome. I have come across a dll by someone else who claims to have it working in VS2010:
http://code.google.com/p/tesseractdotnet/issues/detail?id=1
I am adding a reference to the dll which can be found in the attached to post 64 from the website above. Every time I build my project I get an AccessViolationException saying that an attempt was made to read or write protected memory.
public void StartOCR()
{
const string language = "eng";
const string TessractData = #"C:\Users\Joe\Desktop\tessdata\";
using (TesseractProcessor processor = new TesseractProcessor())
{
using (Bitmap bmp = Bitmap.FromFile(fileName) as Bitmap)
{
if (processor.Init(TessractData, language, (int)eOcrEngineMode.OEM_DEFAULT))
{
string text = processor.Recognize(bmp);
}
}
}
}
The access violation exception always points to if (processor.Init(TessractData, language, (int)eOcrEngineMode.OEM_DEFAULT)). I've seen a few suggestions to make sure the solution platform is set to x86 in the configuration manager and that the tessdata folder location is finished with trailing slash, to no avail. Any ideas?
It appeared to be the contents of the tessdata folder that was causing the problem. Obtained the tessdata folder from the first link and all is now working.
I have just completed a project with tesseract engine 3. i think, there is a bug in the engine, that need to be rectified. What i Did to remove "AccessViolationError" is, add "\tessdata" to the real tessdata directory string. I don't know why, but the engine seems to be truncating the innermost directory in the Tessdata path.
Just made Full OCR package (Dlls+Tessdata(english)) that works with .net framework 4.
If somebody has the same problem and advice with trailing slash doesn't work, try... TWO ending slashes! Seriosly. It works for me.
if (processor.Init(#".\tessdata\\", "eng", (int)eOcrEngineMode.OEM_DEFAULT))
Seems your problem relates to stability issue mentioned here. On the official site there is a recommendation to use previous stable release 2.4.1. You can install it from nuget.org via the package manager command: Install-Package Tesseract -Version 2.4.1

Categories