System.Version.ToString()

Here are the examples of the csharp api System.Version.ToString() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1015 Examples 7

19 Source : PostgresMigrations.cs
with MIT License
from centridsol

protected override void UpdateMigrationTables(byte[] snapshotData)
        {

            migrationScriptExecutor.AddSQLCommand($@"INSERT INTO {DalConsts.MIGRATION_TABLE_NAME}  (
                                                    runDate,
                                                    efcoreVersion,
                                                    metadata,
                                                    snapshot
                                                    ) 
                                                    VALUES
                                                    (NOW(),
                                                    '{typeof(DbContext).replacedembly.GetName().Version.ToString()}',
                                                    '{migrationMetadata.metadata}',
                                                     decode('{BitConverter.ToString(snapshotData).Replace("-", "")}', 'hex'));");

            
        }

19 Source : SQLiteMigrations.cs
with MIT License
from centridsol

protected override void UpdateMigrationTables(byte[] snapshotData)
        {
             migrationScriptExecutor.AddSQLCommand($@"INSERT INTO {DalConsts.MIGRATION_TABLE_NAME}  (
                                                    runDate,
                                                    efcoreVersion,
                                                    metadata,
                                                    snapshot
                                                    ) 
                                                    VALUES
                                                    (strftime('%Y-%m-%d %H:%M','now'),
                                                    '{typeof(DbContext).replacedembly.GetName().Version.ToString()}',
                                                    '{migrationMetadata.metadata}',
                                                    x'{BitConverter.ToString(snapshotData).Replace("-", "")}');");
        }

19 Source : VersionStringConverter.cs
with GNU General Public License v3.0
from chaincase-app

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if (value is Version version)
			{
				return version.ToString();
			}
			else
			{
				throw new TypeArgumentException(value, typeof(Version), nameof(value));
			}
		}

19 Source : UpdateProcess.cs
with Apache License 2.0
from chancezheng

public bool CheckAppVersion()
        {
            bool isNeedUpdate = false;
            string httpAddress = MedicalReportViewModel.GetBinPath() + "\\AutoUpdate\\updateinfo.xml";
            string currentVersion = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString();
            ThreadPool.QueueUserWorkItem(q =>
            {
                var client = new WebClient();
                client.DownloadDataCompleted += (obj, e) =>
                {
                    try
                    {
                        MemoryStream ms = new MemoryStream(e.Result);

                        UpdateInfo updateInfo = new UpdateInfo();
                        XDoreplacedent doreplacedent = XDoreplacedent.Load(ms);
                        XElement rootElement = doreplacedent.Element("UpdateInfo");
                        updateInfo.AppName = rootElement.Element("AppName").Value;
                        updateInfo.AppVersion = rootElement.Element("AppVersion") == null || string.IsNullOrEmpty(rootElement.Element("AppVersion").Value) ? null : new Version(rootElement.Element("AppVersion").Value);
                        updateInfo.RequiredMinVersion = rootElement.Element("RequiredMinVersion") == null || string.IsNullOrEmpty(rootElement.Element("RequiredMinVersion").Value) ? null : new Version(rootElement.Element("RequiredMinVersion").Value);
                        updateInfo.Description = rootElement.Element("Description").Value;
                        updateInfo.MD5 = Guid.NewGuid();

                        ms.Close();
                        isNeedUpdate = StartUpdate(updateInfo);
                        if (isNeedUpdate)
                        {
                            //启动更新程序
                            Process.Start(Directory.GetCurrentDirectory() + "\\AppUpdate\\netcoreapp3.1\\AutoUpdatedApp.exe");

                            foreach (var process in Process.GetProcessesByName(AppExeName))
                            {
                                process.Kill();
                            }

                            isNeedUpdate = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine(ex.Message);
                    }
                };
                client.DownloadDataAsync(new Uri(httpAddress, UriKind.Absolute));
            });

            return isNeedUpdate;
        }

19 Source : VRTK_Defines.cs
with MIT License
from charles-river-analytics

private static string ExactVersionSymbol(Version version)
        {
            return string.Format("{0}{1}", VersionScriptingDefineSymbolPrefix, version.ToString().Replace(".", "_"));
        }

19 Source : CommandLine.cs
with Apache License 2.0
from CheckPointSW

public void DoMigration(CommandLine commandLine)
        {
            if (!_successCommands)
                return;

            string fileName = Path.GetFileNameWithoutExtension(commandLine.ConfigFileName);
            //Console.WriteLine("File name: " + fileName);

            if (string.IsNullOrEmpty(commandLine.ConfigFileName) || string.IsNullOrEmpty(fileName))
            {
                if (FormatOutput == "text")
                    Console.WriteLine("Configuration file is not selected.", MessageTypes.Error);
                else
                {
                    JsonReport jsonReport = new JsonReport(
                        msg: "Configuration file is not selected.",
                        err: "err_cannot_convert_configuration_file");
                    Console.WriteLine(jsonReport.PrintJson());
                }
                return;
            }

            if (!File.Exists(commandLine.ConfigFileName))
            {
                if (FormatOutput == "text")
                    Console.WriteLine("Cannot find configuration file.", MessageTypes.Error);
                else
                {
                    JsonReport jsonReport = new JsonReport(
                        msg: "Cannot find configuration file.",
                        err: "err_cannot_convert_configuration_file");
                    Console.WriteLine(jsonReport.PrintJson());
                }
                return;
            }

            if (fileName.Length > 20)
            {
                if (FormatOutput == "text")
                    Console.WriteLine("Configuration file name is restricted to 20 characters at most.", MessageTypes.Error);
                else
                {
                    JsonReport jsonReport = new JsonReport(
                        msg: "Configuration file name is restricted to 20 characters at most.",
                        err: "err_cannot_convert_configuration_file");
                    Console.WriteLine(jsonReport.PrintJson());
                }
                return;
            }

            if (!Directory.Exists(commandLine.TargetFolder))
            {
                if (FormatOutput == "text")
                    Console.WriteLine("Cannot find target folder for conversion output.", MessageTypes.Error);
                else
                {
                    JsonReport jsonReport = new JsonReport(
                        msg: "Cannot find target folder for conversion output.",
                        err: "err_cannot_convert_configuration_file");
                    Console.WriteLine(jsonReport.PrintJson());
                }
                return;
            }

            VendorParser vendorParser;

            switch (commandLine.Vendor)
            {
                case "CiscoASA":
                    CiscoParser.SpreadAclRemarks = _isCiscoSpreadAclRemarks;
                    vendorParser = new CiscoParser();
                    break;
                case "FirePower":
                    vendorParser = new CiscoParser()
                    {
                        isUsingForFirePower = true
                    };
                    break;
                case "JuniperSRX":
                    vendorParser = new JuniperParser();
                    break;
                case "JuniperSSG":
                    vendorParser = new ScreenOSParser();
                    break;
                case "FortiNet":
                    vendorParser = new FortiGateParser();
                    break;
                case "PaloAlto":
                    vendorParser = new PaloAltoParser();
                    break;
                case "Panorama":
                    vendorParser = new PanoramaParser();
                    break;
                default:
                    throw new InvalidDataException("Unexpected!!!");
            }

            try
            {
                string ciscoFile = commandLine.ConfigFileName;
                Console.Write("Parsing configuration file...");

                if (commandLine.Vendor.Equals("Panorama"))
                {
                    
                    PanoramaParser panParser = (PanoramaParser)vendorParser;
                    panParser.ParseWithTargetFolder(ciscoFile, Path.GetFullPath(TargetFolder));
                }
                else
                {
                    vendorParser.Parse(ciscoFile);
                }

                Console.WriteLine("Done.");

            }
            catch (Exception ex)
            {
                if (FormatOutput == "text")
                {
                    Console.WriteLine("\nCould not parse configuration file.", MessageTypes.Error);
                    return;
                }
                else
                {
                    JsonReport jsonReport = new JsonReport(
                        msg: "Could not parse configuration file.",
                        err: "err_cannot_parse_configuration_file");
                    Console.WriteLine("\n" + jsonReport.PrintJson());
                    return;
                }
            }

            #region check middleware version
            switch (commandLine.Vendor)
            {
                case "CiscoASA":
                    if (string.IsNullOrEmpty(vendorParser.Version))
                    {
                        if (FormatOutput == "text")
                            Console.WriteLine("Unspecified ASA version.\nCannot find ASA version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        else
                        {
                            JsonReport jsonReport = new JsonReport(
                                msg: "Unspecified ASA version. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file");
                            Console.WriteLine(jsonReport.PrintJson());
                        }
                        return;
                    }
                    else if (vendorParser.MajorVersion < 8 || (vendorParser.MajorVersion == 8 && vendorParser.MinorVersion < 3))
                    {
                        if (FormatOutput == "text")
                            Console.WriteLine("Unsupported ASA version (" + vendorParser.Version + "). This tool supports ASA 8.3 and above configuration files. The configuration may not parse correctly.", MessageTypes.Warning);
                        else
                        {
                            JsonReport jsonReport = new JsonReport(
                                msg: "Unsupported ASA version (" + vendorParser.Version + "). This tool supports ASA 8.3 and above configuration files. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file");
                            Console.WriteLine(jsonReport.PrintJson());
                        }
                        return;
                    }
                    break;

                case "JuniperSRX":
                    if (string.IsNullOrEmpty(vendorParser.Version))
                    {
                        if (FormatOutput == "text")
                            Console.WriteLine("Unspecified SRX version.\nCannot find SRX version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        else
                        {
                            JsonReport jsonReport = new JsonReport(
                                msg: "Unspecified SRX version. Cannot find SRX version for the selected configuration. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file");
                            Console.WriteLine(jsonReport.PrintJson());
                        }
                        return;
                    }
                    else if (vendorParser.MajorVersion < 12 || (vendorParser.MajorVersion == 12 && vendorParser.MinorVersion < 1))
                    {
                        if (FormatOutput == "text")
                            Console.WriteLine("Unsupported SRX version (" + vendorParser.Version + ").\nThis tool supports SRX 12.1 and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        else
                        {
                            JsonReport jsonReport = new JsonReport(
                                msg: "Unsupported SRX version (" + vendorParser.Version + "). This tool supports SRX 12.1 and above configuration files. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file");
                            Console.WriteLine(jsonReport.PrintJson());
                        }
                        return;
                    }
                    break;

                case "JuniperSSG":
                    break;
                
                case "FirePower":
                    if (string.IsNullOrEmpty(vendorParser.Version))
                    {
                        if (FormatOutput == "text")
                            Console.WriteLine("Unspecified NGFW version.\nCannot find version for the selected configuration.\nThe configuration may not parse correctly.");
                        else
                        {
                            JsonReport jsonReport = new JsonReport(
                                msg: "Unspecified NGFW version.\nCannot find version for the selected configuration.\nThe configuration may not parse correctly.", err: "err_unsupported_version_configuration_file");
                            Console.WriteLine(jsonReport.PrintJson());
                        }
                        return;
                    }
                    else if (vendorParser.MajorVersion < 6 || (vendorParser.MajorVersion == 6 && vendorParser.MinorVersion < 4))
                    {
                        if (FormatOutput == "text")
                            Console.WriteLine("Unsupported version (" + vendorParser.Version + ").\nThis tool supports NGFW 6.4 and above configuration files.\nThe configuration may not parse correctly.");
                        else
                        {
                            JsonReport jsonReport = new JsonReport(
                                msg: "Unsupported version(" + vendorParser.Version + ").\nThis tool supports NGFW 6.4 and above configuration files.\nThe configuration may not parse correctly.", err: "err_unsupported_version_configuration_file");
                            Console.WriteLine(jsonReport.PrintJson());
                        }
                        return;
                    }
                    break;

                case "FortiNet":
                    if (string.IsNullOrEmpty(vendorParser.Version))
                    {
                        if (FormatOutput == "text")
                            Console.WriteLine("Unspecified FortiGate version.\nCannot find FortiGate version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        else
                        {
                            JsonReport jsonReport = new JsonReport(
                                msg: "Unspecified FortiGate version. Cannot find FortiGate version for the selected configuration. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file");
                            Console.WriteLine(jsonReport.PrintJson());
                        }
                        return;
                    }
                    else if (vendorParser.MajorVersion < 5)
                    {
                        if (FormatOutput == "text")
                            Console.WriteLine("Unsupported FortiGate version (" + vendorParser.Version + ").\nThis tool supports FortiGate 5.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        else
                        {
                            JsonReport jsonReport = new JsonReport(
                                msg: "Unsupported FortiGate version (" + vendorParser.Version + "). This tool supports FortiGate 5.x and above configuration files. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file");
                            Console.WriteLine(jsonReport.PrintJson());
                        }
                        return;
                    }
                    break;
                case "PaloAlto":
                    if (string.IsNullOrEmpty(vendorParser.Version))
                    {
                        if (FormatOutput == "text")
                            Console.WriteLine("Unspecified PaloAlto version.\nCannot find PaloAlto PAN-OS version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        else
                        {
                            JsonReport jsonReport = new JsonReport(
                                msg: "Unspecified PaloAlto version. Cannot find PaloAlto PAN-OS version for the selected configuration. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file");
                            Console.WriteLine(jsonReport.PrintJson());
                        }
                        return;
                    }
                    else if (vendorParser.MajorVersion < 7)
                    {
                        if (FormatOutput == "text")
                            Console.WriteLine("Unsupported PaloAlto version (" + vendorParser.Version + ").\nThis tool supports PaloAlto PAN-OS 7.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        else
                        {
                            JsonReport jsonReport = new JsonReport(
                                msg: "Unsupported PaloAlto version (" + vendorParser.Version + "). This tool supports PaloAlto PAN-OS 7.x and above configuration files. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file");
                            Console.WriteLine(jsonReport.PrintJson());
                        }
                        return;
                    }
                    break;
                case "Panorama":
                    if (string.IsNullOrEmpty(vendorParser.Version))
                    {
                        if (FormatOutput == "text")
                            Console.WriteLine("Unspecified PaloAlto Panorama version.\nCannot find PaloAlto Panorama version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        else
                        {
                            JsonReport jsonReport = new JsonReport(
                                msg: "Unspecified PaloAlto Panorama version. Cannot find PaloAlto Panorama version for the selected configuration. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file");
                            Console.WriteLine(jsonReport.PrintJson());
                        }
                        return;
                    }
                    else if (vendorParser.MajorVersion < 7)
                    {
                        if (FormatOutput == "text")
                            Console.WriteLine("Unsupported PaloAlto version (" + vendorParser.Version + ").\nThis tool supports PaloAlto Panorama 7.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        else
                        {
                            JsonReport jsonReport = new JsonReport(
                                msg: "Unsupported PaloAlto version (" + vendorParser.Version + "). This tool supports PaloAlto Panorama 7.x and above configuration files. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file");
                            Console.WriteLine(jsonReport.PrintJson());
                        }
                        return;
                    }
                    break;
            }
            #endregion                       

            string vendorFileName = Path.GetFileNameWithoutExtension(commandLine.ConfigFileName);

            string toolVersion = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString();

            string targetFolder = commandLine.TargetFolder + "\\";

            bool convertNat = commandLine.ConvertNat;

            string ldapAccountUnit = commandLine.LdapAccountUnit;

            vendorParser.Export(targetFolder + vendorFileName + ".json");

            VendorConverter vendorConverter;

            switch (commandLine.Vendor)
            {
                case "CiscoASA":
                    CiscoConverter converter = new CiscoConverter();
                    converter.SkipUnusedObjects = commandLine.DontImportUnusedObjects;
                    vendorConverter = converter;
                    break;
                case "FirePower":
                    vendorConverter = new CiscoConverter()
                    {
                        isUsingForFirePower = true
                    };
                    break;
                case "JuniperSRX":
                    vendorConverter = new JuniperConverter();
                    break;
                case "JuniperSSG":
                    vendorConverter = new ScreenOSConverter();
                    break;
                case "FortiNet":
                    FortiGateConverter fgConverter = new FortiGateConverter();
                    fgConverter.OptimizeConf = commandLine.DontImportUnusedObjects;
                    fgConverter.ConvertUserConf = commandLine.ConvertUserConfiguration;
                    fgConverter.LDAPAccoutUnit = ldapAccountUnit;
                    vendorConverter = fgConverter;
                    break;
                case "PaloAlto":
                    PaloAltoConverter paConverter = new PaloAltoConverter();
                    paConverter.OptimizeConf = commandLine.DontImportUnusedObjects;
                    paConverter.ConvertUserConf = commandLine.ConvertUserConfiguration;
                    paConverter.LDAPAccoutUnit = ldapAccountUnit;
                    vendorConverter = paConverter;
                    break;
                case "Panorama":
                    PanoramaConverter panoramaConverter = new PanoramaConverter();
                    panoramaConverter.OptimizeConf = commandLine.DontImportUnusedObjects;
                    panoramaConverter.ConvertUserConf = commandLine.ConvertUserConfiguration;
                    panoramaConverter.LDAPAccoutUnit = ldapAccountUnit;
                    vendorConverter = panoramaConverter;
                    break;
                default:
                    throw new InvalidDataException("Unexpected!!!");
            }

            vendorConverter.Initialize(vendorParser, commandLine.ConfigFileName, toolVersion, targetFolder, commandLine.Domain, commandLine.formatOutput);
            //if we are in interactive mode
            vendorConverter.IsConsoleRunning = true && _isInteractive;

            try
            {
                Console.WriteLine("Conversion started...");
                Dictionary<string, int> results = vendorConverter.Convert(convertNat);

                if (formatOutput.Equals("text"))
                {
                    Console.WriteLine("Conversion finished.");
                    if (results.ContainsKey("errors"))
                        Console.WriteLine("Errors: {0}", results["errors"]);
                    if (results.ContainsKey("warnings"))
                        Console.WriteLine("Warnings: {0}", results["warnings"]);
                }
                else
                {
                    TotalJsonReport jsonReport = new TotalJsonReport(
                        msg: "Conversion finished",
                        errs: results.ContainsKey("errors") ? results["errors"].ToString() : null,
                        warnings: results.ContainsKey("warnings") ? results["warnings"].ToString() : null);
                    Console.WriteLine(jsonReport.PrintJson());
                }

            }
            catch (Exception ex)
            {

                if (ex is InvalidDataException && ex.Message != null && ex.Message.Contains("Policy exceeds the maximum number"))
                {
                    if (FormatOutput == "text")
                    {
                        Console.WriteLine(String.Format("{1}{0}{2}{0}{3}", Environment.NewLine, "SmartMove is unable to convert the provided policy.",
                                                          "Reason: Policy exceeds the maximum number of supported policy layers.",
                                                          "To replacedure the smooth conversion of your data, it is recommended to contact Check Point Professional Services by sending an e-mail to [email protected]"));
                    }
                    else
                    {
                        JsonReport jsonReport = new JsonReport(
                            msg: "SmartMove is unable to convert the provided policy. Reason: Policy exceeds the maximum number of supported policy layers.",
                            err: "generic_error");
                        Console.WriteLine(jsonReport.PrintJson());
                    }
                }
                else
                {
                    if (FormatOutput == "text")
                        Console.WriteLine("Could not convert configuration file.", MessageTypes.Error);
                    else
                    {
                        JsonReport jsonReport = new JsonReport(
                            msg: "Could not convert configuration file.",
                            err: "err_cannot_convert_configuration_file");
                        Console.WriteLine(jsonReport.PrintJson());
                    }
                }
                return;
            }
            finally
            {
                if (vendorConverter.Progress != null)
                    vendorConverter.Progress.Dispose();
            }

            vendorConverter.ExportConfigurationAsHtml();
            vendorConverter.ExportPolicyPackagesAsHtml();
            if (commandLine.ConvertNat)
            {
                vendorConverter.ExportNatLayerAsHtml();
            }
        }

19 Source : MainWindow.xaml.cs
with Apache License 2.0
from CheckPointSW

private async void Go_OnClick(object sender, RoutedEventArgs e)
        {
            string fileName = Path.GetFileNameWithoutExtension(ConfigFilePath.Text);

            if (string.IsNullOrEmpty(ConfigFilePath.Text) || string.IsNullOrEmpty(fileName))
            {
                ShowMessage("Configuration file is not selected.", MessageTypes.Error);
                return;
            }

            if (!File.Exists(ConfigFilePath.Text))
            {
                ShowMessage("Cannot find configuration file.", MessageTypes.Error);
                return;
            }

            if (fileName.Length > 20)
            {
                ShowMessage("Configuration file name is restricted to 20 characters at most.", MessageTypes.Error);
                return;
            }

            if (!Directory.Exists(TargetFolderPath.Text))
            {
                ShowMessage("Cannot find target folder for conversion output.", MessageTypes.Error);
                return;
            }

            if (ConvertUserConfiguration)
            {
                if (LDAPAccountUnit.Text.Trim().Equals("") || LDAPAccountUnit.Text.Trim().Contains(" "))
                {
                    ShowMessage("LDAP Account Unit field cannot be empty or containt space(s).", MessageTypes.Error);
                    return;
                }
            }

            VendorParser vendorParser;

            switch (_supportedVendors.SelectedVendor)
            {
                case Vendor.CiscoASA:
                    vendorParser = new CiscoParser();
                    break;
                case Vendor.FirePower:
                    vendorParser = new CiscoParser() { 
                        isUsingForFirePower = true 
                    };
                    break;
                case Vendor.JuniperJunosOS:
                    vendorParser = new JuniperParser();
                    break;
                case Vendor.JuniperScreenOS:
                    vendorParser = new ScreenOSParser();
                    break;
                case Vendor.FortiGate:
                    vendorParser = new FortiGateParser();
                    break;
                case Vendor.PaloAlto:
                    vendorParser = new PaloAltoParser();
                    break;
                case Vendor.PaloAltoPanorama:
                    string compressorsDirPath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "compressors";
                    string compressorZip = Path.Combine(compressorsDirPath, "zip.exe");
                    string compressorGtar = Path.Combine(compressorsDirPath, "gtar.exe");
                    string compressorGzip = Path.Combine(compressorsDirPath, "gzip.exe");
                    if (!File.Exists(compressorZip) || !File.Exists(compressorGtar) || !File.Exists(compressorGzip))
                    {
                        ShowMessage(String.Format("{1}{0}{2}", Environment.NewLine, "The system cannot find the required files. ",
                        "Please follow"), MessageTypes.Error, "these instructions", "https://github.com/CheckPointSW/SmartMove#smart-connector-and-paloalto-panorama-instructions");
                        return;
                    }
                    vendorParser = new PanoramaParser();
                    break;
                default:
                    throw new InvalidDataException("Unexpected!!!");
            }
			
            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            EnableDisableControls(false);
            ProgressPanel.Visibility = Visibility.Visible;
            ResultsPanel.Visibility = Visibility.Collapsed;
            OutputPanel.Visibility = Visibility.Visible;

            UpdateProgress(10, "Parsing configuration file ...");
			
            string vendorFileName = Path.GetFileNameWithoutExtension(ConfigFilePath.Text);
            string toolVersion = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString();
            string targetFolder = TargetFolderPath.Text + "\\";
            bool convertNat = ConvertNATConfiguration;
            string ldapAccountUnit = LDAPAccountUnit.Text.Trim();

            try
            {
                string ciscoFile = ConfigFilePath.Text;
		        switch (_supportedVendors.SelectedVendor)
                {
                    case Vendor.PaloAltoPanorama:
                        PanoramaParser panParser = (PanoramaParser)vendorParser;                        
                        await Task.Run(() => panParser.ParseWithTargetFolder(ciscoFile,targetFolder));
                        break;
                    default:
                        await Task.Run(() => vendorParser.Parse(ciscoFile));
                        break;
                }

            }
            catch (Exception ex)
            {
                Mouse.OverrideCursor = null;
                EnableDisableControls(true);
                OutputPanel.Visibility = Visibility.Collapsed;
                ShowMessage(string.Format("Could not parse configuration file.\n\nMessage: {0}\nModule:\t{1}\nClreplaced:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error);
                return;
            }

            switch (_supportedVendors.SelectedVendor)
            {
                case Vendor.CiscoASA:
                    if (string.IsNullOrEmpty(vendorParser.Version))
                    {
                        ShowMessage("Unspecified ASA version.\nCannot find ASA version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    else if (vendorParser.MajorVersion < 8 || (vendorParser.MajorVersion == 8 && vendorParser.MinorVersion < 3))
                    {
                        ShowMessage("Unsupported ASA version (" + vendorParser.Version + ").\nThis tool supports ASA 8.3 and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    break;

                case Vendor.FirePower:
                    if (string.IsNullOrEmpty(vendorParser.Version))
                    {
                        ShowMessage("Unspecified NGFW version.\nCannot find version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    else if (vendorParser.MajorVersion < 6 || (vendorParser.MajorVersion == 6 && vendorParser.MinorVersion < 4))
                    {
                        ShowMessage("Unsupported version (" + vendorParser.Version + ").\nThis tool supports NGFW 6.4 and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    break;

                case Vendor.JuniperJunosOS:
                    if (string.IsNullOrEmpty(vendorParser.Version))
                    {
                        ShowMessage("Unspecified SRX version.\nCannot find SRX version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    else if (vendorParser.MajorVersion < 12 || (vendorParser.MajorVersion == 12 && vendorParser.MinorVersion < 1))
                    {
                        ShowMessage("Unsupported SRX version (" + vendorParser.Version + ").\nThis tool supports SRX 12.1 and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    break;

                case Vendor.JuniperScreenOS:
                    break;

                case Vendor.FortiGate:
                    if (string.IsNullOrEmpty(vendorParser.Version))
                    {
                        ShowMessage("Unspecified FortiGate version.\nCannot find FortiGate version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    else if(vendorParser.MajorVersion < 5)
                    {
                        ShowMessage("Unsupported FortiGate version (" + vendorParser.Version + ").\nThis tool supports FortiGate 5.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    break;
                case Vendor.PaloAlto:
                    if (string.IsNullOrEmpty(vendorParser.Version))
                    {
                        ShowMessage("Unspecified PaloAlto version.\nCannot find PaloAlto PAN-OS version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    else if (vendorParser.MajorVersion < 7)
                    {
                        ShowMessage("Unsupported PaloAlto version (" + vendorParser.Version + ").\nThis tool supports PaloAlto PAN-OS 7.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    break;
                case Vendor.PaloAltoPanorama:
                    if (string.IsNullOrEmpty(vendorParser.Version))
                    {
                        ShowMessage("Unspecified PaloAlto version.\nCannot find PaloAlto Panorama version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    else if (vendorParser.MajorVersion < 7)
                    {
                        ShowMessage("Unsupported PaloAlto version (" + vendorParser.Version + ").\nThis tool supports PaloAlto Panorama 7.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    break;
            }

            vendorParser.Export(targetFolder + vendorFileName + ".json");

            VendorConverter vendorConverter;

            switch (_supportedVendors.SelectedVendor)
            {
                case Vendor.CiscoASA:
                    CiscoConverter ciscoConverter = new CiscoConverter();
                    ciscoConverter.SkipUnusedObjects = SkipUnusedObjectsConversion;
                    vendorConverter = ciscoConverter;
                    break;
                case Vendor.FirePower:
                    vendorConverter = new CiscoConverter() {
                        isUsingForFirePower = true
                    };
                    break;
                case Vendor.JuniperJunosOS:
                    vendorConverter = new JuniperConverter();
                    break;
                case Vendor.JuniperScreenOS:
                    vendorConverter = new ScreenOSConverter();
                    break;
                case Vendor.FortiGate:
                    FortiGateConverter fgConverter = new FortiGateConverter();
                    fgConverter.OptimizeConf = SkipUnusedObjectsConversion;
                    fgConverter.ConvertUserConf = ConvertUserConfiguration;
                    fgConverter.LDAPAccoutUnit = ldapAccountUnit.Trim();
                    fgConverter.CreateManagnetReport = ExportManagmentReport;
                    vendorConverter = fgConverter;
                    break;
                case Vendor.PaloAlto:
                    PaloAltoConverter paConverter = new PaloAltoConverter();
                    paConverter.OptimizeConf = SkipUnusedObjectsConversion;
                    paConverter.ConvertUserConf = ConvertUserConfiguration;
                    paConverter.LDAPAccoutUnit = ldapAccountUnit.Trim();
                    vendorConverter = paConverter;
                    break;
                case Vendor.PaloAltoPanorama:
                    PanoramaConverter panoramaConverter = new PanoramaConverter();                    
                    panoramaConverter.OptimizeConf = SkipUnusedObjectsConversion;
                    panoramaConverter.ConvertUserConf = ConvertUserConfiguration;
                    panoramaConverter.LDAPAccoutUnit = ldapAccountUnit.Trim();
                    panoramaConverter.CreateManagnetReport = ExportManagmentReport;
                    vendorConverter = panoramaConverter;
                    break;
                default:
                    throw new InvalidDataException("Unexpected!!!");
            }

            //here outputformat was set to 'json' by default manually because there is no an option for it on GUI
            vendorConverter.Initialize(vendorParser, ConfigFilePath.Text, toolVersion, targetFolder, DomainName.Text, "json");
            vendorConverter.ConversionProgress += OnConversionProgress;

            try
            {
                await Task.Run(() => vendorConverter.Convert(convertNat));
            }
            catch (Exception ex)
            {
                Mouse.OverrideCursor = null;
                EnableDisableControls(true);
                OutputPanel.Visibility = Visibility.Collapsed;
                if (ex is InvalidDataException && ex.Message != null && ex.Message.Contains("Policy exceeds the maximum number"))
                {
                    ShowMessage(String.Format("{1}{0}{2}{0}{3}", Environment.NewLine, "SmartMove is unable to convert the provided policy.",
                                                "Reason: Policy exceeds the maximum number of supported policy layers.",
                                                "To replacedure the smooth conversion of your data, it is recommended to contact Check Point Professional Services by sending an e-mail to"),
                    MessageTypes.Error, "[email protected]", "mailto:[email protected]");
                }
                else
                {
                    ShowMessage(string.Format("Could not convert configuration file.\n\nMessage: {0}\nModule:\t{1}\nClreplaced:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error);
                }
                return;
            }

            UpdateProgress(90, "Exporting Check Point configuration ...");
            vendorConverter.ExportConfigurationAsHtml();
            vendorConverter.ExportPolicyPackagesAsHtml();
            if (ConvertNATConfiguration)
            {
		        ConvertedNatPolicyLink.MouseUp -= Link_OnClick;
                vendorConverter.ExportNatLayerAsHtml();

                //check if the user asked for NAT policy and no rules found.
                if (vendorConverter.RulesInNatLayer() == 0 ) // anly if 0 then we do not show NAT report.
                {
                    ConvertedNatPolicyLink.Style = (Style)ConvertedNatPolicyLink.FindResource("NormalTextBloclStyle");
                }
                else // otherwise it is single NAT report or Catalog for NAT reports (value = -1)
                {
                    ConvertedNatPolicyLink.Style = (Style)ConvertedNatPolicyLink.FindResource("HyperLinkStyle");
                    ConvertedNatPolicyLink.MouseUp += Link_OnClick;
                }
            }
            if (ExportManagmentReport && (typeof(PanoramaConverter) != vendorConverter.GetType() && typeof(FortiGateConverter) != vendorConverter.GetType()))
            {
                vendorConverter.ExportManagmentReport();
            }
            UpdateProgress(100, "");

            vendorConverter.ConversionProgress -= OnConversionProgress;

            Mouse.OverrideCursor = null;
            EnableDisableControls(true);
            ProgressPanel.Visibility = Visibility.Collapsed;
            ResultsPanel.Visibility = Visibility.Visible;

            ShowResults(vendorConverter, vendorParser.ParsedLines);
        }

19 Source : MenuWindow.xaml.cs
with Apache License 2.0
from CheckPointSW

private void ShowDisclaimer()
        {
            // Display the disclaimer doreplacedent only once per tool version.
            string version = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString();
            if (!File.Exists(version))
            {
                var disclaimerWindow = new DisclaimerWindow();
                var res = disclaimerWindow.ShowDialog();

                if (res.HasValue && res.Value)
                {
                    // Create a flag file.
                    var fsFlag = new FileStream(version, FileMode.CreateNew, FileAccess.Write);
                    fsFlag.Close();
                }
                else
                {
                    Close();
                }
            }
        }

19 Source : AnalyzeWindow.xaml.cs
with Apache License 2.0
from CheckPointSW

private async void replacedyze_OnClickAsync(object sender, RoutedEventArgs e)
        {
            string fileName = Path.GetFileNameWithoutExtension(ConfigFilePath.Text);

            if (string.IsNullOrEmpty(ConfigFilePath.Text) || string.IsNullOrEmpty(fileName))
            {
                ShowMessage("Configuration file is not selected.", MessageTypes.Error);
                return;
            }

            if (!File.Exists(ConfigFilePath.Text))
            {
                ShowMessage("Cannot find configuration file.", MessageTypes.Error);
                return;
            }

            if (fileName.Length > 20)
            {
                ShowMessage("Configuration file name is restricted to 20 characters at most.", MessageTypes.Error);
                return;
            }

            if (!Directory.Exists(TargetFolderPath.Text))
            {
                ShowMessage("Cannot find target folder for conversion output.", MessageTypes.Error);
                return;
            }

            VendorParser vendorParser;

            switch (_supportedVendors.SelectedVendor)
            {
                case Vendor.CiscoASA:
                    vendorParser = new CiscoParser();
                    break;
                case Vendor.JuniperJunosOS:
                    vendorParser = new JuniperParser();
                    break;
                case Vendor.JuniperScreenOS:
                    vendorParser = new ScreenOSParser();
                    break;
                case Vendor.FortiGate:
                    vendorParser = new FortiGateParser();
                    break;
                case Vendor.PaloAlto:
                    vendorParser = new PaloAltoParser();
                    break;
                case Vendor.PaloAltoPanorama:
                    string compressorsDirPath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "compressors";
                    string compressorZip = Path.Combine(compressorsDirPath, "zip.exe");
                    string compressorGtar = Path.Combine(compressorsDirPath, "gtar.exe");
                    string compressorGzip = Path.Combine(compressorsDirPath, "gzip.exe");
                    if (!File.Exists(compressorZip) || !File.Exists(compressorGtar) || !File.Exists(compressorGzip))
                    {
                        ShowMessage(String.Format("{1}{0}{2}", Environment.NewLine, "The system cannot find the required files. ",
                        "Please follow"), MessageTypes.Error, "these instructions", "https://github.com/CheckPointSW/SmartMove#smart-connector-and-paloalto-panorama-instructions");
                        return;
                    }
                    vendorParser = new PanoramaParser();
                    break;
                default:
                    throw new InvalidDataException("Unexpected!!!");
            }

            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            EnableDisableControls(false);
            ProgressPanel.Visibility = Visibility.Visible;
            ResultsPanel.Visibility = Visibility.Collapsed;
            OutputPanel.Visibility = Visibility.Visible;

            UpdateProgress(10, "Parsing configuration file ...");

            string vendorFileName = Path.GetFileNameWithoutExtension(ConfigFilePath.Text);
            string toolVersion = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString();
            string targetFolder = TargetFolderPath.Text + "\\";

            try
            {
                string ciscoFile = ConfigFilePath.Text;
                switch (_supportedVendors.SelectedVendor)
                {
                    case Vendor.PaloAltoPanorama:
                        PanoramaParser panParser = (PanoramaParser)vendorParser;
                        await Task.Run(() => panParser.ParseWithTargetFolder(ciscoFile, targetFolder));
                        break;
                    default:
                        await Task.Run(() => vendorParser.Parse(ciscoFile));
                        break;
                }

            }
            catch (Exception ex)
            {
                Mouse.OverrideCursor = null;
                EnableDisableControls(true);
                OutputPanel.Visibility = Visibility.Collapsed;
                ShowMessage(string.Format("Could not parse configuration file.\n\nMessage: {0}\nModule:\t{1}\nClreplaced:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error);
                return;
            }

            switch (_supportedVendors.SelectedVendor)
            {
                case Vendor.CiscoASA:
                    if (string.IsNullOrEmpty(vendorParser.Version))
                    {
                        ShowMessage("Unspecified ASA version.\nCannot find ASA version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    else if (vendorParser.MajorVersion < 8 || (vendorParser.MajorVersion == 8 && vendorParser.MinorVersion < 3))
                    {
                        ShowMessage("Unsupported ASA version (" + vendorParser.Version + ").\nThis tool supports ASA 8.3 and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    break;

                case Vendor.JuniperJunosOS:
                    if (string.IsNullOrEmpty(vendorParser.Version))
                    {
                        ShowMessage("Unspecified SRX version.\nCannot find SRX version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    else if (vendorParser.MajorVersion < 12 || (vendorParser.MajorVersion == 12 && vendorParser.MinorVersion < 1))
                    {
                        ShowMessage("Unsupported SRX version (" + vendorParser.Version + ").\nThis tool supports SRX 12.1 and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    break;

                case Vendor.JuniperScreenOS:
                    break;

                case Vendor.FortiGate:
                    if (string.IsNullOrEmpty(vendorParser.Version))
                    {
                        ShowMessage("Unspecified FortiGate version.\nCannot find FortiGate version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    else if (vendorParser.MajorVersion < 5)
                    {
                        ShowMessage("Unsupported FortiGate version (" + vendorParser.Version + ").\nThis tool supports FortiGate 5.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    break;
                case Vendor.PaloAlto:
                    if (string.IsNullOrEmpty(vendorParser.Version))
                    {
                        ShowMessage("Unspecified PaloAlto version.\nCannot find PaloAlto PAN-OS version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    else if (vendorParser.MajorVersion < 7)
                    {
                        ShowMessage("Unsupported PaloAlto version (" + vendorParser.Version + ").\nThis tool supports PaloAlto PAN-OS 7.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    break;
                case Vendor.PaloAltoPanorama:
                    if (string.IsNullOrEmpty(vendorParser.Version))
                    {
                        ShowMessage("Unspecified PaloAlto version.\nCannot find PaloAlto Panorama version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    else if (vendorParser.MajorVersion < 7)
                    {
                        ShowMessage("Unsupported PaloAlto version (" + vendorParser.Version + ").\nThis tool supports PaloAlto Panorama 7.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning);
                        return;
                    }
                    break;
            }

            vendorParser.Export(targetFolder + vendorFileName + ".json");

            VendorConverter vendorConverter;

            switch (_supportedVendors.SelectedVendor)
            {
                case Vendor.CiscoASA:
                    vendorConverter = new CiscoConverter();
                    break;
                case Vendor.JuniperJunosOS:
                    vendorConverter = new JuniperConverter();
                    break;
                case Vendor.JuniperScreenOS:
                    vendorConverter = new ScreenOSConverter();
                    break;
                case Vendor.FortiGate:
                    vendorConverter = new FortiGateConverter();
                    break;
                case Vendor.PaloAlto:
                    vendorConverter = new PaloAltoConverter();
                    break;
                case Vendor.PaloAltoPanorama:
                    vendorConverter = new PanoramaConverter();
                    break;
                default:
                    throw new InvalidDataException("Unexpected!!!");
            }

            //here outputformat was set to 'json' by default manually because there is no an option for it on GUI
            vendorConverter.Initialize(vendorParser, ConfigFilePath.Text, toolVersion, targetFolder, "", "json");
            vendorConverter.ConversionProgress += OnConversionProgress;

            try
            {
                await Task.Run(() => vendorConverter.replacedyze());
            }
            catch (Exception ex)
            {
                Mouse.OverrideCursor = null;
                EnableDisableControls(true);
                OutputPanel.Visibility = Visibility.Collapsed;
                if (ex is InvalidDataException && ex.Message != null && ex.Message.Contains("Policy exceeds the maximum number"))
                {
                    ShowMessage(String.Format("{1}{0}{2}{0}{3}", Environment.NewLine, "Smartreplacedyze is unable to replacedyze the provided policy.",
                                                "Reason: Policy exceeds the maximum number of supported policy layers.",
                                                "To replacedure the smooth conversion of your data, it is recommended to contact Check Point Professional Services by sending an e-mail to"),
                    MessageTypes.Error, "[email protected]", "mailto:[email protected]");
                }
                else
                {
                    ShowMessage(string.Format("Could not convert process file.\n\nMessage: {0}\nModule:\t{1}\nClreplaced:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error);
                }
                return;
            }

            UpdateProgress(90, "Exporting Check Point report ...");
            //if ((typeof(PanoramaConverter) != vendorConverter.GetType() && typeof(FortiGateConverter) != vendorConverter.GetType()))
            //{
            //    vendorConverter.ExportManagmentReport();
            //}
            UpdateProgress(100, "");

            vendorConverter.ConversionProgress -= OnConversionProgress;

            Mouse.OverrideCursor = null;
            EnableDisableControls(true);
            ProgressPanel.Visibility = Visibility.Collapsed;
            ResultsPanel.Visibility = Visibility.Visible;

            ShowResults(vendorConverter);

        }

19 Source : SystemHelper.cs
with Apache License 2.0
from Chem4Word

private List<string> Initialise()
        {
            try
            {
                List<string> timings = new List<string>();

                string message = $"SystemHelper.Initialise() started at {SafeDate.ToLongDate(DateTime.Now)}";
                timings.Add(message);
                Debug.WriteLine(message);

                Stopwatch sw = new Stopwatch();
                sw.Start();

                WordVersion = -1;

                #region Get Machine Guid

                MachineId = GetMachineId();

                ProcessId = Process.GetCurrentProcess().Id;

                #endregion Get Machine Guid

                #region Get OS Version

                // The current code returns 6.2.* for Windows 8.1 and Windows 10 on some systems
                // https://msdn.microsoft.com/en-gb/library/windows/desktop/ms724832(v=vs.85).aspx
                // https://msdn.microsoft.com/en-gb/library/windows/desktop/dn481241(v=vs.85).aspx
                // However as we do not NEED the exact version number,
                //  I am not going to implement the above as they are too risky

                try
                {
                    OperatingSystem operatingSystem = Environment.OSVersion;

                    string ProductName = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName");
                    string CsdVersion = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CSDVersion");

                    if (!string.IsNullOrEmpty(ProductName))
                    {
                        StringBuilder sb = new StringBuilder();
                        if (!ProductName.StartsWith("Microsoft"))
                        {
                            sb.Append("Microsoft ");
                        }
                        sb.Append(ProductName);
                        if (!string.IsNullOrEmpty(CsdVersion))
                        {
                            sb.AppendLine($" {CsdVersion}");
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(operatingSystem.ServicePack))
                            {
                                sb.Append($" {operatingSystem.ServicePack}");
                            }
                        }

                        sb.Append($" {OsBits}");
                        sb.Append($" [{operatingSystem.Version}]");
                        sb.Append($" {CultureInfo.CurrentCulture.Name}");

                        SystemOs = sb.ToString().Replace(Environment.NewLine, "").Replace("Service Pack ", "SP");
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    SystemOs = "Exception " + ex.Message;
                }

                #endregion Get OS Version

                #region Get Office/Word Version

                try
                {
                    Click2RunProductIds = OfficeHelper.GetClick2RunProductIds();

                    WordVersion = OfficeHelper.GetWinWordVersionNumber();

                    WordProduct = OfficeHelper.GetWordProduct(Click2RunProductIds);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    WordProduct = "Exception " + ex.Message;
                }

                #endregion Get Office/Word Version

                #region Get Product Version and Location using reflection

                replacedembly replacedembly = replacedembly.GetExecutingreplacedembly();
                // CodeBase is the location of the installed files
                Uri uriCodeBase = new Uri(replacedembly.CodeBase);
                AddInLocation = Path.GetDirectoryName(uriCodeBase.LocalPath);

                Version productVersion = replacedembly.GetName().Version;
                replacedemblyVersionNumber = productVersion.ToString();

                AddInVersion = "Chem4Word V" + productVersion;

                #endregion Get Product Version and Location using reflection

                #region Get IpAddress on Thread

                // These can be tested via http://www.ipv6proxy.net/

                // Our locations
                _placesToTry.Add($"https://www.chem4word.co.uk/{Constants.Chem4WordVersionFiles}/client-ip-date.php");
                _placesToTry.Add($"http://www.chem4word.com/{Constants.Chem4WordVersionFiles}/client-ip-date.php");
                _placesToTry.Add($"https://chem4word.azurewebsites.net/{Constants.Chem4WordVersionFiles}/client-ip-date.php");

                // Other Locations
                _placesToTry.Add("https://api.my-ip.io/ip");
                _placesToTry.Add("https://ip.seeip.org");
                _placesToTry.Add("https://ipapi.co/ip");
                _placesToTry.Add("https://ident.me/");
                _placesToTry.Add("https://api6.ipify.org/");
                _placesToTry.Add("https://v4v6.ipv6-test.com/api/myip.php");

                message = $"GetIpAddress started at {SafeDate.ToLongDate(DateTime.Now)}";
                StartUpTimings.Add(message);
                Debug.WriteLine(message);

                _ipStopwatch = new Stopwatch();
                _ipStopwatch.Start();

                Thread thread1 = new Thread(GetExternalIpAddress);
                thread1.SetApartmentState(ApartmentState.STA);
                thread1.Start(null);

                #endregion Get IpAddress on Thread

                GetDotNetVersionFromRegistry();

                AllAddIns = InfoHelper.GetListOfAddIns();

                GatherBootUpTimeEtc();

                try
                {
                    BrowserVersion = new WebBrowser().Version.ToString();
                }
                catch
                {
                    BrowserVersion = "?";
                }

                GetScreens();

#if DEBUG
                Thread thread2 = new Thread(GetGitStatus);
                thread2.SetApartmentState(ApartmentState.STA);
                thread2.Start(null);
#endif

                sw.Stop();

                message = $"SystemHelper.Initialise() took {sw.ElapsedMilliseconds.ToString("#,000", CultureInfo.InvariantCulture)}ms";
                timings.Add(message);
                Debug.WriteLine(message);

                return timings;
            }
            catch (ThreadAbortException threadAbortException)
            {
                // Do Nothing
                Debug.WriteLine(threadAbortException.Message);
            }

            return new List<string>();
        }

19 Source : SystemHelper.cs
with Apache License 2.0
from Chem4Word

private List<string> Initialise()
        {
            try
            {
                List<string> timings = new List<string>();

                string message = $"SystemHelper.Initialise() started at {SafeDate.ToLongDate(DateTime.Now)}";
                timings.Add(message);
                Debug.WriteLine(message);

                Stopwatch sw = new Stopwatch();
                sw.Start();

                WordVersion = -1;

                #region Get Machine Guid

                MachineId = GetMachineId();

                ProcessId = Process.GetCurrentProcess().Id;

                #endregion Get Machine Guid

                #region Get OS Version

                // The current code returns 6.2.* for Windows 8.1 and Windows 10 on some systems
                // https://msdn.microsoft.com/en-gb/library/windows/desktop/ms724832(v=vs.85).aspx
                // https://msdn.microsoft.com/en-gb/library/windows/desktop/dn481241(v=vs.85).aspx
                // However as we do not NEED the exact version number,
                //  I am not going to implement the above as they are too risky

                try
                {
                    OperatingSystem operatingSystem = Environment.OSVersion;

                    string ProductName = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName");
                    string CsdVersion = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CSDVersion");

                    if (!string.IsNullOrEmpty(ProductName))
                    {
                        StringBuilder sb = new StringBuilder();
                        if (!ProductName.StartsWith("Microsoft"))
                        {
                            sb.Append("Microsoft ");
                        }
                        sb.Append(ProductName);
                        if (!string.IsNullOrEmpty(CsdVersion))
                        {
                            sb.AppendLine($" {CsdVersion}");
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(operatingSystem.ServicePack))
                            {
                                sb.Append($" {operatingSystem.ServicePack}");
                            }
                        }

                        sb.Append($" {OsBits}");
                        sb.Append($" [{operatingSystem.Version}]");
                        sb.Append($" {CultureInfo.CurrentCulture.Name}");

                        SystemOs = sb.ToString().Replace(Environment.NewLine, "").Replace("Service Pack ", "SP");
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    SystemOs = "Exception " + ex.Message;
                }

                #endregion Get OS Version

                #region Get Office/Word Version

                try
                {
                    Click2RunProductIds = OfficeHelper.GetClick2RunProductIds();

                    WordVersion = OfficeHelper.GetWinWordVersionNumber();

                    WordProduct = OfficeHelper.GetWordProduct(Click2RunProductIds);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    WordProduct = "Exception " + ex.Message;
                }

                #endregion Get Office/Word Version

                #region Get Product Version and Location using reflection

                replacedembly replacedembly = replacedembly.GetExecutingreplacedembly();
                // CodeBase is the location of the installed files
                Uri uriCodeBase = new Uri(replacedembly.CodeBase);
                AddInLocation = Path.GetDirectoryName(uriCodeBase.LocalPath);

                Version productVersion = replacedembly.GetName().Version;
                replacedemblyVersionNumber = productVersion.ToString();

                AddInVersion = "Chem4Word V" + productVersion;

                #endregion Get Product Version and Location using reflection

                #region Get IpAddress on Thread

                // These can be tested via http://www.ipv6proxy.net/

                // Our locations
                _placesToTry.Add($"https://www.chem4word.co.uk/{Constants.Chem4WordVersionFiles}/client-ip-date.php");
                _placesToTry.Add($"http://www.chem4word.com/{Constants.Chem4WordVersionFiles}/client-ip-date.php");
                _placesToTry.Add($"https://chem4word.azurewebsites.net/{Constants.Chem4WordVersionFiles}/client-ip-date.php");

                // Other Locations
                _placesToTry.Add("https://api.my-ip.io/ip");
                _placesToTry.Add("https://ip.seeip.org");
                _placesToTry.Add("https://ipapi.co/ip");
                _placesToTry.Add("https://ident.me/");
                _placesToTry.Add("https://api6.ipify.org/");
                _placesToTry.Add("https://v4v6.ipv6-test.com/api/myip.php");

                message = $"GetIpAddress started at {SafeDate.ToLongDate(DateTime.Now)}";
                StartUpTimings.Add(message);
                Debug.WriteLine(message);

                _ipStopwatch = new Stopwatch();
                _ipStopwatch.Start();

                Thread thread1 = new Thread(GetExternalIpAddress);
                thread1.SetApartmentState(ApartmentState.STA);
                thread1.Start(null);

                #endregion Get IpAddress on Thread

                GetDotNetVersionFromRegistry();

                AllAddIns = InfoHelper.GetListOfAddIns();

                GatherBootUpTimeEtc();

                try
                {
                    BrowserVersion = new WebBrowser().Version.ToString();
                }
                catch
                {
                    BrowserVersion = "?";
                }

                GetScreens();

#if DEBUG
                message = $"GetGitStatus started at {SafeDate.ToLongDate(DateTime.Now)}";
                StartUpTimings.Add(message);
                Debug.WriteLine(message);

                Thread thread2 = new Thread(GetGitStatus);
                thread2.SetApartmentState(ApartmentState.STA);
                thread2.Start(null);
#endif

                sw.Stop();

                message = $"SystemHelper.Initialise() took {SafeDouble.replacedtring0(sw.ElapsedMilliseconds)}ms";
                timings.Add(message);
                Debug.WriteLine(message);

                return timings;
            }
            catch (ThreadAbortException threadAbortException)
            {
                // Do Nothing
                Debug.WriteLine(threadAbortException.Message);
            }

            return new List<string>();
        }

19 Source : 消息_获取系统消息.cs
with GNU General Public License v2.0
from CHKZL

public static string 系统消息()
        {
            int 下载中 = 0, 下载完成 = 0;
            foreach (var item in Auxiliary.MMPU.DownList)
            {
                if (item.DownIofo.下载状态)
                    下载中++;
                else
                    下载完成++;
            }
            string 版本 = "";
            if (MMPU.启动模式 == 0)
            {
                版本 = MMPU.DDTV版本号;
            }
            else if (MMPU.启动模式 == 1)
            {
                版本 = MMPU.DDTVLiveRec版本号;
            }
            SystemInfo systemInfo = new SystemInfo()
            {
                DDTVCore_Ver = 版本,
                Room_Quanreplacedy = bilibili.RoomList.Count,
                ServerAID=MMPU.ServerAID,
                ServerGroup=MMPU.ServerGroup,
                ServerName=MMPU.ServerName,
                os_Info = new OS_Info()
                {
                    replacedociated_Users = Environment.UserName,
                    OS_Ver = RuntimeInformation.OSDescription,
                    OS_Tpye = RuntimeInformation.OSArchitecture.ToString(),
                    Memory_Usage = Process.GetCurrentProcess().WorkingSet64,
                    Runtime_Ver = RuntimeInformation.ProcessArchitecture.ToString(),
                    UserInteractive = Environment.UserInteractive,
                    Current_Directory = Environment.CurrentDirectory,
                    WebCore_Ver = Environment.Version.ToString(),
                    AppCore_Ver = RuntimeInformation.FrameworkDescription

                },
                download_Info = new Download_Info()
                {
                    Downloading = 下载中,
                    Completed_Downloads = 下载完成
                },
                ver_Info = new Ver_Info()
                {
                    IsNewVer = MMPU.是否有新版本,
                    NewVer = MMPU.是否有新版本 ? MMPU.检测到的新版本号 : null,
                    Update_Log = MMPU.是否有新版本 ? MMPU.更新公告 : null,
                }
            };
            return ReturnInfoPackage.InfoPkak((int)ServerSendMessageCode.请求成功, new List<SystemInfo>() { systemInfo });
        }

19 Source : hpg.cs
with MIT License
from christophevg

private bool ShowVersion() {
      replacedembly replacedembly = replacedembly.GetExecutingreplacedembly();
      replacedemblyName name = replacedembly.GetName();
      Console.WriteLine("Human Parser Generator version {0}", name.Version.ToString());
      return false;
    }

19 Source : ModuleService.cs
with MIT License
from ChromaControl

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await Task.Delay(1, stoppingToken);

            if (_deviceProvider == null)
            {
                _logger.LogError("No Device Provider Set, Cannot Initialize!!!");
                return;
            }

            var version = replacedembly.GetEntryreplacedembly().GetName().Version.ToString().Substring(0, 5);

            _logger.LogInformation($"Initializing Chroma Control - {_deviceProvider.Name} v{version}...");
            _logger.LogInformation("Initializing Device Provider...");

            _deviceProvider.Initialize();
            _deviceProvider.RequestControl();

            foreach (var device in _deviceProvider.Devices)
            {
                _logger.LogInformation($"Found Device: {device.Name} - {device.Lights.Count()} Lights");
            }

            _logger.LogInformation("Initializing Razer Chroma Broadcast SDK...");

            RzChromaBroadcastAPI.Init(_deviceProvider.GetGuid());

            RzChromaBroadcastAPI.RegisterEventNotification(OnChromaBroadcastEvent);

            _logger.LogInformation($"Chroma Control - {_deviceProvider.Name} Started Succesfully!");

            while (!stoppingToken.IsCancellationRequested)
            {
                await Task.Delay(1000, stoppingToken);
            }

            RzChromaBroadcastAPI.UnRegisterEventNotification();
            RzChromaBroadcastAPI.UnInit();
        }

19 Source : Program.cs
with MIT License
from chromelyapps

private static int Main(string[] args)
        {
            CiTrace("Application", "Started");

            var core = typeof(IChromelyConfiguration).replacedembly;
            CiTrace("Chromely.Core", core.GetName().Version.ToString());
            CiTrace("Platform", ChromelyRuntime.Platform.ToString());

            var appDirectory = AppDomain.CurrentDomain.BaseDirectory;
            CiTrace("AppDirectory", appDirectory);
            var startUrl = $"file:///{appDirectory}/index.html";

            var config = DefaultConfiguration.CreateForRuntimePlatform();
            config.CefDownloadOptions = new CefDownloadOptions(true, true);
            config.WindowOptions.Position = new WindowPosition(1, 2);
            config.WindowOptions.Size = new WindowSize(1000, 600);
            config.StartUrl = startUrl;
            config.DebuggingMode = true;
            config.WindowOptions.RelativePathToIconFile = "chromely.ico";

            CiTrace("Configuration", "Created");

            try
            {
                var builder = AppBuilder.Create();
                builder = builder.UseConfig<DefaultConfiguration>(config);
                builder = builder.UseWindow<TestWindow>();
                builder = builder.UseApp<ChromelyBasicApp>();
                builder = builder.Build();
                builder.Run(args);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
            CiTrace("Application", "Done");
            return 0;
        }

19 Source : ResultsWriter.cs
with MIT License
from chstetco

void WriteResultsToXml(ITestResultAdaptor result, XmlWriter xmlWriter)
        {
            // XML format as specified at https://github.com/nunit/docs/wiki/Test-Result-XML-Format

            var testRunNode = new TNode(k_TestRunNode);

            testRunNode.AddAttribute(k_Id, "2");
            testRunNode.AddAttribute(k_Testcasecount, (result.PreplacedCount + result.FailCount + result.SkipCount + result.InconclusiveCount).ToString());
            testRunNode.AddAttribute(k_Result, result.ResultState.ToString());
            testRunNode.AddAttribute(k_Total, (result.PreplacedCount + result.FailCount + result.SkipCount + result.InconclusiveCount).ToString());
            testRunNode.AddAttribute(k_Preplaceded, result.PreplacedCount.ToString());
            testRunNode.AddAttribute(k_Failed, result.FailCount.ToString());
            testRunNode.AddAttribute(k_Inconclusive, result.InconclusiveCount.ToString());
            testRunNode.AddAttribute(k_Skipped, result.SkipCount.ToString());
            testRunNode.AddAttribute(k_replacederts, result.replacedertCount.ToString());
            testRunNode.AddAttribute(k_EngineVersion, k_nUnitVersion);
            testRunNode.AddAttribute(k_ClrVersion, Environment.Version.ToString());
            testRunNode.AddAttribute(k_StartTime, result.StartTime.ToString(k_TimeFormat));
            testRunNode.AddAttribute(k_EndTime, result.EndTime.ToString(k_TimeFormat));
            testRunNode.AddAttribute(k_Duration, result.Duration.ToString());

            var resultNode = result.ToXml();
            testRunNode.ChildNodes.Add(resultNode);

            testRunNode.WriteTo(xmlWriter);
        }

19 Source : Program.cs
with Apache License 2.0
from Cinegy

private static int Run(Options opts)
        {
            Console.CancelKeyPress += Console_CancelKeyPress;

            _logger = LogManager.GetCurrentClreplacedLogger();

            var buildVersion = replacedembly.GetEntryreplacedembly().GetName().Version.ToString();

            LogSetup.ConfigureLogger("srtstreamreplacedyser", opts.OrganizationId, opts.DescriptorTags, "https://telemetry.cinegy.com", opts.TelemetryEnabled, false, "SRTStreamreplacedyser", buildVersion);

            _replacedyser = new replacedyser(_logger);

            var location = replacedembly.GetEntryreplacedembly().Location;

            _logger.Info($"Cinegy Transport Stream Monitoring and replacedysis Tool (Built: {File.GetCreationTime(location)})");

            try
            {
                Console.CursorVisible = false;
                Console.SetWindowSize(120, 50);
                Console.OutputEncoding = Encoding.Unicode;
            }
            catch
            {
                Console.WriteLine("Failed to increase console size - probably screen resolution is low");
            }
            _options = opts;

            GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;

            WorkLoop();

            return 0;
        }

19 Source : DataCoreDatabase.cs
with GNU General Public License v3.0
from CitizensReactor

internal static void InitializeSignature(out Int64[] signature)
        {
            var thisreplacedembley = replacedembly.Getreplacedembly(typeof(DataCoreDatabase));
            var thisVersion = thisreplacedembley.GetName().Version;
            var hash = DataCore2Util.SHA256(Encoding.UTF8.GetBytes(thisVersion.ToString()));
            signature = new long[4] {
                BitConverter.ToInt64(hash, 0),
                BitConverter.ToInt64(hash, 8),
                BitConverter.ToInt64(hash, 16),
                BitConverter.ToInt64(hash, 24)
            };
        }

19 Source : Configuration.cs
with GNU General Public License v3.0
from Cleric-K

public bool Upgrade() {
			var currentVersion = RuntimeVersion;
			var prevVersion = new Version(0,0,0,0);
			
			try {
				prevVersion = new Version(this.Version);
			}
			catch(Exception){}
			
            if(prevVersion < currentVersion) {
                DoUpgrade(prevVersion, currentVersion);
                Version = currentVersion.ToString();
				return true;
			}
			
			return false;
		}

19 Source : CloudEventController.cs
with Apache License 2.0
from cloudevents

[HttpGet("generate")]
        public ActionResult<string> GenerateCloudEvent()
        {
            var evt = new CloudEvent
            {
                Type = "CloudNative.CloudEvents.AspNetCoreSample",
                Source = new Uri("https://github.com/cloudevents/sdk-csharp"),
                Time = DateTimeOffset.Now,
                DataContentType = "application/json",
                Id = Guid.NewGuid().ToString(),
                Data = new
                {
                    Language = "C#",
                    EnvironmentVersion = Environment.Version.ToString()
                }
            };
            // Format the event as the body of the response. This is UTF-8 JSON because of
            // the CloudEventFormatter we're using, but EncodeStructuredModeMessage always
            // returns binary data. We could return the data directly, but for debugging
            // purposes it's useful to have the JSON string.
            var bytes = formatter.EncodeStructuredModeMessage(evt, out var contentType);
            string json = Encoding.UTF8.GetString(bytes.Span);
            var result = Ok(json);

            // Specify the content type of the response: this is what makes it a CloudEvent.
            // (In "binary mode", the content type is the content type of the data, and headers
            // indicate that it's a CloudEvent.)
            result.ContentTypes.Add(contentType.MediaType);
            return result;
        }

19 Source : MainForm.cs
with MIT License
from CmlLib

private string getLibraryVersion()
        {
            try
            {
                return replacedembly.Getreplacedembly(typeof(CMLauncher)).GetName().Version.ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return null;
            }
        }

19 Source : AstarUpdateWindow.cs
with GNU General Public License v3.0
from coconauts

public void OnDestroy () {
			if ( version != null && !setReminder ) {
				Debug.Log ("Closed window, reminding again tomorrow");
				EditorPrefs.SetString ("AstarRemindUpdateDate", System.DateTime.UtcNow.AddDays(1).ToString(System.Globalization.CultureInfo.InvariantCulture));
				EditorPrefs.SetString ("AstarRemindUpdateVersion", version.ToString() );
			}
		}

19 Source : AstarUpdateWindow.cs
with GNU General Public License v3.0
from coconauts

void OnGUI () {

			if ( largeStyle == null ) {
				largeStyle = EditorStyles.largeLabel;
				largeStyle.fontSize = 32;
				largeStyle.alignment = TextAnchor.UpperCenter;
				largeStyle.richText = true;
				
				normalStyle = EditorStyles.label;
				normalStyle.wordWrap = true;
				normalStyle.richText = true;
			}

			if ( version == null ) {
				return;
			}

			//GUILayout.BeginHorizontal ();
			//GUILayout.FlexibleSpace();
			GUILayout.Label ("New Update Available!", largeStyle);
			GUILayout.Label ("There is a new version of the <b>A* Pathfinding Project</b> available for download.\n" +
			    "The new version is <b>"+version.ToString()+"</b> you have <b>" + AstarPath.Version.ToString()+"</b>\n\n"+
			                 "<i>Summary:</i>\n"+summary, normalStyle
			);

			GUILayout.FlexibleSpace ();

			GUILayout.BeginHorizontal ();
			GUILayout.FlexibleSpace ();

			GUILayout.BeginVertical ();

			Color col = GUI.color;
			GUI.backgroundColor *= new Color ( 0.5f,  1f, 0.5f);
			if (GUILayout.Button ("Take me to the download page!", GUILayout.Height ( 30 ), GUILayout.MaxWidth(300))) {
				Application.OpenURL ( downloadURL );
			}
			GUI.backgroundColor = col;


			if (GUILayout.Button ("What's new? (full changelog)")) {
				Application.OpenURL (AstarPathEditor.GetURL ("changelog"));
			}

			GUILayout.EndVertical ();

			GUILayout.FlexibleSpace ();
			GUILayout.EndHorizontal ();

			//GUILayout.Space ( 90 );
			GUILayout.FlexibleSpace ();

			GUILayout.BeginHorizontal ();
			//GUILayout.FlexibleSpace ();

			if ( GUILayout.Button ("Skip this version", GUILayout.MaxWidth (100) ) ) {
				EditorPrefs.SetString ("AstarSkipUpToVersion", version.ToString());
				setReminder = true;
				Close();
			}

			if ( GUILayout.Button ("Remind me later ( 1 week )", GUILayout.MaxWidth (200) ) ) {
				EditorPrefs.SetString ("AstarRemindUpdateDate", System.DateTime.UtcNow.AddDays(7).ToString(System.Globalization.CultureInfo.InvariantCulture));
				EditorPrefs.SetString ("AstarRemindUpdateVersion", version.ToString() );
				setReminder = true;
				Close();
			}

			GUILayout.FlexibleSpace ();
			GUILayout.EndHorizontal ();
			//GUILayout.FlexibleSpace();
			//GUILayout.EndHorizontal ();
		}

19 Source : MainWindow.xaml.cs
with MIT License
from coldino

private static string CalculateApplicationVersion()
        {
            try
            {
                return ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
            }
            catch (InvalidDeploymentException)
            {
                return DEV_STRING;
            }
        }

19 Source : ConanAbout.cs
with MIT License
from conan-io

protected internal override async Task MenuItemCallbackAsync()
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
            var replacedembly = replacedembly.GetExecutingreplacedembly();
            string version = replacedembly.GetName().Version.ToString();
            string fileVersionInfo = replacedembly.GetCustomAttribute<replacedemblyDescriptionAttribute>().Description.ToString();
            Logger.Log($"About Conan Extension for Visual Studio: {version} ({fileVersionInfo})");

            string message = String.Format("Conan Extension for Visual Studio\n" +
                $"Version\t: {version}\n" +
                $"Commit\t: {fileVersionInfo}");
            MessageBox.Show(message, "About Conan Extension", MessageBoxButtons.OK);
        }

19 Source : Program.cs
with MIT License
from coverlet-coverage

static string GetreplacedemblyVersion() => typeof(Program).replacedembly.GetName().Version.ToString();

19 Source : UpdateManager.cs
with Apache License 2.0
from cqjjjzr

public string GetCurrentVersion()
        {
            return _mgr?.CurrentlyInstalledVersion()?.ToString() ?? replacedembly.GetCallingreplacedembly().GetName().Version.ToString();
        }

19 Source : DesktopLyrics.cs
with Apache License 2.0
from cqjjjzr

public PluginInfo Initialise(IntPtr apiInterfacePtr)
        {
            var versions = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString().Split('.');

            _mbApiInterface = new MusicBeeApiInterface();
            _mbApiInterface.Initialise(apiInterfacePtr);
            _about.PluginInfoVersion = PluginInfoVersion;
            _about.Name = "Desktop Lyrics";
            _about.Description = "Display lyrics on your desktop!";
            _about.Author = "Charlie Jiang";
            _about.TargetApplication = "";   // current only applies to artwork, lyrics or instant messenger name that appears in the provider drop down selector or target Instant Messenger
            _about.Type = PluginType.General;
            _about.VersionMajor = short.Parse(versions[0]);  // your plugin version
            _about.VersionMinor = short.Parse(versions[1]);
            _about.Revision = short.Parse(versions[2]);
            _about.MinInterfaceVersion = MinInterfaceVersion;
            _about.MinApiRevision = MinApiRevision;
            _about.ReceiveNotifications = ReceiveNotificationFlags.PlayerEvents;
            _about.ConfigurationPanelHeight = 32;   // height in pixels that musicbee should reserve in a panel for config settings. When set, a handle to an empty panel will be preplaceded to the Configure function

            _lyricsCtrl = new LyricsController(_mbApiInterface);
            return _about;
        }

19 Source : NeteaseLyrics.cs
with Apache License 2.0
from cqjjjzr

public PluginInfo Initialise(IntPtr apiInterfacePtr)
        {
            var versions = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString().Split('.');

            _mbApiInterface = new MusicBeeApiInterface();
            _mbApiInterface.Initialise(apiInterfacePtr);
            _about.PluginInfoVersion = PluginInfoVersion;
            _about.Name = "Netease Lyrics";
            _about.Description = "A plugin to retrieve lyrics from Netease Cloud Music.(从网易云音乐获取歌词的插件。)";
            _about.Author = "Charlie Jiang";
            _about.TargetApplication = "";   // current only applies to artwork, lyrics or instant messenger name that appears in the provider drop down selector or target Instant Messenger
            _about.Type = PluginType.LyricsRetrieval;
            _about.VersionMajor = short.Parse(versions[0]);  // your plugin version
            _about.VersionMinor = short.Parse(versions[1]);
            _about.Revision = short.Parse(versions[2]);
            _about.MinInterfaceVersion = MinInterfaceVersion;
            _about.MinApiRevision = MinApiRevision;
            _about.ReceiveNotifications = ReceiveNotificationFlags.DownloadEvents;
            _about.ConfigurationPanelHeight = 50;   // height in pixels that musicbee should reserve in a panel for config settings. When set, a handle to an empty panel will be preplaceded to the Configure function

            string noTranslatePath = Path.Combine(_mbApiInterface.Setting_GetPersistentStoragePath(), NoTranslateFilename);
            string configPath = Path.Combine(_mbApiInterface.Setting_GetPersistentStoragePath(), ConfigFilename);
            if (File.Exists(configPath))
            {
                try
                {
                    _config = JsonConvert.DeserializeObject<NeteaseConfig>(File.ReadAllText(configPath, Encoding.UTF8));
                }
                catch (Exception ex)
                {
                    _mbApiInterface.MB_Trace("[NeteaseMusic] Failed to load config" + ex);
                }
            }
            if (File.Exists(noTranslatePath))
            {
                File.Delete(noTranslatePath);
                _config.format = NeteaseConfig.OutputFormat.Original;
                SaveSettingsInternal();
            }

            return _about;
        }

19 Source : GitHub.cs
with GNU General Public License v3.0
from CrackyStudio

public static bool IsNewVersionAvailable()
        {
            try
            {
                MainWindow.currentVersion = System.Reflection.replacedembly.GetEntryreplacedembly().GetName().Version.ToString();
                string latestVersion;
                string html = string.Empty;
                string URL = @"https://api.github.com/repos/CrackyStudio/arkso/releases/latest";

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
                request.AutomaticDecompression = DecompressionMethods.GZip;
                request.Method = "GET";
                request.ContentType = "application/json";
                request.UserAgent = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36";

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (Stream stream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream))
                {
                    html = reader.ReadToEnd();
                }

                json = Json.ParseString(html);

                MainWindow.currentVersion = MainWindow.currentVersion.Substring(0, Math.Min(MainWindow.currentVersion.Length, 3));
                latestVersion = json["tag_name"].ToString().TrimStart('v');

                double cv = double.Parse(MainWindow.currentVersion);
                double lv = double.Parse(latestVersion);

                if (cv < lv)
                {
                    return true;
                }
                else
                {
                    Console.WriteLine("");
                    return false;
                }
            } 
            catch (Exception ex)
            {
                MainWindow.currentVersion = MainWindow.currentVersion.Substring(0, Math.Min(MainWindow.currentVersion.Length, 3));
                Utils.Log($"{ex.Message}\n{ex.InnerException}", "ERROR");
                return false;
            }
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from Crauzer

private async void CheckForUpdate()
        {
            if (Config.Get<bool>("CheckForUpdates"))
            {
                //Do it in try so we don't crash if there isn't internet connection
                try
                {
                    GitHubClient gitClient = new GitHubClient(new ProductHeaderValue("Obsidian"));
                    IReadOnlyList<Release> releases = await gitClient.Repository.Release.GetAll("Crauzer", "Obsidian");
                    Release newestRelease = releases[0];

                    // Tags can contain other characters but Version accepts only {x.x.x.x} format
                    // this way we can avoid showing the update message for beta versions
                    if (Version.TryParse(newestRelease.TagName, out Version newestVersion))
                    {
                        // Show update message only if the release version is higher than the one currently executing
                        if (newestVersion > replacedembly.GetExecutingreplacedembly().GetName().Version)
                        {
                            await DialogHelper.ShowMessageDialog(Localization.Get("UpdateMessage"));
                            Process.Start("cmd", "/C start https://github.com/Crauzer/Obsidian/releases/tag/" + newestVersion.ToString());
                        }
                    }
                }
                catch (Exception) { }
            }
        }

19 Source : MSBuildTools.cs
with MIT License
from cre8ivepark

private static string ProcessPlatformTemplate(string platformTemplate, string platformName, string configuration, BuildTarget buildTarget, TargetFramework targetFramework, IEnumerable<string> references, IEnumerable<string> defines, params HashSet<string>[] priorToCheck)
        {
            if (Utilities.TryGetXMLTemplate(platformTemplate, "PLATFORM_COMMON_REFERENCE", out string platformCommonReferenceTemplate))
            {
                ProcessReferences(buildTarget, references, out HashSet<string> platformreplacedemblySearchPaths, out HashSet<string> platformreplacedemblyReferencePaths, priorToCheck);

                string targetUWPPlatform = uwpTargetPlatformVersion;
                // If the version string is not a valid one, default to the highest available SDK version on the machine.
                if (string.IsNullOrWhiteSpace(targetUWPPlatform) || !Version.TryParse(targetUWPPlatform, out _))
                {
                    targetUWPPlatform = Utilities.GetUWPSDKs().Max().ToString(4);
                }

                string minUWPPlatform = uwpMinPlatformVersion;
                if (string.IsNullOrWhiteSpace(minUWPPlatform) || new Version(minUWPPlatform) < DefaultMinUWPSDK)
                {
                    minUWPPlatform = DefaultMinUWPSDK.ToString();
                }

                Dictionary<string, string> platformTokens = new Dictionary<string, string>()
                {
                    {"<!--TARGET_FRAMEWORK_TOKEN-->", targetFramework.AsMSBuildString() },
                    {"<!--PLATFORM_COMMON_DEFINE_CONSTANTS-->", string.Join(";", defines) },
                    {"<!--PLATFORM_COMMON_replacedEMBLY_SEARCH_PATHS_TOKEN-->", string.Join(";", platformreplacedemblySearchPaths)},

                    // These are UWP specific, but they will be no-op if not needed
                    { "<!--UWP_TARGET_PLATFORM_VERSION_TOKEN-->", targetUWPPlatform },
                    { "<!--UWP_MIN_PLATFORM_VERSION_TOKEN-->", minUWPPlatform }
                };

                platformTokens.Add(platformCommonReferenceTemplate, string.Join("\r\n", GetReferenceEntries(platformCommonReferenceTemplate, platformreplacedemblyReferencePaths)));

                return Utilities.ReplaceTokens(platformTemplate, platformTokens);
            }
            else
            {
                Debug.LogError($"Invalid platform template format for '{platformName}' with configuration '{configuration}'");
                return platformTemplate;
            }
        }

19 Source : FrmMain.cs
with GNU General Public License v3.0
from Crowley2012

private void CheckUpdate()
        {
            bool checkingUpdate = true;
            int attempts = 0;

            while (checkingUpdate && attempts < 3)
            {
                try
                {
                    using (var webClient = new WebClient())
                    {
                        webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2;)");

                        ApiGithub release = JsonConvert.DeserializeObject<ApiGithub>(webClient.DownloadString("https://api.github.com/repos/Crowley2012/MyCryptoMonitor/releases/latest"));
                        Version currentVersion = new Version(replacedembly.GetExecutingreplacedembly().GetName().Version.ToString());
                        Version latestVersion = new Version(release.tag_name);

                        if (currentVersion.CompareTo(latestVersion) < 0)
                        {
                            if (MessageBox.Show($"Download new version?\n\nCurrent Version: {currentVersion}\nLatest Version {latestVersion}", "Update Available", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
                                System.Diagnostics.Process.Start("https://github.com/Crowley2012/MyCryptoMonitor/releases/latest");
                        }

                        checkingUpdate = false;
                    }
                }
                catch (WebException)
                {
                    attempts++;
                    UpdateStatus("Failed checking for update");
                }
            }
        }

19 Source : UpdatesChecker.cs
with MIT License
from crouvpony47

internal static async Task<bool> CheckRemoteVersion()
        {
            try
            {
                var httph = new HttpClientHandler();
                var http = new HttpClient(httph);
                http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0");
                var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                serializer.MaxJsonLength = 2097152; // 2 Mb

                string[] thisVersion = System.Reflection.replacedembly.GetExecutingreplacedembly().GetName().Version.ToString().Split('.');

                var jsonString = await http.GetStringAsync(@"https://api.github.com/repos/crouvpony47/furdown/releases");
                var jsonRoot = (object[])serializer.DeserializeObject(jsonString);

                if (jsonRoot.Length == 0)
                {
                    Console.WriteLine("Updater :: Warning :: no releases found on GitHub");
                    return false;
                }

                foreach (var releaseJson in jsonRoot)
                {
                    var releaseDict = releaseJson as Dictionary<string, object>;
                    var tag = (string)releaseDict["tag_name"];
                    tag = tag.Replace("v.", "");
                    var prerelease = (bool)releaseDict["prerelease"];
                    if (prerelease)
                    {
                        Console.WriteLine("Updater :: Note :: found prerelease, " + tag);
                        continue;
                    }

                    Console.WriteLine("Updater :: Note :: found release, " + tag);

                    var remoteVersion = tag.Split('.');
                    var versionComp = thisVersion.Zip(remoteVersion, (tvp, rvp) =>
                    {
                        return string.Compare(tvp, rvp, StringComparison.Ordinal);
                    });

                    foreach (int c in versionComp)
                    {
                        if (c < 0)
                        {
                            Console.WriteLine("Updater :: Note :: an update is available");
                            Console.WriteLine("Updater :: Note :: see https://github.com/crouvpony47/furdown/releases");
                            return true;
                        }
                        else if (c > 0)
                        {
                            Console.WriteLine("Updater :: Note :: current version is newer than the latest released one");
                            return false;
                        }
                    }
                    return false;
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine("Updater :: Error :: " + exc.Message);
            }
            return false;
        }

19 Source : VersionTagHelper.cs
with MIT License
from csharpfritz

public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
		{
			var versionString = "";
			output.TagName = "span";
			output.TagMode = TagMode.StartTagAndEndTag;
			var childContent = await output.GetChildContentAsync();
			output.Content.AppendHtml(childContent);
			if (replacedemblyType == null)
			{
			replacedemblyType = GetType();
			}
			switch (Type)
			{
			case VersionType.FileVersion:
				versionString = replacedemblyType
					.GetTypeInfo().replacedembly
					.GetCustomAttribute<replacedemblyFileVersionAttribute>()?
					.Version ?? "";
				break;
			case VersionType.ProductVersion:    // also covers VersionType.InformationalVersion
				versionString = replacedemblyType
					.GetTypeInfo().replacedembly
					.GetCustomAttribute<replacedemblyInformationalVersionAttribute>()?
					.InformationalVersion ?? "";
				break;
			case VersionType.replacedemblyVersion:
				versionString = replacedemblyType
					.replacedembly.GetName().Version.ToString();
				break;
			default:
				break;
			}
			output.Content.Append(versionString);

			await base.ProcessAsync(context, output);
			return;
		}

19 Source : VersionConverter.cs
with MIT License
from csinkers

public override void Write(Utf8JsonWriter writer, Version value, JsonSerializerOptions options)
        {
            if (writer == null) throw new ArgumentNullException(nameof(writer));
            if (value == null)
                writer.WriteNullValue();
            else
                writer.WriteStringValue(value.ToString());
        }

19 Source : MainWindow.xaml.cs
with MIT License
from cuiliang

private void OnLoaded(object sender, RoutedEventArgs e)
        {
            LoadSettings();

            WindowState = WindowState.Minimized;

            // update auto startup checkbox
            LoadAutoStartStatus();

            // 设置
            PnlSettings.DataContext = AppSetting;
            

            //
            replacedle = $"ClickShow {replacedembly.GetExecutingreplacedembly().GetName().Version.ToString()}";


            ApplySettings();


            // 最后启动挂钩
            _mouseHook = new MouseHook.MouseHook();
            _mouseHook.MouseDown += MouseHookOnMouseDown;
            _mouseHook.MouseMove += MouseHookOnMouseMove;
            _mouseHook.MouseUp += MouseHookOnMouseUp;
            _mouseHook.Start();

            // 检查版本更新
            Task.Run(async () =>
            {
                await Task.Delay(1000 * 10 );
                CheckUpdate();
            });
            
        }

19 Source : WebSocketClientHandshaker07.cs
with MIT License
from cuteant

protected internal override IFullHttpRequest NewHandshakeRequest()
        {
            Uri wsUrl = Uri;

            // Get 16 bit nonce and base 64 encode it
            byte[] nonce = WebSocketUtil.RandomBytes(16);
            string key = WebSocketUtil.Base64String(nonce);

            string acceptSeed = key + MagicGuid;
            byte[] sha1 = WebSocketUtil.Sha1(Encoding.ASCII.GetBytes(acceptSeed));
            _expectedChallengeResponseString = new AsciiString(WebSocketUtil.Base64String(sha1));

#if DEBUG
            if (Logger.DebugEnabled)
            {
                Logger.WebSocketVersion07ClientHandshakeKey(key, _expectedChallengeResponseString);
            }
#endif

            // Format request
            var request = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Get, UpgradeUrl(wsUrl),
                Unpooled.Empty);
            HttpHeaders headers = request.Headers;

            if (CustomHeaders is object)
            {
                _ = headers.Add(CustomHeaders);
                if (!headers.Contains(HttpHeaderNames.Host))
                {
                    // Only add HOST header if customHeaders did not contain it.
                    //
                    // See https://github.com/netty/netty/issues/10101
                    _ = headers.Set(HttpHeaderNames.Host, WebsocketHostValue(wsUrl));
                }
            }
            else
            {
                _ = headers.Set(HttpHeaderNames.Host, WebsocketHostValue(wsUrl));
            }

            _ = headers.Set(HttpHeaderNames.Upgrade, HttpHeaderValues.Websocket)
                .Set(HttpHeaderNames.Connection, HttpHeaderValues.Upgrade)
                .Set(HttpHeaderNames.SecWebsocketKey, key);

            if (!headers.Contains(HttpHeaderNames.SecWebsocketOrigin))
            {
                _ = headers.Set(HttpHeaderNames.SecWebsocketOrigin, WebsocketOriginValue(wsUrl));
            }

            string expectedSubprotocol = ExpectedSubprotocol;
            if (!string.IsNullOrEmpty(expectedSubprotocol))
            {
                _ = headers.Set(HttpHeaderNames.SecWebsocketProtocol, expectedSubprotocol);
            }

            _ = headers.Set(HttpHeaderNames.SecWebsocketVersion, Version.ToString());

            return request;
        }

19 Source : WebSocketClientHandshaker08.cs
with MIT License
from cuteant

protected internal override IFullHttpRequest NewHandshakeRequest()
        {
            Uri wsUrl = Uri;

            // Get 16 bit nonce and base 64 encode it
            byte[] nonce = WebSocketUtil.RandomBytes(16);
            string key = WebSocketUtil.Base64String(nonce);

            string acceptSeed = key + MagicGuid;
            byte[] sha1 = WebSocketUtil.Sha1(Encoding.ASCII.GetBytes(acceptSeed));
            _expectedChallengeResponseString = new AsciiString(WebSocketUtil.Base64String(sha1));

#if DEBUG
            if (Logger.DebugEnabled)
            {
                Logger.WebSocketVersion08ClientHandshakeKey(key, _expectedChallengeResponseString);
            }
#endif

            // Format request
            var request = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Get, UpgradeUrl(wsUrl),
                Unpooled.Empty);
            HttpHeaders headers = request.Headers;

            if (CustomHeaders is object)
            {
                _ = headers.Add(CustomHeaders);
                if (!headers.Contains(HttpHeaderNames.Host))
                {
                    // Only add HOST header if customHeaders did not contain it.
                    //
                    // See https://github.com/netty/netty/issues/10101
                    _ = headers.Set(HttpHeaderNames.Host, WebsocketHostValue(wsUrl));
                }
            }
            else
            {
                _ = headers.Set(HttpHeaderNames.Host, WebsocketHostValue(wsUrl));
            }

            _ = headers.Set(HttpHeaderNames.Upgrade, HttpHeaderValues.Websocket)
                .Set(HttpHeaderNames.Connection, HttpHeaderValues.Upgrade)
                .Set(HttpHeaderNames.SecWebsocketKey, key);

            if (!headers.Contains(HttpHeaderNames.SecWebsocketOrigin))
            {
                _ = headers.Set(HttpHeaderNames.SecWebsocketOrigin, WebsocketOriginValue(wsUrl));
            }

            string expectedSubprotocol = ExpectedSubprotocol;
            if (!string.IsNullOrEmpty(expectedSubprotocol))
            {
                _ = headers.Set(HttpHeaderNames.SecWebsocketProtocol, expectedSubprotocol);
            }

            _ = headers.Set(HttpHeaderNames.SecWebsocketVersion, Version.ToString());

            return request;
        }

19 Source : WebSocketClientHandshaker13.cs
with MIT License
from cuteant

protected internal override IFullHttpRequest NewHandshakeRequest()
        {
            Uri wsUrl = Uri;

            // Get 16 bit nonce and base 64 encode it
            byte[] nonce = WebSocketUtil.RandomBytes(16);
            string key = WebSocketUtil.Base64String(nonce);

            string acceptSeed = key + MagicGuid;
            byte[] sha1 = WebSocketUtil.Sha1(Encoding.ASCII.GetBytes(acceptSeed));
            _expectedChallengeResponseString = new AsciiString(WebSocketUtil.Base64String(sha1));

#if DEBUG
            if (Logger.DebugEnabled)
            {
                Logger.WebSocketVersion13ClientHandshakeKey(key, _expectedChallengeResponseString);
            }
#endif

            // Format request
            var request = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Get, UpgradeUrl(wsUrl),
                Unpooled.Empty);
            HttpHeaders headers = request.Headers;

            if (CustomHeaders is object)
            {
                _ = headers.Add(CustomHeaders);
                if (!headers.Contains(HttpHeaderNames.Host))
                {
                    // Only add HOST header if customHeaders did not contain it.
                    //
                    // See https://github.com/netty/netty/issues/10101
                    _ = headers.Set(HttpHeaderNames.Host, WebsocketHostValue(wsUrl));
                }
            }
            else
            {
                _ = headers.Set(HttpHeaderNames.Host, WebsocketHostValue(wsUrl));
            }

            _ = headers.Set(HttpHeaderNames.Upgrade, HttpHeaderValues.Websocket)
                .Set(HttpHeaderNames.Connection, HttpHeaderValues.Upgrade)
                .Set(HttpHeaderNames.SecWebsocketKey, key);

            if (!headers.Contains(HttpHeaderNames.Origin))
            {
                _ = headers.Set(HttpHeaderNames.Origin, WebsocketOriginValue(wsUrl));
            }

            string expectedSubprotocol = ExpectedSubprotocol;
            if (!string.IsNullOrEmpty(expectedSubprotocol))
            {
                _ = headers.Set(HttpHeaderNames.SecWebsocketProtocol, expectedSubprotocol);
            }

            _ = headers.Set(HttpHeaderNames.SecWebsocketVersion, Version.ToString());

            return request;
        }

19 Source : Client.cs
with MIT License
from cwensley

public void Start()
		{
			if (SynchronizationContext.Current == null)
				SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

			var config = new NetPeerConfiguration("PabloDraw");
			//config.Port = port;
#if SIMULATE_LATENCY
			config.SimulatedMinimumLatency = 0.2f;
			config.SimulatedRandomLatency = 0.5f;
			config.SimulatedLoss = 0.01f;
#endif
			
			#if DEBUG
			config.EnableMessageType(NetIncomingMessageType.DebugMessage);
			#endif
			client = new NetClient(config);
			
			var startupMessage = client.CreateMessage();
			startupMessage.WriteVariableInt32(Server.VERSION);
			var version = replacedembly.GetEntryreplacedembly().GetName().Version;
			startupMessage.Write(version.ToString());
			startupMessage.Write(Preplacedword);
			CurrentUser.Send(new SendCommandArgs(startupMessage, this));

			client.RegisterReceivedCallback(ReceiveCallback);
			client.Start();
			if (!string.IsNullOrEmpty(Hostname))
				client.Connect(Hostname, Port, startupMessage);
			else
				client.Connect(new IPEndPoint(IPAddress.Loopback, Port), startupMessage);
		}

19 Source : ConnectorClientEx.cs
with MIT License
from CXuesong

internal static string GetClientVersion<T>(T client) where T : ServiceClient<T>
        {
            var type = client.GetType();
            var replacedembly = type.GetTypeInfo().replacedembly;
            return replacedembly.GetName().Version.ToString();
        }

19 Source : CrashWindow.xaml.cs
with GNU General Public License v3.0
from CyanLabs

public string SendReport(Exception exception)
        {
            try
            {
                CrashContainer crashContainer = new();
                StackTrace st = new(exception, true);
                StackFrame frame = st.GetFrame(st.FrameCount - 1);

                crashContainer.ErrorName = exception.GetType().ToString();
                if (frame != null)
                    crashContainer.ErrorLocation = $"{frame.GetFileName()}/{frame.GetMethod().Name}/{frame.GetFileLineNumber()}";
                crashContainer.Logs = AppMan.Logger.Log;
                
                Dictionary<string, string> values = new()
                {
                    {"computername", Environment.MachineName},
                    {"detail", JsonConvert.SerializeObject(crashContainer)},
                    {"version", replacedembly.GetEntryreplacedembly()?.GetName().Version.ToString()},
                    {"error", crashContainer.ErrorName},
                    {"message", exception.Message},
                    {"operatingsystem", SystemHelper.GetOsFriendlyName()},
                    {"branch", AppMan.App.LauncherPrefs.ReleaseTypeInstalled.ToString()}
                };
                
                HttpRequestMessage httpRequestMessage = new()
                {
                    Method = HttpMethod.Post,
                    RequestUri = new Uri(Api.CrashLogPost),
                    Headers = { 
                        { nameof(HttpRequestHeader.Authorization), $"Bearer {ApiSecret.Token}" },
                    },
                    Content = new FormUrlEncodedContent(values)
                };

                HttpResponseMessage response = AppMan.Client.SendAsync(httpRequestMessage).GetAwaiter().GetResult();
                return response.Content.ReadreplacedtringAsync().GetAwaiter().GetResult();
            }
            catch (HttpRequestException)
            {
                return null;
            }
        }

19 Source : Program.cs
with Apache License 2.0
from CycloneDX

public static void AddMetadataTool(Bom bom)
        {
            string toolname = "CycloneDX module for .NET";

            if (bom.Metadata == null) {
                bom.Metadata = new Metadata();
            }
            if (bom.Metadata.Tools == null)
            {
                bom.Metadata.Tools = new List<Tool>();
            }
            var index = bom.Metadata.Tools.FindIndex(p => p.Name == toolname);
            if (index == -1)
            {
                bom.Metadata.Tools.Add(new Tool
                {
                    Name = toolname,
                    Vendor = "CycloneDX",
                    Version = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString()
                }
                );
            }
            else
            {
                bom.Metadata.Tools[index].Version = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString();
            }

        }

19 Source : Connection.cs
with MIT License
from CymaticLabs

public static IDictionary<string, object> DefaultClientProperties()
        {
            System.Reflection.replacedembly replacedembly =
                System.Reflection.replacedembly.Getreplacedembly(typeof(Connection));
            string version = replacedembly.GetName().Version.ToString();
            //TODO: Get the rest of this data from the replacedembly Attributes
            IDictionary<string, object> table = new Dictionary<string, object>();
            table["product"] = Encoding.UTF8.GetBytes("RabbitMQ");
            table["version"] = Encoding.UTF8.GetBytes(version);
            table["platform"] = Encoding.UTF8.GetBytes(".NET");
            table["copyright"] = Encoding.UTF8.GetBytes("Copyright (C) 2007-2014 GoPivotal, Inc.");
            table["information"] = Encoding.UTF8.GetBytes("Licensed under the MPL.  " +
                                                          "See http://www.rabbitmq.com/");
            return table;
        }

19 Source : AddFilesCommand.cs
with Apache License 2.0
from CycloneDX

public static async Task<int> AddFiles(AddFilesCommandOptions options)
        {
            Contract.Requires(options != null);
            var outputToConsole = string.IsNullOrEmpty(options.OutputFile);

            var thisTool = new Tool
            {
                Name = "CycloneDX CLI",
                Vendor = "CycloneDX",
                Version = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString(),
            };

            var bom = options.NoInput ? new Bom() : await CliUtils.InputBomHelper(options.InputFile, options.InputFormat).ConfigureAwait(false);
            if (bom == null) return (int)ExitCode.ParameterValidationError;

            if (bom.SerialNumber is null) bom.SerialNumber = "urn:uuid:" + System.Guid.NewGuid().ToString();
            if (bom.Metadata is null) bom.Metadata = new Metadata();
            bom.Metadata.Timestamp = DateTime.UtcNow;
            if (bom.Metadata.Tools is null) bom.Metadata.Tools = new List<Tool>();
            if (!bom.Metadata.Tools.Exists(tool => tool.Name == thisTool.Name && tool.Version == thisTool.Version))
                bom.Metadata.Tools.Add(thisTool);

            if (options.OutputFormat == BomFormat.autodetect) options.OutputFormat = CliUtils.AutoDetectBomFormat(options.OutputFile);
            if (options.OutputFormat == BomFormat.autodetect)
            {
                Console.WriteLine($"Unable to auto-detect output format");
                return (int)ExitCode.ParameterValidationError;
            }

            if (string.IsNullOrEmpty(options.BasePath))
            {
                options.BasePath = Directory.GetCurrentDirectory();
            }
            options.BasePath = Path.GetFullPath(options.BasePath);

            if (!outputToConsole) Console.WriteLine($"Processing base path {options.BasePath}");

            if (options.Include == null) options.Include = new List<string> { "**/**" };
            if (options.Exclude == null) options.Exclude = new List<string>();

            var files = new HashSet<string>();

            foreach (var includePattern in options.Include)
            {
                if (!outputToConsole) Console.WriteLine($"Processing include pattern {includePattern}");
                var ant = new Ant(includePattern);
                var antDir = new AntDirectory(ant);
                var matchingFiles = antDir.SearchRecursively(options.BasePath);
                foreach (var file in matchingFiles)
                {
                    files.Add(file);
                }
            }

            foreach (var excludePattern in options.Exclude)
            {
                if (!outputToConsole) Console.WriteLine($"Processing exclude pattern {excludePattern}");
                var ant = new Ant(excludePattern);
                files.RemoveWhere(s => ant.IsMatch(s));
            }

            if (files.Count > 0)
            {
                if (bom.Components == null) bom.Components = new List<Component>();
            
                var existingFiles = bom.Components.Where<Component>(component => component.Type == Component.Clreplacedification.File);

                foreach (var file in files)
                {
                    // Ant file names are prefixed with "/"
                    var baseFilename = file.StartsWith("/", false, CultureInfo.InvariantCulture) ? file.Substring(1) : file;
                    if (!existingFiles.Any<Component>(component => component.Name == baseFilename))
                    {
                        if (!outputToConsole) Console.WriteLine($"Adding file {baseFilename}");
                        var fullPath = Path.Combine(options.BasePath, baseFilename);
                        var fileComponent = new Component
                        {
                            Type = Component.Clreplacedification.File,
                            Name = baseFilename,
                            Hashes = GetFileHashes(fullPath),
                        };
                        var shortHash = fileComponent.Hashes.First(h => h.Alg == Hash.HashAlgorithm.SHA_1).Content.Substring(0, 12);
                        fileComponent.Version = $"0.0.0-{shortHash}";
                        bom.Components.Add(fileComponent);
                    }
                    else
                    {
                        if (!outputToConsole) Console.WriteLine($"Skipping file {baseFilename} as it is already in the BOM");
                    }
                }
            }

            if (!outputToConsole) Console.WriteLine("Writing output file...");

            return await CliUtils.OutputBomHelper(bom, options.OutputFormat, options.OutputFile).ConfigureAwait(false);
        }

19 Source : Program.cs
with Apache License 2.0
from CycloneDX

async Task<int> OnExecuteAsync() {
            if (version)
            {
                Console.WriteLine(replacedembly.GetExecutingreplacedembly().GetName().Version?.ToString());
                return 0;
            }

            Console.WriteLine();

            // check parameter values
            if (string.IsNullOrEmpty(SolutionOrProjectFile)) {

                Console.Error.WriteLine($"A path is required");
                return (int)ExitCode.SolutionOrProjectFileParameterMissing;
            }

            if (string.IsNullOrEmpty(outputDirectory)) {
                Console.Error.WriteLine($"The output directory is required");
                return (int)ExitCode.OutputDirectoryParameterMissing;
            }

            if ((string.IsNullOrEmpty(githubUsername) ^ string.IsNullOrEmpty(githubToken))
                || (string.IsNullOrEmpty(githubUsernameDeprecated) ^ string.IsNullOrEmpty(githubTokenDeprecated)))
            {
                Console.Error.WriteLine($"Both GitHub username and token are required");
                return (int)ExitCode.GitHubParameterMissing;
            }

            dotnetCommandService.TimeoutMilliseconds = dotnetCommandTimeout;
            projectFileService.DisablePackageRestore = disablePackageRestore;

            // retrieve nuget package cache paths
            var packageCachePathsResult = dotnetUtilsService.GetPackageCachePaths();
            if (!packageCachePathsResult.Success)
            {
                Console.Error.WriteLine("Unable to find local package cache locations...");
                Console.Error.WriteLine(packageCachePathsResult.ErrorMessage);
                return (int)ExitCode.LocalPackageCacheError;
            }

            Console.WriteLine("Found the following local nuget package cache locations:");
            foreach (var path in packageCachePathsResult.Result)
            {
                Console.WriteLine($"    {path}");
            }

            // instantiate services

            var fileDiscoveryService = new FileDiscoveryService(Program.fileSystem);
            GithubService githubService = null;
            if (!(disableGithubLicenses || disableGithubLicensesDeprecated))
            {
                // GitHubService requires its own HttpClient as it adds a default authorization header
                if (!string.IsNullOrEmpty(githubBearerToken))
                {
                    githubService = new GithubService(new HttpClient(), githubBearerToken);
                }
                else if (!string.IsNullOrEmpty(githubBearerTokenDeprecated))
                {
                    githubService = new GithubService(new HttpClient(), githubBearerTokenDeprecated);
                }
                else if (!string.IsNullOrEmpty(githubUsername))
                {
                    githubService = new GithubService(new HttpClient(), githubUsername, githubToken);
                }
                else if (!string.IsNullOrEmpty(githubUsernameDeprecated))
                {
                    githubService = new GithubService(new HttpClient(), githubUsernameDeprecated, githubTokenDeprecated);
                }
                else
                {
                    githubService = new GithubService(new HttpClient());
                }
            }
            var nugetService = new NugetService(
                Program.fileSystem,
                packageCachePathsResult.Result,
                githubService,
                Program.httpClient,
                baseUrl);

            var packages = new HashSet<NugetPackage>();

            // determine what we are replacedyzing and do the replacedysis
            var fullSolutionOrProjectFilePath = Program.fileSystem.Path.GetFullPath(SolutionOrProjectFile);

            var topLevelComponent = new Component
            {
                // name is set below
                Version = string.IsNullOrEmpty(setVersion) ? "0.0.0" : setVersion,
                Type = setType == Component.Clreplacedification.Null ? Component.Clreplacedification.Application : setType,
            };

            try
            {
                if (SolutionOrProjectFile.ToLowerInvariant().EndsWith(".sln", StringComparison.OrdinalIgnoreCase))
                {
                    packages = await solutionFileService.GetSolutionNugetPackages(fullSolutionOrProjectFilePath, baseIntermediateOutputPath, excludetestprojects).ConfigureAwait(false);
                    topLevelComponent.Name = fileSystem.Path.GetFileNameWithoutExtension(SolutionOrProjectFile);
                }
                else if (Utils.IsSupportedProjectType(SolutionOrProjectFile) && scanProjectReferences)
                {
                    packages = await projectFileService.RecursivelyGetProjectNugetPackagesAsync(fullSolutionOrProjectFilePath, baseIntermediateOutputPath, excludetestprojects).ConfigureAwait(false);
                    topLevelComponent.Name = fileSystem.Path.GetFileNameWithoutExtension(SolutionOrProjectFile);
                }
                else if (Utils.IsSupportedProjectType(SolutionOrProjectFile))
                {
                    packages = await projectFileService.GetProjectNugetPackagesAsync(fullSolutionOrProjectFilePath, baseIntermediateOutputPath, excludetestprojects).ConfigureAwait(false);
                    topLevelComponent.Name = fileSystem.Path.GetFileNameWithoutExtension(SolutionOrProjectFile);
                }
                else if (Program.fileSystem.Path.GetFileName(SolutionOrProjectFile).ToLowerInvariant().Equals("packages.config", StringComparison.OrdinalIgnoreCase))
                {
                    packages = await packagesFileService.GetNugetPackagesAsync(fullSolutionOrProjectFilePath).ConfigureAwait(false);
                    topLevelComponent.Name = fileSystem.Path.GetDirectoryName(fullSolutionOrProjectFilePath);
                }
                else if (fileSystem.Directory.Exists(fullSolutionOrProjectFilePath))
                {
                    packages = await packagesFileService.RecursivelyGetNugetPackagesAsync(fullSolutionOrProjectFilePath).ConfigureAwait(false);
                    topLevelComponent.Name = fileSystem.Path.GetDirectoryName(fullSolutionOrProjectFilePath);
                }
                else
                {
                    Console.Error.WriteLine($"Only .sln, .csproj, .vbproj, and packages.config files are supported");
                    return (int)ExitCode.InvalidOptions;
                }
            }
            catch (DotnetRestoreException)
            {
                return (int)ExitCode.DotnetRestoreFailed;
            }

            if (!string.IsNullOrEmpty(setName))
            {
                topLevelComponent.Name = setName;
            }

            // get all the components and depdency graph from the NuGet packages
            var components = new HashSet<Component>();
            var dependencies = new List<Dependency>();
            var directDependencies = new Dependency { Dependencies = new List<Dependency>() };
            var transitiveDepencies = new HashSet<string>();
            try
            {
                var bomRefLookup = new Dictionary<string, string>();
                foreach (var package in packages)
                {
                    var component = await nugetService.GetComponentAsync(package).ConfigureAwait(false);
                    if (component != null
                        && (component.Scope != Component.ComponentScope.Excluded || !excludeDev)
                    )
                    {
                        components.Add(component);
                    }
                    bomRefLookup[component.Name.ToLower(CultureInfo.InvariantCulture)] = component.BomRef;
                }
                // now that we have all the bom ref lookups we need to enumerate all the dependencies
                foreach (var package in packages)
                {
                    var packageDepencies = new Dependency
                    {
                        Ref = bomRefLookup[package.Name.ToLower(CultureInfo.InvariantCulture)],
                        Dependencies = new List<Dependency>()
                    };
                    if (package.Dependencies != null)
                    {
                        foreach (var dep in package.Dependencies)
                        {
                            transitiveDepencies.Add(bomRefLookup[dep.ToLower(CultureInfo.InvariantCulture)]);
                            packageDepencies.Dependencies.Add(new Dependency
                            {
                                Ref = bomRefLookup[dep.ToLower(CultureInfo.InvariantCulture)]
                            });
                        }
                    }
                    dependencies.Add(packageDepencies);
                }
            }
            catch (InvalidGitHubApiCredentialsException)
            {
                return (int)ExitCode.InvalidGitHubApiCredentials;
            }
            catch (GitHubApiRateLimitExceededException)
            {
                return (int)ExitCode.GitHubApiRateLimitExceeded;
            }
            catch (GitHubLicenseResolutionException)
            {
                return (int)ExitCode.GitHubLicenseResolutionFailed;
            }
            // now we loop through all the dependencies to check which are direct
            foreach (var dep in dependencies)
            {
                if (!transitiveDepencies.Contains(dep.Ref))
                {
                    directDependencies.Dependencies.Add(new Dependency { Ref = dep.Ref });
                }
            }

            // create the BOM
            Console.WriteLine();
            Console.WriteLine("Creating CycloneDX BOM");
            var bom = new Bom
            {
                Version = 1,
            };

            if (!string.IsNullOrEmpty(importMetadataPath))
            {
                if (!File.Exists(importMetadataPath))
                {
                    Console.Error.WriteLine($"Metadata template '{importMetadataPath}' does not exist.");
                    return (int)ExitCode.InvalidOptions;
                }
                else
                {
                    bom = ReadMetaDataFromFile(bom, importMetadataPath);
                }
            }

            if (bom.Metadata is null)
            {
                bom.Metadata = new Metadata
                {
                    Component = topLevelComponent
                };
            }
            else if (bom.Metadata.Component is null)
            {
                bom.Metadata.Component = topLevelComponent;
            }
            else
            {
                if (string.IsNullOrEmpty(bom.Metadata.Component.Name))
                {
                    bom.Metadata.Component.Name = topLevelComponent.Name;
                }
                if (string.IsNullOrEmpty(bom.Metadata.Component.Version))
                {
                    bom.Metadata.Component.Version = topLevelComponent.Version;
                }
                if (bom.Metadata.Component.Type == Component.Clreplacedification.Null)
                {
                    bom.Metadata.Component.Type = Component.Clreplacedification.Application;
                }
            }

            if (string.IsNullOrEmpty(bom.Metadata.Component.BomRef))
            {
                bom.Metadata.Component.BomRef = $"{bom.Metadata.Component.Name}@{bom.Metadata.Component.Version}";
            }

            AddMetadataTool(bom);

            if (!(noSerialNumber || noSerialNumberDeprecated)) bom.SerialNumber = "urn:uuid:" + System.Guid.NewGuid().ToString();
            bom.Components = new List<Component>(components);
            bom.Components.Sort((x, y) => {
                if (x.Name == y.Name)
                    return string.Compare(x.Version, y.Version, StringComparison.InvariantCultureIgnoreCase);
                else
                    return string.Compare(x.Name, y.Name, StringComparison.InvariantCultureIgnoreCase);
            });
            bom.Dependencies = dependencies;
            directDependencies.Ref = bom.Metadata.Component.BomRef;
            bom.Dependencies.Add(directDependencies);
            bom.Dependencies.Sort((x, y) => string.Compare(x.Ref, y.Ref, StringComparison.InvariantCultureIgnoreCase));

            var bomContents = BomService.CreateDoreplacedent(bom, json);

            // check if the output directory exists and create it if needed
            var bomPath = Program.fileSystem.Path.GetFullPath(outputDirectory);
            if (!Program.fileSystem.Directory.Exists(bomPath))
                Program.fileSystem.Directory.CreateDirectory(bomPath);

            // write the BOM to disk
            var bomFilename = Program.fileSystem.Path.Combine(bomPath, json ? "bom.json" : "bom.xml");
            Console.WriteLine("Writing to: " + bomFilename);
            Program.fileSystem.File.WriteAllText(bomFilename, bomContents);

            return 0;
        }

19 Source : AddClient.cs
with MIT License
from CymaticLabs

public static int Main(string[] args) {
            if (args.Length < 1) {
                Console.Error.WriteLine("Usage: AddClient <uri> [<number> ...]");
                Console.Error.WriteLine("RabbitMQ .NET client version "+typeof(IModel).replacedembly.GetName().Version.ToString());
                Console.Error.WriteLine("Parameters:");
                Console.Error.WriteLine("  <uri> = \"amqp://user:preplaced@host:port/vhost\"");
                return 2;
            }

            ConnectionFactory cf = new ConnectionFactory();
            cf.Uri = args[0];

            using (IConnection conn = cf.CreateConnection()) {
                using (IModel ch = conn.CreateModel()) {

                    object[] addends = new object[args.Length - 1];
                    for (int i = 0; i < args.Length - 1; i++) {
                        addends[i] = double.Parse(args[i + 1]);
                    }

                    SimpleRpcClient client = new SimpleRpcClient(ch, "AddServer");
                    client.TimeoutMilliseconds = 5000;
                    client.TimedOut += new EventHandler(TimedOutHandler);
                    client.Disconnected += new EventHandler(DisconnectedHandler);
                    object[] reply = client.Call(addends);
                    if (reply == null) {
                        Console.WriteLine("Timeout or disconnection.");
                    } else {
                        Console.WriteLine("Reply: {0}", reply[0]);
                    }
                }
            }
            return 0;
        }

19 Source : AddServer.cs
with MIT License
from CymaticLabs

public static int Main(string[] args) {
            if (args.Length < 1) {
                Console.Error.WriteLine("Usage: AddServer <uri>");
                Console.Error.WriteLine("RabbitMQ .NET client version "+typeof(IModel).replacedembly.GetName().Version.ToString());
                Console.Error.WriteLine("Parameters:");
                Console.Error.WriteLine("  <uri> = \"amqp://user:preplaced@host:port/vhost\"");
                return 2;
            }

            ConnectionFactory cf = new ConnectionFactory();
            cf.Uri = args[0];
            using (IConnection conn = cf.CreateConnection()) {
                using (IModel ch = conn.CreateModel()) {
                    ch.QueueDeclare("AddServer", false, false, false, null);
                    Subscription sub = new Subscription(ch, "AddServer");
                    new AddServer(sub).MainLoop();
                }
            }
            return 0;
        }

19 Source : DeclareQueue.cs
with MIT License
from CymaticLabs

public static int Main(string[] args) {
            int optionIndex = 0;
            bool durable = false;
            bool delete = false;
            IDictionary<string, object> arguments = null;
            while (optionIndex < args.Length) {
                if (args[optionIndex] == "/durable") { durable = true; }
                else if (args[optionIndex] == "/delete") { delete = true; }
                else if (args[optionIndex].StartsWith("/arg:")) {
                    if (arguments == null) { arguments = new Dictionary<string, object>(); }
                    string[] pieces = args[optionIndex].Split(new Char[] { ':' });
                    if (pieces.Length >= 3) {
                        arguments[pieces[1]] = pieces[2];
                    }
                }
                else { break; }
                optionIndex++;
            }

            if (((args.Length - optionIndex) < 2) ||
                (((args.Length - optionIndex) % 2) != 0))
                {
                    Console.Error.WriteLine("Usage: DeclareQueue [<option> ...] <uri> <queue> [<exchange> <routingkey>] ...");
                    Console.Error.WriteLine("RabbitMQ .NET client version "+typeof(IModel).replacedembly.GetName().Version.ToString());
                    Console.Error.WriteLine("Parameters:");
                    Console.Error.WriteLine("  <uri> = \"amqp://user:preplaced@host:port/vhost\"");
                    Console.Error.WriteLine("Available options:");
                    Console.Error.WriteLine("  /durable      declare a durable queue");
                    Console.Error.WriteLine("  /delete       delete after declaring");
                    Console.Error.WriteLine("  /arg:KEY:VAL  add longstr entry to arguments table");
                    return 2;
                }

            string serverAddress = args[optionIndex++];
            string inputQueueName = args[optionIndex++];
            ConnectionFactory cf = new ConnectionFactory();
            cf.Uri = serverAddress;

            using (IConnection conn = cf.CreateConnection())
                {
                    using (IModel ch = conn.CreateModel()) {

                        string finalName = ch.QueueDeclare(inputQueueName, durable,
                                                           false, false, arguments);
                        Console.WriteLine("{0}\t{1}", finalName, durable);

                        while ((optionIndex + 1) < args.Length) {
                            string exchange = args[optionIndex++];
                            string routingKey = args[optionIndex++];
                            ch.QueueBind(finalName, exchange, routingKey, null);
                            Console.WriteLine("{0}\t{1}\t{2}", finalName, exchange, routingKey);
                        }

                        if (delete) {
                            ch.QueueDelete(finalName);
                        }

                        return 0;
                    }
                }
        }

See More Examples