BF2Statistics.Redirector.ApplyRedirectsAsync C# (CSharp) Method

ApplyRedirectsAsync() public static method

Applies the specified IP address redirects for the chosen redirect method
public static ApplyRedirectsAsync ( IProgress Progress ) : Task
Progress IProgress
return Task
        public static Task<bool> ApplyRedirectsAsync(IProgress<TaskStep> Progress)
        {
            return Task.Run(() =>
            {
                // Remove old settings
                if (RedirectsEnabled) RemoveRedirects();

                // Invalid on no IP addresses
                if (StatsServerAddress == null && GamespyServerAddress == null)
                    return false;

                // Set new desired addresses
                if (StatsServerAddress != null)
                    Program.Config.LastStatsServerAddress = StatsServerAddress.ToString();
                if (GamespyServerAddress != null)
                    Program.Config.LastLoginServerAddress = GamespyServerAddress.ToString();
                Program.Config.Save();

                // Can't do anything with a dns server
                if (RedirectMethod == RedirectMode.DnsServer) return true;

                // === Apply new settings === //

                // Grab hosts file base
                HostsFile hFile = (RedirectMethod == RedirectMode.HostsFile)
                    ? HostsFileSys as HostsFile
                    : HostsFileIcs as HostsFile;

                // Unlock system hosts file
                if (RedirectMethod == RedirectMode.HostsFile)
                {
                    // Make sure file is writable
                    if (SysHostsFile.IsLocked && !HostsFileSys.UnLock())
                    {
                        Progress.Report(new TaskStep(0, "Cannot allow READ permissions on the Hosts File", true, hFile.LastException));
                        return false;
                    }
                    else
                        Progress.Report(new TaskStep(0, ""));
                }

                // Make sure file is writable
                if (!hFile.CanRead)
                {
                    Progress.Report(new TaskStep(1, "Cannot read the Hosts File", true, hFile.LastException));
                    return false;
                }
                else
                    Progress.Report(new TaskStep(1, ""));

                // Make sure file is readable
                if (!hFile.CanWrite)
                {
                    Progress.Report(new TaskStep(2, "Cannot write to the Hosts File", true, hFile.LastException));
                    return false;
                }
                else
                    Progress.Report(new TaskStep(2, ""));

                // ===== Set Redirect Addresses ===== //

                // Stats Server
                if (StatsServerAddress != null)
                    hFile.Set(Bf2StatsHost, StatsServerAddress);

                // Gamespy Servers
                if (GamespyServerAddress != null)
                {
                    foreach (string hostname in GamespyHosts)
                        hFile.Set(hostname, GamespyServerAddress);
                }

                // Report Progress
                Progress.Report(new TaskStep(3, "Gamespy Redirects Set"));

                // ===== Save Redirects ===== //

                int Step = 4;
                string ErrDesc = "";
                try
                {
                    // Attempt to save the hosts file
                    ErrDesc = "Unable to  Save Hosts File!";
                    hFile.Save();

                    // Report Success
                    Progress.Report(new TaskStep(Step++, "Hosts File Saved Successfully"));

                    // Rebuild the DNS Cache
                    ErrDesc = "Failed to Rebuild the DNS Cache";
                    RebuildDNSCache(CancellationToken.None);

                    // Report Success
                    Progress.Report(new TaskStep(Step++, "DNS Cache Rebuilt Successfully"));
                }
                catch (Exception e)
                {
                    RemoveRedirects();
                    Progress.Report(new TaskStep(Step, ErrDesc, true, e));
                    return false;
                }

                // Lock system hosts File
                if (RedirectMethod == RedirectMode.HostsFile)
                {
                    if (!Program.Config.LockHostsFile)
                    {
                        // Report Success
                        Progress.Report(new TaskStep(Step++, ""));
                        return true;
                    }
                    else if (HostsFileSys.Lock())
                    {
                        // Report Success
                        Progress.Report(new TaskStep(Step++, "Hosts File Read Permissions Removed"));
                        return true;
                    }
                    else
                    {
                        // Report Error
                        Progress.Report(new TaskStep(Step++, "Cannot Remove Hosts File Read Permissions!",
                            true, HostsFileSys.LastException));
                        return true;
                    }
                }

                return true;
            });
        }

Usage Example

        /// <summary>
        /// When the Step is changed, this method handles the processing of
        /// the next step
        /// </summary>
        protected async void AfterSelectProcessing()
        {
            // Disable buttons until processing is complete
            NextBtn.Enabled = false;
            PrevBtn.Enabled = false;
            bool IsErrorFree;

            // Do processing
            // Get our previous step
            switch (pageControl1.SelectedTab.Name)
            {
            case "tabPageSelect":
                // We dont do anything here
                NextBtn.Enabled = true;
                break;

            case "tabPageRedirectType":
                // We dont do much here
                PrevBtn.Enabled = NextBtn.Enabled = true;
                break;

            case "tabPageVerifyHosts":
            case "tabPageVerifyIcs":
                // Create new progress
                SyncProgress <TaskStep> Myprogress = new SyncProgress <TaskStep>(RedirectStatusUpdate);

                // Apply redirects
                IsErrorFree = await Redirector.ApplyRedirectsAsync(Myprogress);

                if (IsErrorFree)
                {
                    NextBtn.Enabled = true;
                }
                else
                {
                    // Remove redirect if there are errors
                    await Task.Delay(ERRORPAGE_DELAY);

                    ShowHostsErrorPage();
                }
                break;

            case "tabPageDiagnostic":
                // Run in a new thread of course
                bool DiagnosticResult = await Task.Run <bool>(() => VerifyDnsCache());

                // Switch page
                if (DiagnosticResult)
                {
                    NextBtn.Enabled = true;
                }
                else
                {
                    // Remove redirect if there are errors
                    Redirector.RemoveRedirects();
                    await Task.Delay(ERRORPAGE_DELAY);

                    // Show Error Page
                    ShowDnsErrorPage();
                }
                break;

            case "tabPageSuccess":
                PrevBtn.Visible   = false;
                CancelBtn.Visible = false;
                NextBtn.Text      = "Finish";
                NextBtn.Enabled   = true;
                NextBtn.Location  = CancelBtn.Location;
                return;

            case "tabPageError":
                break;
            }

            // Unlock the previos button
            if (pageControl1.SelectedTab != tabPageSelect)
            {
                PrevBtn.Enabled = true;
            }
        }