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 : RCEPControl.cs
with MIT License
from 0x0ade

[RCEndpoint(true, "/asms", null, null, "replacedembly List", "List of all loaded replacedemblies.")]
        public static void ASMs(Frontend f, HttpRequestEventArgs c) {
            f.RespondJSON(c, AppDomain.CurrentDomain.Getreplacedemblies().Select(asm => new {
                asm.GetName().Name,
                Version = asm.GetName().Version?.ToString() ?? "",
                Context =
#if NETCORE
                    (replacedemblyLoadContext.GetLoadContext(asm) ?? replacedemblyLoadContext.Default)?.Name ?? "Unknown",
#else
                    AppDomain.CurrentDomain.FriendlyName
#endif
            }).ToList());
        }

19 Source : DataMapModInfo.cs
with MIT License
from 0x0ade

public override void Write(CelesteNetBinaryWriter writer) {
            writer.WriteNetString(MapSID);
            writer.WriteNetString(MapName);
            writer.WriteNetString(ModID);
            writer.WriteNetString(ModName);
            writer.WriteNetString(ModVersion.ToString());
        }

19 Source : DataModRec.cs
with MIT License
from 0x0ade

public override void Write(CelesteNetBinaryWriter writer) {
            writer.WriteNetString(ModID);
            writer.WriteNetString(ModName);
            writer.WriteNetString(ModVersion.ToString());
        }

19 Source : GetAssemblyVersion.cs
with zlib License
from 0x0ade

static void Main(string[] args)
	{
		Console.Write(replacedembly.LoadFile(args[0]).GetName().Version.ToString());
	}

19 Source : BuildInFormatters.cs
with MIT License
from 1996v

public void Serialize(ref BssomWriter writer, ref BssomSerializeContext context, Version value)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }
            writer.Write(value.ToString());
        }

19 Source : BuildInFormatters.cs
with MIT License
from 1996v

public int Size(ref BssomSizeContext context, Version value)
        {
            if (value == null)
            {
                return BssomBinaryPrimitives.NullSize;
            }

            return BssomBinaryPrimitives.StringSize(value.ToString()) + BssomBinaryPrimitives.BuildInTypeCodeSize;
        }

19 Source : CodeGenerate.cs
with MIT License
from 2881099

public async Task<string> Setup(TaskBuild taskBuild, string code, List<DbTableInfo> dbTables, DbTableInfo dbTableInfo)
        {
            StringBuilder plus = new StringBuilder();
            try
            {
                var config = new TemplateServiceConfiguration();
                config.EncodedStringFactory = new RawStringFactory();
                Engine.Razor = RazorEngineService.Create(config);
                var razorId = Guid.NewGuid().ToString("N");
                Engine.Razor.Compile(code, razorId);

                var sw = new StringWriter();
                var model = new RazorModel(taskBuild, dbTables, dbTableInfo);
                Engine.Razor.Run(razorId, sw, null, model);

                plus.AppendLine("//------------------------------------------------------------------------------");
                plus.AppendLine("// <auto-generated>");
                plus.AppendLine("//     此代码由工具生成。");
                plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                plus.AppendLine("//     Website: http://www.freesql.net");
                plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                plus.AppendLine("// </auto-generated>");
                plus.AppendLine("//------------------------------------------------------------------------------");
                plus.Append(sw.ToString());
                plus.AppendLine();
                return await Task.FromResult(plus.ToString());
            }
            catch
            {
                return await Task.FromResult(plus.ToString());
            }
        }

19 Source : CodeGenerate.cs
with MIT License
from 2881099

public async Task<string> Setup(TaskBuild taskBuild, List<DbTableInfo> outputTables)
        {
            try
            {
                var paths = await Task.Run(() =>
                {
                    var config = new TemplateServiceConfiguration();
                    config.EncodedStringFactory = new RawStringFactory();
                    Engine.Razor = RazorEngineService.Create(config);

                    string path = string.Empty;


                    foreach (var templatesPath in taskBuild.Templates)
                    {
                        path = $"{taskBuild.GeneratePath}\\{taskBuild.DbName}\\{templatesPath.Replace(".tpl", "").Trim()}";
                        if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                        var razorId = Guid.NewGuid().ToString("N");
                        var html = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Templates", templatesPath));
                        Engine.Razor.Compile(html, razorId);
                        //开始生成操作
                        foreach (var table in outputTables)
                        {
                            var sw = new StringWriter();
                            var model = new RazorModel(taskBuild, outputTables, table);
                            Engine.Razor.Run(razorId, sw, null, model);
                            StringBuilder plus = new StringBuilder();
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.AppendLine("// <auto-generated>");
                            plus.AppendLine("//     此代码由工具生成。");
                            plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                            plus.AppendLine("//     Website: http://www.freesql.net");
                            plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                            plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                            plus.AppendLine("// </auto-generated>");
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.Append(sw.ToString());
                            plus.AppendLine();
                            var outPath = $"{path}\\{taskBuild.FileName.Replace("{name}", model.GetCsName(table.Name))}";
                            if (!string.IsNullOrEmpty(taskBuild.RemoveStr))
                                outPath = outPath.Replace(taskBuild.RemoveStr, "").Trim();
                            File.WriteAllText(outPath, plus.ToString());
                        }
                    }
                    return path;
                });
                Process.Start(paths);
                return "生成成功";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成时发生异常,请检查模版代码: {ex.Message}.");
                return $"生成时发生异常,请检查模版代码: {ex.Message}.";
            }
        }

19 Source : CodeGenerate.cs
with MIT License
from 2881099

public async Task<string> Setup(Models.TaskBuild task)
        {



            try
            {
                var paths = await Task.Run(() =>
                 {

                     var config = new TemplateServiceConfiguration();
                     config.EncodedStringFactory = new RawStringFactory();
                     var service = RazorEngineService.Create(config);
                     Engine.Razor = service;


                     ///本次要操作的数据库
                     var dataBases = task.TaskBuildInfos.Where(a => a.Level == 1).ToList();

                     string path = string.Empty;

                     foreach (var db in dataBases)
                     {
                         //创建数据库连接
                         using (IFreeSql fsql = new FreeSql.FreeSqlBuilder()
                        .UseConnectionString(db.DataBaseConfig.DataType, db.DataBaseConfig.ConnectionStrings)
                        .Build())
                         {

                             //取指定数据库信息
                             var tables = fsql.DbFirst.GetTablesByDatabase(db.Name);
							 var outputTables = tables;

                             //是否有指定表
                             var uTables = task.TaskBuildInfos.Where(a => a.Level > 1).Select(a => a.Name).ToArray();
                             if (uTables.Length > 0)
                                 //过滤不要的表
                                 outputTables = outputTables.Where(a => uTables.Contains(a.Name)).ToList();

                             //根据用户设置组装生成路径并验证目录是否存在
                             path = $"{task.GeneratePath}\\{db.Name}";
                             if (!Directory.Exists(path))
                                 Directory.CreateDirectory(path);

							 var razorId = Guid.NewGuid().ToString("N");
							 Engine.Razor.Compile(task.Templates.Code, razorId);
                             //开始生成操作
                             foreach (var table in outputTables)
                             {
								 var sw = new StringWriter();
								 var model = new RazorModel(fsql, task, tables, table);
								 Engine.Razor.Run(razorId, sw, null, model);
 

                                 StringBuilder plus = new StringBuilder();
                                 plus.AppendLine("//------------------------------------------------------------------------------");
                                 plus.AppendLine("// <auto-generated>");
                                 plus.AppendLine("//     此代码由工具生成。");
                                 plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                                 plus.AppendLine("//     Website: http://www.freesql.net");
                                 plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                                 plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                                 plus.AppendLine("// </auto-generated>");
                                 plus.AppendLine("//------------------------------------------------------------------------------");

                                 plus.Append(sw.ToString());

                                 plus.AppendLine();
                                 File.WriteAllText($"{path}\\{task.FileName.Replace("{name}", model.GetCsName(table.Name))}", plus.ToString());
                             }
                         }
                     }
                     return path;
                 });

                Process.Start(paths);
                return "生成成功";
            }
            catch (Exception ex)
            {
                return "生成时发生异常,请检查模版代码.";
            }


        }

19 Source : Machine.cs
with MIT License
from 3RD-Dimension

private void ParseStartup(string line)
        {     // TODO Kinda Successfull, still need to find a way to ask for it just after recieving OK message on Connection
            Match m = StartupRegex.Match(line);

            int major, minor;
            char rev;

            if (!m.Success ||
                !int.TryParse(m.Groups[1].Value, out major) ||
                !int.TryParse(m.Groups[2].Value, out minor) ||
                !char.TryParse(m.Groups[3].Value, out rev))
            {
                RaiseEvent(Info, "Could not read GRBL Version.");
                return;
            }
            // TODO Display current GRBL version in the Connection or About box
            Version v = new Version(major, minor, (int)rev);
            GRBL_Version = v.ToString();
            Console.WriteLine("GRBL Version is " + GRBL_Version);
            if (v < Constants.MinimumGrblVersion)
            {
                ReportError("Outdated version of grbl detected!");
                ReportError($"Please upgrade to at least grbl v{Constants.MinimumGrblVersion.Major}.{Constants.MinimumGrblVersion.Minor}{(char)Constants.MinimumGrblVersion.Build}");
            }

        }

19 Source : UwpAppxBuildTools.cs
with Apache License 2.0
from abist-co-ltd

private static bool UpdateAppxManifest(IBuildInfo buildInfo)
        {
            string manifestFilePath = GetManifestFilePath(buildInfo);
            if (manifestFilePath == null)
            {
                // Error has already been logged
                return false;
            }

            var rootNode = XElement.Load(manifestFilePath);
            var idenreplacedyNode = rootNode.Element(rootNode.GetDefaultNamespace() + "Idenreplacedy");

            if (idenreplacedyNode == null)
            {
                Debug.LogError($"Package.appxmanifest for build (in path - {manifestFilePath}) is missing an <Idenreplacedy /> node");
                return false;
            }

            var dependencies = rootNode.Element(rootNode.GetDefaultNamespace() + "Dependencies");

            if (dependencies == null)
            {
                Debug.LogError($"Package.appxmanifest for build (in path - {manifestFilePath}) is missing <Dependencies /> node.");
                return false;
            }

            UpdateDependenciesElement(dependencies, rootNode.GetDefaultNamespace());
            AddCapabilities(buildInfo, rootNode);

            // We use XName.Get instead of string -> XName implicit conversion because
            // when we preplaced in the string "Version", the program doesn't find the attribute.
            // Best guess as to why this happens is that implicit string conversion doesn't set the namespace to empty
            var versionAttr = idenreplacedyNode.Attribute(XName.Get("Version"));

            if (versionAttr == null)
            {
                Debug.LogError($"Package.appxmanifest for build (in path - {manifestFilePath}) is missing a Version attribute in the <Idenreplacedy /> node.");
                return false;
            }

            // replacedume package version always has a '.' between each number.
            // According to https://msdn.microsoft.com/library/windows/apps/br211441.aspx
            // Package versions are always of the form Major.Minor.Build.Revision.
            // Note: Revision number reserved for Windows Store, and a value other than 0 will fail WACK.
            var version = PlayerSettings.WSA.packageVersion;
            var newVersion = new Version(version.Major, version.Minor, buildInfo.AutoIncrement ? version.Build + 1 : version.Build, version.Revision);

            PlayerSettings.WSA.packageVersion = newVersion;
            versionAttr.Value = newVersion.ToString();
            rootNode.Save(manifestFilePath);
            return true;
        }

19 Source : OVRPluginUpdater.cs
with MIT License
from absurd-joy

public static string GetVersionDescription(System.Version version)
	{
		bool isVersionValid = (version != invalidVersion);
		return isVersionValid ? version.ToString() : "(Unknown)";
	}

19 Source : ONSPAudioPluginUpdater.cs
with MIT License
from absurd-joy

public static string GetVersionDescription(System.Version version)
    {
        bool isVersionValid = (version != invalidVersion);
        return isVersionValid ? version.ToString() : "(Unknown)";
    }

19 Source : ExportExampleHelper.cs
with MIT License
from ABTSoftware

public static string GetSciChartVersion()
        {
            var replacedemblyName = new replacedemblyName(typeof(SciChartSurface).replacedembly.FullName);
            return replacedemblyName.Version.ToString();
        }

19 Source : GitCliManager.cs
with MIT License
from actions

public async Task LoadGitExecutionInfo(RunnerActionPluginExecutionContext context)
        {
            // Resolve the location of git.
            gitPath = WhichUtil.Which("git", require: true, trace: context);
            ArgUtil.File(gitPath, nameof(gitPath));

            // Get the Git version.    
            gitVersion = await GitVersion(context);
            ArgUtil.NotNull(gitVersion, nameof(gitVersion));
            context.Debug($"Detect git version: {gitVersion.ToString()}.");

            // Resolve the location of git-lfs.
            // This should be best effort since checkout lfs objects is an option.
            // We will check and ensure git-lfs version later
            gitLfsPath = WhichUtil.Which("git-lfs", require: false, trace: context);

            // Get the Git-LFS version if git-lfs exist in %PATH%.
            if (!string.IsNullOrEmpty(gitLfsPath))
            {
                gitLfsVersion = await GitLfsVersion(context);
                context.Debug($"Detect git-lfs version: '{gitLfsVersion?.ToString() ?? string.Empty}'.");
            }

            // required 2.0, all git operation commandline args need min git version 2.0
            Version minRequiredGitVersion = new Version(2, 0);
            EnsureGitVersion(minRequiredGitVersion, throwOnNotMatch: true);

            // suggest user upgrade to 2.9 for better git experience
            Version recommendGitVersion = new Version(2, 9);
            if (!EnsureGitVersion(recommendGitVersion, throwOnNotMatch: false))
            {
                context.Output($"To get a better Git experience, upgrade your Git to at least version '{recommendGitVersion}'. Your current Git version is '{gitVersion}'.");
            }

            // Set the user agent.
            string gitHttpUserAgentEnv = $"git/{gitVersion.ToString()} (github-actions-runner-git/{BuildConstants.RunnerPackage.Version})";
            context.Debug($"Set git useragent to: {gitHttpUserAgentEnv}.");
            gitEnv["GIT_HTTP_USER_AGENT"] = gitHttpUserAgentEnv;
        }

19 Source : AdminTaskHandler.cs
with GNU General Public License v3.0
from AdhocAdam

public override void ExecuteCommand(IList<NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection<string> parameters)
        {
            /* 
            This GUID is generated automatically when you import the Management Pack with the singleton admin setting clreplaced in it. 
            You can get this GUID by running a query like: 
            Select BaseManagedEnreplacedyID, FullName where FullName like ‘%<enter your clreplaced ID here>%’ 
            where the GUID you want is returned in the BaseManagedEnreplacedyID column in the result set 
            */
            /*In this above example I imported the MP, and then used:
                Select BaseManagedEnreplacedyID, FullName
                From BaseManagedEnreplacedy
                where FullName like 'SMLets%'
              against the ServiceManager DB to figure out the following strSingletonBaseManagedObjectID. Per 
              https://blogs.technet.microsoft.com/servicemanager/2011/05/26/getting-management-pack-elements-using-the-sdk/
              the id is always unique and never changes as its based on the MP ID, Element Names, and the key token.
             */

            String strSingletonBaseManagedObjectID = "a0022e87-75a8-65ee-4581-d923ff06a564";

            //Get the server name to connect to and connect to the server 
            String strServerName = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString();
            EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName);
            
            //Get the Object using the GUID from above – since this is a singleton object we can get it by GUID 
            EnterpriseManagementObject emoAdminSetting = emg.EnreplacedyObjects.GetObject<EnterpriseManagementObject>(new Guid(strSingletonBaseManagedObjectID), ObjectQueryOptions.Default);

            //Get the SMLets Exchange Connector MP
            ManagementPack smletsMP = emg.ManagementPacks.GetManagementPack(new Guid("15d8b765-a2f8-b63e-ad14-472f9b3c12f0"));
            
            //Create a new "wizard" (also used for property dialogs as in this case), set the replacedle bar, create the data, and add the pages 
            WizardStory wizard = new WizardStory();
            wizard.WizardWindowreplacedle = "SMLets Exchange Connector Settings v" + smletsMP.Version.ToString();
            WizardData data = new AdminSettingWizardData(emoAdminSetting);
            wizard.WizardData = data;
            wizard.AddLast(new WizardStep("General", typeof(GeneralSettingsForm), wizard.WizardData));
            wizard.AddLast(new WizardStep("DLL", typeof(DLLForm), wizard.WizardData));
            wizard.AddLast(new WizardStep("Processing Logic", typeof(ProcessingLogicForm), wizard.WizardData));
            wizard.AddLast(new WizardStep("File Attachments", typeof(FileAttachmentForm), wizard.WizardData));
            wizard.AddLast(new WizardStep("Templates", typeof(TemplateForm), wizard.WizardData));
            wizard.AddLast(new WizardStep("Multi-Mailbox", typeof(MultipleMailboxes), wizard.WizardData));
            wizard.AddLast(new WizardStep("Parsing Keywords", typeof(KeywordsForm), wizard.WizardData));
            wizard.AddLast(new WizardStep("Cireson", typeof(CiresonIntegrationForm), wizard.WizardData));
            wizard.AddLast(new WizardStep("Announcements", typeof(AnnouncementsForm), wizard.WizardData));
            wizard.AddLast(new WizardStep("SCOM", typeof(SCOMIntegrationForm), wizard.WizardData));
            wizard.AddLast(new WizardStep("A.I.", typeof(ArtificialIntelligence), wizard.WizardData));
            wizard.AddLast(new WizardStep("Translation", typeof(AzureTranslate), wizard.WizardData));
            wizard.AddLast(new WizardStep("Vision", typeof(AzureVision), wizard.WizardData));
            wizard.AddLast(new WizardStep("Transcription", typeof(AzureSpeech), wizard.WizardData));
            wizard.AddLast(new WizardStep("Workflow", typeof(WorkflowSettings), wizard.WizardData));
            wizard.AddLast(new WizardStep("Logging", typeof(Logging), wizard.WizardData));
            wizard.AddLast(new WizardStep("History", typeof(HistoryForm), wizard.WizardData));
            wizard.AddLast(new WizardStep("About", typeof(AboutForm), wizard.WizardData));

            //Show the property page 
            PropertySheetDialog wizardWindow = new PropertySheetDialog(wizard);
            wizardWindow.Width = 1100;
            wizardWindow.Height = 700;

            //Update the view when done so the new values are shown 
            bool? dialogResult = wizardWindow.ShowDialog();
            if (dialogResult.HasValue && dialogResult.Value)
            {
                RequestViewRefresh();
            }
        }

19 Source : AppInfoMiddleware.cs
with MIT License
from Adoxio

private string GetInfo()
		{
			var replacedembly = Getreplacedembly();
			var version = replacedembly.Version.ToString();
			var info = new JObject(new JProperty("version", version));

			return info.ToString(Formatting.Indented);
		}

19 Source : AutoUpdater.cs
with MIT License
from adrianmteo

public async Task CheckForUpdates(bool force)
        {
            if (Model.Status == UpdateStatus.Checking)
            {
                Logger.Warning("Cannot check for new updates because the status says it's already checking for one");
                return;
            }

            if (!force && Model.LastCheckInMinutes < 30)
            {
                Logger.Warning("Cannot check for new updates because the last check was less than 30m");
                return;
            }

            Logger.Info("Checking for updates...");

            Model.LastCheck = DateTime.Now;
            Model.Status = UpdateStatus.Checking;

            JsonDownloader jsonDownloader = new JsonDownloader();

            try
            {
                GithubModel response = await jsonDownloader.GetObject<GithubModel>("https://api.github.com/repos/adrianmteo/Luna/releases/latest");

                Version newVersion = new Version(response.tag_name.Substring(1));

                if (newVersion > LocalVersion)
                {
                    Logger.Info("Found new update with version {0}", newVersion);

                    GithubModel.replacedets replacedet = response.replacedets.First(e => e.name.ToLower().Contains("exe"));

                    Model.Version = newVersion.ToString();
                    Model.Changelog = response.body;
                    Model.DownloadUrl = replacedet.browser_download_url;
                    Model.DownloadName = replacedet.name;

                    if (AutoUpdate)
                    {
                        await DownloadUpdate();
                    }
                    else
                    {
                        Model.Status = UpdateStatus.NewUpdate;
                    }
                }
                else
                {
                    Logger.Info("No new updates found...");

                    Model.Status = UpdateStatus.NoUpdate;
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);

                Model.Status = UpdateStatus.Error;
            }
        }

19 Source : CSharpSmartContractRunner.cs
with MIT License
from AElfProject

public virtual async Task<IExecutive> RunAsync(SmartContractRegistration reg)
        {
            var code = reg.Code.ToByteArray();

            var loadContext = GetLoadContext();

            replacedembly replacedembly = Loadreplacedembly(code, loadContext);

            if (replacedembly == null)
            {
                throw new InvalidreplacedemblyException("Invalid binary code.");
            }

            ContractVersion = replacedembly.GetName().Version?.ToString();

            var executive = new Executive(replacedembly)
            {
                ContractHash = reg.CodeHash,
                ContractVersion = ContractVersion
            };
            
            // replacedemblyLoadContext needs to be called after initializing the Executive
            // to ensure that it is not unloaded early in release mode.
            loadContext.Unload();

            return await Task.FromResult(executive);
        }

19 Source : NetAppServiceTest.cs
with MIT License
from AElfProject

[Fact]
        public async Task GetNetWorkInfo_Test()
        {
            var connectionTime = TimestampHelper.GetUtcNow();
            var ipAddressOne = "192.168.1.1:1680";
            var onePubkey = "048f5ced21f8d687cb9ade1c22dc0e183b05f87124c82073f5d82a09b139cc466efbfb6f28494d0a9d7366fcb769fe5436cfb7b5d322a2b0f69c4bcb1c33ac24ad";
            
            var peerOne = BuildPeer(ipAddressOne, onePubkey, connectionTime, true);
            _peerPool.TryAddPeer(peerOne);
            
            var ipAddressTwo = "192.168.1.2:1680";
            var twoPubkey = "040a7bf44d2c79fe5e270943773783a24eed5cda3e71fa49470cdba394a23832d5c831e233cddebea2720c194dffadd656d4dedf84643818ca77edeee17ad4307a";
            
            var peerTwo = BuildPeer(ipAddressTwo, twoPubkey, connectionTime, false);
            _peerPool.TryAddPeer(peerTwo);
            
            var peers = await GetResponseAsObjectAsync<List<PeerDto>>("api/net/peers");
            
            var networkInfo = await GetResponseAsObjectAsync<GetNetworkInfoOutput>("/api/net/networkInfo");
            networkInfo.Version.ShouldBe(typeof(NetApplicationWebAppAElfModule).replacedembly.GetName().Version.ToString());
            networkInfo.ProtocolVersion.ShouldBe(KernelConstants.ProtocolVersion);
            networkInfo.Connections.ShouldBe(peers.Count);
        }

19 Source : Version.cs
with Mozilla Public License 2.0
from ahyahy

public new string ToString()
        {
            return M_Version.ToString();
        }

19 Source : VersionService.cs
with MIT License
from AiursoftWeb

private static string SDKVersion()
        {
            var version = replacedembly.GetExecutingreplacedembly().GetName().Version?.ToString().Split('.');
            if (version == null)
            {
                return null;
            }
            return $"{version[0]}.{version[1]}.{version[2]}";
        }

19 Source : VersionConverter.cs
with MIT License
from AkiniKites

public override void WriteJson(JsonWriter writer, Version value, JsonSerializer serializer)
        {
            if (value != null)
            {
                writer.WriteValue(value.ToString());
            }
            else
            {
                writer.WriteNull();
            }
        }

19 Source : AboutDialog.xaml.cs
with GNU Affero General Public License v3.0
from akshinmustafayev

public void LoadDataInfoIntoTheForm()
        {
            Aboutreplacedle.Content = "EasyJob Executor " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString();
            AboutInfo.Content = "Author: Akshin Mustafayev. Contrubutions made to the project by the Github community";
            string readme = CommonUtils.ReadreplacedemblyFile("LICENSE.txt");
            RichTextBox1.Doreplacedent.Blocks.Clear();
            var plainText = ConvertToPlainText(readme);
            RichTextBox1.AppendText(plainText);
        }

19 Source : DependencyChecker.cs
with GNU General Public License v3.0
from Albo1125

public static bool DependencyCheckMain(string CallingPlugin, Version Albo1125CommonVer, float MinimumRPHVersion, string installationVideoURL, Version MadeForGTAVersion = null, Version MadeForLSPDFRVersion = null, Version RAGENativeUIVersion = null, string[] AudioFilesToCheckFor = null, string[] OtherRequiredFilesToCheckFor = null)
        {
            bool CheckPreplacededSuccessfully = true;
            Game.LogTrivial("Albo1125.Common.dll " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + " starting standard dependency check for " + CallingPlugin);
            if (scid == null)
            {
                scid = NativeFunction.Natives.GET_PLAYER_NAME<string>(Game.LocalPlayer);
                Game.LogTrivial("SCID:/" + scid + "/");
            }
            if (File.Exists("Albo1125.Common.dll"))
            {
                Version InstalledCommonVer = new Version(FileVersionInfo.GetVersionInfo("Albo1125.Common.dll").ProductVersion);
                if (InstalledCommonVer.CompareTo(Albo1125CommonVer) >= 0)
                {
                    if (MadeForGTAVersion != null)
                    {
                        Game.LogTrivial("GAME VERSION: " + Game.ProductVersion.ToString());
                        int compare = Game.ProductVersion.CompareTo(MadeForGTAVersion);
                        if (compare > 0)
                        {
                            Game.LogTrivial(CallingPlugin + " compatibility warning: The current game version is newer than " + MadeForGTAVersion.ToString() + " and may or may not be incompatible due to RPH changes. Use at own risk.");
                        }
                    }

                    if (MadeForLSPDFRVersion != null)
                    {
                        if (File.Exists("Plugins/LSPD First Response.dll"))
                        {
                            Version InstalledLSPDFRVer = new Version(FileVersionInfo.GetVersionInfo("Plugins/LSPD First Response.dll").ProductVersion);
                            if (InstalledLSPDFRVer.CompareTo(MadeForLSPDFRVersion) != 0)
                            {
                                Game.LogTrivial(CallingPlugin + " compatibility warning: Different LSPD First Response.dll version detected, use at your own risk! This mod was made for LSPDFR " + MadeForLSPDFRVersion.ToString());
                                Game.DisplayNotification(CallingPlugin + " compatibility warning: Different LSPD First Response.dll version detected, use at your own risk! This mod was made for LSPDFR " + MadeForLSPDFRVersion.ToString());
                                //Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "Detected invalid LSPD First Response.dll version. To run this mod, you need LSPDFR " + MadeForLSPDFRVersion.ToString());
                                //CheckPreplacededSuccessfully = false;
                            }
                        }
                        else
                        {
                            Game.LogTrivial("LSPD First Response.dll not installed.");
                            Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "Couldn't detect required LSPD First Response.dll. You must install it.");
                            CheckPreplacededSuccessfully = false;
                        }

                    }
                    if (RAGENativeUIVersion != null)
                    {
                        if (File.Exists("RAGENativeUI.dll"))
                        {
                            Version InstalledNativeUIVer = new Version(FileVersionInfo.GetVersionInfo("RAGENativeUI.dll").ProductVersion);
                            if (InstalledNativeUIVer.CompareTo(RAGENativeUIVersion) < 0)
                            {
                                Game.LogTrivial("RAGENativeUI.dll out of date. Required version of RAGENativeUI to run this mod: " + RAGENativeUIVersion);
                                Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "RAGENativeUI.dll out of date. Required version of RAGENativeUI to run this mod: " + RAGENativeUIVersion);
                                CheckPreplacededSuccessfully = false;
                            }
                        }
                        else
                        {
                            Game.LogTrivial("RAGENativeUI.dll is not installed. You must install it to run this mod.");
                            Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "RAGENativeUI.dll is not installed. You must install it to run this mod.");
                            CheckPreplacededSuccessfully = false;
                        }
                    }
                    if (AudioFilesToCheckFor != null)
                    {
                        foreach (string s in AudioFilesToCheckFor)
                        {
                            if (!File.Exists(s))
                            {
                                Game.LogTrivial("Couldn't find the required audio file at " + s);
                                Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "You are missing required (new) audio files. Path is: " + s);

                                CheckPreplacededSuccessfully = false;
                            }
                        }
                    }
                    if (OtherRequiredFilesToCheckFor != null)
                    {
                        foreach (string s in OtherRequiredFilesToCheckFor)
                        {
                            if (!File.Exists(s))
                            {
                                Game.LogTrivial("Couldn't find the required file at " + s);
                                Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "You are missing required (new) files. Path is: " + s);
                                CheckPreplacededSuccessfully = false;
                            }
                        }

                    }
                    if (!CheckForRageVersion(MinimumRPHVersion))
                    {
                        CheckPreplacededSuccessfully = false;
                        Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "RAGEPluginHook is out of date. This mod requires RPH " + MinimumRPHVersion);
                    }

                }
                else
                {
                    Game.LogTrivial("Albo1125.Common.dll is out of date. This mod requires Albo1125.Common " + Albo1125CommonVer);
                    Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "Albo1125.Common.dll is out of date. This mod requires Albo1125.Common " + Albo1125CommonVer);
                    CheckPreplacededSuccessfully = false;
                }
            }
            else
            {
                CheckPreplacededSuccessfully = false;
                Game.LogTrivial("Albo1125.Common.dll is not installed. This mod requires Albo1125.Common to be installed. You've successfully run this without actually having it on your PC...spooky.");
                Plugins_URL_Errors.Add(CallingPlugin, installationVideoURL, "Albo1125.Common.dll is not installed. This mod requires Albo1125.Common to be installed. You've successfully run this without actually having it on your PC...spooky.");
            }
            if (RegisteredPluginsForDependencyChecks.Contains(CallingPlugin)) { RegisteredPluginsForDependencyChecks.Remove(CallingPlugin); }
            if (RegisteredPluginsForDependencyChecks.Count == 0 && Plugins_URL_Errors.Count > 0) { DisplayDependencyErrors(); }

            Game.LogTrivial("Dependency check for " + CallingPlugin + " successful: " + CheckPreplacededSuccessfully);
            return CheckPreplacededSuccessfully;

        }

19 Source : UpdateChecker.cs
with GNU General Public License v3.0
from Albo1125

public static void InitialiseUpdateCheckingProcess()
        {
            Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Starting update checks.");
            Directory.CreateDirectory("Albo1125.Common/UpdateInfo");
            if (!File.Exists("Albo1125.Common/CommonVariables.xml"))
            {
                new XDoreplacedent(
                        new XElement("CommonVariables")
                    )
                    .Save("Albo1125.Common/CommonVariables.xml");
            }
            try
            {
                XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                if (!string.IsNullOrWhiteSpace((string)CommonVariablesDoc.Root.Element("NextUpdateCheckDT")))
                {

                    try
                    {
                        if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value == replacedembly.GetExecutingreplacedembly().GetName().Version.ToString())
                        {
                            Game.LogTrivial("Albo1125.Common update checking has been disabled. Skipping checks.");
                            Game.LogTrivial("Albo1125.Common note: please do not request support for old versions.");
                            return;
                        }
                        DateTime UpdateCheckDT = DateTime.FromBinary(long.Parse(CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value));
                        if (DateTime.Now < UpdateCheckDT)
                        {

                            Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Not checking for updates until " + UpdateCheckDT.ToString());
                            return;
                        }
                    }
                    catch (Exception e) { Game.LogTrivial(e.ToString()); Game.LogTrivial("Albo1125.Common handled exception. #1"); }

                }

                
                DateTime NextUpdateCheckDT = DateTime.Now.AddDays(1);
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = NextUpdateCheckDT.ToBinary().ToString();
                CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
                CommonVariablesDoc = null;
                GameFiber.StartNew(delegate
                {


                    GetUpdateNodes();
                    foreach (UpdateEntry entry in AllUpdateEntries.ToArray())
                    {
                        CheckForModificationUpdates(entry.Name, new Version(FileVersionInfo.GetVersionInfo(entry.Path).FileVersion), entry.FileID, entry.DownloadLink);
                    }
                    if (PluginsDownloadLink.Count > 0) { DisplayUpdates(); }
                    Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Update checks complete.");
                });
            }
            catch (System.Xml.XmlException e)
            {
                Game.LogTrivial(e.ToString());
                Game.DisplayNotification("Error while processing XML files. To fix this, please delete the following folder and its contents: Grand Theft Auto V/Albo1125.Common");
                Albo1125.Common.CommonLibrary.ExtensionMethods.DisplayPopupTextBoxWithConfirmation("Albo1125.Common", "Error while processing XML files. To fix this, please delete the following folder and its contents: Grand Theft Auto V/Albo1125.Common", false);
                throw e;
            }

            



        }

19 Source : Main.cs
with GNU General Public License v3.0
from Albo1125

public override void Initialize()
        {
            //Event handler for detecting if the player goes on duty
            Game.LogTrivial("Arrest Manager " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125, loaded successfully!");
            
            Game.LogTrivial("Please go on duty to start Arrest Manager.");

            Functions.OnOnDutyStateChanged += Functions_OnOnDutyStateChanged;

        }

19 Source : UpdateChecker.cs
with GNU General Public License v3.0
from Albo1125

private static void NextUpdateCallback(Popup p)
        {
            if (p.IndexOfGivenAnswer == 0)
            {
                Game.LogTrivial("Continue pressed");
                Index++;
                if (PluginsDownloadLink.Count > Index)
                {
                    Popup pop = new Popup("Albo1125.Common Update Check", "Update " + (Index + 1) + ": " + PluginsDownloadLink[Index].Item1, new List<string>() { "Continue", "Go to download page" },
                        false, false, NextUpdateCallback);
                    pop.Display();
                }
                else
                {
                    Popup pop = new Popup("Albo1125.Common Update Check", "Please install updates to maintain stability and don't request support for old versions.",
                        new List<string>() { "-", "Open installation/troubleshooting video tutorial", "Continue to game.", "Delay next update check by a week.", "Delay next update check by a month.",
                            "Fully disable update checks (not recommended)." }, false, false, NextUpdateCallback);
                    pop.Display();
                }
            }
            else if (p.IndexOfGivenAnswer == 1)
            {
                Game.LogTrivial("GoToDownload pressed.");
                if (PluginsDownloadLink.Count > Index && Index >= 0)
                {
                    System.Diagnostics.Process.Start(PluginsDownloadLink[Index].Item2);
                }
                else
                {
                    System.Diagnostics.Process.Start("https://youtu.be/af434m72rIo?list=PLEKypmos74W8PMP4k6xmVxpTKdebvJpFb");
                }
                p.Display();
            }
            else if (p.IndexOfGivenAnswer == 2)
            {
                Game.LogTrivial("ExitButton pressed.");
            }
            else if (p.IndexOfGivenAnswer == 3)
            {
                Game.LogTrivial("Delay by week pressed");
                DateTime NextUpdateCheckDT = DateTime.Now.AddDays(6);
                XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = NextUpdateCheckDT.ToBinary().ToString();
                CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
                CommonVariablesDoc = null;
            }
            else if (p.IndexOfGivenAnswer == 4)
            {
                Game.LogTrivial("Delay by month pressed");
                DateTime NextUpdateCheckDT = DateTime.Now.AddMonths(1);
                XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = NextUpdateCheckDT.ToBinary().ToString();
                CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
                CommonVariablesDoc = null;
            }
            else if (p.IndexOfGivenAnswer == 5)
            {
                Game.LogTrivial("Disable Update Checks pressed.");
                XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString();
                CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
                CommonVariablesDoc = null;
                Popup pop = new Popup("Albo1125.Common Update Check", "Update checking has been disabled for this version of Albo1125.Common." +
                    "To re-enable it, delete the Albo1125.Common folder from your Grand Theft Auto V folder. Please do not request support for old versions.", false, true);
                pop.Display();
            }
        }

19 Source : Main.cs
with GNU General Public License v3.0
from Albo1125

public override void Initialize()
        {
            //Event handler for detecting if the player goes on duty

            Functions.OnOnDutyStateChanged += Functions_OnOnDutyStateChanged;
            Game.LogTrivial("replacedorted Callouts " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() +", developed by Albo1125, has been initialised.");
            Game.LogTrivial("Go on duty to start replacedorted Callouts.");


        }

19 Source : Main.cs
with GNU General Public License v3.0
from Albo1125

public override void Initialize()
        {
            Game.Console.Print("PoliceSmartRadio " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125, loaded successfully!");
            Game.Console.Print("Special thanks to FinKone for the inspiration and OfficerSquare for the default UI.");
            Game.Console.Print("Please go on duty to start Police SmartRadio.");

            Functions.OnOnDutyStateChanged += Functions_OnOnDutyStateChanged;
        }

19 Source : Main.cs
with GNU General Public License v3.0
from Albo1125

public static void Functions_OnOnDutyStateChanged(bool onDuty)
        {
            if (onDuty)
            {
                Albo1125.Common.UpdateChecker.InitialiseUpdateCheckingProcess();
                if (Albo1125.Common.DependencyChecker.DependencyCheckMain(PluginName, Albo1125CommonVer, MinimumRPHVersion, MadeForGTAVersion, MadeForLSPDFRVersion, AudioFilesToCheckFor : AudioFilesToCheckFor, OtherRequiredFilesToCheckFor : OtherFilesToCheckFor))
                {
                    if (!Albo1125.Common.DependencyChecker.CheckIfThereAreNoConflictingFiles(PluginName, conflictingFiles))
                    {
                        Game.LogTrivial("Old Police Radio still installed.");
                        Game.DisplayNotification("~r~~h~Police SmartRadio detected the old PoliceRadio modification. You must delete it before using Police SmartRadio.");
                        Albo1125.Common.CommonLibrary.ExtensionMethods.DisplayPopupTextBoxWithConfirmation("Police SmartRadio Dependencies", "Police SmartRadio detected the old PoliceRadio modification. You must delete it before using Police SmartRadio. Unloading...", true);
                        return;
                    }
                    if (!Albo1125.Common.DependencyChecker.CheckIfFileExists("Plugins/LSPDFR/Traffic Policer.dll", TrafficPolicerVersion))
                    {
                        Game.LogTrivial("Traffic Policer is out of date for LSPDR+. Aborting. Required version: " + TrafficPolicerVersion.ToString());
                        Game.DisplayNotification("~r~~h~Police SmartRadio detected Traffic Policer version lower than ~b~" + TrafficPolicerVersion.ToString());
                        Albo1125.Common.CommonLibrary.ExtensionMethods.DisplayPopupTextBoxWithConfirmation("Police SmartRadio Dependencies", "Police SmartRadio did not detect Traffic Policer or detected Traffic Policer version lower than " + TrafficPolicerVersion.ToString() + ". Please install the appropriate version of Traffic Policer (link under Requirements on the download page). Unloading Police SmartRadio...", true);
                        return;
                    }
                    if (!Albo1125.Common.DependencyChecker.CheckIfFileExists("Plugins/LSPDFR/Arrest Manager.dll", ArrestManagerVersion))
                    {
                        //Game.LogTrivial("Arrest Manager is out of date for Police SmartRadio. Aborting. Required version: " + ArrestManagerVersion.ToString());
                        Game.DisplayNotification("~r~Police SmartRadio is optimized for use with the latest Arrest Manager - you are advised to install it.");
                        //Albo1125.Common.CommonLibrary.ExtensionMethods.DisplayPopupTextBoxWithConfirmation("Police SmartRadio Dependencies", "Police SmartRadio did not detect Arrest Manager or detected Arrest Manager version lower than " + ArrestManagerVersion.ToString() + ". Please install the appropriate version of Arrest Manager (link under Requirements on the download page). Unloading Police SmartRadio...", true);
                    }
                    GameFiber.StartNew(delegate
                    {
                        AppDomain.CurrentDomain.replacedemblyResolve += new ResolveEventHandler(ResolvereplacedemblyEventHandler);
                        while (!IsLSPDFRPluginRunning("Traffic Policer"))
                        {
                            GameFiber.Yield();
                        }
                        PoliceSmartRadio.Initialise();

                    });
                }
            }
        }

19 Source : Main.cs
with GNU General Public License v3.0
from Albo1125

public override void Initialize()
        {
            //Event handler for detecting if the player goes on duty

            
            Game.LogTrivial("Traffic Policer " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125, has been initialised.");
            Game.LogTrivial("Go on duty to start Traffic Policer - Traffic Policer.Initialise done.");
            

        }

19 Source : Main.cs
with GNU General Public License v3.0
from Albo1125

public override void Initialize()
        {
            Functions.OnOnDutyStateChanged += Functions_OnOnDutyStateChanged;
            Game.LogTrivial("LSPDFR+ " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125, has been initialised.");
            Game.LogTrivial("Go on duty to start LSPDFR+.");
            Albo1125.Common.UpdateChecker.VerifyXmlNodeExists(PluginName, FileID, DownloadURL, Path);
            Albo1125.Common.DependencyChecker.RegisterPluginForDependencyChecks(PluginName);

        }

19 Source : CrashForm.cs
with MIT License
from AlexGyver

private void sendButton_Click(object sender, EventArgs e) {
      try {
        Version version = typeof(CrashForm).replacedembly.GetName().Version;
        WebRequest request = WebRequest.Create(
          "http://openhardwaremonitor.org/report.php");
        request.Method = "POST";
        request.Timeout = 5000;
        request.ContentType = "application/x-www-form-urlencoded";

        string report =
          "type=crash&" +
          "version=" + Uri.EscapeDataString(version.ToString()) + "&" +
          "report=" + Uri.EscapeDataString(reportTextBox.Text) + "&" +
          "comment=" + Uri.EscapeDataString(commentTextBox.Text) + "&" +
          "email=" + Uri.EscapeDataString(emailTextBox.Text);
        byte[] byteArray = Encoding.UTF8.GetBytes(report);
        request.ContentLength = byteArray.Length;

        try {
          Stream dataStream = request.GetRequestStream();
          dataStream.Write(byteArray, 0, byteArray.Length);
          dataStream.Close();

          WebResponse response = request.GetResponse();
          dataStream = response.GetResponseStream();
          StreamReader reader = new StreamReader(dataStream);
          string responseFromServer = reader.ReadToEnd();
          reader.Close();
          dataStream.Close();
          response.Close();

          Close();
        } catch (WebException) {
          MessageBox.Show("Sending the crash report failed.", "Error", 
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
      } catch {
      }
    }

19 Source : ReportForm.cs
with MIT License
from AlexGyver

private void sendButton_Click(object sender, EventArgs e) {
      Version version = typeof(CrashForm).replacedembly.GetName().Version;
      WebRequest request = WebRequest.Create(
        "http://openhardwaremonitor.org/report.php");
      request.Method = "POST";
      request.Timeout = 5000;
      request.ContentType = "application/x-www-form-urlencoded";

      string report =
        "type=hardware&" +
        "version=" + Uri.EscapeDataString(version.ToString()) + "&" +
        "report=" + Uri.EscapeDataString(reportTextBox.Text) + "&" +
        "comment=" + Uri.EscapeDataString(commentTextBox.Text) + "&" +
        "email=" + Uri.EscapeDataString(emailTextBox.Text);
      byte[] byteArray = Encoding.UTF8.GetBytes(report);
      request.ContentLength = byteArray.Length;

      try {
        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        WebResponse response = request.GetResponse();
        dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        reader.Close();
        dataStream.Close();
        response.Close();

        Close();
      } catch (WebException) {
        MessageBox.Show("Sending the hardware report failed.", "Error",
          MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }

19 Source : Computer.cs
with MIT License
from AlexGyver

public string GetReport() {

      using (StringWriter w = new StringWriter(CultureInfo.InvariantCulture)) {

        w.WriteLine();
        w.WriteLine("Open Hardware Monitor Report");
        w.WriteLine();

        Version version = typeof(Computer).replacedembly.GetName().Version;

        NewSection(w);
        w.Write("Version: "); w.WriteLine(version.ToString());
        w.WriteLine();

        NewSection(w);
        w.Write("Common Language Runtime: ");
        w.WriteLine(Environment.Version.ToString());
        w.Write("Operating System: ");
        w.WriteLine(Environment.OSVersion.ToString());
        w.Write("Process Type: ");
        w.WriteLine(IntPtr.Size == 4 ? "32-Bit" : "64-Bit");
        w.WriteLine();

        string r = Ring0.GetReport();
        if (r != null) {
          NewSection(w);
          w.Write(r);
          w.WriteLine();
        }

        NewSection(w);
        w.WriteLine("Sensors");
        w.WriteLine();
        foreach (IGroup group in groups) {
          foreach (IHardware hardware in group.Hardware)
            ReportHardwareSensorTree(hardware, w, "");
        }
        w.WriteLine();

        NewSection(w);
        w.WriteLine("Parameters");
        w.WriteLine();
        foreach (IGroup group in groups) {
          foreach (IHardware hardware in group.Hardware)
            ReportHardwareParameterTree(hardware, w, "");
        }
        w.WriteLine();

        foreach (IGroup group in groups) {
          string report = group.GetReport();
          if (!string.IsNullOrEmpty(report)) {
            NewSection(w);
            w.Write(report);
          }

          IHardware[] hardwareArray = group.Hardware;
          foreach (IHardware hardware in hardwareArray)
            ReportHardware(hardware, w);

        }
        return w.ToString();
      }
    }

19 Source : Model.cs
with Apache License 2.0
from Algoryx

public static Model Read( string filename )
    {
      var fileInfo = new FileInfo( filename );
      if ( !fileInfo.Exists )
        throw new UrdfIOException( $"URDF file {fileInfo.FullName} doesn't exist." );
      if ( fileInfo.Extension.ToLowerInvariant() != ".urdf" )
        throw new UrdfIOException( $"Unknown file extension {fileInfo.Extension}." );

      using ( var stream = fileInfo.OpenRead() ) {
        var doreplacedent = XDoreplacedent.Load( fileInfo.OpenRead(), LoadOptions.SetLineInfo );
        if ( doreplacedent == null )
          throw new UrdfIOException( $"Unable to parse URDF file {filename}." );
        if ( doreplacedent.Root == null )
          throw new UrdfIOException( "Unable to parse URDF file - file seems empty." );
        if ( doreplacedent.Root.Name != "robot" )
          throw new UrdfIOException( $"Expecting root attribute name 'robot', got '{doreplacedent.Root.Name}'." );

        // How should we handle doreplacedents without: <?xml version="1.0" ?>.
        if ( doreplacedent.Declaration != null ) {
          var version = Version.Parse( doreplacedent.Declaration.Version );
          if ( version.Major != 1 && version.Minor != 0 )
            throw new UrdfIOException( $"Unsupported version {version.ToString()}, supported version is 1.0." );
        }
        return Instantiate<Model>( doreplacedent.Root );
      }
    }

19 Source : AliyunSDKUtils.cs
with MIT License
from aliyunmq

static string DetermineOSVersion()
        {
            return Environment.OSVersion.Version.ToString();
        }

19 Source : StandardClassLibraryFormatter.cs
with Apache License 2.0
from allenai

public void Serialize(ref MessagePackWriter writer, Version value, MessagePackSerializerOptions options)
        {
            if (value == null)
            {
                writer.WriteNil();
            }
            else
            {
                writer.Write(value.ToString());
            }
        }

19 Source : EliteAttack.cs
with GNU General Public License v3.0
from alterNERDtive

public static void VA_Init1(dynamic vaProxy)
        {
            VA = vaProxy;
            Log.Notice("Initializing …");
            VA.SetText("EliteAttack.version", VERSION.ToString());
            Log.Notice("Init successful.");
        }

19 Source : RatAttack.cs
with GNU General Public License v3.0
from alterNERDtive

public static void VA_Init1(dynamic vaProxy)
        {
            VA = vaProxy;
            Log.Notice("Initializing …");
            VA.SetText("RatAttack.version", VERSION.ToString());
            vaProxy.ProfileChanged += new Action<Guid?, Guid?, String, String>(On_ProfileChanged);
            Log.Notice("Init successful.");
        }

19 Source : SpanshAttack.cs
with GNU General Public License v3.0
from alterNERDtive

public static void VA_Init1(dynamic vaProxy)
        {
            VA = vaProxy;
            Log.Notice("Initializing …");
            VA.SetText("SpanshAttack.version", VERSION.ToString());
            Log.Notice("Init successful.");
        }

19 Source : base.cs
with GNU General Public License v3.0
from alterNERDtive

private static void UpdateCheck()
        {
            Version latestVersion;
            try
            {
                latestVersion = new Version(new WebClient().DownloadString("https://raw.githubusercontent.com/alterNERDtive/VoiceAttack-profiles/release/VERSION"));
            }
            catch (Exception)
            {
                throw new Exception("Error fetching latest profiles version from Github.");
            }

            Log.Notice($"Local version: {VERSION}, latest release: {latestVersion}.");

            Commands.TriggerEvent("alterNERDtive-base.updateCheck",
                parameters: new dynamic[] { new string[] { VERSION.ToString(), latestVersion.ToString() }, new bool[] { VERSION.CompareTo(latestVersion) < 0 } });
        }

19 Source : base.cs
with GNU General Public License v3.0
from alterNERDtive

public static void VA_Init1(dynamic vaProxy)
        {
            VA = vaProxy;
            Log.Notice("Initializing …");
            VA.SetText("alterNERDtive-base.version", VERSION.ToString());
            vaProxy.BooleanVariableChanged += new Action<String, Boolean?, Boolean?, Guid?>((name, from, to, id) => { ConfigurationChanged(name, from, to, id); });
            vaProxy.DateVariableChanged += new Action<String, DateTime?, DateTime?, Guid?>((name, from, to, id) => { ConfigurationChanged(name, from, to, id); });
            vaProxy.DecimalVariableChanged += new Action<String, decimal?, decimal?, Guid?>((name, from, to, id) => { ConfigurationChanged(name, from, to, id); });
            vaProxy.IntegerVariableChanged += new Action<String, int?, int?, Guid?>((name, from, to, id) => { ConfigurationChanged(name, from, to, id); });
            vaProxy.TextVariableChanged += new Action<String, String, String, Guid?>((name, from, to, id) => { ConfigurationChanged(name, from, to, id); });
            VA.SetBoolean("alterNERDtive-base.initialized", true);
            Commands.TriggerEvent("alterNERDtive-base.initialized", wait: false, logMissing: false);
            Log.Notice("Init successful.");
        }

19 Source : OverlayBase`1.cs
with GNU General Public License v2.0
from AmanoTooko

protected virtual void InitializeOverlay()
    {
      try
      {
        this.Overlay = new OverlayForm(replacedembly.GetExecutingreplacedembly().GetName().Version.ToString(), this.Name, "about:blank", this.Config.MaxFrameRate);
        if (!Util.IsOnScreen((Form) this.Overlay))
          this.Overlay.StartPosition = FormStartPosition.WindowsDefaultLocation;
        else
          this.Overlay.Location = this.Config.Position;
        this.Overlay.Text = this.Name;
        this.Overlay.Size = this.Config.Size;
        this.Overlay.IsClickThru = this.Config.IsClickThru;
        this.Overlay.Renderer.BrowserError += (EventHandler<BrowserErrorEventArgs>) ((o, e) => this.Log(LogLevel.Error, "浏览器错误: {0}, {1}, {2}", (object) e.ErrorCode, (object) e.ErrorText, (object) e.Url));
        this.Overlay.Renderer.BrowserLoad += (EventHandler<BrowserLoadEventArgs>) ((o, e) =>
        {
          this.Log(LogLevel.Debug, "浏览器读取: {0}: {1}", (object) e.HttpStatusCode, (object) e.Url);
          this.NotifyOverlayState();
        });
        this.Overlay.Renderer.BrowserConsoleLog += (EventHandler<BrowserConsoleLogEventArgs>) ((o, e) => this.Log(LogLevel.Info, "浏览器控制: {0} (目标: {1}, 行: {2})", (object) e.Message, (object) e.Source, (object) e.Line));
        this.Config.UrlChanged += (EventHandler<UrlChangedEventArgs>) ((o, e) => this.Navigate(e.NewUrl));
        if (this.CheckUrl(this.Config.Url))
          this.Navigate(this.Config.Url);
        else
          this.Navigate("about:blank");
        this.Overlay.Show();
        this.Overlay.Visible = this.Config.IsVisible;
        this.Overlay.Locked = this.Config.IsLocked;
      }
      catch (Exception ex)
      {
        this.Log(LogLevel.Error, "初始化美化窗口: {0}", (object) this.Name, (object) ex);
      }
    }

19 Source : CommonUtilities.cs
with GNU General Public License v2.0
from AmanoTooko

public static async void GetLatestVersion()
        {
            var wc = new WebClient();
            try
            {
                var nowVersion = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString();
               
                System.Threading.Thread.Sleep(50);
                var newVersionJson = await UpdateHelper.UpdateHelper.CheckUpdate();
                System.Threading.Thread.Sleep(50);
                
                try
                {
                    var versionObj = JsonConvert.DeserializeObject<versionObject>(newVersionJson);
                    ParameterController.countDownPacket = versionObj.countDownPacket;
                    ParameterController.ensemblePacket = versionObj.ensemblePacket;
                    ParameterController.ensembleStartPacket = versionObj.ensembleStartPacket;
                    ParameterController.ensembleStopPacket = versionObj.ensembleStopPacket;
                    ParameterController.partyStopPacket = versionObj.partyStopPacket;
                    
                    if (versionObj.isRefuseToUse||versionObj.APIVersion==2)
                    {
                        Environment.Exit(-1);
                    }
                    if (nowVersion != versionObj.Version)
                    {
                        if (MessageBox.Show(new Form() { TopMost = true }, $"检测到新版本{versionObj.Version}已经发布,点击确定下载最新版哦!\r\n " +
                                           $"当然就算你点了取消,这个提示每次打开还会出现的哦!" +
                                           $"下载错误可以去NGA发布帖哦!bbs.nga.cn/read.php?tid=18790669 \r\n" +
                                           $"新版本更新内容:{versionObj.Description}", "哇——更新啦!",
                               MessageBoxButtons.OKCancel,
                               MessageBoxIcon.Information) == DialogResult.OK)
                        {
                            Process.Start("http://blog.ffxiv.cat/index.php/download/");

                        }
                        if (versionObj.isForceUpdate)
                        {
                            Environment.Exit(-2);
                        }
                    }
                       



                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                    Console.WriteLine(e);
                    
                }
                
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                
            }
        }

19 Source : OpenVPNSession.cs
with GNU General Public License v3.0
from Amebis

protected override void DoRun()
        {
            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
            try
            {
                try
                {
                    // Start OpenVPN management interface on IPv4 loopack interface (any TCP free port).
                    var mgmtServer = new TcpListener(IPAddress.Loopback, 0);
                    mgmtServer.Start();
                    try
                    {
                        try
                        {
                            // Purge stale log files.
                            var timestamp = DateTime.UtcNow.Subtract(new TimeSpan(30, 0, 0, 0));
                            foreach (var f in Directory.EnumerateFiles(WorkingFolder, "*.txt", SearchOption.TopDirectoryOnly))
                            {
                                SessionAndWindowInProgress.Token.ThrowIfCancellationRequested();
                                if (File.GetLastWriteTimeUtc(f) <= timestamp)
                                {
                                    try { File.Delete(LogPath); }
                                    catch { }
                                }
                            }
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception) { /* Failure to remove stale log files is not fatal. */ }

                        try
                        {
                            // Save OpenVPN configuration file.
                            using (var fs = new FileStream(
                                ConfigurationPath,
                                FileMode.Create,
                                FileAccess.Write,
                                FileShare.Read,
                                1048576,
                                FileOptions.SequentialScan))
                            using (var sw = new StreamWriter(fs))
                            {
                                // Save profile's configuration to file.

                                if (Properties.SettingsEx.Default.OpenVPNRemoveOptions is StringCollection openVPNRemoveOptions)
                                {
                                    // Remove options on the OpenVPNRemoveOptions list on the fly.
                                    using (var sr = new StringReader(ProfileConfig))
                                    {
                                        string inlineTerm = null;
                                        bool inlineRemove = false;
                                        for (; ; )
                                        {
                                            var line = sr.ReadLine();
                                            if (line == null)
                                                break;

                                            var trimmedLine = line.Trim();
                                            if (!string.IsNullOrEmpty(trimmedLine))
                                            {
                                                // Not an empty line.
                                                if (inlineTerm == null)
                                                {
                                                    // Not inside an inline option block = Regular parsing mode.
                                                    if (!trimmedLine.StartsWith("#") &&
                                                        !trimmedLine.StartsWith(";"))
                                                    {
                                                        // Not a comment.
                                                        var option = eduOpenVPN.Configuration.ParseParams(trimmedLine);
                                                        if (option.Count > 0)
                                                        {
                                                            if (option[0].StartsWith("<") && !option[0].StartsWith("</") && option[0].EndsWith(">"))
                                                            {
                                                                // Start of an inline option.
                                                                var o = option[0].Substring(1, option[0].Length - 2);
                                                                inlineTerm = "</" + o + ">";
                                                                inlineRemove = openVPNRemoveOptions.Contains(o);
                                                                if (inlineRemove)
                                                                {
                                                                    sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
                                                                    line = "# " + line;
                                                                }
                                                            }
                                                            else if (openVPNRemoveOptions.Contains(option[0]))
                                                            {
                                                                sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
                                                                line = "# " + line;
                                                            }
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    // Inside an inline option block.
                                                    if (inlineRemove)
                                                    {
                                                        // Remove the inline option content.
                                                        line = "# " + line;
                                                    }

                                                    if (trimmedLine == inlineTerm)
                                                    {
                                                        // Inline option terminator found. Returning to regular parsing mode.
                                                        inlineTerm = null;
                                                    }
                                                }
                                            }

                                            sw.WriteLine(line);
                                        }
                                    }
                                }
                                else
                                    sw.Write(ProfileConfig);

                                // Append eduVPN Client specific configuration directives.
                                sw.WriteLine();
                                sw.WriteLine();
                                sw.WriteLine("# eduVPN Client for Windows");

                                // Introduce ourself (to OpenVPN server).
                                var replacedembly = replacedembly.GetExecutingreplacedembly();
                                var replacedemblyreplacedleAttribute = Attribute.GetCustomAttributes(replacedembly, typeof(replacedemblyreplacedleAttribute)).SingleOrDefault() as replacedemblyreplacedleAttribute;
                                var replacedemblyVersion = replacedembly?.GetName()?.Version;
                                sw.WriteLine("setenv IV_GUI_VER " + eduOpenVPN.Configuration.EscapeParamValue(replacedemblyreplacedleAttribute?.replacedle + " " + replacedemblyVersion?.ToString()));

                                // Configure log file (relative to WorkingFolder).
                                sw.WriteLine("log-append " + eduOpenVPN.Configuration.EscapeParamValue(ConnectionId + ".txt"));

                                // Configure interaction between us and openvpn.exe.
                                sw.WriteLine("management " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Address.ToString()) + " " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Port.ToString()) + " stdin");
                                sw.WriteLine("management-client");
                                sw.WriteLine("management-hold");
                                sw.WriteLine("management-query-preplacedwords");
                                sw.WriteLine("management-query-remote");

                                // Configure client certificate.
                                sw.WriteLine("cert " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));
                                sw.WriteLine("key " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));

                                // Ask when username/preplacedword is denied.
                                sw.WriteLine("auth-retry interact");
                                sw.WriteLine("auth-nocache");

                                // Set Wintun interface to be used.
                                sw.Write("windows-driver wintun\n");
                                sw.Write("dev-node " + eduOpenVPN.Configuration.EscapeParamValue(Properties.Settings.Default.Clientreplacedle) + "\n");

#if DEBUG
                                // Renegotiate data channel every 5 minutes in debug versions.
                                sw.WriteLine("reneg-sec 300");
#endif

                                if (Environment.OSVersion.Version < new Version(6, 2))
                                {
                                    // Windows 7 is using tiny 8kB send/receive socket buffers by default.
                                    // Increase to 64kB which is default from Windows 8 on.
                                    sw.WriteLine("sndbuf 65536");
                                    sw.WriteLine("rcvbuf 65536");
                                }

                                var openVPNAddOptions = Properties.SettingsEx.Default.OpenVPNAddOptions;
                                if (!string.IsNullOrWhiteSpace(openVPNAddOptions))
                                {
                                    sw.WriteLine();
                                    sw.WriteLine();
                                    sw.WriteLine("# Added by OpenVPNAddOptions setting:");
                                    sw.WriteLine(openVPNAddOptions);
                                }
                            }
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception ex) { throw new AggregateException(string.Format(Resources.Strings.ErrorSavingProfileConfiguration, ConfigurationPath), ex); }

                        bool retry;
                        do
                        {
                            retry = false;

                            // Connect to OpenVPN Interactive Service to launch the openvpn.exe.
                            using (var openvpnInteractiveServiceConnection = new eduOpenVPN.InteractiveService.Session())
                            {
                                var mgmtPreplacedword = Membership.GeneratePreplacedword(16, 6);
                                try
                                {
                                    openvpnInteractiveServiceConnection.Connect(
                                        string.Format("openvpn{0}\\service", InstanceName),
                                        WorkingFolder,
                                        new string[] { "--config", ConnectionId + ".conf", },
                                        mgmtPreplacedword + "\n",
                                        3000,
                                        SessionAndWindowInProgress.Token);
                                }
                                catch (OperationCanceledException) { throw; }
                                catch (Exception ex) { throw new AggregateException(Resources.Strings.ErrorInteractiveService, ex); }

                                try
                                {
                                    // Wait and accept the openvpn.exe on our management interface (--management-client parameter).
                                    var mgmtClientTask = mgmtServer.AcceptTcpClientAsync();
                                    try { mgmtClientTask.Wait(30000, SessionAndWindowInProgress.Token); }
                                    catch (AggregateException ex) { throw ex.InnerException; }
                                    var mgmtClient = mgmtClientTask.Result;
                                    try
                                    {
                                        // Start the management session.
                                        ManagementSession.Start(mgmtClient.GetStream(), mgmtPreplacedword, SessionAndWindowInProgress.Token);

                                        // Initialize session and release openvpn.exe to get started.
                                        ManagementSession.SetVersion(3, SessionAndWindowInProgress.Token);
                                        ManagementSession.ReplayAndEnableState(SessionAndWindowInProgress.Token);
                                        ManagementSession.ReplayAndEnableEcho(SessionAndWindowInProgress.Token);
                                        ManagementSession.SetByteCount(5, SessionAndWindowInProgress.Token);
                                        ManagementSession.ReleaseHold(SessionAndWindowInProgress.Token);

                                        Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--));
                                        try
                                        {
                                            // Wait for the session to end gracefully.
                                            ManagementSession.Monitor.Join();
                                            if (ManagementSession.Error != null && !(ManagementSession.Error is OperationCanceledException))
                                            {
                                                // Session reported an error. Retry.
                                                retry = true;
                                            }
                                        }
                                        finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++)); }
                                    }
                                    finally { mgmtClient.Close(); }
                                }
                                finally
                                {
                                    Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
                                        () =>
                                        {
                                            // Cleanup status properties.
                                            State = SessionStatusType.Disconnecting;
                                            StateDescription = Resources.Strings.OpenVPNStateTypeExiting;
                                            TunnelAddress = null;
                                            IPv6TunnelAddress = null;
                                            ConnectedAt = null;
                                            BytesIn = null;
                                            BytesOut = null;
                                        }));

                                    // Wait for openvpn.exe to finish. Maximum 30s.
                                    try { Process.GetProcessById(openvpnInteractiveServiceConnection.ProcessId)?.WaitForExit(30000); }
                                    catch (ArgumentException) { }
                                }
                            }
                        } while (retry);
                    }
                    finally
                    {
                        mgmtServer.Stop();
                    }
                }
                finally
                {
                    // Delete profile configuration file. If possible.
                    try { File.Delete(ConfigurationPath); }
                    catch { }
                }
            }
            finally
            {
                Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
                    () =>
                    {
                        // Cleanup status properties.
                        State = SessionStatusType.Disconnected;
                        StateDescription = "";

                        Wizard.TaskCount--;
                    }));
                PropertyUpdater.Stop();
            }
        }

19 Source : SelfUpdatePromptPage.cs
with GNU General Public License v3.0
from Amebis

public void CheckForUpdates()
        {
            try
            {
                Parallel.ForEach(new List<Action>()
                    {
                        () =>
                        {
                            // Get self-update.
                            var res = Properties.SettingsEx.Default.SelfUpdateDiscovery;
                            Trace.TraceInformation("Downloading self-update JSON discovery from {0}...", res.Uri.AbsoluteUri);
                            var obj = Properties.Settings.Default.ResponseCache.GetSeq(res, Window.Abort.Token);

                            var repoVersion = new Version((string)obj["version"]);
                            Trace.TraceInformation("Online version: {0}", repoVersion.ToString());
                            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => {
                                AvailableVersion = repoVersion;
                                Changelog = eduJSON.Parser.GetValue(obj, "changelog_uri", out string changelogUri) ? new Uri(changelogUri) : null;
                                Wizard.SelfUpdateProgressPage.DownloadUris = new List<Uri>(((List<object>)obj["uri"]).Select(uri => new Uri(res.Uri, (string)uri)));
                                Wizard.SelfUpdateProgressPage.Hash = ((string)obj["hash-sha256"]).FromHexToBin();
                                Wizard.SelfUpdateProgressPage.Arguments = eduJSON.Parser.GetValue(obj, "arguments", out string installerArguments) ? installerArguments : null;
                            }));
                        },

                        () =>
                        {
                            // Evaluate installed products.
                            Version productVersion = null;
                            var productId = Properties.Settings.Default.SelfUpdateBundleId.ToUpperInvariant();
                            Trace.TraceInformation("Evaluating installed products...");
                            using (var hklmKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
                            using (var uninstallKey = hklmKey.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", false))
                            {
                                foreach (var productKeyName in uninstallKey.GetSubKeyNames())
                                {
                                    Window.Abort.Token.ThrowIfCancellationRequested();
                                    using (var productKey = uninstallKey.OpenSubKey(productKeyName))
                                    {
                                        var bundleUpgradeCode = productKey.GetValue("BundleUpgradeCode");
                                        if ((bundleUpgradeCode is string   bundleUpgradeCodeString && bundleUpgradeCodeString.ToUpperInvariant() == productId ||
                                                bundleUpgradeCode is string[] bundleUpgradeCodeArray  && bundleUpgradeCodeArray.FirstOrDefault(code => code.ToUpperInvariant() == productId) != null) &&
                                            productKey.GetValue("BundleVersion") is string bundleVersionString)
                                        {
                                            // Our product entry found.
                                            productVersion = new Version(productKey.GetValue("DisplayVersion") is string displayVersionString ? displayVersionString : bundleVersionString);
                                            Trace.TraceInformation("Installed version: {0}", productVersion.ToString());
                                            break;
                                        }
                                    }
                                }
                            }
                            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => { InstalledVersion = productVersion; }));
                        },
                    },
                    action =>
                    {
                        Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
                        try { action(); }
                        finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--)); }
                    });
            }
            catch (AggregateException ex)
            {
                var nonCancelledException = ex.InnerExceptions.Where(innerException => !(innerException is OperationCanceledException));
                if (nonCancelledException.Any())
                    throw new AggregateException(Resources.Strings.ErrorSelfUpdateDetection, nonCancelledException.ToArray());
                throw new OperationCanceledException();
            }

            //// Mock the values for testing.
            //InstalledVersion = new Version(1, 0);
            //Properties.Settings.Default.SelfUpdateLastReminder = DateTime.MinValue;

            try
            {
                if (new Version(Properties.Settings.Default.SelfUpdateLastVersion) == AvailableVersion &&
                    (Properties.Settings.Default.SelfUpdateLastReminder == DateTime.MaxValue ||
                    (DateTime.UtcNow - Properties.Settings.Default.SelfUpdateLastReminder).TotalDays < 3))
                {
                    // We already prompted user for this version.
                    // Either user opted not to be reminded of this version update again,
                    // or it has been less than three days since the last prompt.
                    Trace.TraceInformation("Update deferred by user choice.");
                    return;
                }
            }
            catch { }

            if (InstalledVersion == null)
            {
                // Nothing to update.
                Trace.TraceInformation("Product not installed or version could not be determined.");
                return; // Quit self-updating.
            }

            if (AvailableVersion <= InstalledVersion)
            {
                // Product already up-to-date.
                Trace.TraceInformation("Update not required.");
                return;
            }

            // We're in the background thread - raise the prompt event via dispatcher.
            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
            {
                if (Wizard.NavigateTo.CanExecute(this))
                {
                    Properties.Settings.Default.SelfUpdateLastVersion = AvailableVersion.ToString();
                    Properties.Settings.Default.SelfUpdateLastReminder = DateTime.UtcNow;
                    Wizard.NavigateTo.Execute(this);
                }
            }));
        }

19 Source : CheckForUpdates.cs
with Apache License 2.0
from AmpScm

private void OnResponse(IAsyncResult ar)
        {
            IAnkhConfigurationService config = Context.GetService<IAnkhConfigurationService>();
            bool failed = true;
            string tag = null;
            try
            {
                WebRequest rq = ((WebRequest)ar.AsyncState);
                WebResponse wr;
                try
                {
                    wr = rq.EndGetResponse(ar);
                }
                catch (WebException e)
                {
                    HttpWebResponse hwr = e.Response as HttpWebResponse;

                    if (hwr != null)
                    {
                        if (hwr.StatusCode == HttpStatusCode.NotFound)
                        {
                            failed = false;
                            return; // File not found.. Update info not yet or no longer available
                        }
                    }

                    return;
                }
                catch
                {
                    return;
                }

                if (wr.ContentLength > 65536) // Not for us.. We expect a few hundred bytes max
                    return;

                string body;
                using (Stream s = wr.GetResponseStream())
                using (StreamReader sr = new StreamReader(s))
                {
                    body = sr.ReadToEnd().Trim();
                }

                if (string.IsNullOrEmpty(body))
                {
                    failed = false;
                    return;
                }

                if (body[0] != '<' || body[body.Length - 1] != '>')
                    return; // No valid xml or empty

                failed = false;

                XmlDoreplacedent doc = new XmlDoreplacedent();
                doc.LoadXml(body);

                string replacedle = NodeText(doc, "/u/i/t");
                string header = NodeText(doc, "/u/i/h") ?? replacedle;
                string description = NodeText(doc, "/u/i/d");
                string url = NodeText(doc, "/u/i/u");
                string urltext = NodeText(doc, "/u/i/l");

                string version = NodeText(doc, "/u/i/v");
                string newVersion = NodeText(doc, "/u/i/n") ?? version;

                tag = NodeText(doc, "/u/g");

                if (!string.IsNullOrEmpty(replacedle) && !string.IsNullOrEmpty(description))
                {
                    if (!string.IsNullOrEmpty(version))
                    {
                        Version v = new Version(version);

                        if (v <= GetCurrentVersion(Context))
                            return;
                    }

                    if (!string.IsNullOrEmpty(tag))
                    {
                        using (RegistryKey rk = config.OpenUserInstanceKey("UpdateCheck"))
                        {
                            string pTag = rk.GetValue("SkipTag") as string;

                            if (pTag == tag)
                                return;
                        }
                    }

                    IAnkhCommandService cs = Context.GetService<IAnkhCommandService>();

                    cs.PostExecCommand(AnkhCommand.CheckForUpdates,
                        new string[] { replacedle, header, description, url, urltext, version, newVersion, tag });
                }
            }
            finally
            {
                using (RegistryKey rk = config.OpenUserInstanceKey("UpdateCheck"))
                {
                    object fails = rk.GetValue("Fails", 0);
                    rk.DeleteValue("LastCheck", false);
                    rk.DeleteValue("LastVersion", false);
                    rk.DeleteValue("FailedChecks", false);
                    rk.SetValue("LastCheck", DateTime.UtcNow.Ticks);
                    rk.SetValue("LastVersion", GetCurrentVersion(Context).ToString());
                    if (tag != null)
                        rk.SetValue("LastTag", tag);
                    else
                        rk.DeleteValue("LastTag", false);

                    if (failed)
                    {
                        int f = 0;
                        if (fails is int)
                            f = (int)fails + 1;

                        rk.SetValue("FailedChecks", f);
                    }
                }
            }
        }

19 Source : CheckForUpdates.cs
with Apache License 2.0
from AmpScm

public static void MaybePerformUpdateCheck(IAnkhServiceProvider context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (_checkedOnce)
                return;

            _checkedOnce = true;

            IAnkhConfigurationService config = context.GetService<IAnkhConfigurationService>();
            using (RegistryKey rk = config.OpenUserInstanceKey("UpdateCheck"))
            {
                int interval = 24 * 6; // 6 days
                object value = rk.GetValue("Interval");

                if (value is int)
                {
                    interval = (int)value;

                    if (interval <= 0)
                        return;
                }

                TimeSpan ts = TimeSpan.FromHours(interval);

                value = rk.GetValue("LastVersion");

                if (IsDevVersion() || (value is string && (string)value == GetCurrentVersion(context).ToString()))
                {
                    value = rk.GetValue("LastCheck");
                    long lv;
                    if (value is string && long.TryParse((string)value, out lv))
                    {
                        DateTime lc = new DateTime(lv, DateTimeKind.Utc);

                        if ((lc + ts) > DateTime.UtcNow)
                            return;

                        // TODO: Check the number of fails to increase the check interval
                    }
                }
            }

            context.GetService<IAnkhScheduler>().Schedule(new TimeSpan(0, 0, 20), AnkhCommand.CheckForUpdates);
        }

See More Examples