public static string ImportElement(string nodeName, string filename)
 {
     try {
         XDocument xml        = XDocument.Load(filename);
         XElement  settingsXE = xml.Descendants(ns + "Settings").FirstOrDefault();
         XElement  xe         = settingsXE.Elements(ns + nodeName).First();
         log.Debug("Retrieved setting '" + nodeName + "' with value '" + xe.Value + "'");
         return(xe.Value);
     } catch (System.InvalidOperationException ex) {
         if (OGCSexception.GetErrorCode(ex) == "0x80131509")   //Sequence contains no elements
         {
             log.Warn("'" + nodeName + "' could not be found.");
         }
         else
         {
             log.Error("Failed retrieving '" + nodeName + "' from " + filename);
             OGCSexception.Analyse(ex);
         }
         return(null);
     } catch (System.Exception ex) {
         log.Error("Failed retrieving '" + nodeName + "' from " + filename);
         OGCSexception.Analyse(ex);
         return(null);
     }
 }
        private static Boolean exceptionIsDeleted(Microsoft.Office.Interop.Outlook.Exception oExcp)
        {
            if (oExcp.Deleted)
            {
                return(true);
            }
            AppointmentItem ai = null;

            try {
                ai = oExcp.AppointmentItem;
                return(false);
            } catch (System.Exception ex) {
                OGCSexception.Analyse(ex);
                if (ex.Message == "You changed one of the recurrences of this item, and this instance no longer exists. Close any open items and try again.")
                {
                    log.Warn("This Outlook recurrence instance has become inaccessible, probably due to caching");
                    return(true);
                }
                else
                {
                    log.Warn("Error when determining if Outlook recurrence is deleted or not.\r\n" + ex.Message);
                    return(true);
                }
            } finally {
                ai = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(ai);
            }
        }
Example #3
0
        private void checkForUpdate(String localVersion)
        {
            if (System.Diagnostics.Debugger.IsAttached && File.Exists(tzdbFilename))
            {
                return;
            }

            log.Debug("Checking for new timezone database...");
            String nodatimeURL = "http://nodatime.org/tzdb/latest.txt";
            String html        = "";

            System.Net.WebClient wc = new System.Net.WebClient();
            wc.Headers.Add("user-agent", Settings.Instance.Proxy.BrowserUserAgent);
            try {
                html = wc.DownloadString(nodatimeURL);
            } catch (System.Exception ex) {
                log.Error("Failed to get latest NodaTime db version.");
                OGCSexception.Analyse(ex);
                return;
            }

            if (string.IsNullOrEmpty(html))
            {
                log.Warn("Empty response from " + nodatimeURL);
            }
            else
            {
                html = html.TrimEnd('\r', '\n');
                if (html.EndsWith(localVersion + ".nzd"))
                {
                    log.Debug("Already have latest TZDB version.");
                }
                else
                {
                    Regex           rgx     = new Regex(@"https*:.*/tzdb(.*)\.nzd$", RegexOptions.IgnoreCase);
                    MatchCollection matches = rgx.Matches(html);
                    if (matches.Count > 0)
                    {
                        String remoteVersion = matches[0].Result("$1");
                        if (string.Compare(localVersion, remoteVersion, System.StringComparison.InvariantCultureIgnoreCase) < 0)
                        {
                            log.Debug("There is a new version " + remoteVersion);
                            try {
                                wc.DownloadFile(html, tzdbFilename);
                                log.Debug("New TZDB version downloaded - disposing of reference to old db data.");
                                instance = null;
                            } catch (System.Exception ex) {
                                log.Error("Failed to download new TZDB database from " + html);
                                OGCSexception.Analyse(ex);
                            }
                        }
                    }
                    else
                    {
                        log.Warn("Regex to extract latest version is no longer working!");
                    }
                }
            }
        }
        /// <summary>
        /// Check if there is a new release of the application.
        /// </summary>
        /// <param name="updateButton">The button that triggered this, if manually called.</param>
        public async void CheckForUpdate(Button updateButton = null)
        {
            if (string.IsNullOrEmpty(nonGitHubReleaseUri) && Program.InDeveloperMode)
            {
                return;
            }

            bt = updateButton;
            log.Debug((isManualCheck ? "Manual" : "Automatic") + " update check requested.");
            if (isManualCheck)
            {
                updateButton.Text = "Checking...";
            }

            try {
                if (!string.IsNullOrEmpty(nonGitHubReleaseUri) || Program.IsInstalled)
                {
                    try {
                        if (await githubCheck())
                        {
                            log.Info("Restarting OGCS.");
                            try {
                                System.Diagnostics.Process.Start(restartUpdateExe, "--processStartAndWait OutlookGoogleCalendarSync.exe");
                            } catch (System.Exception ex) {
                                OGCSexception.Analyse(ex, true);
                            }
                            try {
                                Forms.Main.Instance.NotificationTray.ExitItem_Click(null, null);
                            } catch (System.Exception ex) {
                                log.Error("Failed to exit via the notification tray icon. " + ex.Message);
                                log.Debug("NotificationTray is " + (Forms.Main.Instance.NotificationTray == null ? "null" : "not null"));
                                Forms.Main.Instance.Close();
                            }
                        }
                    } finally {
                        if (isManualCheck)
                        {
                            updateButton.Text = "Check For Update";
                        }
                    }
                }
                else
                {
                    zipChecker();
                }
            } catch (ApplicationException ex) {
                log.Error(ex.Message + " " + ex.InnerException.Message);
                if (OgcsMessageBox.Show("The upgrade failed.\nWould you like to get the latest version from the project website manually?", "Upgrade Failed", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start("https://phw198.github.io/OutlookGoogleCalendarSync/");
                }
            } catch (System.Exception ex) {
                log.Fail("Failure checking for update. " + ex.Message);
                if (isManualCheck)
                {
                    OgcsMessageBox.Show("Unable to check for new version.", "Check Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        private static void isNewVersion(Boolean isSquirrelInstall)
        {
            string settingsVersion = string.IsNullOrEmpty(Settings.Instance.Version) ? "Unknown" : Settings.Instance.Version;

            if (settingsVersion != Application.ProductVersion)
            {
                log.Info("New version detected - upgraded from " + settingsVersion + " to " + Application.ProductVersion);
                try {
                    Program.ManageStartupRegKey(recreate: true);
                } catch (System.Exception ex) {
                    if (ex is System.Security.SecurityException)
                    {
                        OGCSexception.LogAsFail(ref ex);                                          //User doesn't have rights to access registry
                    }
                    OGCSexception.Analyse("Failed accessing registry for startup key.", ex);
                }
                Settings.Instance.Version = Application.ProductVersion;
                if (Application.ProductVersion.EndsWith(".0"))   //Release notes not updated for hotfixes.
                {
                    System.Diagnostics.Process.Start("https://github.com/phw198/OutlookGoogleCalendarSync/blob/master/docs/Release%20Notes.md");
                    if (isSquirrelInstall)
                    {
                        Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.upgrade, "from=" + settingsVersion + ";to=" + Application.ProductVersion);
                    }
                }
            }

            //Check upgrade to Squirrel release went OK
            try {
                if (isSquirrelInstall)
                {
                    Int32  upgradedFrom       = Int16.MaxValue;
                    String expectedInstallDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                    expectedInstallDir = Path.Combine(expectedInstallDir, "OutlookGoogleCalendarSync");
                    String paddedVersion = "";
                    if (settingsVersion != "Unknown")
                    {
                        foreach (String versionBit in settingsVersion.Split('.'))
                        {
                            paddedVersion += versionBit.PadLeft(2, '0');
                        }
                        upgradedFrom = Convert.ToInt32(paddedVersion);
                    }
                    if ((settingsVersion == "Unknown" || upgradedFrom < 2050000) &&
                        !System.Windows.Forms.Application.ExecutablePath.ToString().StartsWith(expectedInstallDir))
                    {
                        log.Warn("OGCS is running from " + System.Windows.Forms.Application.ExecutablePath.ToString());
                        OgcsMessageBox.Show("A suspected improper install location has been detected.\r\n" +
                                            "Click 'OK' for further details.", "Improper Install Location",
                                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        System.Diagnostics.Process.Start("https://github.com/phw198/OutlookGoogleCalendarSync/issues/265");
                    }
                }
            } catch (System.Exception ex) {
                log.Warn("Failed to determine if OGCS is installed in the correct location.");
                log.Error(ex.Message);
            }
        }
        private String parseEmoji(String output, Markup?markupPrefix = null)
        {
            if (markupPrefix != null)
            {
                output = (":" + markupPrefix.ToString() + ":") + output;
            }

            try {
                //div
                output = Regex.Replace(output, ":info:(<p>)*", "<div class='info'>$1<span class='em em-information_source'></span>");
                output = Regex.Replace(output, ":warning:(<p>)*", "<div class='warning'>$1<span class='em em-warning'></span>");
                output = Regex.Replace(output, ":(error|fail):(<p>)*", "<div class='error'>$2<span class='em em-collision'></span>");
                if (output.StartsWith("<div"))
                {
                    output += "</div>";
                }

                Regex           rgx     = new Regex(":clock(\\d{1,4}):<p>", RegexOptions.IgnoreCase);
                MatchCollection matches = rgx.Matches(output);
                if (matches.Count > 0)
                {
                    String clockTime = matches[0].Result("$1");
                    output = output.Replace(":clock" + clockTime + ":<p>", "<div class='info'><p><span class='em em-clock" + clockTime + "'></span>") + "</div>";
                }

                //h2
                output = output.Replace(":h2:", "<h2 class='sectionHeader'>");
                output = output.Replace(":mag_right:", "<h2 class='sectionHeader'><span class='em em-mag_right'></span>");
                output = output.Replace(":checkered_flag:", "<h2 class='sectionHeader'><span class='em em-checkered_flag'></span>");
                output = output.Replace(":syncDirection:", "<h2 class='sectionHeader'><span class='em em-repeat' style='padding-right: 9px; margin-left:-30px;'></span>");
                if (output.StartsWith("<h2"))
                {
                    output += "</h2>";
                }

                //sectionEnd
                output = output.Replace(":sectionEnd:", "<p class='sectionEnd'>");
                if (output.StartsWith("<p"))
                {
                    output += "</p>";
                }

                output = output.Replace(":appointmentEnd:", "<p class='appointmentEnd'>");
                if (output.StartsWith("<p"))
                {
                    output += "</p>";
                }

                output = output.Replace(":calendar:", "<span class='em em-date' style='margin-top:5px'></span>");
                output = output.Replace("(R)", "<span class='em em-repeat'></span>");
                output = output.Replace("=>", "");
            } catch (System.Exception ex) {
                log.Error("Failed parsing for emoji.");
                OGCSexception.Analyse(ex);
            }
            return(output);
        }
Example #7
0
        private void findCalendars(Folders folders, Dictionary <string, MAPIFolder> calendarFolders, String excludeDeletedFolder, MAPIFolder defaultCalendar = null)
        {
            //Initiate progress bar (red line underneath "Getting calendars" text)
            System.Drawing.Graphics g          = MainForm.Instance.tabOutlook.CreateGraphics();
            System.Drawing.Pen      p          = new System.Drawing.Pen(System.Drawing.Color.Red, 3);
            System.Drawing.Point    startPoint = new System.Drawing.Point(MainForm.Instance.lOutlookCalendar.Location.X,
                                                                          MainForm.Instance.lOutlookCalendar.Location.Y + MainForm.Instance.lOutlookCalendar.Size.Height + 3);
            double stepSize = MainForm.Instance.lOutlookCalendar.Size.Width / folders.Count;

            int fldCnt = 0;

            foreach (MAPIFolder folder in folders)
            {
                fldCnt++;
                System.Drawing.Point endPoint = new System.Drawing.Point(MainForm.Instance.lOutlookCalendar.Location.X + Convert.ToInt16(fldCnt * stepSize),
                                                                         MainForm.Instance.lOutlookCalendar.Location.Y + MainForm.Instance.lOutlookCalendar.Size.Height + 3);
                try { g.DrawLine(p, startPoint, endPoint); } catch { /*May get GDI+ error if g has been repainted*/ }
                System.Windows.Forms.Application.DoEvents();
                try {
                    OlItemType defaultItemType = folder.DefaultItemType;
                    if (defaultItemType == OlItemType.olAppointmentItem)
                    {
                        if (defaultCalendar == null ||
                            (folder.EntryID != defaultCalendar.EntryID))
                        {
                            calendarFolders.Add(folder.Name, folder);
                        }
                    }
                    if (folder.EntryID != excludeDeletedFolder && folder.Folders.Count > 0)
                    {
                        findCalendars(folder.Folders, calendarFolders, excludeDeletedFolder, defaultCalendar);
                    }
                } catch (System.Exception ex) {
                    OGCSexception.Analyse(ex);
                    if (oApp.Session.ExchangeConnectionMode.ToString().Contains("Disconnected") ||
                        ex.Message.StartsWith("Network problems are preventing connection to Microsoft Exchange.") ||
                        OGCSexception.GetErrorCode(ex, 0x000FFFFF) == "0x00040115")
                    {
                        log.Info("Currently disconnected from Exchange - unable to retrieve MAPI folders.");
                        MainForm.Instance.ToolTips.SetToolTip(MainForm.Instance.cbOutlookCalendars,
                                                              "The Outlook calendar to synchonize with.\nSome may not be listed as you are currently disconnected.");
                    }
                    else
                    {
                        log.Error("Failed to recurse MAPI folders.");
                        log.Error(ex.Message);
                        MessageBox.Show("A problem was encountered when searching for Outlook calendar folders.",
                                        "Calendar Folders", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            p.Dispose();
            try { g.Clear(System.Drawing.Color.White); } catch { }
            g.Dispose();
            System.Windows.Forms.Application.DoEvents();
        }
        public void UpdateWithError(String moreOutput, System.Exception ex, bool notifyBubble = false)
        {
            Markup emoji = Markup.error;

            if (OGCSexception.LoggingAsFail(ex))
            {
                emoji = Markup.fail;
            }
            Update(moreOutput + (!string.IsNullOrEmpty(moreOutput) ? "<br/>" : "") + OGCSexception.FriendlyMessage(ex), emoji, notifyBubble: notifyBubble);
        }
Example #9
0
 /// <summary>
 /// Fails silently if node to be moved does not exist.
 /// </summary>
 /// <param name="nodeName">Node to be moved</param>
 /// <param name="parent">The parent of node being moved</param>
 /// <param name="target">New parent</param>
 public static void MoveElement(String nodeName, XElement parent, XElement target)
 {
     try {
         XElement sourceElement = getElement(nodeName, parent);
         target.Add(sourceElement);
         removeElement(nodeName, parent);
     } catch (System.Exception ex) {
         OGCSexception.Analyse("Could not move '" + nodeName + "'", ex);
     }
 }
Example #10
0
        private void processOutlookExceptions(ref AppointmentItem ai, Event ev, Boolean forceCompare)
        {
            if (!HasExceptions(ev, checkLocalCacheOnly: true))
            {
                return;
            }

            RecurrencePattern oPattern = null;

            try {
                oPattern = ai.GetRecurrencePattern();
                foreach (Event gExcp in Recurrence.Instance.googleExceptions.Where(exp => exp.RecurringEventId == ev.Id))
                {
                    DateTime oExcpDate = gExcp.OriginalStartTime.DateTime ?? DateTime.Parse(gExcp.OriginalStartTime.Date);
                    log.Fine("Found Google exception for " + oExcpDate.ToString());

                    AppointmentItem newAiExcp = null;
                    try {
                        getOutlookInstance(oPattern, oExcpDate, ref newAiExcp);
                        if (newAiExcp == null)
                        {
                            continue;
                        }

                        if (gExcp.Status != "cancelled")
                        {
                            int itemModified = 0;
                            OutlookOgcs.Calendar.Instance.UpdateCalendarEntry(ref newAiExcp, gExcp, ref itemModified, forceCompare);
                            if (itemModified > 0)
                            {
                                try {
                                    newAiExcp.Save();
                                } catch (System.Exception ex) {
                                    OGCSexception.Analyse(ex);
                                    if (ex.Message == "Cannot save this item.")
                                    {
                                        Forms.Main.Instance.Console.Update("Uh oh! Outlook wasn't able to save this recurrence exception! " +
                                                                           "You may have two occurences on the same day, which it doesn't allow.", Console.Markup.warning);
                                    }
                                }
                            }
                        }
                        else
                        {
                            Forms.Main.Instance.Console.Update(OutlookOgcs.Calendar.GetEventSummary(newAiExcp) + "<br/>Deleted.", Console.Markup.calendar);
                            newAiExcp.Delete();
                        }
                    } finally {
                        newAiExcp = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(newAiExcp);
                    }
                }
            } finally {
                oPattern = (RecurrencePattern)OutlookOgcs.Calendar.ReleaseObject(oPattern);
            }
        }
 public static void StackTraceToString()
 {
     try {
         String stackString = "";
         List <System.Diagnostics.StackFrame> stackFrames = new System.Diagnostics.StackTrace().GetFrames().ToList();
         stackFrames.ForEach(sf => stackString += sf.GetMethod().Name + " < ");
         log.Warn("StackTrace path: " + stackString);
     } catch (System.Exception ex) {
         OGCSexception.Analyse(ex);
     }
 }
 private static void clickOnceUninstallError(System.Exception ex)
 {
     if (OGCSexception.GetErrorCode(ex) == "0x80131509")
     {
         log.Debug("No ClickOnce install found.");
     }
     else
     {
         log.Error("Failed removing ClickOnce install.");
         OGCSexception.Analyse(ex, true);
     }
 }
Example #13
0
        /// <summary>
        /// Check if there is a new release of the application.
        /// </summary>
        /// <param name="updateButton">The button that triggered this, if manually called.</param>
        public async void CheckForUpdate(Button updateButton = null)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                return;
            }

            bt = updateButton;
            log.Debug((isManualCheck ? "Manual" : "Automatic") + " update check requested.");
            if (isManualCheck)
            {
                updateButton.Text = "Checking...";
            }

            Settings.Instance.Proxy.Configure();

            try {
                if (IsSquirrelInstall())
                {
                    if (await githubCheck())
                    {
                        log.Info("Restarting OGCS.");
                        try {
                            System.Diagnostics.Process.Start(restartUpdateExe, "--processStartAndWait OutlookGoogleCalendarSync.exe");
                        } catch (System.Exception ex) {
                            OGCSexception.Analyse(ex, true);
                        }
                        try {
                            MainForm.Instance.NotificationTray.ExitItem_Click(null, null);
                        } catch (System.Exception ex) {
                            log.Error("Failed to exit via the notification tray icon. " + ex.Message);
                            log.Debug("NotificationTray is " + (MainForm.Instance.NotificationTray == null ? "null" : "not null"));
                            MainForm.Instance.Close();
                        }
                    }
                    if (isManualCheck)
                    {
                        updateButton.Text = "Check For Update";
                    }
                }
                else
                {
                    zipChecker();
                }
            } catch (System.Exception ex) {
                log.Error("Failure checking for update. " + ex.Message);
                if (isManualCheck)
                {
                    MessageBox.Show("Unable to check for new version.", "Check Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
 private static void onAppUpdate(Version version)
 {
     try {
         using (var mgr = new Squirrel.UpdateManager(null, "OutlookGoogleCalendarSync")) {
             log.Info("Recreating shortcuts.");
             mgr.CreateShortcutsForExecutable(Path.GetFileName(System.Windows.Forms.Application.ExecutablePath),
                                              Squirrel.ShortcutLocation.Desktop | Squirrel.ShortcutLocation.StartMenu, false);
         }
     } catch (System.Exception ex) {
         log.Error("Problem encountered on app update.");
         OGCSexception.Analyse(ex, true);
     }
 }
        public static void ExportElement(string nodeName, object nodeValue, string filename)
        {
            XDocument xml = null;

            try {
                xml = XDocument.Load(filename);
            } catch (System.Exception ex) {
                OGCSexception.Analyse("Failed to load " + filename, ex, true);
                throw;
            }
            XElement settingsXE = null;

            try {
                settingsXE = xml.Descendants(ns + "Settings").FirstOrDefault();
            } catch (System.Exception ex) {
                log.Debug(filename + " head: " + xml.ToString().Substring(0, Math.Min(200, xml.ToString().Length)));
                OGCSexception.Analyse("Could not access 'Settings' element.", ex, true);
                return;
            }
            try {
                XElement xe = settingsXE.Elements(ns + nodeName).First();
                if (nodeValue == null && nodeName == "CloudLogging")   //Nullable Boolean node(s)
                {
                    XNamespace i = "http://www.w3.org/2001/XMLSchema-instance";
                    xe.SetAttributeValue(i + "nil", "true"); //Add nullable attribute 'i:nil="true"'
                    xe.SetValue(String.Empty);
                }
                else
                {
                    xe.SetValue(nodeValue);
                    if (nodeValue is Boolean && nodeValue != null)
                    {
                        xe.RemoveAttributes(); //Remove nullable attribute 'i:nil="true"'
                    }
                }
                xml.Save(filename);
                log.Debug("Setting '" + nodeName + "' updated to '" + nodeValue + "'");
            } catch (System.Exception ex) {
                if (OGCSexception.GetErrorCode(ex) == "0x80131509")   //Sequence contains no elements
                {
                    log.Debug("Adding Setting " + nodeName + " to settings.xml");
                    settingsXE.Add(new XElement(ns + nodeName, nodeValue));
                    xml.Root.Sort();
                    xml.Save(filename);
                }
                else
                {
                    OGCSexception.Analyse("Failed to export setting " + nodeName + "=" + nodeValue + " to " + filename + " file.", ex);
                }
            }
        }
 public void UpdateItem(String itemName, String itemText = null, Boolean enabled = true) {
     try {
         ToolStripItem[] items = this.icon.ContextMenuStrip.Items.Find(itemName, true);
         if (items.Count() > 0) {
             ToolStripItem item = items.First();
             item.Text = itemText ?? item.Text;
             item.Enabled = enabled;
         } else {
             log.Warn("Could not find menu item with name \"" + itemName + "\"");
         }
     } catch (System.Exception ex) {
         OGCSexception.Analyse(ex, true);
     }
 }
Example #17
0
        /// <summary>
        /// Check if there is a new release of the application.
        /// </summary>
        /// <param name="updateButton">The button that triggered this, if manually called.</param>
        public async void CheckForUpdate(Button updateButton = null)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                return;
            }

            bt = updateButton;
            log.Debug((isManualCheck ? "Manual" : "Automatic") + " update check requested.");
            if (isManualCheck)
            {
                updateButton.Text = "Checking...";
            }

            Settings.Instance.Proxy.Configure();

            try {
                if (await githubCheck())
                {
                    if (isManualCheck)
                    {
                        updateButton.Text = "Check For Update";
                    }
                    if (restartRequested)
                    {
                        log.Debug("Restarting");
                        try {
                            //UpdateManager.RestartApp(restartExe); //Removes ClickOnce, but doesn't restart properly
                            System.Diagnostics.Process.Start(restartUpdateExe, "--processStartAndWait OutlookGoogleCalendarSync.exe");
                        } catch (System.Exception ex) {
                            OGCSexception.Analyse(ex, true);
                        }
                        MainForm.Instance.NotificationTray.ExitItem_Click(null, null);
                    }
                }
                else
                {
                    legacyCodeplexCheck();
                }
            } catch (System.Exception ex) {
                log.Error("Failure checking for update. " + ex.Message);
                try { legacyCodeplexCheck(); } catch { }
            } finally {
                if (isManualCheck)
                {
                    updateButton.Text = "Check for Update";
                }
            }
        }
 public void CallGappScript(String type)
 {
     log.Debug("Switching to MD5 for " + type);
     try {
         Forms.Main.Instance.GappBrowser.Navigate("https://script.google.com/macros/s/AKfycbwWILS02uGDgR5rSWEkzOS5FHc1N3MEPpIaMz0zOGIDhQRbhAw/exec?action=makePrivate&accountType=" + type + "&gmailAccount=" + Settings.Instance.GaccountEmail);
         while (Forms.Main.Instance.GappBrowser.ReadyState != WebBrowserReadyState.Complete)
         {
             System.Windows.Forms.Application.DoEvents();
             System.Threading.Thread.Sleep(100);
         }
     } catch (System.Exception ex) {
         OGCSexception.Analyse(ex);
     }
     log.Debug("Done");
 }
 private static void onInitialInstall(Version version)
 {
     try {
         using (var mgr = new Squirrel.UpdateManager(null, "OutlookGoogleCalendarSync")) {
             log.Info("Creating shortcuts.");
             mgr.CreateShortcutsForExecutable(Path.GetFileName(System.Windows.Forms.Application.ExecutablePath),
                                              Squirrel.ShortcutLocation.Desktop | Squirrel.ShortcutLocation.StartMenu, false);
             log.Debug("Creating uninstaller registry keys.");
             mgr.CreateUninstallerRegistryEntry().Wait();
         }
     } catch (System.Exception ex) {
         log.Error("Problem encountered on initiall install.");
         OGCSexception.Analyse(ex, true);
     }
     onFirstRun();
 }
 public static void MakeSquirrelAware()
 {
     try {
         log.Debug("Setting up Squirrel handlers.");
         Squirrel.SquirrelAwareApp.HandleEvents(
             onFirstRun: onFirstRun,
             onInitialInstall: v => onInitialInstall(v),
             onAppUpdate: v => onAppUpdate(v),
             onAppUninstall: v => onAppUninstall(v),
             arguments: fixCliArgs()
             );
     } catch (System.Exception ex) {
         log.Error("SquirrelAwareApp.HandleEvents failed.");
         OGCSexception.Analyse(ex, true);
     }
 }
 private static void purgeLogFiles(Int16 retention)
 {
     log.Info("Purging log files older than " + retention + " days...");
     foreach (String file in System.IO.Directory.GetFiles(UserFilePath, "*.log.????-??-??", SearchOption.TopDirectoryOnly))
     {
         if (System.IO.File.GetLastWriteTime(file) < DateTime.Now.AddDays(-retention))
         {
             try {
                 System.IO.File.Delete(file);
                 log.Debug("Deleted " + MaskFilePath(file));
             } catch (System.Exception ex) {
                 OGCSexception.Analyse("Could not delete file " + file, OGCSexception.LogAsFail(ex));
             }
         }
     }
     log.Info("Purge complete.");
 }
Example #22
0
 private static void onFirstRun()
 {
     try {
         log.Debug("Removing ClickOnce install...");
         var migrator = new ClickOnceToSquirrelMigrator.InSquirrelAppMigrator(Application.ProductName);
         migrator.Execute().Wait();
         log.Info("ClickOnce install has been removed.");
     } catch (System.InvalidOperationException ex) {
         if (OGCSexception.GetErrorCode(ex) == "0x80131509")
         {
             log.Debug("No ClickOnce install found.");
         }
     } catch (System.Exception ex) {
         log.Error("Failed removing ClickOnce install.");
         OGCSexception.Analyse(ex, true);
     }
 }
Example #23
0
        public Boolean IsSquirrelInstall()
        {
            Boolean isSquirrelInstall = false;

            try {
                using (var updateManager = new Squirrel.UpdateManager(null)) {
                    //This just checks if there is an Update.exe file in the parent directory of the OGCS executable
                    isSquirrelInstall = updateManager.IsInstalledApp;
                }
            } catch (System.Exception ex) {
                log.Error("Failed to determine if app is a Squirrel install. Assuming not.");
                OGCSexception.Analyse(ex);
            }

            log.Info("This " + (isSquirrelInstall ? "is" : "is not") + " a Squirrel " + (Program.IsClickOnceInstall ? "aware ClickOnce " : "") + "install.");
            return(isSquirrelInstall);
        }
Example #24
0
        /// <summary>
        /// Replay the logs that the CloudLogger appender did not buffer (because it was off)
        /// </summary>
        private void replayLogs()
        {
            try {
                String        logFile = Path.Combine(log4net.GlobalContext.Properties["LogPath"].ToString(), log4net.GlobalContext.Properties["LogFilename"].ToString());
                List <String> lines   = new List <String>();
                using (FileStream logFileStream = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
                    StreamReader logFileReader = new StreamReader(logFileStream);
                    while (!logFileReader.EndOfStream)
                    {
                        lines.Add(logFileReader.ReadLine());
                    }
                }
                //"2018-07-14 17:22:41,740 DEBUG  10 OutlookGoogleCalendarSync.XMLManager [59] -  Retrieved setting 'CloudLogging' with value 'true'"
                //We want the logging level and the message strings
                Regex rgx = new Regex(@"^\d{4}-\d{2}-\d{2}\s[\d:,]+\s(\w+)\s+\d+\s[\w\.]+\s\[\d+\]\s-\s+(.*?)$", RegexOptions.IgnoreCase);
                foreach (String line in lines.Skip(lines.Count - 50).ToList())
                {
                    MatchCollection matches = rgx.Matches(line);
                    if (matches.Count > 0)
                    {
                        switch (matches[0].Groups[1].ToString())
                        {
                        case "FINE": log.Fine(matches[0].Groups[2].ToString()); break;

                        case "DEBUG": log.Debug(matches[0].Groups[2]); break;

                        case "INFO": log.Info(matches[0].Groups[2]); break;

                        case "WARN": log.Warn(matches[0].Groups[2]); break;

                        case "ERROR": log.Error(matches[0].Groups[2]); break;

                        default: log.Debug(matches[0].Groups[2]); break;
                        }
                    }
                    else
                    {
                        log.Debug(line);
                    }
                }
            } catch (System.Exception ex) {
                log.Warn("Failed to replay logs.");
                OGCSexception.Analyse(ex);
            }
        }
Example #25
0
 public static void Load(String XMLfile = null)
 {
     try {
         Settings.Instance = XMLManager.Import <Settings>(XMLfile ?? ConfigFile);
         log.Fine("User settings loaded.");
         Settings.isLoaded = true;
     } catch (ApplicationException ex) {
         log.Error(ex.Message);
         ResetFile(XMLfile);
         try {
             Settings.Instance = XMLManager.Import <Settings>(XMLfile ?? ConfigFile);
             log.Debug("User settings loaded successfully this time.");
         } catch (System.Exception ex2) {
             log.Error("Still failed to load settings!");
             OGCSexception.Analyse(ex2);
         }
     }
 }
Example #26
0
        /// <summary>
        /// Imports from XML and returns the resulting object of type T.
        /// </summary>
        /// <param name="filename">The XML file from which to import.</param>
        /// <returns></returns>
        public static T Import <T>(string filename)
        {
            FileStream fs     = new FileStream(filename, FileMode.Open, FileAccess.Read);
            T          result = default(T);

            try {
                result = (T) new DataContractSerializer(typeof(T)).ReadObject(fs);
            } catch (System.Exception ex) {
                log.Error("Failed to import settings");
                OGCSexception.Analyse(ex);
                if (MainForm.Instance != null)
                {
                    MainForm.Instance.tabApp.SelectedTab = MainForm.Instance.tabPage_Settings;
                }
            }
            fs.Close();
            return(result);
        }
        private static String getDefaultBrowserPath()
        {
            String urlAssociation = @"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http";
            String browserPathKey = @"$BROWSER$\shell\open\command";

            RegistryKey userChoiceKey = null;

            try {
                //Read default browser path from userChoiceLKey
                userChoiceKey = Registry.CurrentUser.OpenSubKey(urlAssociation + @"\UserChoice", false);

                //If user choice was not found, try machine default
                if (userChoiceKey == null)
                {
                    //Read default browser path from Win XP registry key
                    var browserKey = Registry.ClassesRoot.OpenSubKey(@"HTTP\shell\open\command", false);

                    //If browser path wasn’t found, try Win Vista (and newer) registry key
                    if (browserKey == null)
                    {
                        browserKey = Registry.CurrentUser.OpenSubKey(urlAssociation, false);
                    }
                    String path = CleanifyBrowserPath(browserKey.GetValue(null) as String);
                    browserKey.Close();
                    return(path);
                }
                else
                {
                    // user defined browser choice was found
                    String progId = (userChoiceKey.GetValue("ProgId").ToString());
                    userChoiceKey.Close();

                    // now look up the path of the executable
                    String concreteBrowserKey = browserPathKey.Replace("$BROWSER$", progId);
                    var    kp          = Registry.ClassesRoot.OpenSubKey(concreteBrowserKey, false);
                    String browserPath = CleanifyBrowserPath(kp.GetValue(null) as String);
                    kp.Close();
                    return(browserPath);
                }
            } catch (System.Exception ex) {
                OGCSexception.Analyse(ex);
                return("");
            }
        }
        /// <summary>
        /// Imports from XML and returns the resulting object of type T.
        /// </summary>
        /// <param name="filename">The XML file from which to import.</param>
        /// <returns></returns>
        public static T Import <T>(string filename)
        {
            FileStream fs     = new FileStream(filename, FileMode.Open, FileAccess.Read);
            T          result = default(T);

            try {
                result = (T) new DataContractSerializer(typeof(T)).ReadObject(fs);
            } catch (System.Exception ex) {
                OGCSexception.Analyse(ex);
                if (Forms.Main.Instance != null)
                {
                    Forms.Main.Instance.tabApp.SelectedTab = Forms.Main.Instance.tabPage_Settings;
                }
                throw new ApplicationException("Failed to import settings.");
            } finally {
                fs.Close();
            }
            return(result);
        }
Example #29
0
 public static void Load(string XMLfile = null)
 {
     try {
         Settings.Instance = XMLManager.Import <Settings>(XMLfile ?? Program.SettingsFile);
         log.Fine("User settings loaded.");
     } catch (ApplicationException ex) {
         log.Error(ex.Message);
         System.Windows.Forms.MessageBox.Show("Your OGCS settings appear to be corrupt and will have to be reset.",
                                              "Corrupt OGCS Settings", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation);
         log.Warn("Resetting settings.xml file to defaults.");
         Settings.Instance.Save(XMLfile ?? Program.SettingsFile);
         try {
             Settings.Instance = XMLManager.Import <Settings>(XMLfile ?? Program.SettingsFile);
             log.Debug("User settings loaded successfully this time.");
         } catch (System.Exception ex2) {
             log.Error("Still failed to load settings!");
             OGCSexception.Analyse(ex2);
         }
     }
 }
        public static void TrackVersions()
        {
            if (Program.InDeveloperMode)
            {
                return;
            }

            //OUTLOOK CLIENT
            String outlookVersion = "Unknown";

            try {
                switch (OutlookOgcs.Factory.OutlookVersion)
                {
                case 11: outlookVersion = "2003"; break;

                case 12: outlookVersion = "2007"; break;

                case 14: outlookVersion = "2010"; break;

                case 15: outlookVersion = "2013"; break;

                case 16: outlookVersion = "2016"; break;

                case 17: outlookVersion = "2019"; break;

                default: outlookVersion = "Unknown-" + OutlookOgcs.Factory.OutlookVersion; break;
                }
            } catch (System.Exception ex) {
                log.Fail("Failed determining Outlook client version.");
                if (ex is ApplicationException)
                {
                    throw;
                }
                OGCSexception.Analyse(ex);
                outlookVersion = "Unknown";
            }
            Send(Analytics.Category.outlook, Analytics.Action.version, outlookVersion);

            //OGCS APPLICATION
            Send(Analytics.Category.ogcs, Analytics.Action.version, System.Windows.Forms.Application.ProductVersion);
        }