Here are the examples of the csharp api System.Diagnostics.FileVersionInfo.GetVersionInfo(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
617 Examples
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 0x2b00b1e5
License : GNU General Public License v3.0
Project Creator : 0x2b00b1e5
static void GetFLPaths()
{
string path = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Image-Line\\Shared\\Paths", "FL Studio", null);
if(path == null)
{
Console.WriteLine("No FL Studio path detected!\n\n");
Console.Write("Please enter full path to the FL Studio executable: ");
string output = Console.ReadLine();
System.Diagnostics.FileVersionInfo FLInf = System.Diagnostics.FileVersionInfo.GetVersionInfo(output);
if (FLInf.ProductName != "FL Studio")
{
Console.WriteLine("\n This file doesn't appear to be a FL Studio executable...try again!");
GetFLPaths();
}
FLStudioPaths = output;
}
else
{
FLStudioPaths = path;
Console.WriteLine(string.Format("Found FL Studio at path: {0}", path));
Console.WriteLine("Correct? (Y/N)");
switch (Console.ReadKey().Key)
{
case ConsoleKey.Y:
break;
case ConsoleKey.N:
Console.Write("Please enter full path to the FL Studio executable: ");
string output = Console.ReadLine();
output.Replace("\"", string.Empty);
System.Diagnostics.FileVersionInfo FLInf = System.Diagnostics.FileVersionInfo.GetVersionInfo(output);
if (FLInf.ProductName != "FL Studio")
{
Console.WriteLine("\n This file doesn't appear to be a FL Studio executable...try again!");
System.Threading.Thread.Sleep(1000);
GetFLPaths();
}
FLStudioPaths = output;
break;
}
}
}
19
View Source File : StatusViewClasses.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne
License : GNU General Public License v3.0
Project Creator : 1RedOne
public static string GetOSRealVersionInfo()
{
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(
Path.Combine(
System.Environment.GetFolderPath(System.Environment.SpecialFolder.System),
"kernel32.dll"));
return fvi.ProductVersion;
}
19
View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
public static string GetVersion()
{
try
{
string location = GetExePath();
return string.Format("v2rayN - V{0} - {1}",
FileVersionInfo.GetVersionInfo(location).FileVersion.ToString(),
File.GetLastWriteTime(location).ToString("yyyy/MM/dd"));
}
catch (Exception ex)
{
SaveLog(ex.Message, ex);
return string.Empty;
}
}
19
View Source File : UpdateHandle.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
private void responseHandler(string type, string redirectUrl)
{
try
{
string version = redirectUrl.Substring(redirectUrl.LastIndexOf("/", StringComparison.Ordinal) + 1);
string curVersion;
string message;
string url;
if (type == "v2fly")
{
curVersion = "v" + getCoreVersion(type);
message = string.Format(UIRes.I18N("IsLatestCore"), curVersion);
string osBit = Environment.Is64BitProcess ? "64" : "32";
url = string.Format(v2flyCoreUrl, version, osBit);
}
else if (type == "xray")
{
curVersion = "v" + getCoreVersion(type);
message = string.Format(UIRes.I18N("IsLatestCore"), curVersion);
string osBit = Environment.Is64BitProcess ? "64" : "32";
url = string.Format(xrayCoreUrl, version, osBit);
}
else if (type == "v2rayN")
{
curVersion = FileVersionInfo.GetVersionInfo(Utils.GetExePath()).FileVersion.ToString();
message = string.Format(UIRes.I18N("IsLatestN"), curVersion);
url = string.Format(nUrl, version);
}
else
{
throw new ArgumentException("Type");
}
if (curVersion == version)
{
AbsoluteCompleted?.Invoke(this, new ResultEventArgs(false, message));
return;
}
AbsoluteCompleted?.Invoke(this, new ResultEventArgs(true, url));
}
catch (Exception ex)
{
Utils.SaveLog(ex.Message, ex);
_updateFunc(false, ex.Message);
}
}
19
View Source File : dlgSettings.cs
License : MIT License
Project Creator : 86Box
License : MIT License
Project Creator : 86Box
private void Get86BoxVersion()
{
try
{
FileVersionInfo vi = FileVersionInfo.GetVersionInfo(txtEXEdir.Text + @"\86Box.exe");
if (vi.FilePrivatePart >= 2008) //Officially supported builds
{
lbl86BoxVer1.Text = vi.FileMajorPart.ToString() + "." + vi.FileMinorPart.ToString() + "." + vi.FileBuildPart.ToString() + "." + vi.FilePrivatePart.ToString() + " - supported";
lbl86BoxVer1.ForeColor = Color.ForestGreen;
}
else if (vi.FilePrivatePart >= 1763 && vi.FilePrivatePart < 2008) //Should mostly work...
{
lbl86BoxVer1.Text = vi.FileMajorPart.ToString() + "." + vi.FileMinorPart.ToString() + "." + vi.FileBuildPart.ToString() + "." + vi.FilePrivatePart.ToString() + " - partially supported";
lbl86BoxVer1.ForeColor = Color.Orange;
}
else //Completely unsupported, since version info can't be obtained anyway
{
lbl86BoxVer1.Text = "Unknown - not supported";
lbl86BoxVer1.ForeColor = Color.Red;
}
}
catch(FileNotFoundException ex)
{
lbl86BoxVer1.Text = "86Box.exe not found";
lbl86BoxVer1.ForeColor = Color.Gray;
}
}
19
View Source File : OVRPluginUpdater.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
private static System.Version GetPluginVersion(string path)
{
System.Version pluginVersion = invalidVersion;
try
{
pluginVersion = new System.Version(Path.GetFileName(path));
}
catch
{
pluginVersion = invalidVersion;
}
if (pluginVersion == invalidVersion)
{
//Unable to determine version from path, fallback to Win64 DLL meta data
path += GetPluginBuildTargetSubPath(PluginPlatform.Win64);
if (!File.Exists(path))
{
path += GetDisabledPluginSuffix();
if (!File.Exists(path))
{
return invalidVersion;
}
}
FileVersionInfo pluginVersionInfo = FileVersionInfo.GetVersionInfo(path);
if (pluginVersionInfo == null || pluginVersionInfo.ProductVersion == null || pluginVersionInfo.ProductVersion == "")
{
return invalidVersion;
}
pluginVersion = new System.Version(pluginVersionInfo.ProductVersion);
}
return pluginVersion;
}
19
View Source File : ExportExampleHelper.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public static bool IsreplacedemblyVersionMatch(string folderPath, string replacedemblyName)
{
//var fullPath = string.Format(@"{0}\{1}", folderPath, replacedemblyName);
var fullPath = string.Format(@"{0}{1}", folderPath, replacedemblyName);
bool isMatch = FileVersionInfo.GetVersionInfo(fullPath).FileVersion == GetSciChartVersion();
return isMatch;
}
19
View Source File : AboutViewModel.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
public static string GetInformationalVersion(replacedembly replacedembly) => FileVersionInfo.GetVersionInfo(replacedembly.Location).ProductVersion;
19
View Source File : VSVersionProvider.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private static Version? GetFileVersion()
{
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "devenv.exe");
if (!File.Exists(path))
return null; // Not running inside Visual Studio
try
{
FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(path);
return fileVersionInfo != null
? new Version(fileVersionInfo.FileMajorPart, fileVersionInfo.FileMinorPart)
: null;
}
catch (IOException)
{
return null;
}
}
19
View Source File : HomeController.cs
License : MIT License
Project Creator : adamajammary
License : MIT License
Project Creator : adamajammary
public IActionResult About()
{
string location = replacedembly.GetExecutingreplacedembly().Location;
FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(location);
About model = new About
{
AppName = versionInfo.ProductName,
Copyright = versionInfo.LegalCopyright,
Url = "https://www.jammary.com/",
Version = ("Version " + versionInfo.ProductVersion)
};
return View(model);
}
19
View Source File : InfoWidget.cs
License : MIT License
Project Creator : ademanuele
License : MIT License
Project Creator : ademanuele
void SetupVersionLabel()
{
replacedembly replacedembly = replacedembly.GetExecutingreplacedembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(replacedembly.Location);
string version = fvi.ProductVersion;
var font = Pango.FontDescription.FromString("Courier 20");
versionLabel.ModifyFont(font);
versionLabel.Text = $"Version {version}";
}
19
View Source File : PortalConfiguration.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static Uri GetFullServiceUrl(string url)
{
if (url == null)
{
return null;
}
const string path = "XRMServices/2011/Organization.svc/web";
var separator = url.EndsWith("/") ? string.Empty : "/";
var svcUri = new Uri(url + separator + path);
var version = System.Diagnostics.FileVersionInfo.GetVersionInfo(typeof(OrganizationWebProxyClient).replacedembly.Location).FileVersion;
var fullUrl = new UriBuilder(svcUri) { Query = "SDKClientVersion=" + version };
return fullUrl.Uri;
}
19
View Source File : ApplicationAccess.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public ApplicationInfo GetApplicationInfo(string fpath)
{
var fv = System.Diagnostics.FileVersionInfo.GetVersionInfo(fpath);
return new ApplicationInfo()
{
Name = fv.ProductName,
Version = fv.ProductVersion,
Description = fv.FileDescription,
Location = Path.GetDirectoryName(fpath),
InstallDate = File.GetCreationTime(fpath)
};
}
19
View Source File : LocalStorage.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
private void WriteApplicationInfo(Snapshot sshot, Database db)
{
if (string.IsNullOrEmpty(sshot.ProcessName))
return;
if (db.IsExist("ApplicationInfo", new { ProcessName = sshot.ProcessName }))
return;
try
{
if (!string.IsNullOrEmpty(sshot.FileName))
{
var fv = FileVersionInfo.GetVersionInfo(sshot.FileName);
var app = new
{
ProcessName = sshot.ProcessName,
FileName = sshot.FileName,
Description = fv.FileDescription,
};
db.Insert("ApplicationInfo", app);
}
else
{
db.Insert("ApplicationInfo", new { ProcessName = sshot.ProcessName });
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
}
19
View Source File : TroubleshootingWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
private void FillKnownData()
{
OSDescription.Text = RuntimeInformation.OSDescription;
FrameworkDescription.Text = RuntimeInformation.FrameworkDescription;
OsD.Text = RuntimeInformation.OSArchitecture.ToString();
PowerShellPath.Text = config.default_powershell_path;
if(config.powershell_arguments == "")
{
PowerShellArguments.Text = "empty";
PowerShellArguments.Foreground = new SolidColorBrush(Color.FromRgb(128, 128, 128));
}
else
{
PowerShellArguments.Text = config.powershell_arguments;
}
if(File.Exists(config.default_powershell_path))
{
try
{
var versionInfo = FileVersionInfo.GetVersionInfo(config.default_powershell_path);
PowerShellVersion.Text = versionInfo.FileVersion;
}
catch
{
PowerShellVersion.Text = "unable to get version";
PowerShellVersion.Foreground = new SolidColorBrush(Color.FromRgb(128, 128, 128));
}
}
if(Directory.Exists(System.IO.Path.GetPathRoot(Environment.SystemDirectory) + @"Program Files\WindowsPowerShell\Modules"))
{
try
{
string[] dirs = Directory.GetDirectories(System.IO.Path.GetPathRoot(Environment.SystemDirectory) + @"Program Files\WindowsPowerShell\Modules", "*", SearchOption.TopDirectoryOnly);
foreach (string dir in dirs)
{
PowerShellModules.Text = PowerShellModules.Text + dir + Environment.NewLine;
}
}
catch { }
}
if (Directory.Exists(System.IO.Path.GetPathRoot(Environment.SystemDirectory) + @"Windows\System32\WindowsPowerShell\v1.0\Modules"))
{
try
{
string[] dirs = Directory.GetDirectories(System.IO.Path.GetPathRoot(Environment.SystemDirectory) + @"Windows\System32\WindowsPowerShell\v1.0\Modules", "*", SearchOption.TopDirectoryOnly);
foreach (string dir in dirs)
{
PowerShellModules.Text = PowerShellModules.Text + dir + Environment.NewLine;
}
}
catch { }
}
if (Directory.Exists(System.IO.Path.GetPathRoot(Environment.SystemDirectory) + @"Program Files (x86)\WindowsPowerShell\Modules"))
{
try
{
string[] dirs = Directory.GetDirectories(System.IO.Path.GetPathRoot(Environment.SystemDirectory) + @"Program Files (x86)\WindowsPowerShell\Modules", "*", SearchOption.TopDirectoryOnly);
foreach (string dir in dirs)
{
PowerShellModules.Text = PowerShellModules.Text + dir + Environment.NewLine;
}
}
catch { }
}
}
19
View Source File : DependencyChecker.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
public static bool DependencyCheckMain(string CallingPlugin, Version Albo1125CommonVer, float MinimumRPHVersion, string installationVideoURL, Version MadeForGTAVersion = null, Version MadeForLSPDFRVersion = null, Version RAGENativeUIVersion = null, string[] AudioFilesToCheckFor = null, string[] OtherRequiredFilesToCheckFor = null)
{
bool CheckPreplacededSuccessfully = true;
Game.LogTrivial("Albo1125.Common.dll " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + " starting standard dependency check for " + CallingPlugin);
if (scid == null)
{
scid = NativeFunction.Natives.GET_PLAYER_NAME<string>(Game.LocalPlayer);
Game.LogTrivial("SCID:/" + scid + "/");
}
if (File.Exists("Albo1125.Common.dll"))
{
Version InstalledCommonVer = new Version(FileVersionInfo.GetVersionInfo("Albo1125.Common.dll").ProductVersion);
if (InstalledCommonVer.CompareTo(Albo1125CommonVer) >= 0)
{
if (MadeForGTAVersion != null)
{
Game.LogTrivial("GAME VERSION: " + Game.ProductVersion.ToString());
int compare = Game.ProductVersion.CompareTo(MadeForGTAVersion);
if (compare > 0)
{
Game.LogTrivial(CallingPlugin + " compatibility warning: The current game version is newer than " + MadeForGTAVersion.ToString() + " and may or may not be incompatible due to RPH changes. Use at own risk.");
}
}
if (MadeForLSPDFRVersion != null)
{
if (File.Exists("Plugins/LSPD First Response.dll"))
{
Version InstalledLSPDFRVer = new Version(FileVersionInfo.GetVersionInfo("Plugins/LSPD First Response.dll").ProductVersion);
if (InstalledLSPDFRVer.CompareTo(MadeForLSPDFRVersion) != 0)
{
Game.LogTrivial(CallingPlugin + " compatibility warning: Different LSPD First Response.dll version detected, use at your own risk! This mod was made for LSPDFR " + MadeForLSPDFRVersion.ToString());
Game.DisplayNotification(CallingPlugin + " compatibility warning: Different LSPD First Response.dll version detected, use at your own risk! This mod was made for LSPDFR " + MadeForLSPDFRVersion.ToString());
//Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "Detected invalid LSPD First Response.dll version. To run this mod, you need LSPDFR " + MadeForLSPDFRVersion.ToString());
//CheckPreplacededSuccessfully = false;
}
}
else
{
Game.LogTrivial("LSPD First Response.dll not installed.");
Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "Couldn't detect required LSPD First Response.dll. You must install it.");
CheckPreplacededSuccessfully = false;
}
}
if (RAGENativeUIVersion != null)
{
if (File.Exists("RAGENativeUI.dll"))
{
Version InstalledNativeUIVer = new Version(FileVersionInfo.GetVersionInfo("RAGENativeUI.dll").ProductVersion);
if (InstalledNativeUIVer.CompareTo(RAGENativeUIVersion) < 0)
{
Game.LogTrivial("RAGENativeUI.dll out of date. Required version of RAGENativeUI to run this mod: " + RAGENativeUIVersion);
Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "RAGENativeUI.dll out of date. Required version of RAGENativeUI to run this mod: " + RAGENativeUIVersion);
CheckPreplacededSuccessfully = false;
}
}
else
{
Game.LogTrivial("RAGENativeUI.dll is not installed. You must install it to run this mod.");
Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "RAGENativeUI.dll is not installed. You must install it to run this mod.");
CheckPreplacededSuccessfully = false;
}
}
if (AudioFilesToCheckFor != null)
{
foreach (string s in AudioFilesToCheckFor)
{
if (!File.Exists(s))
{
Game.LogTrivial("Couldn't find the required audio file at " + s);
Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "You are missing required (new) audio files. Path is: " + s);
CheckPreplacededSuccessfully = false;
}
}
}
if (OtherRequiredFilesToCheckFor != null)
{
foreach (string s in OtherRequiredFilesToCheckFor)
{
if (!File.Exists(s))
{
Game.LogTrivial("Couldn't find the required file at " + s);
Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "You are missing required (new) files. Path is: " + s);
CheckPreplacededSuccessfully = false;
}
}
}
if (!CheckForRageVersion(MinimumRPHVersion))
{
CheckPreplacededSuccessfully = false;
Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "RAGEPluginHook is out of date. This mod requires RPH " + MinimumRPHVersion);
}
}
else
{
Game.LogTrivial("Albo1125.Common.dll is out of date. This mod requires Albo1125.Common " + Albo1125CommonVer);
Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "Albo1125.Common.dll is out of date. This mod requires Albo1125.Common " + Albo1125CommonVer);
CheckPreplacededSuccessfully = false;
}
}
else
{
CheckPreplacededSuccessfully = false;
Game.LogTrivial("Albo1125.Common.dll is not installed. This mod requires Albo1125.Common to be installed. You've successfully run this without actually having it on your PC...spooky.");
Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "Albo1125.Common.dll is not installed. This mod requires Albo1125.Common to be installed. You've successfully run this without actually having it on your PC...spooky.");
}
if (RegisteredPluginsForDependencyChecks.Contains(CallingPlugin)) { RegisteredPluginsForDependencyChecks.Remove(CallingPlugin); }
if (RegisteredPluginsForDependencyChecks.Count == 0 && Plugins_URL_Errors.Count > 0) { DisplayDependencyErrors(); }
Game.LogTrivial("Dependency check for " + CallingPlugin + " successful: " + CheckPreplacededSuccessfully);
return CheckPreplacededSuccessfully;
}
19
View Source File : DependencyChecker.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
public static bool CheckIfFileExists(string file, Version MinVer = null)
{
if (File.Exists(file))
{
Version InstalledVer = new Version(FileVersionInfo.GetVersionInfo(file).ProductVersion);
if (MinVer == null || InstalledVer.CompareTo(MinVer) >= 0)
{
return true;
}
}
return false;
}
19
View Source File : UpdateChecker.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
public static void InitialiseUpdateCheckingProcess()
{
Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Starting update checks.");
Directory.CreateDirectory("Albo1125.Common/UpdateInfo");
if (!File.Exists("Albo1125.Common/CommonVariables.xml"))
{
new XDoreplacedent(
new XElement("CommonVariables")
)
.Save("Albo1125.Common/CommonVariables.xml");
}
try
{
XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
if (!string.IsNullOrWhiteSpace((string)CommonVariablesDoc.Root.Element("NextUpdateCheckDT")))
{
try
{
if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value == replacedembly.GetExecutingreplacedembly().GetName().Version.ToString())
{
Game.LogTrivial("Albo1125.Common update checking has been disabled. Skipping checks.");
Game.LogTrivial("Albo1125.Common note: please do not request support for old versions.");
return;
}
DateTime UpdateCheckDT = DateTime.FromBinary(long.Parse(CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value));
if (DateTime.Now < UpdateCheckDT)
{
Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Not checking for updates until " + UpdateCheckDT.ToString());
return;
}
}
catch (Exception e) { Game.LogTrivial(e.ToString()); Game.LogTrivial("Albo1125.Common handled exception. #1"); }
}
DateTime NextUpdateCheckDT = DateTime.Now.AddDays(1);
if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = NextUpdateCheckDT.ToBinary().ToString();
CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
CommonVariablesDoc = null;
GameFiber.StartNew(delegate
{
GetUpdateNodes();
foreach (UpdateEntry entry in AllUpdateEntries.ToArray())
{
CheckForModificationUpdates(entry.Name, new Version(FileVersionInfo.GetVersionInfo(entry.Path).FileVersion), entry.FileID, entry.DownloadLink);
}
if (PluginsDownloadLink.Count > 0) { DisplayUpdates(); }
Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Update checks complete.");
});
}
catch (System.Xml.XmlException e)
{
Game.LogTrivial(e.ToString());
Game.DisplayNotification("Error while processing XML files. To fix this, please delete the following folder and its contents: Grand Theft Auto V/Albo1125.Common");
Albo1125.Common.CommonLibrary.ExtensionMethods.DisplayPopupTextBoxWithConfirmation("Albo1125.Common", "Error while processing XML files. To fix this, please delete the following folder and its contents: Grand Theft Auto V/Albo1125.Common", false);
throw e;
}
}
19
View Source File : DependencyChecker.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
private static bool CheckForRageVersion(float MinimumVersion)
{
string RPHFile = "RAGEPluginHook.exe";
string[] files = Directory.GetFiles(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location), "*.exe", SearchOption.TopDirectoryOnly);
foreach (string file in files)
{
if (Path.GetFileName(file).ToLower() == "ragepluginhook.exe")
{
RPHFile = file;
break;
}
}
var versionInfo = FileVersionInfo.GetVersionInfo(RPHFile);
float Rageversion;
try
{
Rageversion = float.Parse(versionInfo.ProductVersion.Substring(0, 4), CultureInfo.InvariantCulture);
Game.LogTrivial("Albo1125.Common detected RAGEPluginHook version: " + Rageversion.ToString());
//If user's RPH version is older than the minimum
if (Rageversion < MinimumVersion)
{
CorrectRPHVersion = false;
}
//If user's RPH version is (above) the specified minimum
else
{
CorrectRPHVersion = true;
}
}
catch (Exception e)
{
//If for whatever reason the version couldn't be found.
Game.LogTrivial(e.ToString());
Game.LogTrivial("Unable to detect your Rage installation.");
if (File.Exists("RAGEPluginHook.exe"))
{
Game.LogTrivial("RAGEPluginHook.exe exists");
}
else { Game.LogTrivial("RAGEPluginHook doesn't exist."); }
Game.LogTrivial("Rage Version: " + versionInfo.ProductVersion.ToString());
Game.DisplayNotification("Albo1125.Common was unable to detect RPH installation. Please send me your logfile.");
CorrectRPHVersion = false;
}
return CorrectRPHVersion;
}
19
View Source File : MKMHelpers.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick
public static void LogError(string subject, string errorMessage, bool popup, string sURL = "")
{
lock (errorLogLock)
{
// if this the first error of this run, write a header with current date and time in the error log file to know which errors are old and which new
// monitoring when (if) first error happens helps limit the size of the log in runs when no error happens
// TODO - maybe clean the log once in a while?
if (firstError)
{
System.Reflection.replacedembly replacedembly = System.Reflection.replacedembly.GetExecutingreplacedembly();
System.Diagnostics.FileVersionInfo fileVersionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(replacedembly.Location);
using (var sw = File.AppendText(@".\\error_log.txt"))
{
sw.WriteLine(DateTime.Now.ToString() + ", version: " + fileVersionInfo.ProductVersion);
firstError = false;
}
}
string msg = "Error with " + subject + ": " + errorMessage;
using (var sw = File.AppendText(@".\\error_log.txt"))
{
if (sURL.Length > 0)
sw.WriteLine(msg + " @ " + sURL);
else
sw.WriteLine(msg);
}
MainView.Instance.LogMainWindow(msg);
if (popup)
MessageBox.Show(msg, "MKMTool encountered error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
19
View Source File : Utils.cs
License : MIT License
Project Creator : AmazingDM
License : MIT License
Project Creator : AmazingDM
public static string GetFileVersion(string file)
{
return File.Exists(file) ? FileVersionInfo.GetVersionInfo(file).FileVersion : string.Empty;
}
19
View Source File : MetaController.cs
License : MIT License
Project Creator : Amitpnk
License : MIT License
Project Creator : Amitpnk
[HttpGet("/info")]
public ActionResult<string> Info()
{
var replacedembly = typeof(Startup).replacedembly;
var lastUpdate = System.IO.File.GetLastWriteTime(replacedembly.Location);
var version = FileVersionInfo.GetVersionInfo(replacedembly.Location).ProductVersion;
return Ok($"Version: {version}, Last Updated: {lastUpdate}");
}
19
View Source File : UpdateManager.cs
License : MIT License
Project Creator : Analogy-LogViewer
License : MIT License
Project Creator : Analogy-LogViewer
private Version UpdaterVersion()
{
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(UpdaterExecutable);
return new Version(fvi.FileVersion);
}
19
View Source File : Host.cs
License : MIT License
Project Creator : ancientproject
License : MIT License
Project Creator : ancientproject
public static int Main(string[] c_args)
{
if (Environment.GetEnvironmentVariable("WT_SESSION") == null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Environment.SetEnvironmentVariable($"RUNE_EMOJI_USE", "0");
Environment.SetEnvironmentVariable($"RUNE_COLOR_USE", "0");
Environment.SetEnvironmentVariable($"RUNE_NIER_USE", "0");
Environment.SetEnvironmentVariable($"NO_COLOR", "true");
ForegroundColor = ConsoleColor.Gray;
WriteLine($"no windows-terminal: coloring, emoji and nier has disabled.");
ForegroundColor = ConsoleColor.White;
}
AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => { ConsoleExtensions.Disable(); };
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var raw = new FluentCommandLineParser<Args>();
raw.Setup(x => x.sourceFiles)
.As('s', "source")
.WithDescription("Source files.")
.SetDefault(new List<string>());
raw.Setup(x => x.OutFile)
.As('o', "out")
.WithDescription("Out file.");
raw.Setup(x => x.extension)
.As('e', "ext")
.WithDescription("Extension of file.")
.SetDefault("dlx");
raw.Parse(c_args);
var args = raw.Object;
var ver = FileVersionInfo.GetVersionInfo(typeof(Host).replacedembly.Location).ProductVersion;
WriteLine($"Ancient replacedembler compiler version {ver}".Pastel(Color.Gray));
WriteLine($"Copyright (C) 2020 Yuuki Wesp.\n\n".Pastel(Color.Gray));
if (!args.sourceFiles.Any())
{
Warn(Warning.NoSource, "No source files specified.");
return 1;
}
if (string.IsNullOrEmpty(args.OutFile))
{
Error(Warning.OutFileNotSpecified, "Outputs without source must have the --out option specified.");
return 1;
}
if (!args.sourceFiles.Select(x => new FileInfo(x).Exists).All(x => x))
{
Error(Warning.SourceFileNotFound, "One source file not found.");
return 1;
}
var source = File.ReadAllText(args.sourceFiles.First()).Replace("\r", "");
try
{
var e = Evolve(source);
var c = Compile(e, args);
File.WriteAllBytes($"{args.OutFile}.{args.extension}", c.data);
File.WriteAllBytes($"{args.OutFile}.pdb", c.map);
return 0;
}
catch (AncientCompileException)
{ }
catch (AncientEvolveException)
{ }
catch (Exception e)
{
WriteLine(e);
}
return 1;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : ANF-Studios
License : MIT License
Project Creator : ANF-Studios
public static string GetInstalledWinPathVersion()
{
FileVersionInfo winPathVersion = null;
string installationPath = Environment.Is64BitOperatingSystem
? "C:\\Program Files\\WinPath\\WinPath.exe"
: "C:\\Program Files (x86)\\WinPath\\WinPath.exe";
if (File.Exists(installationPath))
winPathVersion = FileVersionInfo.GetVersionInfo(installationPath);
else
return null;
return $"{winPathVersion.FileMajorPart}.{winPathVersion.FileMinorPart}.{winPathVersion.FileBuildPart}";
}
19
View Source File : UpdateChecker.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
[MethodImpl(MethodImplOptions.NoInlining)]
public static void ShowSplash()
{
if (isShowen)
{
return;
}
isShowen = true;
try
{
// エントリアセンブリのパスを出力する
var entry = replacedembly.GetEntryreplacedembly().Location;
Logger.Trace($"Entry {entry}");
// ついでにFFXIV_ACT_Pluginのバージョンを出力する
var ffxivPlugin = ActGlobals.oFormActMain?.ActPlugins?
.FirstOrDefault(
x => x.pluginFile.Name.ContainsIgnoreCase("FFXIV_ACT_Plugin"))?
.pluginFile.FullName;
if (File.Exists(ffxivPlugin))
{
var vi = FileVersionInfo.GetVersionInfo(ffxivPlugin);
if (vi != null)
{
Logger.Trace($"FFXIV_ACT_Plugin v{vi.FileMajorPart}.{vi.FileMinorPart}.{vi.FileBuildPart}.{vi.FilePrivatePart}");
}
}
// Hojoringのバージョンを出力しつつSPLASHを表示する
var hojoring = GetHojoring();
if (hojoring != null)
{
var ver = hojoring.Version as Version;
if (ver != null)
{
Logger.Trace($"Hojoring v{ver.Major}.{ver.Minor}.{ver.Revision}");
}
hojoring.ShowSplash("initializing...");
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
19
View Source File : KHPCPatchManager.cs
License : Apache License 2.0
Project Creator : AntonioDePau
License : Apache License 2.0
Project Creator : AntonioDePau
[STAThread]
static void Main(string[] args){
if (Environment.OSVersion.Version.Major >= 6)
SetProcessDPIAware();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(Executingreplacedembly.Location);
version = "v" + fvi.ProductVersion;
if(!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "/resources")){
UpdateResources();
}
if(!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "/resources/custom_filenames.txt")){
File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "/resources/custom_filenames.txt", "");
}
Console.WriteLine($"KHPCPatchManager {version}");
string hedFile = null, pkgFile = null, pkgFolder = null;
List<string> originFolder = new List<string>();
List<string> patchFolders = new List<string>();
bool help = false;
try{
for(int i=0;i<args.Length;i++){
if(Path.GetExtension(args[i]) == ".hed"){
hedFile = args[i];
}else if(Path.GetExtension(args[i]) == ".pkg"){
pkgFile = args[i];
}else if(Directory.Exists(args[i])){
pkgFolder = args[i];
patchFolders.Add(args[i]);
}else if(Path.GetExtension(args[i]) == ".kh1pcpatch"){
patchType.Add("KH1");
originFolder.Add(args[i]);
}else if(Path.GetExtension(args[i]) == ".kh2pcpatch"){
patchType.Add("KH2");
originFolder.Add(args[i]);
}else if(Path.GetExtension(args[i]) == ".compcpatch"){
patchType.Add("COM");
originFolder.Add(args[i]);
}else if(Path.GetExtension(args[i]) == ".bbspcpatch"){
patchType.Add("BBS");
originFolder.Add(args[i]);
}else if(Path.GetExtension(args[i]) == ".dddpcpatch"){
patchType.Add("DDD");
originFolder.Add(args[i]);
}else{
if(args[i] == "help" || args[i] == "-help" || args[i] == "--help" || args[i] == "-h" || args[i] == "--h" || args[i] == "?") help = true;
}
}
if(hedFile != null){
Console.WriteLine("Extracting pkg...");
OpenKh.Egs.EgsTools.Extract(hedFile, hedFile + "_out");
Console.WriteLine("Done!");
}else if(pkgFile != null && pkgFolder != null){
Console.WriteLine("Patching pkg...");
OpenKh.Egs.EgsTools.Patch(pkgFile, pkgFolder, pkgFolder + "_out");
Console.WriteLine("Done!");
}else if(pkgFile == null && pkgFolder != null){
Console.WriteLine("Creating patch...");
using(var zip = new ZipFile()){
for(int i=0;i<patchFolders.Count;i++){
Console.WriteLine("Adding: {0}", patchFolders[i]);
zip.AddDirectory(patchFolders[i], "");
if (Directory.Exists(patchFolders[i] + @"\kh1_first") || Directory.Exists(patchFolders[i] + @"\kh1_second") || Directory.Exists(patchFolders[i] + @"\kh1_third") || Directory.Exists(patchFolders[i] + @"\kh1_fourth") || Directory.Exists(patchFolders[i] + @"\kh1_fifth")){
zip.Save("MyPatch.kh1pcpatch");
}else if (Directory.Exists(patchFolders[i] + @"\kh2_first") || Directory.Exists(patchFolders[i] + @"\kh2_second") || Directory.Exists(patchFolders[i] + @"\kh2_third") || Directory.Exists(patchFolders[i] + @"\kh2_fourth") || Directory.Exists(patchFolders[i] + @"\kh2_fifth") || Directory.Exists(patchFolders[i] + @"\kh2_sixth")){
zip.Save("MyPatch.kh2pcpatch");
}else if (Directory.Exists(patchFolders[i] + @"\Recom")){
zip.Save("MyPatch.compcpatch");
}else if (Directory.Exists(patchFolders[i] + @"\bbs_first") || Directory.Exists(patchFolders[i] + @"\bbs_second") || Directory.Exists(patchFolders[i] + @"\bbs_third") || Directory.Exists(patchFolders[i] + @"\bbs_fourth")){
zip.Save("MyPatch.bbspcpatch");
}else if (Directory.Exists(patchFolders[i] + @"\kh3d_first") || Directory.Exists(patchFolders[i] + @"\kh3d_second") || Directory.Exists(patchFolders[i] + @"\kh3d_third") || Directory.Exists(patchFolders[i] + @"\kh3d_fourth")){
zip.Save("MyPatch.dddpcpatch");
}
}
}
Console.WriteLine("Done!");
}else if(originFolder.Count > 0){
if(patchType.Distinct().ToList().Count == 1){
ApplyPatch(originFolder, patchType[0]);
}else{
Console.WriteLine(multiplePatchTypesSelected);
}
}else if(help){
Console.WriteLine("\nHow to use KHPCPatchManager in CLI:");
Console.WriteLine("- Feed a .hed file to unpack the replacedociated .pkg file:\n khpcpatchmanager <hed_file>\n");
Console.WriteLine("- Feed a .pkg file and its unpacked folder to patch it:\n khpcpatchmanager <pkg_file> <unpacked_pkg_folder>\n");
Console.WriteLine("- Feed a folder(s) (extracted .pkg format) to create a kh1pcpatch, kh2pcpatch, bbspcpatch, compcpatch or a dddpcpatch:\n khpcpatchmanager <unpacked_pkg_folder>\n");
Console.WriteLine("- Feed a kh1pcpatch, kh2pcpatch, bbspcpatch, compcpatch or a dddpcpatch to patch your .pkgs:\n khpcpatchmanager <.[kh1/com/kh2/bbs/ddd]pcpatch file>\n");
}else{
InitUI();
}
}catch(Exception e){
Console.WriteLine($"Error: {e}");
}
if(!GUI_Displayed) Console.ReadLine();
}
19
View Source File : Program.cs
License : MIT License
Project Creator : AntonyCorbett
License : MIT License
Project Creator : AntonyCorbett
private static string GetVersion()
{
System.Reflection.replacedembly replacedembly = System.Reflection.replacedembly.GetExecutingreplacedembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(replacedembly.Location);
return fvi.FileVersion ?? "Unknown";
}
19
View Source File : ConnectionTests.cs
License : MIT License
Project Creator : Archomeda
License : MIT License
Project Creator : Archomeda
[Fact]
public void ConstructorTest()
{
string key = "test key";
var locale = Locale.German;
string userAgent = "HelloTyria";
var httpClient = Subsreplacedute.For<IHttpClient>();
var cacheMethod = Subsreplacedute.For<ICacheMethod>();
string version = new Version(FileVersionInfo.GetVersionInfo(typeof(Gw2Client).replacedembly.Location).FileVersion).ToString(3);
string expectedUserAgent = $"Gw2Sharp/{version} (https://github.com/Archomeda/Gw2Sharp)";
var connection1 = new Connection();
var connection2 = new Connection(key);
var connection3 = new Connection(locale);
var connection4 = new Connection(key, locale);
var connection5 = new Connection(key, locale, httpClient: httpClient, cacheMethod: cacheMethod);
var connection6 = new Connection(key, locale, userAgent: userAgent, httpClient: httpClient, cacheMethod: cacheMethod);
var connection7 = new Connection(null!);
var connection8 = new Connection(null!, Locale.English, httpClient: httpClient, cacheMethod: cacheMethod);
using (new replacedertionScope())
{
connection1.AccessToken.Should().BeEmpty();
connection1.Locale.Should().Be(Locale.English);
connection1.UserAgent.Should().Be(expectedUserAgent);
connection1.HttpClient.Should().BeOfType<HttpClient>();
connection1.CacheMethod.Should().BeOfType<MemoryCacheMethod>();
connection2.AccessToken.Should().Be(key);
connection2.Locale.Should().Be(Locale.English);
connection2.UserAgent.Should().Be(expectedUserAgent);
connection2.HttpClient.Should().BeOfType<HttpClient>();
connection2.CacheMethod.Should().BeOfType<MemoryCacheMethod>();
connection3.AccessToken.Should().BeEmpty();
connection3.Locale.Should().Be(locale);
connection3.UserAgent.Should().Be(expectedUserAgent);
connection3.HttpClient.Should().BeOfType<HttpClient>();
connection3.CacheMethod.Should().BeOfType<MemoryCacheMethod>();
connection4.AccessToken.Should().Be(key);
connection4.Locale.Should().Be(locale);
connection4.UserAgent.Should().Be(expectedUserAgent);
connection4.HttpClient.Should().BeOfType<HttpClient>();
connection4.CacheMethod.Should().BeOfType<MemoryCacheMethod>();
connection5.AccessToken.Should().Be(key);
connection5.Locale.Should().Be(locale);
connection5.UserAgent.Should().Be(expectedUserAgent);
connection5.HttpClient.Should().Be(httpClient);
connection5.CacheMethod.Should().Be(cacheMethod);
connection6.AccessToken.Should().Be(key);
connection6.Locale.Should().Be(locale);
connection6.UserAgent.Should().Be($"{userAgent} {expectedUserAgent}");
connection6.HttpClient.Should().Be(httpClient);
connection6.CacheMethod.Should().Be(cacheMethod);
connection7.AccessToken.Should().BeEmpty();
connection8.UserAgent.Should().NotBeNullOrEmpty();
}
}
19
View Source File : ArkStartupBase.cs
License : MIT License
Project Creator : ARKlab
License : MIT License
Project Creator : ARKlab
public virtual void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddApplicationInsightsTelemetryProcessor<ArkSkipUselessSpamTelemetryProcessor>();
services.AddSingleton<ITelemetryInitializer, WebApiUserTelemetryInitializer>();
services.AddSingleton<ITelemetryInitializer, WebApi4xxreplaceduccessTelemetryInitializer>();
services.AddSingleton<ITelemetryInitializer, GlobalInfoTelemetryInitializer>();
services.AddSingleton<ITelemetryInitializer, DoNotSampleFailures>();
services.Configure<SamplingPercentageEstimatorSettings>(o =>
{
o.MovingAverageRatio = 0.5;
o.MaxTelemetryItemsPerSecond = 1;
o.SamplingPercentageDecreaseTimeout = TimeSpan.FromMinutes(1);
});
services.Configure<SamplingPercentageEstimatorSettings>(o =>
{
Configuration.GetSection("ApplicationInsights:EstimatorSettings").Bind(o);
});
services.AddApplicationInsightsTelemetry(o =>
{
o.InstrumentationKey = Configuration["ApplicationInsights:InstrumentationKey"];
o.EnableAdaptiveSampling = false; // enabled below by EnableAdaptiveSamplingWithCustomSettings
o.EnableHeartbeat = true;
o.AddAutoCollectedMetricExtractor = true;
o.RequestCollectionOptions.InjectResponseHeaders = true;
o.RequestCollectionOptions.TrackExceptions = true;
o.DeveloperMode = Debugger.IsAttached;
o.ApplicationVersion = FileVersionInfo.GetVersionInfo(this.GetType().replacedembly.Location).FileVersion;
});
services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>((module, o) => { module.EnableSqlCommandTextInstrumentation = true; });
// this MUST be after the MS AddApplicationInsightsTelemetry to work. IPostConfigureOptions is NOT working as expected.
services.AddSingleton<IConfigureOptions<TelemetryConfiguration>, EnableAdaptiveSamplingWithCustomSettings>();
if (!string.IsNullOrWhiteSpace(Configuration.GetConnectionString(NLog.NLogDefaultConfigKeys.SqlConnStringName)))
services.AddSingleton<ITelemetryProcessorFactory>(
new SkipSqlDatabaseDependencyFilterFactory(Configuration.GetConnectionString(NLog.NLogDefaultConfigKeys.SqlConnStringName)));
services.Configure<SnapshotCollectorConfiguration>(o =>
{
});
services.Configure<SnapshotCollectorConfiguration>(Configuration.GetSection(nameof(SnapshotCollectorConfiguration)));
services.AddSnapshotCollector();
services.AddCors();
}
19
View Source File : AssemblyExtensions.cs
License : GNU General Public License v3.0
Project Creator : Artentus
License : GNU General Public License v3.0
Project Creator : Artentus
public static FileVersionInfo FileVersion(this replacedembly replacedembly)
=> FileVersionInfo.GetVersionInfo(replacedembly.Location);
19
View Source File : Extensions.cs
License : GNU General Public License v3.0
Project Creator : AutoDarkMode
License : GNU General Public License v3.0
Project Creator : AutoDarkMode
public static string CommitHash()
{
try
{
System.Reflection.replacedembly replacedembly = System.Reflection.replacedembly.GetExecutingreplacedembly();
string productVersion = FileVersionInfo.GetVersionInfo(replacedembly.Location).ProductVersion;
string commitHash = FileVersionInfo.GetVersionInfo(replacedembly.Location).ProductVersion[(productVersion.LastIndexOf("-") + 2)..];
return commitHash;
}
catch
{
return "";
}
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : AutoDarkMode
License : GNU General Public License v3.0
Project Creator : AutoDarkMode
static void Main(string[] args)
{
LoggerSetup();
Logger.Info($"Auto Dark Mode Updater {Version.Major}.{Version.Minor}.{Version.Build}");
ShutdownService();
if (args.Length > 2)
{
if (args[0].Contains("--notify"))
{
restoreShell = args[1].Equals(true.ToString(), StringComparison.Ordinal);
restoreApp = args[2].Equals(true.ToString(), StringComparison.Ordinal);
}
}
try
{
currentVersion = FileVersionInfo.GetVersionInfo(Extensions.ExecutionPathSvc);
if (currentVersion != null)
{
Logger.Info($"currently installed version: {currentVersion.FileVersion}");
}
}
catch (Exception ex)
{
Logger.Warn(ex, "could not read installed version:");
}
MoveToTemp();
CopyNewFiles();
Cleanup();
try
{
patchedVersion = FileVersionInfo.GetVersionInfo(Extensions.ExecutionPathSvc);
}
catch (Exception ex)
{
Logger.Warn(ex, "could not read installed version:");
}
if (patchedVersion != null)
{
Logger.Info($"patch complete, installed version: {patchedVersion.FileVersion}");
}
else
{
Logger.Info("patch complete");
}
UpdateInnoInstallerString();
Logger.Info("starting service");
if (restoreShell) Logger.Info("relaunching shell");
if (restoreApp) Logger.Info("relaunching app");
Relaunch(restoreShell, restoreApp, false);
}
19
View Source File : UserDataContext.cs
License : MIT License
Project Creator : automuteus
License : MIT License
Project Creator : automuteus
public UserDataContext(IDialogCoordinator dialogCoordinator, IAppSettings settings)
{
DialogCoordinator = dialogCoordinator;
Settings = settings;
Settings.debug = AmongUsCapture.Settings.PersistentSettings.debugConsole;
Settings.PropertyChanged += SettingsOnPropertyChanged;
AccentColors = ThemeManager.Current.Themes
.GroupBy(x => x.ColorScheme)
.OrderBy(a => a.Key)
.Select(a => new AccentColorMenuData { Name = a.Key, ColorBrush = a.First().ShowcaseBrush })
.ToList();
FileVersionInfo v = FileVersionInfo.GetVersionInfo(App.GetExecutablePath());
Version = $"{v.FileMajorPart}.{v.FileMinorPart}.{v.FileBuildPart}";
try
{
GitHubClient client = new GitHubClient(new ProductHeaderValue("AmongUsCapture", Version));
Release latest = new Release();
try
{
latest = client.Repository.Release.GetLatest("automuteus", "amonguscapture").Result;
}
catch (Exception e)
{
latest = client.Repository.Release.GetLatest("denverquane", "amonguscapture").Result;
}
LatestReleasereplacedetURL = latest.replacedets.First(x => x.Name == "AmongUsCapture.zip").BrowserDownloadUrl;
if (latest.replacedets.Any(x => x.Name == "AmongUsCapture.zip.sha256.pgp"))
LatestReleasereplacedetSignedHashURL = latest.replacedets.First(x => x.Name == "AmongUsCapture.zip.sha256.pgp").BrowserDownloadUrl;
LatestVersion = $"{latest.TagName}";
}
catch (Exception e)
{
Console.WriteLine(e);
LatestVersion = "ERROR";
}
OnPropertyChanged(nameof(LatestVersion));
OnPropertyChanged(nameof(Version));
OnPropertyChanged(nameof(AccentColors));
}
19
View Source File : App.xaml.cs
License : MIT License
Project Creator : automuteus
License : MIT License
Project Creator : automuteus
public void SetupLoggingConfig() {
var LoggingConfig = new NLog.Config.LoggingConfiguration();
FileVersionInfo v = FileVersionInfo.GetVersionInfo(App.GetExecutablePath());
var logfile = new NLog.Targets.FileTarget("logfile")
{
FileName = "${specialfolder:folder=ApplicationData:cached=true}/AmongUsCapture/logs/latest.log",
ArchiveFileName= "${specialfolder:folder=ApplicationData:cached=true}/AmongUsCapture/logs/{#}.log",
ArchiveNumbering= ArchiveNumberingMode.Date,
Layout = "${time:universalTime=True}|${level:uppercase=true}|${logger}|${message}",
MaxArchiveFiles = 100,
ArchiveOldFileOnStartup = true,
ArchiveDateFormat= "yyyy-MM-dd HH_mm_ss",
Header = $"Capture version: {v.FileMajorPart}.{v.FileMinorPart}.{v.FileBuildPart}.{v.FilePrivatePart}\n",
Footer = $"\nCapture version: {v.FileMajorPart}.{v.FileMinorPart}.{v.FileBuildPart}.{v.FilePrivatePart}"
};
LoggingConfig.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
NLog.LogManager.Configuration = LoggingConfig;
}
19
View Source File : Extensions.cs
License : MIT License
Project Creator : avestura
License : MIT License
Project Creator : avestura
public static string GetVersion()
{
replacedembly replacedembly = replacedembly.GetExecutingreplacedembly();
FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(replacedembly.Location);
return fileVersionInfo.ProductVersion;
}
19
View Source File : BaseSourceCodeWriter.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
public static void WriteSourceLicenseHeader(TextWriter writer)
{
var fileVersionInfo = FileVersionInfo.GetVersionInfo(System.Reflection.replacedembly.GetExecutingreplacedembly().Location);
writer.WriteLine("/*******************************************************************************");
writer.WriteLine(" * {0}", fileVersionInfo.LegalCopyright);
writer.WriteLine(" * Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use");
writer.WriteLine(" * this file except in compliance with the License. A copy of the License is located at");
writer.WriteLine(" *");
writer.WriteLine(" * http://aws.amazon.com/apache2.0");
writer.WriteLine(" *");
writer.WriteLine(" * or in the \"license\" file accompanying this file.");
writer.WriteLine(" * This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR");
writer.WriteLine(" * CONDITIONS OF ANY KIND, either express or implied. See the License for the");
writer.WriteLine(" * specific language governing permissions and limitations under the License.");
writer.WriteLine(" * *****************************************************************************");
writer.WriteLine(" *");
writer.WriteLine(" * AWS Tools for Windows (TM) PowerShell (TM)");
writer.WriteLine(" *");
writer.WriteLine(" */");
writer.WriteLine();
}
19
View Source File : CommonCmdlets.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
protected override void ProcessRecord()
{
base.ProcessRecord();
var powershellreplacedembly = TypeFactory.GetTypeInfo(typeof(BaseCmdlet)).replacedembly;
using (var sw = new StringWriter())
{
var powershellInfo = FileVersionInfo.GetVersionInfo(powershellreplacedembly.Location);
sw.WriteLine();
sw.WriteLine(powershellInfo.ProductName);
sw.WriteLine("Version {0}", powershellInfo.FileVersion);
sw.WriteLine(powershellInfo.LegalCopyright);
var sdkreplacedembly = TypeFactory.GetTypeInfo(typeof(AWSCredentials)).replacedembly;
var sdkInfo = FileVersionInfo.GetVersionInfo(sdkreplacedembly.Location);
sw.WriteLine();
sw.WriteLine(sdkInfo.ProductName);
sw.WriteLine("Core Runtime Version {0}", sdkInfo.FileVersion);
sw.WriteLine(sdkInfo.LegalCopyright);
sw.WriteLine();
sw.WriteLine("Release notes: {0}", "https://github.com/aws/aws-tools-for-powershell/blob/master/CHANGELOG.md");
sw.WriteLine();
// recognise 3rd party libraries
sw.WriteLine("This software includes third party software subject to the following copyrights:");
sw.WriteLine("- Logging from log4net, Apache License");
sw.WriteLine("[http://logging.apache.org/log4net/license.html]");
WriteObject(sw.ToString());
}
if (ListServiceVersionInfo.IsPresent)
{
var services = GetAWSServiceCmdlet.GetServices();
foreach (var service in services.OrderBy(service => service.Name))
{
var result = new PSObject();
result.Properties.Add(new PSNoteProperty("Service", service.Description));
result.Properties.Add(new PSNoteProperty("Noun Prefix", service.CmdletNounPrefix));
#if MODULAR
result.Properties.Add(new PSNoteProperty("Module Name", service.ModuleName));
#endif
result.Properties.Add(new PSNoteProperty("SDK replacedembly Version", service.SDKreplacedemblyVersion));
WriteObject(result);
}
}
}
19
View Source File : AWSXRayRecorderImpl.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
protected void PopulateContexts()
{
RuntimeContext = new Dictionary<string, object>();
// Prepare XRay section for runtime context
var xrayContext = new ConcurrentDictionary<string, string>();
#if NET45
xrayContext["sdk"] = "X-Ray for .NET";
#else
xrayContext["sdk"] = "X-Ray for .NET Core";
#endif
string currentreplacedemblyLocation = replacedembly.GetExecutingreplacedembly().Location;
if (!string.IsNullOrEmpty(currentreplacedemblyLocation))
{
xrayContext["sdk_version"] = FileVersionInfo.GetVersionInfo(currentreplacedemblyLocation).ProductVersion;
}
else
{
xrayContext["sdk_version"] = "Unknown";
}
RuntimeContext["xray"] = xrayContext;
#if NET45
ServiceContext["runtime"] = ".NET Framework";
#else
ServiceContext["runtime"] = ".NET Core Framework";
#endif
ServiceContext["runtime_version"] = Environment.Version.ToString();
}
19
View Source File : AWSXRayRecorderTests.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
[TestMethod]
public void TestXrayContext()
{
_recorder.BeginSegment("test", TraceId);
var segment = AWSXRayRecorder.Instance.TraceContext.GetEnreplacedy();
_recorder.EndSegment();
IDictionary<string, string> xray = (ConcurrentDictionary<string, string>)segment.Aws["xray"];
var versionText =
FileVersionInfo.GetVersionInfo(replacedembly.Getreplacedembly(typeof(AWSXRayRecorderBuilder)).Location)
.ProductVersion;
replacedert.AreEqual(versionText, xray["sdk_version"]);
#if NET45
replacedert.AreEqual("X-Ray for .NET", xray["sdk"]);
#else
replacedert.AreEqual("X-Ray for .NET Core", xray["sdk"]);
#endif
}
19
View Source File : Program.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
static void Main(string[] args)
{
PortingreplacedistantCLI cli = new PortingreplacedistantCLI();
cli.HandleCommand(args);
var logConfiguration = new LoggerConfiguration().Enrich.FromLogContext()
.MinimumLevel.Debug()
.WriteTo.Console();
var replacedemblypath = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
var telemetryConfiguration = JsonSerializer.Deserialize<TelemetryConfiguration>(File.ReadAllText(Path.Combine(replacedemblypath, "PortingreplacedistantTelemetryConfig.json")));
var configuration = new PortingreplacedistantConfiguration();
var roamingFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var logs = Path.Combine(roamingFolder, "Porting replacedistant for .NET", "logs");
var logFilePath = Path.Combine(logs, "portingreplacedistant-client-cli.log");
var metricsFilePath = Path.Combine(logs, "portingreplacedistant-client-cli.metrics");
string version = FileVersionInfo.GetVersionInfo(replacedembly.GetExecutingreplacedembly().Location).ProductVersion;
var outputTemplate = "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] (Porting replacedistant Client CLI) (" + version + ") {SourceContext}: {Message:lj}{NewLine}{Exception}";
Serilog.Formatting.Display.MessageTemplateTextFormatter tf =
new Serilog.Formatting.Display.MessageTemplateTextFormatter(outputTemplate, CultureInfo.InvariantCulture);
logConfiguration.WriteTo.File(
logFilePath,
rollingInterval: RollingInterval.Infinite,
rollOnFileSizeLimit: false,
outputTemplate: outputTemplate);
Log.Logger = logConfiguration.CreateLogger();
if (cli.isSchema)
{
if (cli.schemaVersion)
{
Console.WriteLine(Common.Model.Schema.version);
}
}
if (cli.isreplacedess)
{
try
{
TelemetryCollector.Builder(Log.Logger, metricsFilePath);
var portingreplacedistantBuilder = PortingreplacedistantBuilder.Build(configuration, logConfig =>
logConfig.SetMinimumLevel(LogLevel.Debug)
.AddSerilog(logger: Log.Logger, dispose: true));
var portingreplacedistantClient = portingreplacedistantBuilder.GetPortingreplacedistant();
var reportExporter = portingreplacedistantBuilder.GetReportExporter();
var solutionSettings = cli.IgnoreProjects != null && cli.IgnoreProjects.Count != 0 ?
new replacedyzerSettings
{
IgnoreProjects = cli.IgnoreProjects,
TargetFramework = cli.Target
} : new replacedyzerSettings
{
IgnoreProjects = new List<string>(),
TargetFramework = cli.Target
};
var startTime = DateTime.Now;
Task<SolutionreplacedysisResult> replacedyzeResults;
if (solutionSettings.UseGenerator)
{
replacedyzeResults = replacedyzeSolutionGenerator(portingreplacedistantClient, cli.SolutionPath, solutionSettings);
}
else
{
replacedyzeResults = portingreplacedistantClient.replacedyzeSolutionAsync(cli.SolutionPath, solutionSettings);
replacedyzeResults.Wait();
}
if (replacedyzeResults.IsCompletedSuccessfully)
{
reportExporter.GenerateJsonReport(replacedyzeResults.Result, cli.OutputPath);
TelemetryCollector.SolutionreplacedessmentCollect(replacedyzeResults.Result, cli.Target, "1.8.0", $"Porting replacedistant Client CLI", DateTime.Now.Subtract(startTime).TotalMilliseconds, cli.Tag);
}
else
{
Log.Logger.Error("err generated solution replacedysis report");
}
if (cli.PortingProjects != null && cli.PortingProjects.Count != 0)
{
var PortingProjectResults = replacedyzeResults.Result.ProjectreplacedysisResults
.Where(project => cli.PortingProjects.Contains(project.ProjectName));
var FilteredRecommendedActions = PortingProjectResults
.SelectMany(project => project.PackagereplacedysisResults.Values
.Where(package =>
{
var comp = package.Result.CompatibilityResults.GetValueOrDefault(cli.Target);
return comp.Compatibility != Compatibility.COMPATIBLE && comp.CompatibleVersions.Count != 0;
})
.SelectMany(package => package.Result.Recommendations.RecommendedActions));
var PortingRequest = new PortingRequest
{
Projects = replacedyzeResults.Result.SolutionDetails.Projects.Where(p => cli.PortingProjects.Contains(p.ProjectName)).ToList(),
SolutionPath = cli.SolutionPath,
TargetFramework = cli.Target.ToString(),
RecommendedActions = FilteredRecommendedActions.ToList(),
IncludeCodeFix = true
};
var portingResults = portingreplacedistantClient.ApplyPortingChanges(PortingRequest);
reportExporter.GenerateJsonReport(portingResults, cli.SolutionPath, cli.OutputPath);
}
UploadLogs(cli.Profile, telemetryConfiguration, logFilePath, metricsFilePath);
}
catch (Exception ex)
{
Log.Logger.Error(ex, "error when using the tools :");
UploadLogs(cli.Profile, telemetryConfiguration, logFilePath, metricsFilePath);
Environment.Exit(-1);
}
}
}
19
View Source File : AdvHDUnpacker.cs
License : MIT License
Project Creator : Azukee
License : MIT License
Project Creator : Azukee
private static bool IsAdvHDGame(string gameDirectory)
{
foreach (string file in Directory.GetFiles(gameDirectory, "*.exe"))
if (System.Diagnostics.FileVersionInfo.GetVersionInfo(file).FileDescription == "ADVPlayerHD")
return true;
return false;
}
19
View Source File : DurableHttpClientFactory.cs
License : MIT License
Project Creator : Azure
License : MIT License
Project Creator : Azure
private static Version GetreplacedemblyVersion(replacedembly replacedembly)
{
var replacedemblyInfo = FileVersionInfo.GetVersionInfo(replacedembly.Location);
var replacedemblyVersion = new Version(
replacedemblyInfo.FileMajorPart,
replacedemblyInfo.FileMinorPart,
replacedemblyInfo.FileBuildPart);
return replacedemblyVersion;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : Azure
License : MIT License
Project Creator : Azure
private static string GetCliVersion(string path)
{
string cliVersion = string.Empty;
Console.WriteLine($"Searching for core tools builds in {path}...");
foreach (string file in Directory.GetFiles(path, "*", SearchOption.AllDirectories))
{
if (file.EndsWith(".zip"))
{
var zip = ZipFile.OpenRead(file);
foreach (var entry in zip.Entries)
{
if (entry.Name == "func.dll")
{
ZipFileExtensions.ExtractToFile(entry, "func.dll", true);
cliVersion = FileVersionInfo.GetVersionInfo(".\\func.dll").FileVersion;
break;
}
}
}
}
return cliVersion;
}
19
View Source File : TraceMiddleware.cs
License : Apache License 2.0
Project Creator : Azure-App-Service
License : Apache License 2.0
Project Creator : Azure-App-Service
private static ITracer TraceStartup(HttpContext httpContext)
{
ITracer tracer = null;
// 0 means this is the very first request starting up Kudu
if (0 == Interlocked.Exchange(ref _traceStartup, 1))
{
tracer = TraceServices.CreateRequestTracer(httpContext);
if (tracer != null && tracer.TraceLevel > TraceLevel.Off)
{
var attribs = GetTraceAttributes(httpContext);
// force always trace
attribs[TraceExtensions.AlwaysTrace] = "1";
// Dump environment variables
foreach (DictionaryEntry entry in System.Environment.GetEnvironmentVariables())
{
var key = (string) entry.Key;
if (key.StartsWith("SCM", StringComparison.OrdinalIgnoreCase))
{
attribs[key] = (string) entry.Value;
}
}
tracer.Trace(XmlTracer.StartupRequestTrace, attribs);
}
OperationManager.SafeExecute(() =>
{
var requestId = (string) httpContext.Items[Constants.RequestIdHeader];
var replacedembly = replacedembly.GetExecutingreplacedembly();
var fvi = FileVersionInfo.GetVersionInfo(replacedembly.Location);
KuduEventGenerator.Log().GenericEvent(
ServerConfiguration.GetApplicationName(),
string.Format("StartupRequest pid:{0}, domain:{1}", Process.GetCurrentProcess().Id,
AppDomain.CurrentDomain.Id),
requestId,
System.Environment.GetEnvironmentVariable(SettingsKeys.ScmType),
System.Environment.GetEnvironmentVariable(SettingsKeys.WebSiteSku),
fvi.FileVersion);
});
}
return tracer;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : Azure-Samples
License : MIT License
Project Creator : Azure-Samples
public async static Task MainAsync(string[] args)
{
try
{
var shouldShowHelp = false;
// shutdown token sources
ShutdownTokenSource = new CancellationTokenSource();
// command line options
Mono.Options.OptionSet options = new Mono.Options.OptionSet {
{ "cf|configfile=", $"the filename containing action configuration.\nDefault: '{OpcActionConfigurationFilename}'", (string p) => OpcActionConfigurationFilename = p },
{ "tc|testconnectivity", $"tests connectivity with the default server '{TestConnectivity}'.\nDefault: {TestConnectivity}", b => TestConnectivity = b != null },
{ "tu|testunsecureconnectivity", $"tests connectivity with the default server '{TestUnsecureConnectivity}' using an unsecured endpoint.\nDefault: {TestUnsecureConnectivity}", b => TestUnsecureConnectivity = b != null },
{ "de|defaultendpointurl=", $"endpoint OPC UA server used as default.\nDefault: {DefaultEndpointUrl}", (string s) => DefaultEndpointUrl = s },
{ "sw|sessionconnectwait=", $"specify the wait time in seconds we try to connect to disconnected endpoints and starts monitoring unmonitored items\nMin: 10\nDefault: {SessionConnectWait}", (int i) => {
if (i > 10)
{
SessionConnectWait = i;
}
else
{
throw new OptionException("The sessionconnectwait must be greater than 10 sec", "sessionconnectwait");
}
}
},
{ "di|diagnosticsinterval=", $"shows diagnostic info at the specified interval in seconds (need log level info). 0 disables diagnostic output.\nDefault: {DiagnosticsInterval}", (uint u) => DiagnosticsInterval = u },
{ "lf|logfile=", $"the filename of the logfile to use.\nDefault: './{_logFileName}'", (string l) => _logFileName = l },
{ "lt|logflushtimespan=", $"the timespan in seconds when the logfile should be flushed.\nDefault: {_logFileFlushTimeSpanSec} sec", (int s) => {
if (s > 0)
{
_logFileFlushTimeSpanSec = TimeSpan.FromSeconds(s);
}
else
{
throw new Mono.Options.OptionException("The logflushtimespan must be a positive number.", "logflushtimespan");
}
}
},
{ "ll|loglevel=", $"the loglevel to use (allowed: fatal, error, warn, info, debug, verbose).\nDefault: info", (string l) => {
List<string> logLevels = new List<string> {"fatal", "error", "warn", "info", "debug", "verbose"};
if (logLevels.Contains(l.ToLowerInvariant()))
{
_logLevel = l.ToLowerInvariant();
}
else
{
throw new Mono.Options.OptionException("The loglevel must be one of: fatal, error, warn, info, debug, verbose", "loglevel");
}
}
},
// opc configuration options
{ "ol|opcmaxstringlen=", $"the max length of a string opc can transmit/receive.\nDefault: {OpcMaxStringLength}", (int i) => {
if (i > 0)
{
OpcMaxStringLength = i;
}
else
{
throw new OptionException("The max opc string length must be larger than 0.", "opcmaxstringlen");
}
}
},
{ "ot|operationtimeout=", $"the operation timeout of the OPC UA client in ms.\nDefault: {OpcOperationTimeout}", (int i) => {
if (i >= 0)
{
OpcOperationTimeout = i;
}
else
{
throw new OptionException("The operation timeout must be larger or equal 0.", "operationtimeout");
}
}
},
{ "ct|createsessiontimeout=", $"specify the timeout in seconds used when creating a session to an endpoint. On unsuccessful connection attemps a backoff up to {OpcSessionCreationBackoffMax} times the specified timeout value is used.\nMin: 1\nDefault: {OpcSessionCreationTimeout}", (uint u) => {
if (u > 1)
{
OpcSessionCreationTimeout = u;
}
else
{
throw new OptionException("The createsessiontimeout must be greater than 1 sec", "createsessiontimeout");
}
}
},
{ "ki|keepaliveinterval=", $"specify the interval in seconds se send keep alive messages to the OPC servers on the endpoints it is connected to.\nMin: 2\nDefault: {OpcKeepAliveInterval}", (int i) => {
if (i >= 2)
{
OpcKeepAliveInterval = i;
}
else
{
throw new OptionException("The keepaliveinterval must be greater or equal 2", "keepalivethreshold");
}
}
},
{ "kt|keepalivethreshold=", $"specify the number of keep alive packets a server can miss, before the session is disconneced\nMin: 1\nDefault: {OpcKeepAliveDisconnectThreshold}", (uint u) => {
if (u > 1)
{
OpcKeepAliveDisconnectThreshold = u;
}
else
{
throw new OptionException("The keepalivethreshold must be greater than 1", "keepalivethreshold");
}
}
},
{ "aa|autoaccept", $"trusts all servers we establish a connection to.\nDefault: {AutoAcceptCerts}", b => AutoAcceptCerts = b != null },
{ "to|trustowncert", $"our own certificate is put into the trusted certificate store automatically.\nDefault: {TrustMyself}", t => TrustMyself = t != null },
// cert store options
{ "at|appcertstoretype=", $"the own application cert store type. \n(allowed values: Directory, X509Store)\nDefault: '{OpcOwnCertStoreType}'", (string s) => {
if (s.Equals(CertificateStoreType.X509Store, StringComparison.OrdinalIgnoreCase) || s.Equals(CertificateStoreType.Directory, StringComparison.OrdinalIgnoreCase))
{
OpcOwnCertStoreType = s.Equals(CertificateStoreType.X509Store, StringComparison.OrdinalIgnoreCase) ? CertificateStoreType.X509Store : CertificateStoreType.Directory;
OpcOwnCertStorePath = s.Equals(CertificateStoreType.X509Store, StringComparison.OrdinalIgnoreCase) ? OpcOwnCertX509StorePathDefault : OpcOwnCertDirectoryStorePathDefault;
}
else
{
throw new OptionException();
}
}
},
{ "ap|appcertstorepath=", $"the path where the own application cert should be stored\nDefault (depends on store type):\n" +
$"X509Store: '{OpcOwnCertX509StorePathDefault}'\n" +
$"Directory: '{OpcOwnCertDirectoryStorePathDefault}'", (string s) => OpcOwnCertStorePath = s
},
{ "tp|trustedcertstorepath=", $"the path of the trusted cert store\nDefault '{OpcTrustedCertDirectoryStorePathDefault}'", (string s) => OpcTrustedCertStorePath = s
},
{ "rp|rejectedcertstorepath=", $"the path of the rejected cert store\nDefault '{OpcRejectedCertDirectoryStorePathDefault}'", (string s) => OpcRejectedCertStorePath = s
},
{ "ip|issuercertstorepath=", $"the path of the trusted issuer cert store\nDefault '{OpcIssuerCertDirectoryStorePathDefault}'", (string s) => OpcIssuerCertStorePath = s
},
{ "csr", $"show data to create a certificate signing request\nDefault '{ShowCreateSigningRequestInfo}'", c => ShowCreateSigningRequestInfo = c != null
},
{ "ab|applicationcertbase64=", $"update/set this applications certificate with the certificate preplaceded in as bas64 string", (string s) =>
{
NewCertificateBase64String = s;
}
},
{ "af|applicationcertfile=", $"update/set this applications certificate with the certificate file specified", (string s) =>
{
if (File.Exists(s))
{
NewCertificateFileName = s;
}
else
{
throw new OptionException($"The file '{s}' does not exist.", "applicationcertfile");
}
}
},
{ "pb|privatekeybase64=", $"initial provisioning of the application certificate (with a PEM or PFX fomat) requires a private key preplaceded in as base64 string", (string s) =>
{
PrivateKeyBase64String = s;
}
},
{ "pk|privatekeyfile=", $"initial provisioning of the application certificate (with a PEM or PFX fomat) requires a private key preplaceded in as file", (string s) =>
{
if (File.Exists(s))
{
PrivateKeyFileName = s;
}
else
{
throw new OptionException($"The file '{s}' does not exist.", "privatekeyfile");
}
}
},
{ "cp|certpreplacedword=", $"the optional preplacedword for the PEM or PFX or the installed application certificate", (string s) =>
{
CertificatePreplacedword = s;
}
},
{ "tb|addtrustedcertbase64=", $"adds the certificate to the applications trusted cert store preplaceded in as base64 string (multiple strings supported)", (string s) =>
{
TrustedCertificateBase64Strings = ParseListOfStrings(s);
}
},
{ "tf|addtrustedcertfile=", $"adds the certificate file(s) to the applications trusted cert store preplaceded in as base64 string (multiple filenames supported)", (string s) =>
{
TrustedCertificateFileNames = ParseListOfFileNames(s, "addtrustedcertfile");
}
},
{ "ib|addissuercertbase64=", $"adds the specified issuer certificate to the applications trusted issuer cert store preplaceded in as base64 string (multiple strings supported)", (string s) =>
{
IssuerCertificateBase64Strings = ParseListOfStrings(s);
}
},
{ "if|addissuercertfile=", $"adds the specified issuer certificate file(s) to the applications trusted issuer cert store (multiple filenames supported)", (string s) =>
{
IssuerCertificateFileNames = ParseListOfFileNames(s, "addissuercertfile");
}
},
{ "rb|updatecrlbase64=", $"update the CRL preplaceded in as base64 string to the corresponding cert store (trusted or trusted issuer)", (string s) =>
{
CrlBase64String = s;
}
},
{ "uc|updatecrlfile=", $"update the CRL preplaceded in as file to the corresponding cert store (trusted or trusted issuer)", (string s) =>
{
if (File.Exists(s))
{
CrlFileName = s;
}
else
{
throw new OptionException($"The file '{s}' does not exist.", "updatecrlfile");
}
}
},
{ "rc|removecert=", $"remove cert(s) with the given thumbprint(s) (multiple thumbprints supported)", (string s) =>
{
ThumbprintsToRemove = ParseListOfStrings(s);
}
},
// misc
{ "h|help", "show this message and exit", h => shouldShowHelp = h != null },
};
List<string> extraArgs = new List<string>();
try
{
// parse the command line
extraArgs = options.Parse(args);
}
catch (OptionException e)
{
// initialize logging
InitLogging();
// show message
Logger.Fatal(e, "Error in command line options");
Logger.Error($"Command line arguments: {String.Join(" ", args)}");
// show usage
Usage(options);
return;
}
// initialize logging
InitLogging();
// show usage if requested
if (shouldShowHelp)
{
Usage(options);
return;
}
// validate and parse extra arguments
if (extraArgs.Count > 0)
{
Logger.Error("Error in command line options");
Logger.Error($"Command line arguments: {String.Join(" ", args)}");
Usage(options);
return;
}
//show version
Logger.Information($"{ProgramName} V{FileVersionInfo.GetVersionInfo(replacedembly.GetExecutingreplacedembly().Location).FileVersion} starting up...");
Logger.Debug($"Informational version: V{(Attribute.GetCustomAttribute(replacedembly.GetEntryreplacedembly(), typeof(replacedemblyInformationalVersionAttribute)) as replacedemblyInformationalVersionAttribute).InformationalVersion}");
// allow canceling the application
var quitEvent = new ManualResetEvent(false);
try
{
Console.CancelKeyPress += (sender, eArgs) =>
{
quitEvent.Set();
eArgs.Cancel = true;
ShutdownTokenSource.Cancel();
};
}
catch
{
}
// init OPC configuration and tracing
OpcApplicationConfiguration applicationStackConfiguration = new OpcApplicationConfiguration();
await applicationStackConfiguration.ConfigureAsync();
// read OPC action configuration
OpcConfiguration.Init();
if (!await ReadOpcConfigurationAsync())
{
return;
}
// add well known actions
if (!await CreateOpcActionDataAsync())
{
return;
}
// kick off OPC client activities
await SessionStartAsync();
// initialize diagnostics
Diagnostics.Init();
// stop on user request
Logger.Information("");
Logger.Information("");
Logger.Information($"{ProgramName} is running. Press CTRL-C to quit.");
// wait for Ctrl-C
quitEvent.WaitOne(Timeout.Infinite);
Logger.Information("");
Logger.Information("");
ShutdownTokenSource.Cancel();
Logger.Information($"{ProgramName} is shutting down...");
// shutdown all OPC sessions
await SessionShutdownAsync();
// shutdown diagnostics
await ShutdownAsync();
ShutdownTokenSource = null;
}
catch (Exception e)
{
Logger.Fatal(e, e.StackTrace);
e = e.InnerException ?? null;
while (e != null)
{
Logger.Fatal(e, e.StackTrace);
e = e.InnerException ?? null;
}
Logger.Fatal($"{ProgramName} exiting... ");
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : Azure-Samples
License : MIT License
Project Creator : Azure-Samples
private static void Usage(Mono.Options.OptionSet options)
{
// show usage
Logger.Information("");
Logger.Information($"{ProgramName} V{FileVersionInfo.GetVersionInfo(replacedembly.GetExecutingreplacedembly().Location).FileVersion}");
Logger.Information($"Informational version: V{(Attribute.GetCustomAttribute(replacedembly.GetEntryreplacedembly(), typeof(replacedemblyInformationalVersionAttribute)) as replacedemblyInformationalVersionAttribute).InformationalVersion}");
Logger.Information("");
Logger.Information("Usage: {0}.exe [<options>]", replacedembly.GetEntryreplacedembly().GetName().Name);
Logger.Information("");
Logger.Information($"{ProgramName} to run actions against OPC UA servers.");
Logger.Information("To exit the application, just press CTRL-C while it is running.");
Logger.Information("");
Logger.Information("To specify a list of strings, please use the following format:");
Logger.Information("\"<string 1>,<string 2>,...,<string n>\"");
Logger.Information("or if one string contains commas:");
Logger.Information("\"\"<string 1>\",\"<string 2>\",...,\"<string n>\"\"");
Logger.Information("");
// output the options
Logger.Information("Options:");
StringBuilder stringBuilder = new StringBuilder();
StringWriter stringWriter = new StringWriter(stringBuilder);
options.WriteOptionDescriptions(stringWriter);
string[] helpLines = stringBuilder.ToString().Split("\n");
foreach (var line in helpLines)
{
Logger.Information(line);
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : Azure-Samples
License : MIT License
Project Creator : Azure-Samples
public static async Task MainAsync(string[] args, CancellationToken cancellationToken = default)
{
LoadPluginNodes();
Mono.Options.OptionSet options = CliOptions.InitCommandLineOptions();
// Parse the command line
List<string> extraArgs = options.Parse(args);
InitLogging();
// Show usage if requested
if (ShowHelp)
{
CliOptions.PrintUsage(options);
return;
}
// Validate and parse extra arguments
if (extraArgs.Count > 0)
{
Logger.Error($"Error with command line arguments: {string.Join(" ", args)}");
CliOptions.PrintUsage(options);
return;
}
LogLogo();
Logger.Information($"Current directory is: {Directory.GetCurrentDirectory()}");
Logger.Information($"Log file is: {Path.GetFullPath(LogFileName)}");
Logger.Information($"Log level is: {LogLevel}");
//show version
var fileVersion = FileVersionInfo.GetVersionInfo(replacedembly.GetExecutingreplacedembly().Location);
Logger.Information($"{ProgramName} V{fileVersion.ProductMajorPart}.{fileVersion.ProductMinorPart}.{fileVersion.ProductBuildPart} starting up...");
Logger.Debug($"Informational version: V{(Attribute.GetCustomAttribute(replacedembly.GetEntryreplacedembly(), typeof(replacedemblyInformationalVersionAttribute)) as replacedemblyInformationalVersionAttribute)?.InformationalVersion}");
using var host = CreateHostBuilder(args);
if (ShowPublisherConfigJsonIp || ShowPublisherConfigJsonPh)
{
StartWebServer(host);
}
try
{
await ConsoleServerAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.Fatal(ex, "OPC UA server failed unexpectedly.");
}
Logger.Information("OPC UA server exiting...");
}
19
View Source File : CliOptions.cs
License : MIT License
Project Creator : Azure-Samples
License : MIT License
Project Creator : Azure-Samples
public static void PrintUsage(Mono.Options.OptionSet options)
{
var sb = new StringBuilder();
sb.AppendLine();
sb.AppendLine($"{Program.ProgramName} V{FileVersionInfo.GetVersionInfo(replacedembly.GetExecutingreplacedembly().Location).FileVersion}");
sb.AppendLine($"Informational version: V{(Attribute.GetCustomAttribute(replacedembly.GetEntryreplacedembly(), typeof(replacedemblyInformationalVersionAttribute)) as replacedemblyInformationalVersionAttribute)?.InformationalVersion}");
sb.AppendLine();
sb.AppendLine($"Usage: dotnet {replacedembly.GetEntryreplacedembly().GetName().Name}.dll [<options>]");
sb.AppendLine();
sb.AppendLine("OPC UA PLC for different data simulation scenarios.");
sb.AppendLine("To exit the application, press CTRL-C while it's running.");
sb.AppendLine();
sb.AppendLine("Use the following format to specify a list of strings:");
sb.AppendLine("\"<string 1>,<string 2>,...,<string n>\"");
sb.AppendLine("or if one string contains commas:");
sb.AppendLine("\"\"<string 1>\",\"<string 2>\",...,\"<string n>\"\"");
sb.AppendLine();
// Append the options.
sb.AppendLine("Options:");
using var stringWriter = new StringWriter(sb);
options.WriteOptionDescriptions(stringWriter);
Program.Logger.Information(sb.ToString());
}
19
View Source File : BacktraceAttributes.cs
License : MIT License
Project Creator : backtrace-labs
License : MIT License
Project Creator : backtrace-labs
private void SetLibraryAttributes(BacktraceReport report)
{
var callingreplacedembly = report.Callingreplacedembly;
if (!string.IsNullOrEmpty(report.Fingerprint))
{
Attributes["_mod_fingerprint"] = report.Fingerprint;
}
if (!string.IsNullOrEmpty(report.Factor))
{
Attributes["_mod_factor"] = report.Factor;
}
//A unique identifier of a machine
Attributes["guid"] = GenerateMachineId().ToString();
//Base name of application generating the report
Attributes[APPLICATION_ATTRIBUTE_NAME] = callingreplacedembly.GetName().Name;
Attributes["location"] = callingreplacedembly.Location;
try
{
//in case when calling replacedembly from file system is not available
Attributes["version"] = FileVersionInfo.GetVersionInfo(callingreplacedembly.Location)?.FileVersion;
}
catch (FileNotFoundException) { }
var culture = callingreplacedembly.GetName().CultureInfo.Name;
if (!string.IsNullOrEmpty(culture))
{
Attributes["culture"] = callingreplacedembly.GetName().CultureInfo.Name;
}
#if !NET35
Attributes["dynamic"] = callingreplacedembly.IsDynamic;
Attributes["trusted"] = callingreplacedembly.IsFullyTrusted;
#endif
}
See More Examples