public static void ExportElement(string nodeName, object nodeValue, string filename) { XDocument xml = XDocument.Load(filename); XElement settingsXE = xml.Descendants(ns + "Settings").FirstOrDefault(); try { XElement xe = settingsXE.Elements(ns + nodeName).First(); 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(ex); log.Error("Failed to export setting " + nodeName + "=" + nodeValue + " to settings.xml file."); } } }
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); } }
public void RemoveProfileItem(String itemText) { try { ToolStripItem[] items = this.icon.ContextMenuStrip.Items.Find("sync", false); if (items.Count() > 0) { ToolStripItem item = items.First(); if (item is ToolStripMenuItem) { ToolStripMenuItem rootMenu = item as ToolStripMenuItem; items = rootMenu.DropDown.Items.Find("sync", false); items.ToList().Where(i => i.Text == itemText).ToList().ForEach(j => rootMenu.DropDownItems.Remove(j)); } else { log.Error("'Sync Now' item found does not contain a menu"); } } else { log.Error("Could not find root 'sync' item"); } } catch (System.Exception ex) { if (Forms.Main.Instance.IsDisposed) { return; } OGCSexception.Analyse(ex, true); } }
private static void onAppUninstall(Version version) { try { using (var mgr = new Squirrel.UpdateManager(null, "OutlookGoogleCalendarSync")) { log.Info("Removing shortcuts."); mgr.RemoveShortcutsForExecutable(Path.GetFileName(System.Windows.Forms.Application.ExecutablePath), Squirrel.ShortcutLocation.Desktop | Squirrel.ShortcutLocation.StartMenu); String startMenuFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), "Paul Woolcock"); Directory.Delete(startMenuFolder); log.Debug("Removing registry uninstall keys."); mgr.RemoveUninstallerRegistryEntry(); } if (MessageBox.Show("Sorry to see you go!\nCould you spare 30 seconds for some feedback?", "Uninstalling OGCS", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { log.Debug("User opted to give feedback."); System.Diagnostics.Process.Start("https://docs.google.com/forms/d/e/1FAIpQLSfRWYFdgyfbFJBMQ0dz14patu195KSKxdLj8lpWvLtZn-GArw/viewform"); } else { log.Debug("User opted not to give feedback."); } log.Info("Deleting directory " + Path.GetDirectoryName(Program.SettingsFile)); try { log.Logger.Repository.Shutdown(); log4net.LogManager.Shutdown(); Directory.Delete(Path.GetDirectoryName(Program.SettingsFile), true); } catch (System.Exception ex) { try { log.Error(ex.Message); } catch { } } } catch (System.Exception ex) { log.Error("Problem encountered on app uninstall."); OGCSexception.Analyse(ex, true); } }
public static void ExportElement(string nodeName, object nodeValue, string filename) { XDocument xml = XDocument.Load(filename); XElement settingsXE = xml.Descendants(ns + "Settings").FirstOrDefault(); try { XElement xe = settingsXE.Elements(ns + nodeName).First(); xe.SetValue(nodeValue); 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"); //This appends to the end, which won't import properly. //settingsXE.Add(new XElement(ns + nodeName, nodeValue)); //To save writing a sort method, let's just save everything! Settings.Instance.Save(); } else { OGCSexception.Analyse(ex); log.Error("Failed to export setting " + nodeName + "=" + nodeValue + " to settings.xml file."); } } }
public static void OpenBrowser(String url) { try { System.Diagnostics.Process.Start(url); return; } catch (System.Exception ex) { OGCSexception.Analyse("Could not open default browser.", OGCSexception.LogAsFail(ex)); } //OK, let's try and determine the default browser from the registry and then directly invoke it. Why is this so much work! String browserPath = getDefaultBrowserPath(); if (string.IsNullOrEmpty(browserPath)) { log.Error("No default browser discovered in the registry."); } else { try { log.Debug("Browsing using " + browserPath); System.Diagnostics.Process.Start(browserPath, url); } catch (System.Exception ex) { log.Fail("Could not navigate to " + url); log.Error("Could not open browser with " + browserPath, ex); } } }
public static String FixAlexa(String timezone) { //Alexa (Amazon Echo) is a bit dumb - she creates Google Events with a GMT offset "timezone". Eg GMT-5 //This isn't actually a timezone at all, but an area, and not a legal IANA value. //So to workaround this, we'll turn it into something valid at least, by inverting the offset sign and prefixing "Etc\" //Issues:- // * As it's an area, Microsoft will just guess at the zone - so GMT-5 for CST may end up as Bogata/Lima. // * Not sure what happens with half hour offset, such as in India with GMT+4:30 // * Not sure what happens with Daylight Saving, as zones in the same area may or may not follow DST. try { System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(@"^GMT([+-])(\d{1,2})(:\d\d)*$"); System.Text.RegularExpressions.MatchCollection matches = rgx.Matches(timezone); if (matches.Count > 0) { log.Debug("Found an Alexa \"timezone\" of " + timezone); String fixedTimezone = "Etc/GMT" + (matches[0].Groups[1].Value == "+" ? "-" : "+") + Convert.ToInt16(matches[0].Groups[2].Value).ToString(); log.Debug("Translated to " + fixedTimezone); return(fixedTimezone); } } catch (System.Exception ex) { log.Error("Failed to detect and translate Alexa timezone."); OGCSexception.Analyse(ex); } return(timezone); }
private void getDefaultCalendar(NameSpace oNS, ref MAPIFolder defaultCalendar) { log.Debug("Finding default Mailbox calendar folders"); try { MainForm.Instance.rbOutlookDefaultMB.CheckedChanged -= MainForm.Instance.rbOutlookDefaultMB_CheckedChanged; MainForm.Instance.rbOutlookDefaultMB.Checked = true; Settings.Instance.OutlookService = OutlookCalendar.Service.DefaultMailbox; MainForm.Instance.rbOutlookDefaultMB.CheckedChanged += MainForm.Instance.rbOutlookDefaultMB_CheckedChanged; defaultCalendar = oNS.GetDefaultFolder(OlDefaultFolders.olFolderCalendar); calendarFolders.Add("Default " + defaultCalendar.Name, defaultCalendar); string excludeDeletedFolder = folders.Application.Session.GetDefaultFolder(OlDefaultFolders.olFolderDeletedItems).EntryID; MainForm.Instance.lOutlookCalendar.BackColor = System.Drawing.Color.Yellow; MainForm.Instance.lOutlookCalendar.Text = "Getting calendars"; findCalendars(oNS.DefaultStore.GetRootFolder().Folders, calendarFolders, excludeDeletedFolder, defaultCalendar); MainForm.Instance.lOutlookCalendar.BackColor = System.Drawing.Color.White; MainForm.Instance.lOutlookCalendar.Text = "Select calendar"; } catch (System.Exception ex) { OGCSexception.Analyse(ex, true); throw ex; } }
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 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); }
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(); }
/// <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); } }
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); } }
/// <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); } }
/// <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."); }
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); } }
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); }
/// <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); } }