static void Main(string[] args)
        {
            Console.WriteLine("Log location; " + logFilePath);
            CheckSettings();

            var config  = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = logFilePath
            };
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole");

            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = config;

            void ActualMain()
            {
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                //Upgrade settings
                if (Properties.Settings.Default.UpdateSettings)
                {
                    /* Copy old setting-files in case the Evidence type and Evidence Hash has changed (which it does sometimes) - easier than creating a whole new settings system */
                    try {
                        Configuration accConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
                        string        currentFolder    = new DirectoryInfo(accConfiguration.FilePath).Parent.Parent.FullName;
                        string[]      directories      = Directory.GetDirectories(new DirectoryInfo(currentFolder).Parent.FullName);

                        foreach (string dir in directories)
                        {
                            if (dir != currentFolder.ToString())
                            {
                                var directoriesInDir = Directory.GetDirectories(dir);
                                foreach (string childDir in directoriesInDir)
                                {
                                    string checkPath = Path.Combine(currentFolder, Path.GetFileName(childDir));
                                    if (!Directory.Exists(checkPath))
                                    {
                                        string checkFile = Path.Combine(childDir, "user.config");
                                        if (File.Exists(checkFile))
                                        {
                                            bool xmlHasError = false;
                                            try {
                                                XmlDocument xml = new XmlDocument();
                                                xml.Load(checkFile);

                                                xml.Validate(null);
                                            } catch {
                                                xmlHasError = true;
                                                DoDebug("XML document validation failed (is invalid): " + checkFile);
                                            }

                                            if (!xmlHasError)
                                            {
                                                Directory.CreateDirectory(checkPath);
                                                File.Copy(checkFile, Path.Combine(checkPath, "user.config"), true);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        Console.WriteLine("Error getting settings from older versions of ACC" + e.Message);
                    }
                    /* End "copy settings" */

                    try {
                        Properties.Settings.Default.Upgrade();
                        Properties.Settings.Default.UpdateSettings = false;
                        Properties.Settings.Default.Save();
                    } catch {
                        DoDebug("Failed to upgrade from old settings file.");
                    }

                    Console.WriteLine("Upgraded settings to match last version");
                }

                if (Properties.Settings.Default.LastUpdated == DateTime.MinValue)
                {
                    Properties.Settings.Default.LastUpdated = DateTime.Now;
                }

                //Translator
                string tempDir = Path.Combine(currentLocation, "Translations");

                if (Directory.Exists(tempDir))
                {
                    Translator.translationFolder = Path.Combine(currentLocation, "Translations");
                    Translator.languagesArray    = Translator.GetLanguages();
                }
                else
                {
                    MessageBox.Show("Missing the translations folder. Reinstall the software to fix this issue.", messageBoxTitle);
                }

                string lang = Properties.Settings.Default.ActiveLanguage;

                if (Array.Exists(Translator.languagesArray, element => element == lang))
                {
                    DoDebug("ACC running with language \"" + lang + "\"");

                    Translator.SetLanguage(lang);
                }
                else
                {
                    DoDebug("Invalid language chosen (" + lang + ")");

                    Properties.Settings.Default.ActiveLanguage = "English";
                    Translator.SetLanguage("English");
                }

                Properties.Settings.Default.TimesOpened += 1;
                Properties.Settings.Default.Save();

                SetupDataFolder();
                if (File.Exists(logFilePath))
                {
                    try {
                        File.WriteAllText(logFilePath, string.Empty);
                    } catch {
                        // Don't let this being DENIED crash the software
                        Console.WriteLine("Failed to empty the log");
                    }
                }
                else
                {
                    Console.WriteLine("Trying to create log");
                    CreateLogFile();
                }

                //Check if software already runs, if so kill this instance
                var otherACCs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(currentLocationFull));

                if (otherACCs.Length > 1)
                {
                    //Try kill the _other_ process instead
                    foreach (Process p in otherACCs)
                    {
                        if (p.Id != Process.GetCurrentProcess().Id)
                        {
                            try {
                                p.Kill();
                                DoDebug("Other ACC instance was running. Killed it.");
                            } catch {
                                DoDebug("Could not kill other process of ACC; access denied");
                            }
                        }
                    }
                }

                Application.EnableVisualStyles();

                DoDebug("[ACC begun (v" + softwareVersion + ")]");

                if (Properties.Settings.Default.CheckForUpdates)
                {
                    if (HasInternet())
                    {
                        new Thread(() => {
                            new ACC_Updater().Check();
                        }).Start();
                    }
                    else
                    {
                        DoDebug("Couldn't check for new update as PC does not have access to the internet");
                    }
                }

                //On console close: hide NotifyIcon
                Application.ApplicationExit += new EventHandler(OnApplicationExit);
                handler = new ConsoleEventDelegate(ConsoleEventCallback);
                SetConsoleCtrlHandler(handler, true);

                //Check if software starts with Windows
                if (!Properties.Settings.Default.StartWithWindows)
                {
                    sysIcon.AddOpenOnStartupMenu();
                }

                //Create shortcut folder if doesn't exist
                if (!Directory.Exists(shortcutLocation))
                {
                    Directory.CreateDirectory(shortcutLocation);
                }
                if (!File.Exists(Path.Combine(shortcutLocation, @"example.txt")))
                {
                    //Create example-file
                    try {
                        using (StreamWriter sw = File.CreateText(Path.Combine(shortcutLocation, @"example.txt"))) {
                            sw.WriteLine("This is an example file.");
                            sw.WriteLine("If you haven't already, make your assistant open this file!");
                        }
                    } catch {
                        DoDebug("Could not create or write to example file");
                    }
                }

                //Delete all old action files
                if (Directory.Exists(CheckPath()))
                {
                    DoDebug("Deleting all files in action folder");
                    foreach (string file in Directory.GetFiles(CheckPath(), "*." + Properties.Settings.Default.ActionFileExtension))
                    {
                        int timeout = 0;

                        if (File.Exists(file))
                        {
                            while (ActionChecker.FileInUse(file) && timeout < 5)
                            {
                                timeout++;
                                Thread.Sleep(500);
                            }
                            if (timeout >= 5)
                            {
                                DoDebug("Failed to delete file at " + file + " as file appears to be in use (and has been for 2.5 seconds)");
                            }
                            else
                            {
                                try {
                                    File.Delete(file);
                                } catch (Exception e) {
                                    DoDebug("Failed to delete file at " + file + "; " + e.Message);
                                }
                            }
                        }
                    }
                    DoDebug("Old action files removed - moving on...");
                }

                //SetupListener();
                watcher = new FileSystemWatcher()
                {
                    Path         = CheckPath(),
                    NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                   | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                    Filter = "*." + Properties.Settings.Default.ActionFileExtension,
                    EnableRaisingEvents = true
                };
                watcher.Changed += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Created += new FileSystemEventHandler(new ActionChecker().FileFound);

                DoDebug("\n[" + messageBoxTitle + "] Initiated. \nListening in: \"" + CheckPath() + "\" for \"." + Properties.Settings.Default.ActionFileExtension + "\" extensions");

                sysIcon.TrayIcon.Icon = Properties.Resources.ACC_icon_light;

                RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);

                if (Registry.GetValue(key.Name + @"\AssistantComputerControl", "FirstTime", null) == null)
                {
                    key.CreateSubKey("AssistantComputerControl");
                    key = key.OpenSubKey("AssistantComputerControl", true);
                    key.SetValue("FirstTime", false);

                    Properties.Settings.Default.HasCompletedTutorial = true;
                    Properties.Settings.Default.Save();

                    ShowGettingStarted();

                    DoDebug("Starting setup guide");
                }
                else
                {
                    if (!Properties.Settings.Default.HasCompletedTutorial)
                    {
                        ShowGettingStarted();
                        DoDebug("Didn't finish setup guide last time, opening again");
                    }
                }
                SetRegKey("ActionFolder", CheckPath());
                SetRegKey("ActionExtension", Properties.Settings.Default.ActionFileExtension);

                testActionWindow = new TestActionWindow();

                //If newly updated
                if (Properties.Settings.Default.LastKnownVersion != softwareVersion)
                {
                    //Up(or down)-grade, display version notes
                    Properties.Settings.Default.LastUpdated = DateTime.Now;
                    if (gettingStarted != null)
                    {
                        DoDebug("'AboutVersion' window awaits, as 'Getting Started' is showing");
                        aboutVersionAwaiting = true;
                    }
                    else
                    {
                        Properties.Settings.Default.LastKnownVersion = softwareVersion;
                        new NewVersion().Show();
                    }
                    Properties.Settings.Default.Save();
                }

                /* 'Satisfied' user feedback implementation */
                if ((DateTime.Now - Properties.Settings.Default.LastUpdated).TotalDays >= 7 && Properties.Settings.Default.TimesOpened >= 7 &&
                    gettingStarted == null &&
                    !Properties.Settings.Default.HasPromptedFeedback)
                {
                    //User has had the software/update for at least 7 days, and has opened the software more than 7 times - time to ask for feedback
                    //(also the "getting started" window is not showing)
                    if (HasInternet())
                    {
                        try {
                            WebRequest      request  = WebRequest.Create("https://evalufied.dk/");
                            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                            if (response == null || response.StatusCode != HttpStatusCode.OK)
                            {
                                DoDebug("'Satisfied' is down - won't show faulty feedback window");
                            }
                            else
                            {
                                DoDebug("Showing 'User Feedback' window");
                                Properties.Settings.Default.HasPromptedFeedback = true;
                                Properties.Settings.Default.Save();
                                new UserFeedback().Show();
                            }
                        } catch {
                            DoDebug("Failed to check for 'Satisfied'-availability");
                        }
                    }
                    else
                    {
                        DoDebug("No internet connection, not showing user feedback window");
                    }
                }

                //ShowGettingStarted();

                SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch); //On wake up from sleep
                Application.Run();
            }

            if (sentryToken != "super_secret")
            {
                //Tracking issues with Sentry.IO - not forked from GitHub (official version)
                bool sentryOK = false;
                try {
                    if (Properties.Settings.Default.UID != "")
                    {
                        SentrySdk.ConfigureScope(scope => {
                            scope.User = new Sentry.Protocol.User {
                                Id = Properties.Settings.Default.UID
                            };
                        });
                    }

                    using (SentrySdk.Init(sentryToken)) {
                        sentryOK = true;
                    }
                } catch {
                    //Sentry failed. Error sentry's side or invalid key - don't let this stop the app from running
                    DoDebug("Sentry initiation failed");
                    ActualMain();
                }

                if (sentryOK)
                {
                    try {
                        using (SentrySdk.Init(sentryToken)) {
                            DoDebug("Sentry initiated");
                            ActualMain();
                        }
                    } catch {
                        ActualMain();
                    }
                }
            }
            else
            {
                //Code is (most likely) forked - skip issue tracking
                ActualMain();
            }
        }
Exemplo n.º 2
0
        public UserFeedback()
        {
            InitializeComponent();

            Text = Translator.__("window_name", "user_feedback_window");
        }
        public GettingStarted(int startTab = 0)
        {
            //Start function

            thisForm = this;

            InitializeComponent();
            Thread.CurrentThread.Priority = ThreadPriority.Highest;

            theTabControl = tabControl;

            FormClosed += delegate {
                if (MainProgram.aboutVersionAwaiting)
                {
                    Properties.Settings.Default.LastKnownVersion = MainProgram.softwareVersion;
                    new NewVersion().Show();
                    Properties.Settings.Default.Save();
                }
            };

            tabControl.Appearance = TabAppearance.FlatButtons;
            tabControl.ItemSize   = new Size(0, 1);
            tabControl.SizeMode   = TabSizeMode.Fixed;
            tabControl.BackColor  = Color.White;
            tabControl.SelectTab(startTab);

            tabControl.Selected += delegate {
                if (tabControl.SelectedIndex == 1)
                {
                    //Clicked on recommended setup guide (HTML), can show "move on" popover now
                    //theWebBrowser.Document.InvokeScript("showHelpPopover"); // Why would I do this...?
                }
                else if (tabControl.SelectedIndex == 2)
                {
                    expert.Focus();
                }
            };

            backToSetupGuide.Visible = false;
            theInstance = this;

            //Set GettingStarted web-browser things (unless user has IE >9)
            //Check for IE version using JS, as the C# way requires admin rights, which we don't want to ask for just because of this...

            string fileName = Path.Combine(MainProgram.currentLocation, "WebFiles/IECheck.html");

            /* Internet Explorer test */
            if (File.Exists(fileName))
            {
                string fileLoc = "file:///" + fileName;
                Uri    theUri  = new Uri(fileLoc);
                ieWebBrowser.Url = theUri;
            }
            else
            {
                ieWebBrowser.Visible = false;
            }

            ieWebBrowser.ObjectForScripting = new WebBrowserHandler();
            theWebBrowser = ieWebBrowser;

            //theWebBrowser.DocumentCompleted += BrowserDocumentCompleted;
            theWebBrowser.Navigating += BrowserNavigating;
            theWebBrowser.NewWindow  += NewBrowserWindow;

            /* Getting Started */
            fileName = Path.Combine(MainProgram.currentLocation, "WebFiles/GettingStarted.html");
            if (File.Exists(fileName))
            {
                string fileLoc = "file:///" + fileName;
                Uri    theUri  = new Uri(fileLoc);
                GettingStartedWebBrowser.Url = theUri;
            }
            else
            {
                GettingStartedWebBrowser.Visible = false;
            }

            GettingStartedWebBrowser.ObjectForScripting = new WebBrowserHandler();
            theWebBrowser            = GettingStartedWebBrowser;
            theDoneActionViewBrowser = doneActionViewBrowser;

            theDoneActionViewBrowser.DocumentCompleted += DoneActionGridLoadCompleted;
            theDoneActionViewBrowser.Navigating        += BrowserNavigating;
            theDoneActionViewBrowser.NewWindow         += NewBrowserWindow;

            theWebBrowser.DocumentCompleted += BrowserDocumentCompleted;

            theWebBrowser.Navigating += BrowserNavigating;
            theWebBrowser.NewWindow  += NewBrowserWindow;


            //Further expert settings
            actionFolderPath.KeyDown    += new KeyEventHandler(FreakingStopDingSound);
            actionFileExtension.KeyDown += new KeyEventHandler(FreakingStopDingSound);

            void FreakingStopDingSound(Object o, KeyEventArgs e)
            {
                if (e.KeyCode == Keys.Enter)
                {
                    e.Handled          = true;
                    e.SuppressKeyPress = true;
                }
            }

            actionFolderPath.Text    = MainProgram.CheckPath();
            actionFileExtension.Text = Properties.Settings.Default.ActionFileExtension;

            actionFolderPath.KeyDown += delegate {
                MainProgram.SetCheckFolder(actionFolderPath.Text);
                actionFolderPath.Text = MainProgram.CheckPath();
            };
            actionFolderPath.KeyUp += delegate {
                MainProgram.SetCheckFolder(actionFolderPath.Text);
                actionFolderPath.Text = MainProgram.CheckPath();
            };

            actionFileExtension.KeyDown += delegate { MainProgram.SetCheckExtension(actionFileExtension.Text); };
            actionFileExtension.KeyUp   += delegate { MainProgram.SetCheckExtension(actionFileExtension.Text); };

            expert.Click += delegate {
                expert.Focus();
            };
            customSetupInfo.Click += delegate {
                expert.Focus();
            };

            expertDoneButton.FlatStyle = FlatStyle.Flat;
            expertDoneButton.FlatAppearance.BorderSize = 0;

            VisibleChanged += delegate {
                MainProgram.testingAction  = Visible;
                MainProgram.gettingStarted = Visible ? this : null;
                isConfiguringActions       = Visible;
            };
            FormClosed += delegate {
                //Is needed
                isConfiguringActions       = false;
                MainProgram.testingAction  = false;
                MainProgram.gettingStarted = null;
            };


            this.HandleCreated += delegate {
                Invoke(new Action(() => {
                    FlashWindow.Flash(this);
                    if (Application.OpenForms[this.Name] != null)
                    {
                        Application.OpenForms[this.Name].Activate();
                        Application.OpenForms[this.Name].Focus();
                    }
                }));
            };

            //"Expert setup" translations
            customSetupTitle.Text         = Translator.__("title", "expert_setup");
            customSetupInfo.Text          = Translator.__("description", "expert_setup");
            actionFolderPathLabel.Text    = Translator.__("action_folder_path", "expert_setup");
            actionFileExtensionLabel.Text = Translator.__("action_file_extension", "expert_setup");
            disclaimerLabel.Text          = Translator.__("disclaimer", "expert_setup");
            backToSetupGuide.Text         = Translator.__("back_to_setup", "expert_setup");
            expertDoneButton.Text         = Translator.__("done_button", "expert_setup");
        } // End main function
        public SettingsForm()
        {
            InitializeComponent();

            versionInfo.Text = "|Version " + MainProgram.softwareVersion;

            computerName.KeyDown     += new KeyEventHandler(FreakingStopDingSound);
            fileEditedMargin.KeyDown += new KeyEventHandler(FreakingStopDingSound);
            fileReadDelay.KeyDown    += new KeyEventHandler(FreakingStopDingSound);

            void FreakingStopDingSound(Object o, KeyEventArgs e)
            {
                if (e.KeyCode == Keys.Enter)
                {
                    e.Handled          = true;
                    e.SuppressKeyPress = true;
                }
            }

            //Set values
            startWithWindows.Checked = Properties.Settings.Default.StartWithWindows;
            checkUpdates.Checked     = Properties.Settings.Default.CheckForUpdates;
            betaProgram.Checked      = Properties.Settings.Default.BetaProgram;
            warnDeletion.Checked     = Properties.Settings.Default.WarnWhenDeletingManyFiles;
            defaultComputer.Checked  = Properties.Settings.Default.DefaultComputer;

            computerName.Text      = Properties.Settings.Default.ComputerName;
            fileEditedMargin.Value = (decimal)Properties.Settings.Default.FileEditedMargin;
            fileReadDelay.Value    = (decimal)Properties.Settings.Default.FileReadDelay;
            maxDeleteFiles.Value   = Properties.Settings.Default.MaxDeleteFiles;
            maxDeleteFiles.Enabled = warnDeletion.Checked;

            infoTooltip.SetToolTip(betaProgram, "Receive updates on new beta versions (often unstable, experimental builds)");

            mainPanel.Click += delegate { mainPanel.Focus(); };

            //On change
            //Has to be down & up, otherwise the last character isn't appended for some reason
            computerName.KeyDown          += delegate { Properties.Settings.Default.ComputerName = computerName.Text; Properties.Settings.Default.Save(); };
            computerName.KeyUp            += delegate { Properties.Settings.Default.ComputerName = computerName.Text; Properties.Settings.Default.Save(); };
            fileEditedMargin.ValueChanged += delegate { Properties.Settings.Default.FileEditedMargin = (float)fileEditedMargin.Value; Properties.Settings.Default.Save(); };
            fileReadDelay.ValueChanged    += delegate { Properties.Settings.Default.FileReadDelay = (float)fileReadDelay.Value; Properties.Settings.Default.Save(); };
            maxDeleteFiles.ValueChanged   += delegate { Properties.Settings.Default.MaxDeleteFiles = (int)maxDeleteFiles.Value; Properties.Settings.Default.Save(); };

            /* Translations */
            int    i = 0;
            string activeLanguage = Properties.Settings.Default.ActiveLanguage;

            foreach (string item in Translator.languagesArray)
            {
                programLanguage.Items.Add(item);

                if (activeLanguage == item)
                {
                    programLanguage.SelectedIndex = i;
                }
                ++i;
            }
            Text = Translator.__("window_name", "settings");

            foreach (Control x in this.Controls)
            {
                Translator.TranslateWinForms("settings", x.Controls);
            }
        }
            public void CloudServiceChosen(string service = "")
            {
                switch (service)
                {
                case "dropbox":
                case "onedrive":
                case "googledrive":
                    backgroundCheckerServiceName = service;
                    break;

                default:
                    return;
                }

                if (CloudServiceFunctions.GetCloudServicePath(backgroundCheckerServiceName) != "")
                {
                    //Cloud service found
                    MainProgram.DoDebug("Cloud service " + backgroundCheckerServiceName + " is installed");
                    bool partial = false;

                    if (backgroundCheckerServiceName == "googledrive")
                    {
                        partial = CloudServiceFunctions.GetGoogleDriveFolder() != String.Empty;
                    }

                    if (theWebBrowser != null)
                    {
                        IntPtr theHandle = IntPtr.Zero;
                        try {
                            theHandle = theWebBrowser.Handle;
                        } catch {
                            MainProgram.DoDebug("Failed to get web browser handle.");
                            MessageBox.Show(Translator.__("cloud_setup_failed", "general"), MainProgram.messageBoxTitle);
                        }

                        if (theHandle != IntPtr.Zero)
                        {
                            if (theWebBrowser.Handle != null)
                            {
                                theWebBrowser.Document.InvokeScript("CloudServiceInstalled", new Object[2] {
                                    true, partial
                                });
                            }
                        }
                    }

                    if (partial)
                    {
                        CheckLocalGoogleDrive();
                    }
                }
                else
                {
                    //Not found
                    new Thread(() => {
                        Thread.CurrentThread.IsBackground = true;
                        string checkValue = "";
                        stopCheck         = false;

                        MainProgram.DoDebug("Could not find cloud service. Running loop to check");
                        while (checkValue == "" && !stopCheck)
                        {
                            checkValue = CloudServiceFunctions.GetCloudServicePath(backgroundCheckerServiceName);
                            Thread.Sleep(1000);
                        }
                        if (stopCheck)
                        {
                            stopCheck = false;
                            return;
                        }

                        //Cloud service has been installed since we last checked!
                        MainProgram.DoDebug("Cloud service has been installed since last check. Proceed.");

                        if (theWebBrowser != null)
                        {
                            if (theWebBrowser.Handle != null)
                            {
                                theWebBrowser.Invoke(new Action(() => {
                                    if (backgroundCheckerServiceName == "googledrive")
                                    {
                                        bool partial = CloudServiceFunctions.GetGoogleDriveFolder() != String.Empty;
                                        theWebBrowser.Document.InvokeScript("CloudServiceInstalled", new Object[2] {
                                            true, partial
                                        });
                                        if (partial)
                                        {
                                            CheckLocalGoogleDrive();
                                        }
                                    }
                                    else
                                    {
                                        theWebBrowser.Document.InvokeScript("CloudServiceInstalled", new Object[1] {
                                            true
                                        });
                                    }
                                }));
                            }
                        }
                    }).Start();
                }
            }
        public TestActionWindow()
        {
            InitializeComponent();
            MaximizeBox = false;

            sWebBrowser = webBrowser;

            //TODO: Make it local
            //webBrowser.Url = new Uri(String.Format("file:///{0}/test.html", MainProgram.currentLocation));
            sWebBrowser.Url = new Uri("https://assistantcomputercontrol.com/success_error_listen.html");

            sWebBrowser.DocumentCompleted += delegate {
                browserLoaded = true;
                webBrowser.Document.InvokeScript("showLoader");
            };

            VisibleChanged += VisibilityChanged;
            FormClosed     += delegate { MainProgram.testingAction = false; };

            Text = Translator.__("window_name", "test_action_window");
            string listeningInText = Translator.__("description", "test_action_window") + "\n\n" + Translator.__("listening_in", "test_action_window") + "\n" + MainProgram.CheckPath() + "\n" + Translator.__("listening_for", "test_action_window") + " \"." + Properties.Settings.Default.ActionFileExtension + "\"";

            actionTesterLabel.Text = listeningInText;
        }
 public void AddOpenOnStartupMenu()
 {
     trayMenu.MenuItems.Add(Translator.__("open_on_startup", "tray_menu"), new EventHandler(TrayCreateStartupLink));
 }
        public bool Check(bool debug = false)
        {
            if (MainProgram.isCheckingForUpdate)
            {
                return(false);
            }

            MainProgram.isCheckingForUpdate = true;
            MainProgram.DoDebug("Checking for updates...");

            string latestReleaseJson = null;
            string latestBetaJson    = null;

            //Check and get latest
            if (Properties.Settings.Default.LastOpenedDate.Date != DateTime.UtcNow.Date)
            {
                releaseJsonUrl += "&daily_check";
                betaJsonUrl    += "&daily_check";

                Properties.Settings.Default.LastOpenedDate = DateTime.UtcNow;
                Properties.Settings.Default.Save();
            }

            try {
                if (RemoteFileExists(releaseJsonUrl))
                {
                    using (WebClient client = new WebClient()) {
                        latestReleaseJson = client.DownloadString(releaseJsonUrl);
                    }
                    if (latestReleaseJson == string.Empty)
                    {
                        latestReleaseJson = null;
                    }
                }

                //Check and get beta
                if (Properties.Settings.Default.BetaProgram && RemoteFileExists(betaJsonUrl))
                {
                    using (WebClient client = new WebClient()) {
                        latestBetaJson = client.DownloadString(betaJsonUrl);
                    }
                    if (latestBetaJson == string.Empty)
                    {
                        latestBetaJson = null;
                    }
                }

                if (latestReleaseJson != null || latestBetaJson != null)
                {
                    Version newVersion = null
                    , latestRelease
                    , latestBeta;

                    if (latestReleaseJson != null && latestBetaJson != null)
                    {
                        //Beta program enabled; check both release and beta for newest update
                        latestRelease = JsonConvert.DeserializeObject <Version>(latestReleaseJson);
                        latestBeta    = JsonConvert.DeserializeObject <Version>(latestBetaJson);

                        if (DateTime.Parse(latestRelease.datetime) > DateTime.Parse(MainProgram.releaseDate) ||
                            DateTime.Parse(latestBeta.datetime) > DateTime.Parse(MainProgram.releaseDate))
                        {
                            //Both latest release and beta is ahead of this current build
                            if (DateTime.Parse(latestRelease.datetime) > DateTime.Parse(latestBeta.datetime))
                            {
                                //Release is newest
                                newVersion = latestRelease;
                            }
                            else
                            {
                                //Beta is newest
                                newVersion = latestBeta;
                            }
                        }
                        else
                        {
                            //None of them are newer. Nothing new
                            MainProgram.DoDebug("Software up to date (beta program enabled)");

                            MainProgram.isCheckingForUpdate = false;
                            return(false);
                        }
                    }
                    else if (latestReleaseJson != null && latestBetaJson == null)
                    {
                        //Only check latest
                        latestRelease = JsonConvert.DeserializeObject <Version>(latestReleaseJson);

                        if (DateTime.Parse(latestRelease.datetime) > DateTime.Parse(MainProgram.releaseDate) && latestRelease.version != MainProgram.softwareVersion)
                        {
                            //Newer build
                            newVersion = latestRelease;
                        }
                        else
                        {
                            //Not new, move on
                            MainProgram.DoDebug("Software up to date");
                            MainProgram.isCheckingForUpdate = false;
                            return(false);
                        }
                    }
                    else if (latestReleaseJson == null && latestBetaJson != null)
                    {
                        //Couldn't reach "latest" update, but beta-updates are enabled
                        latestBeta = JsonConvert.DeserializeObject <Version>(latestBetaJson);

                        if (latestBeta != null)
                        {
                            if (DateTime.Parse(latestBeta.datetime) > DateTime.Parse(MainProgram.releaseDate))
                            {
                                //Newer build
                                newVersion = latestBeta;
                            }
                            else
                            {
                                //Not new, move on
                                MainProgram.DoDebug("Software up to date (beta program enabled)");
                                MainProgram.isCheckingForUpdate = false;
                                return(false);
                            }
                        }
                    }
                    else
                    {
                        MainProgram.DoDebug("Both release and beta is NULL, no new updates, or no contact to the server.");
                    }

                    if (newVersion != null && newVersion.version != MainProgram.softwareVersion)
                    {
                        //New version available
                        MainProgram.DoDebug("New software version found (" + newVersion.version + ") [" + newVersion.type + "], current; " + MainProgram.softwareVersion);
                        DialogResult dialogResult = MessageBox.Show(Translator.__("new_version_found", "check_for_update").Replace("{version_num}", newVersion.version).Replace("{version_type}", newVersion.type), Translator.__("new_version_found_title", "check_for_update") + " | " + MainProgram.messageBoxTitle, MessageBoxButtons.YesNo);
                        if (dialogResult == DialogResult.Yes)
                        {
                            MainProgram.DoDebug("User chose \"yes\" to install update");
                            DownloadFile(newVersion.installpath + "&upgrade=true");
                        }
                        else if (dialogResult == DialogResult.No)
                        {
                            MainProgram.DoDebug("User did not want to install update");
                        }
                        MainProgram.isCheckingForUpdate = false;
                        return(true);
                    }
                    else
                    {
                        MainProgram.DoDebug("Software up to date");
                        if (debug)
                        {
                            MessageBox.Show(Translator.__("no_new_update", "check_for_update"), Translator.__("check_for_update_title", "check_for_update") + " | " + MainProgram.messageBoxTitle);
                        }
                    }
                }
                else
                {
                    MainProgram.DoDebug("Could not reach the webserver (both 'release' and 'beta' json files couldn't be reached)");
                    if (debug)
                    {
                        MessageBox.Show(Translator.__("webservers_offline", "check_for_update"), Translator.__("check_for_update_title", "check_for_update") + " | " + MainProgram.messageBoxTitle);
                    }
                }
            } catch (Exception e) {
                MainProgram.DoDebug("Failed to check for update (exception); " + e.Message);
            }

            MainProgram.isCheckingForUpdate = false;
            return(false);
        }
        public static void DownloadFile(string url)
        {
            url += "&upgrade_id=" + Guid.NewGuid();
            if (RemoteFileExists(url + "&just_checking"))
            {
                MainProgram.DoDebug("Downloading file from url; " + url);

                try {
                    WebClient client = new WebClient();
                    Uri       uri    = new Uri(url);

                    MainProgram.updateProgressWindow = new UpdateProgress();
                    MainProgram.updateProgressWindow.Show();

                    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);
                    client.DownloadFileCompleted   += new AsyncCompletedEventHandler(FileDownloadedCallback);

                    targetLocation = Path.Combine(Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Downloads"), "ACCsetup.exe");
                    if (File.Exists(targetLocation))
                    {
                        try {
                            File.Delete(targetLocation);
                        } catch (Exception ex) {
                            MainProgram.DoDebug("Failed to delete file at " + targetLocation);
                            MainProgram.DoDebug("Error; " + ex);
                        }
                    }
                    client.DownloadFileAsync(uri, targetLocation);

                    Application.Run();
                } catch (Exception e) {
                    MainProgram.DoDebug("Failed to download the new ACC installer; " + e.Message);
                    MessageBox.Show(Translator.__("download_failed", "check_for_update"), Translator.__("error", "general") + " | " + MainProgram.messageBoxTitle);
                }
            }
            else
            {
                MainProgram.DoDebug("Failed to update, installation URL does not exist (" + url + ").");
                MessageBox.Show(Translator.__("website_offline", "check_for_update"), Translator.__("error", "general") + " | " + MainProgram.messageBoxTitle);
            }
        }