From 3624e132bbd712c2377b1fdc0d93fe90baa61cb1 Mon Sep 17 00:00:00 2001 From: Paul Woolcock <11843015+phw198@users.noreply.github.com> Date: Mon, 8 Apr 2024 00:14:10 +0100 Subject: [PATCH 1/8] Code refactor under OutlookGoogleCalendarSync.Outlook namespace --- .../Extensions/ColourPicker.cs | 30 ++-- .../Forms/ColourMap.cs | 12 +- .../Forms/MainForm.cs | 118 +++++++-------- .../GoogleOgcs/CustomProperty.cs | 2 +- .../GoogleOgcs/EventColour.cs | 6 +- .../GoogleOgcs/GoogleCalendar.cs | 114 +++++++-------- .../NotificationTray.cs | 2 +- .../OutlookFactory.cs | 18 +-- .../OutlookInterface.cs | 10 +- .../OutlookNew.cs | 92 ++++++------ .../OutlookOld.cs | 48 +++---- .../CustomProperty.cs | 36 ++--- .../ExplorerWatcher.cs | 39 +++-- .../{OutlookOgcs => Outlook}/GMeet.cs | 2 +- .../OutlookCalendar.cs | 83 ++++++----- .../OutlookCategories.cs | 134 +++++++++--------- .../OutlookErrors.cs | 2 +- .../OutlookGoogleCalendarSync.csproj | 20 +-- src/OutlookGoogleCalendarSync/Program.cs | 2 +- src/OutlookGoogleCalendarSync/Recurrence.cs | 82 +++++------ .../SettingsStore/Calendar.cs | 10 +- .../Sync/Calendar.cs | 82 +++++------ src/OutlookGoogleCalendarSync/Sync/Timer.cs | 16 +-- src/OutlookGoogleCalendarSync/Telemetry.cs | 2 +- 24 files changed, 479 insertions(+), 483 deletions(-) rename src/OutlookGoogleCalendarSync/{OutlookOgcs => Outlook.Factory}/OutlookFactory.cs (93%) rename src/OutlookGoogleCalendarSync/{OutlookOgcs => Outlook.Factory}/OutlookInterface.cs (93%) rename src/OutlookGoogleCalendarSync/{OutlookOgcs => Outlook.Factory}/OutlookNew.cs (92%) rename src/OutlookGoogleCalendarSync/{OutlookOgcs => Outlook.Factory}/OutlookOld.cs (95%) rename src/OutlookGoogleCalendarSync/{OutlookOgcs => Outlook}/CustomProperty.cs (91%) rename src/OutlookGoogleCalendarSync/{OutlookOgcs => Outlook}/ExplorerWatcher.cs (89%) rename src/OutlookGoogleCalendarSync/{OutlookOgcs => Outlook}/GMeet.cs (99%) rename src/OutlookGoogleCalendarSync/{OutlookOgcs => Outlook}/OutlookCalendar.cs (96%) rename src/OutlookGoogleCalendarSync/{OutlookOgcs => Outlook}/OutlookCategories.cs (63%) rename src/OutlookGoogleCalendarSync/{Ogcs.Outlook => Outlook}/OutlookErrors.cs (98%) diff --git a/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs b/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs index 944735b8..c780c8c1 100644 --- a/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs +++ b/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs @@ -26,8 +26,8 @@ public void AddColourItems() { /// Add all the available Outlook colours /// public void AddStandardColours() { - foreach (KeyValuePair colour in OutlookOgcs.Categories.Map.Colours) { - Items.Add(new OutlookOgcs.Categories.ColourInfo(colour.Key, colour.Value)); + foreach (KeyValuePair colour in Outlook.Categories.Map.Colours) { + Items.Add(new Outlook.Categories.ColourInfo(colour.Key, colour.Value)); } } @@ -35,9 +35,9 @@ public void AddStandardColours() { /// Add just the colours associated with categories /// public void AddCategoryColours() { - if (OutlookOgcs.Factory.OutlookVersionName == OutlookOgcs.Factory.OutlookVersionNames.Outlook2003) return; + if (Outlook.Factory.OutlookVersionName == Outlook.Factory.OutlookVersionNames.Outlook2003) return; - Items.AddRange(OutlookOgcs.Calendar.Categories.DropdownItems().ToArray()); + Items.AddRange(Outlook.Calendar.Categories.DropdownItems().ToArray()); } public void ColourPicker_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e) { @@ -46,12 +46,12 @@ public void ColourPicker_DrawItem(object sender, System.Windows.Forms.DrawItemEv return; // Get the colour - OutlookOgcs.Categories.ColourInfo colour = (OutlookOgcs.Categories.ColourInfo)Items[e.Index]; + Outlook.Categories.ColourInfo colour = (Outlook.Categories.ColourInfo)Items[e.Index]; ColourCombobox.DrawComboboxItemColour(cbColour, new SolidBrush(colour.Colour), colour.Text, e); } - public new OutlookOgcs.Categories.ColourInfo SelectedItem { - get { return (OutlookOgcs.Categories.ColourInfo)base.SelectedItem; } + public new Outlook.Categories.ColourInfo SelectedItem { + get { return (Outlook.Categories.ColourInfo)base.SelectedItem; } set { base.SelectedItem = value; } } } @@ -187,8 +187,8 @@ public override void InitializeEditingControl(int rowIndex, object initialFormat if (ctl.Items.Count == 0) ctl.PopulateDropdownItems(); if (!string.IsNullOrEmpty(currentText)) this.Value = currentText; - - foreach (OutlookOgcs.Categories.ColourInfo ci in Forms.ColourMap.OutlookComboBox.Items) { + + foreach (Outlook.Categories.ColourInfo ci in Forms.ColourMap.OutlookComboBox.Items) { if (ci.Text == (String)this.Value) { ctl.SelectedValue = ci; break; @@ -206,7 +206,7 @@ public override Type EditType { public override Type ValueType { get { - return typeof(OutlookOgcs.Categories.ColourInfo); + return typeof(Outlook.Categories.ColourInfo); } } @@ -224,7 +224,7 @@ protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.R if (rowIndex < 0) return; - foreach (OutlookOgcs.Categories.ColourInfo ci in Forms.ColourMap.OutlookComboBox.Items) { + foreach (Outlook.Categories.ColourInfo ci in Forms.ColourMap.OutlookComboBox.Items) { if (ci.Text == this.Value.ToString()) { Brush boxBrush = new SolidBrush(ci.Colour); Brush textBrush = SystemBrushes.WindowText; @@ -464,8 +464,8 @@ public OutlookColourCombobox() { } public void PopulateDropdownItems() { - Dictionary cbItems = new Dictionary(); - foreach (OutlookOgcs.Categories.ColourInfo ci in Forms.ColourMap.OutlookComboBox.Items) { + Dictionary cbItems = new Dictionary(); + foreach (Outlook.Categories.ColourInfo ci in Forms.ColourMap.OutlookComboBox.Items) { cbItems.Add(ci, ci.Text); } this.DataSource = new BindingSource(cbItems, null); @@ -479,11 +479,11 @@ void ComboboxColor_DrawItem(object sender, DrawItemEventArgs e) { if (indexItem < 0 || indexItem >= cbColour.Items.Count) return; - KeyValuePair kvp = (KeyValuePair< OutlookOgcs.Categories.ColourInfo, String>)cbColour.Items[indexItem]; + KeyValuePair kvp = (KeyValuePair< Outlook.Categories.ColourInfo, String>)cbColour.Items[indexItem]; if (kvp.Key != null) { // Get the colour OlCategoryColor olColour = kvp.Key.OutlookCategory; - Brush brush = new SolidBrush(OutlookOgcs.Categories.Map.RgbColour(olColour)); + Brush brush = new SolidBrush(Outlook.Categories.Map.RgbColour(olColour)); DrawComboboxItemColour(cbColour, brush, kvp.Value, e); } diff --git a/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs b/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs index adc6acec..20841140 100644 --- a/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs +++ b/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs @@ -24,7 +24,7 @@ public ColourMap() { } private void ColourMap_FormClosed(object sender, EventArgs e) { - OutlookOgcs.Calendar.Disconnect(true); + Outlook.Calendar.Disconnect(true); } protected override void Dispose(bool disposing) { @@ -32,7 +32,7 @@ protected override void Dispose(bool disposing) { if (components != null) components.Dispose(); Forms.Main.Instance.btColourMap.Enabled = true; - OutlookOgcs.Calendar.Disconnect(true); + Outlook.Calendar.Disconnect(true); } base.Dispose(disposing); } @@ -273,22 +273,22 @@ private void ddGoogleColour_SelectedIndexChanged(object sender, EventArgs e) { } if (string.IsNullOrEmpty(oCatName)) - oCatName = OutlookOgcs.Calendar.Instance.GetCategoryColour(ddGoogleColour.SelectedItem.Id, false); + oCatName = Outlook.Calendar.Instance.GetCategoryColour(ddGoogleColour.SelectedItem.Id, false); if (!string.IsNullOrEmpty(oCatName)) { - foreach (OutlookOgcs.Categories.ColourInfo cInfo in ddOutlookColour.Items) { + foreach (Outlook.Categories.ColourInfo cInfo in ddOutlookColour.Items) { if (cInfo.Text == oCatName) { ddOutlookColour.SelectedItem = cInfo; return; } } log.Warn("The category '" + oCatName + "' exists, but wasn't found in Outlook colour dropdown."); - OutlookOgcs.Calendar.Instance.IOutlook.RefreshCategories(); + Outlook.Calendar.Instance.IOutlook.RefreshCategories(); while (ddOutlookColour.Items.Count > 0) ddOutlookColour.Items.RemoveAt(0); ddOutlookColour.AddCategoryColours(); - foreach (OutlookOgcs.Categories.ColourInfo cInfo in ddOutlookColour.Items) { + foreach (Outlook.Categories.ColourInfo cInfo in ddOutlookColour.Items) { if (cInfo.Text == oCatName) { ddOutlookColour.SelectedItem = cInfo; return; diff --git a/src/OutlookGoogleCalendarSync/Forms/MainForm.cs b/src/OutlookGoogleCalendarSync/Forms/MainForm.cs index 4f3f0fed..d5712c67 100644 --- a/src/OutlookGoogleCalendarSync/Forms/MainForm.cs +++ b/src/OutlookGoogleCalendarSync/Forms/MainForm.cs @@ -57,7 +57,7 @@ public Main(string startingTab = null) { this.WindowState = FormWindowState.Minimized; } if (((Sync.Engine.Instance.NextSyncDate ?? DateTime.Now.AddMinutes(10)) - DateTime.Now).TotalMinutes > 5) { - OutlookOgcs.Calendar.Disconnect(onlyWhenNoGUI: true); + Outlook.Calendar.Disconnect(onlyWhenNoGUI: true); } while (!Forms.Splash.BeenAndGone) { System.Threading.Thread.Sleep(100); @@ -278,12 +278,12 @@ public void UpdateGUIsettings_Profile() { #endregion #region Outlook page #region Mailbox - if (OutlookOgcs.Factory.OutlookVersionName == OutlookOgcs.Factory.OutlookVersionNames.Outlook2003) { + if (Outlook.Factory.OutlookVersionName == Outlook.Factory.OutlookVersionNames.Outlook2003) { rbOutlookDefaultMB.Checked = true; rbOutlookAltMB.Enabled = false; rbOutlookSharedCal.Enabled = false; } else { - if (profile.OutlookService == OutlookOgcs.Calendar.Service.AlternativeMailbox) { + if (profile.OutlookService == Outlook.Calendar.Service.AlternativeMailbox) { if (rbOutlookAltMB.Checked) { //Toggle check to force refresh of calendar dropdowns rbOutlookAltMB.CheckedChanged -= new System.EventHandler(this.rbOutlookAltMB_CheckedChanged); @@ -291,7 +291,7 @@ public void UpdateGUIsettings_Profile() { rbOutlookAltMB.CheckedChanged += new System.EventHandler(this.rbOutlookAltMB_CheckedChanged); } rbOutlookAltMB.Checked = true; - } else if (profile.OutlookService == OutlookOgcs.Calendar.Service.SharedCalendar) { + } else if (profile.OutlookService == Outlook.Calendar.Service.SharedCalendar) { if (rbOutlookSharedCal.Checked) { //Toggle check to force refresh of calendar dropdowns rbOutlookSharedCal.CheckedChanged -= new System.EventHandler(this.rbOutlookSharedCal_CheckedChanged); @@ -306,50 +306,50 @@ public void UpdateGUIsettings_Profile() { //Mailboxes the user has access to log.Debug("Find calendar folders"); - if (OutlookOgcs.Calendar.Instance.Folders.Count == 1) { + if (Outlook.Calendar.Instance.Folders.Count == 1) { rbOutlookAltMB.Enabled = false; rbOutlookAltMB.Checked = false; } - Folders theFolders = OutlookOgcs.Calendar.Instance.Folders; - Dictionary> folderIDs = new Dictionary>(); - for (int fld = 1; fld <= theFolders.Count; fld++) { - MAPIFolder theFolder = theFolders[fld]; - try { - //Create a dictionary of folder names and a list of their ID(s) - if (!folderIDs.ContainsKey(theFolder.Name)) { - folderIDs.Add(theFolder.Name, new List(new String[] { theFolder.EntryID })); - } else if (!folderIDs[theFolder.Name].Contains(theFolder.EntryID)) { - folderIDs[theFolder.Name].Add(theFolder.EntryID); + Folders theFolders = Outlook.Calendar.Instance.Folders; + Dictionary> folderIDs = new Dictionary>(); + for (int fld = 1; fld <= theFolders.Count; fld++) { + MAPIFolder theFolder = theFolders[fld]; + try { + //Create a dictionary of folder names and a list of their ID(s) + if (!folderIDs.ContainsKey(theFolder.Name)) { + folderIDs.Add(theFolder.Name, new List(new String[] { theFolder.EntryID })); + } else if (!folderIDs[theFolder.Name].Contains(theFolder.EntryID)) { + folderIDs[theFolder.Name].Add(theFolder.EntryID); + } + } catch (System.Exception ex) { + OGCSexception.Analyse("Failed to get EntryID for folder: " + theFolder.Name, OGCSexception.LogAsFail(ex)); + } finally { + theFolder = (MAPIFolder)Outlook.Calendar.ReleaseObject(theFolder); } - } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to get EntryID for folder: " + theFolder.Name, OGCSexception.LogAsFail(ex)); - } finally { - theFolder = (MAPIFolder)OutlookOgcs.Calendar.ReleaseObject(theFolder); } - } - ddMailboxName.Items.Clear(); - ddMailboxName.Items.AddRange(folderIDs.Keys.ToArray()); - ddMailboxName.SelectedItem = profile.MailboxName; + ddMailboxName.Items.Clear(); + ddMailboxName.Items.AddRange(folderIDs.Keys.ToArray()); + ddMailboxName.SelectedItem = profile.MailboxName; - if (ddMailboxName.SelectedIndex == -1 && ddMailboxName.Items.Count > 0) { - if (profile.OutlookService == OutlookOgcs.Calendar.Service.AlternativeMailbox && string.IsNullOrEmpty(profile.MailboxName)) - log.Warn("Could not find mailbox '" + profile.MailboxName + "' in Alternate Mailbox dropdown. Defaulting to the first in the list."); + if (ddMailboxName.SelectedIndex == -1 && ddMailboxName.Items.Count > 0) { + if (profile.OutlookService == Outlook.Calendar.Service.AlternativeMailbox && string.IsNullOrEmpty(profile.MailboxName)) + log.Warn("Could not find mailbox '" + profile.MailboxName + "' in Alternate Mailbox dropdown. Defaulting to the first in the list."); - ddMailboxName.SelectedIndexChanged -= new System.EventHandler(this.ddMailboxName_SelectedIndexChanged); - ddMailboxName.SelectedIndex = 0; - ddMailboxName.SelectedIndexChanged += new System.EventHandler(this.ddMailboxName_SelectedIndexChanged); - } + ddMailboxName.SelectedIndexChanged -= new System.EventHandler(this.ddMailboxName_SelectedIndexChanged); + ddMailboxName.SelectedIndex = 0; + ddMailboxName.SelectedIndexChanged += new System.EventHandler(this.ddMailboxName_SelectedIndexChanged); + } log.Debug("List Calendar folders"); cbOutlookCalendars.SelectedIndexChanged -= cbOutlookCalendar_SelectedIndexChanged; - cbOutlookCalendars.DataSource = new BindingSource(OutlookOgcs.Calendar.Instance.CalendarFolders, null); + cbOutlookCalendars.DataSource = new BindingSource(Outlook.Calendar.Instance.CalendarFolders, null); cbOutlookCalendars.DisplayMember = "Key"; cbOutlookCalendars.ValueMember = "Value"; cbOutlookCalendars.SelectedIndex = -1; //Reset to nothing selected cbOutlookCalendars.SelectedIndexChanged += cbOutlookCalendar_SelectedIndexChanged; //Select the right calendar int c = 0; - foreach (KeyValuePair calendarFolder in OutlookOgcs.Calendar.Instance.CalendarFolders) { + foreach (KeyValuePair calendarFolder in Outlook.Calendar.Instance.CalendarFolders) { if (calendarFolder.Value.EntryID == profile.UseOutlookCalendar.Id) { cbOutlookCalendars.SelectedIndex = c; break; @@ -358,9 +358,9 @@ public void UpdateGUIsettings_Profile() { } if (cbOutlookCalendars.SelectedIndex == -1) { if (!string.IsNullOrEmpty(profile.UseOutlookCalendar.Id)) { - log.Warn("Outlook calendar '" + profile.UseOutlookCalendar.Name + "' could no longer be found. Selected calendar '" + OutlookOgcs.Calendar.Instance.CalendarFolders.First().Key + "' instead."); + log.Warn("Outlook calendar '" + profile.UseOutlookCalendar.Name + "' could no longer be found. Selected calendar '" + Outlook.Calendar.Instance.CalendarFolders.First().Key + "' instead."); OgcsMessageBox.Show("The Outlook calendar '" + profile.UseOutlookCalendar.Name + "' previously configured for syncing is no longer available.\r\n\r\n" + - "'" + OutlookOgcs.Calendar.Instance.CalendarFolders.First().Key + "' calendar has been selected instead and any automated syncs have been temporarily disabled.", + "'" + Outlook.Calendar.Instance.CalendarFolders.First().Key + "' calendar has been selected instead and any automated syncs have been temporarily disabled.", "Outlook Calendar Unavailable", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); profile.SyncInterval = 0; profile.OutlookPush = false; @@ -372,7 +372,7 @@ public void UpdateGUIsettings_Profile() { #region Categories cbCategoryFilter.SelectedItem = profile.CategoriesRestrictBy == SettingsStore.Calendar.RestrictBy.Include ? "Include" : "Exclude"; - if (OutlookOgcs.Factory.OutlookVersionName == OutlookOgcs.Factory.OutlookVersionNames.Outlook2003) { + if (Outlook.Factory.OutlookVersionName == Outlook.Factory.OutlookVersionNames.Outlook2003) { clbCategories.Items.Clear(); clbCategories.Items.Add("Outlook 2003 has no categories"); cbCategoryFilter.Enabled = false; @@ -382,7 +382,7 @@ public void UpdateGUIsettings_Profile() { profile.AddColours = false; cbAddColours.Enabled = false; } else { - OutlookOgcs.Calendar.Categories.BuildPicker(ref clbCategories); + Outlook.Calendar.Categories.BuildPicker(ref clbCategories); enableOutlookSettingsUI(true); } cbDeleteWhenCatExcl.Checked = profile.DeleteWhenCategoryExcluded; @@ -515,7 +515,7 @@ public void UpdateGUIsettings_Profile() { ddOutlookColour.AddColourItems(); ddOutlookColour.SelectedIndexChanged -= ddOutlookColour_SelectedIndexChanged; - foreach (OutlookOgcs.Categories.ColourInfo cInfo in ddOutlookColour.Items) { + foreach (Outlook.Categories.ColourInfo cInfo in ddOutlookColour.Items) { if (cInfo.OutlookCategory.ToString() == profile.SetEntriesColourValue && cInfo.Text == profile.SetEntriesColourName) { ddOutlookColour.SelectedItem = cInfo; @@ -1333,12 +1333,12 @@ public void rbOutlookDefaultMB_CheckedChanged(object sender, EventArgs e) { if (rbOutlookDefaultMB.Checked) { enableOutlookSettingsUI(false); - ActiveCalendarProfile.OutlookService = OutlookOgcs.Calendar.Service.DefaultMailbox; - OutlookOgcs.Calendar.Instance.Reset(); + ActiveCalendarProfile.OutlookService = Outlook.Calendar.Service.DefaultMailbox; + Outlook.Calendar.Instance.Reset(); //Update available calendars if (LoadingProfileConfig) cbOutlookCalendars.SelectedIndexChanged -= cbOutlookCalendar_SelectedIndexChanged; - cbOutlookCalendars.DataSource = new BindingSource(OutlookOgcs.Calendar.Instance.CalendarFolders, null); + cbOutlookCalendars.DataSource = new BindingSource(Outlook.Calendar.Instance.CalendarFolders, null); if (LoadingProfileConfig) cbOutlookCalendars.SelectedIndexChanged += cbOutlookCalendar_SelectedIndexChanged; refreshCategories(); @@ -1350,14 +1350,14 @@ private void rbOutlookAltMB_CheckedChanged(object sender, EventArgs e) { if (rbOutlookAltMB.Checked) { enableOutlookSettingsUI(false); - ActiveCalendarProfile.OutlookService = OutlookOgcs.Calendar.Service.AlternativeMailbox; + ActiveCalendarProfile.OutlookService = Outlook.Calendar.Service.AlternativeMailbox; if (!LoadingProfileConfig) ActiveCalendarProfile.MailboxName = ddMailboxName.Text; - OutlookOgcs.Calendar.Instance.Reset(); + Outlook.Calendar.Instance.Reset(); //Update available calendars if (LoadingProfileConfig) cbOutlookCalendars.SelectedIndexChanged -= cbOutlookCalendar_SelectedIndexChanged; - cbOutlookCalendars.DataSource = new BindingSource(OutlookOgcs.Calendar.Instance.CalendarFolders, null); + cbOutlookCalendars.DataSource = new BindingSource(Outlook.Calendar.Instance.CalendarFolders, null); if (LoadingProfileConfig) cbOutlookCalendars.SelectedIndexChanged += cbOutlookCalendar_SelectedIndexChanged; refreshCategories(); @@ -1375,12 +1375,12 @@ private void rbOutlookSharedCal_CheckedChanged(object sender, EventArgs e) { } if (rbOutlookSharedCal.Checked) { enableOutlookSettingsUI(false); - ActiveCalendarProfile.OutlookService = OutlookOgcs.Calendar.Service.SharedCalendar; - OutlookOgcs.Calendar.Instance.Reset(); + ActiveCalendarProfile.OutlookService = Outlook.Calendar.Service.SharedCalendar; + Outlook.Calendar.Instance.Reset(); //Update available calendars if (LoadingProfileConfig) cbOutlookCalendars.SelectedIndexChanged -= cbOutlookCalendar_SelectedIndexChanged; - cbOutlookCalendars.DataSource = new BindingSource(OutlookOgcs.Calendar.Instance.CalendarFolders, null); + cbOutlookCalendars.DataSource = new BindingSource(Outlook.Calendar.Instance.CalendarFolders, null); if (LoadingProfileConfig) cbOutlookCalendars.SelectedIndexChanged += cbOutlookCalendar_SelectedIndexChanged; refreshCategories(); @@ -1392,7 +1392,7 @@ private void ddMailboxName_SelectedIndexChanged(object sender, EventArgs e) { rbOutlookAltMB.Checked = true; ActiveCalendarProfile.MailboxName = ddMailboxName.Text; enableOutlookSettingsUI(false); - OutlookOgcs.Calendar.Instance.Reset(); + Outlook.Calendar.Instance.Reset(); refreshCategories(); } } @@ -1428,8 +1428,8 @@ private void clbCategories_SelectedIndexChanged(object sender, EventArgs e) { } private void refreshCategories() { - OutlookOgcs.Calendar.Instance.IOutlook.RefreshCategories(); - OutlookOgcs.Calendar.Categories.BuildPicker(ref clbCategories); + Outlook.Calendar.Instance.IOutlook.RefreshCategories(); + Outlook.Calendar.Categories.BuildPicker(ref clbCategories); enableOutlookSettingsUI(true); } @@ -1492,9 +1492,9 @@ private void tbOutlookDateFormat_Leave(object sender, EventArgs e) { private void btTestOutlookFilter_Click(object sender, EventArgs e) { log.Debug("Testing the Outlook filter string."); try { - MAPIFolder calendar = OutlookOgcs.Calendar.Instance.IOutlook.GetFolderByID(this.ActiveCalendarProfile.UseOutlookCalendar.Id); - int filterCount = OutlookOgcs.Calendar.Instance.FilterCalendarEntries(this.ActiveCalendarProfile, false).Count(); - OutlookOgcs.Calendar.Disconnect(true); + MAPIFolder calendar = Outlook.Calendar.Instance.IOutlook.GetFolderByID(this.ActiveCalendarProfile.UseOutlookCalendar.Id); + int filterCount = Outlook.Calendar.Instance.FilterCalendarEntries(this.ActiveCalendarProfile, false).Count(); + Outlook.Calendar.Disconnect(true); String msg = "The format '" + tbOutlookDateFormat.Text + "' returns " + filterCount + " calendar items within the date range "; msg += ActiveCalendarProfile.SyncStart.ToString(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern); msg += " and " + ActiveCalendarProfile.SyncEnd.ToString(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern); @@ -1899,13 +1899,13 @@ private void tbTargetCalendar_SelectedItemChanged(object sender, EventArgs e) { ActiveCalendarProfile.TargetCalendar = Sync.Direction.GoogleToOutlook; this.ddGoogleColour.Visible = false; this.ddOutlookColour.Visible = true; - if (OutlookOgcs.Factory.OutlookVersionName == OutlookOgcs.Factory.OutlookVersionNames.Outlook2003) + if (Outlook.Factory.OutlookVersionName == Outlook.Factory.OutlookVersionNames.Outlook2003) this.cbColour.Checked = false; break; } case "target calendar": { ActiveCalendarProfile.TargetCalendar = ActiveCalendarProfile.SyncDirection; - if (OutlookOgcs.Factory.OutlookVersionName == OutlookOgcs.Factory.OutlookVersionNames.Outlook2003 + if (Outlook.Factory.OutlookVersionName == Outlook.Factory.OutlookVersionNames.Outlook2003 && ActiveCalendarProfile.SyncDirection.Id == Sync.Direction.GoogleToOutlook.Id) this.cbColour.Checked = false; break; @@ -1991,9 +1991,9 @@ private void ddGoogleColour_SelectedIndexChanged(object sender, EventArgs e) { if (GoogleOgcs.Calendar.IsColourPaletteNull || !GoogleOgcs.Calendar.Instance.ColourPalette.IsCached()) oCatName = ActiveCalendarProfile.SetEntriesColourName; else - oCatName = OutlookOgcs.Calendar.Instance.GetCategoryColour(ddGoogleColour.SelectedItem.Id); + oCatName = Outlook.Calendar.Instance.GetCategoryColour(ddGoogleColour.SelectedItem.Id); - foreach (OutlookOgcs.Categories.ColourInfo cInfo in ddOutlookColour.Items) { + foreach (Outlook.Categories.ColourInfo cInfo in ddOutlookColour.Items) { if (cInfo.Text == oCatName) { ddOutlookColour.SelectedItem = cInfo; break; @@ -2242,8 +2242,8 @@ private void cbAddAttendees_CheckedChanged(object sender, EventArgs e) { tbMaxAttendees.Enabled = cbAddAttendees.Checked; cbCloakEmail.Visible = ActiveCalendarProfile.SyncDirection.Id != Sync.Direction.GoogleToOutlook.Id; cbCloakEmail.Enabled = cbAddAttendees.Checked; - if (cbAddAttendees.Checked && string.IsNullOrEmpty(OutlookOgcs.Calendar.Instance.IOutlook.CurrentUserSMTP())) { - OutlookOgcs.Calendar.Instance.IOutlook.GetCurrentUser(null); + if (cbAddAttendees.Checked && string.IsNullOrEmpty(Outlook.Calendar.Instance.IOutlook.CurrentUserSMTP())) { + Outlook.Calendar.Instance.IOutlook.GetCurrentUser(null); } } private void tbMaxAttendees_ValueChanged(object sender, EventArgs e) { @@ -2644,5 +2644,5 @@ private void btSocialGitHub_Click(object sender, EventArgs e) { Social.GitHub(); } #endregion - } + } } \ No newline at end of file diff --git a/src/OutlookGoogleCalendarSync/GoogleOgcs/CustomProperty.cs b/src/OutlookGoogleCalendarSync/GoogleOgcs/CustomProperty.cs index c2ce5003..19e4d09c 100644 --- a/src/OutlookGoogleCalendarSync/GoogleOgcs/CustomProperty.cs +++ b/src/OutlookGoogleCalendarSync/GoogleOgcs/CustomProperty.cs @@ -216,7 +216,7 @@ public static Boolean ExistAnyOutlookIDs(Event ev) { public static void AddOutlookIDs(ref Event ev, AppointmentItem ai) { Add(ref ev, MetadataId.oCalendarId, Sync.Engine.Calendar.Instance.Profile.UseOutlookCalendar.Id); Add(ref ev, MetadataId.oEntryId, ai.EntryID); - Add(ref ev, MetadataId.oGlobalApptId, OutlookOgcs.Calendar.Instance.IOutlook.GetGlobalApptID(ai)); + Add(ref ev, MetadataId.oGlobalApptId, Outlook.Calendar.Instance.IOutlook.GetGlobalApptID(ai)); CustomProperty.LogProperties(ev, log4net.Core.Level.Debug); } diff --git a/src/OutlookGoogleCalendarSync/GoogleOgcs/EventColour.cs b/src/OutlookGoogleCalendarSync/GoogleOgcs/EventColour.cs index 23658c37..79b310a0 100644 --- a/src/OutlookGoogleCalendarSync/GoogleOgcs/EventColour.cs +++ b/src/OutlookGoogleCalendarSync/GoogleOgcs/EventColour.cs @@ -42,7 +42,7 @@ public String HexValue { public Color RgbValue { get { if (UseWebAppColours) { - if (rgbConvertedFromHex.IsEmpty && HexValue != null) rgbConvertedFromHex = OutlookOgcs.Categories.Map.RgbColour(HexValue); + if (rgbConvertedFromHex.IsEmpty && HexValue != null) rgbConvertedFromHex = Outlook.Categories.Map.RgbColour(HexValue); return rgbConvertedFromHex; } return rgbValue; @@ -254,10 +254,10 @@ public void Get() { else log.Debug(colours.Event__.Count() + " event colours and " + colours.Calendar.Count() + " calendars (with a colour) found."); foreach (KeyValuePair colour in colours.Event__) { - eventPalette.Add(new Palette(Palette.Type.Event, colour.Key, colour.Value.Background, OutlookOgcs.Categories.Map.RgbColour(colour.Value.Background))); + eventPalette.Add(new Palette(Palette.Type.Event, colour.Key, colour.Value.Background, Outlook.Categories.Map.RgbColour(colour.Value.Background))); } foreach (KeyValuePair colour in colours.Calendar) { - calendarPalette.Add(new Palette(Palette.Type.Calendar, colour.Key, colour.Value.Background, OutlookOgcs.Categories.Map.RgbColour(colour.Value.Background))); + calendarPalette.Add(new Palette(Palette.Type.Calendar, colour.Key, colour.Value.Background, Outlook.Categories.Map.RgbColour(colour.Value.Background))); } Forms.Main.Instance.miColourBuildPicker_Click(null, null); } diff --git a/src/OutlookGoogleCalendarSync/GoogleOgcs/GoogleCalendar.cs b/src/OutlookGoogleCalendarSync/GoogleOgcs/GoogleCalendar.cs index 97267353..c4819eda 100644 --- a/src/OutlookGoogleCalendarSync/GoogleOgcs/GoogleCalendar.cs +++ b/src/OutlookGoogleCalendarSync/GoogleOgcs/GoogleCalendar.cs @@ -500,12 +500,12 @@ public void CreateCalendarEntries(List appointments) { newEvent = createCalendarEntry(ai); } catch (System.Exception ex) { if (ex is ApplicationException) { - String summary = OutlookOgcs.Calendar.GetEventSummary("Event creation skipped.
" + ex.Message, ai, out String anonSummary); + String summary = Outlook.Calendar.GetEventSummary("Event creation skipped.
" + ex.Message, ai, out String anonSummary); Forms.Main.Instance.Console.Update(summary, anonSummary, Console.Markup.warning); if (ex.InnerException is Google.GoogleApiException) break; continue; } else { - String summary = OutlookOgcs.Calendar.GetEventSummary("Event creation failed.", ai, out String anonSummary); + String summary = Outlook.Calendar.GetEventSummary("Event creation failed.", ai, out String anonSummary); Forms.Main.Instance.Console.UpdateWithError(summary, ex, logEntry: anonSummary); OGCSexception.Analyse(ex, true); if (OgcsMessageBox.Show("Google event creation failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) @@ -523,7 +523,7 @@ public void CreateCalendarEntries(List appointments) { Forms.Main.Instance.Console.Update("The Google calendar being synced with must not be read-only.
Cannot continue sync.", Console.Markup.fail, newLine: false); return; } - Forms.Main.Instance.Console.UpdateWithError(OutlookOgcs.Calendar.GetEventSummary("New event failed to save.", ai, out String anonSummary, true), ex, logEntry: anonSummary); + Forms.Main.Instance.Console.UpdateWithError(Outlook.Calendar.GetEventSummary("New event failed to save.", ai, out String anonSummary, true), ex, logEntry: anonSummary); OGCSexception.Analyse(ex, true); if (OgcsMessageBox.Show("New Google event failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; @@ -541,7 +541,7 @@ public void CreateCalendarEntries(List appointments) { private Event createCalendarEntry(AppointmentItem ai) { SettingsStore.Calendar profile = Sync.Engine.Calendar.Instance.Profile; - string itemSummary = OutlookOgcs.Calendar.GetEventSummary(ai, out String anonSummary); + string itemSummary = Outlook.Calendar.GetEventSummary(ai, out String anonSummary); log.Debug("Processing >> " + (anonSummary ?? itemSummary)); Forms.Main.Instance.Console.Update(itemSummary, anonSummary, Console.Markup.calendar, verbose: true); @@ -558,7 +558,7 @@ private Event createCalendarEntry(AppointmentItem ai) { ev.Start.DateTime = ai.Start; ev.End.DateTime = ai.End; } - ev = OutlookOgcs.Calendar.Instance.IOutlook.IANAtimezone_set(ev, ai); + ev = Outlook.Calendar.Instance.IOutlook.IANAtimezone_set(ev, ai); ev.Summary = Obfuscate.ApplyRegex(Obfuscate.Property.Subject, ai.Subject, null, Sync.Direction.OutlookToGoogle); if (profile.AddDescription) { @@ -596,7 +596,7 @@ private Event createCalendarEntry(AppointmentItem ai) { //Reminder alert ev.Reminders = new Event.RemindersData(); if (profile.AddReminders) { - if (OutlookOgcs.Calendar.Instance.IsOKtoSyncReminder(ai)) { + if (Outlook.Calendar.Instance.IsOKtoSyncReminder(ai)) { if (ai.ReminderSet) { ev.Reminders.UseDefault = false; EventReminder reminder = new EventReminder { @@ -667,16 +667,16 @@ private Event createCalendarEntry_save(Event ev, AppointmentItem ai) { } } - if (!String.IsNullOrEmpty(createdEvent.Id) && (profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id || OutlookOgcs.CustomProperty.ExistAnyGoogleIDs(ai))) { + if (!String.IsNullOrEmpty(createdEvent.Id) && (profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id || Outlook.CustomProperty.ExistAnyGoogleIDs(ai))) { log.Debug("Storing the Google event IDs in Outlook appointment."); - OutlookOgcs.CustomProperty.AddGoogleIDs(ref ai, createdEvent); - OutlookOgcs.CustomProperty.SetOGCSlastModified(ref ai); + Outlook.CustomProperty.AddGoogleIDs(ref ai, createdEvent); + Outlook.CustomProperty.SetOGCSlastModified(ref ai); ai.Save(); } - if (profile.AddGMeet && OutlookOgcs.GMeet.BodyHasGmeetUrl(ai)) { + if (profile.AddGMeet && Outlook.GMeet.BodyHasGmeetUrl(ai)) { log.Info("Adding GMeet conference details."); - String outlookGMeet = OutlookOgcs.GMeet.RgxGmeetUrl().Match(ai.Body).Value; + String outlookGMeet = Outlook.GMeet.RgxGmeetUrl().Match(ai.Body).Value; GMeet.GoogleMeet(createdEvent, outlookGMeet); createdEvent = patchEvent(createdEvent) ?? createdEvent; log.Fine("Conference data added."); @@ -710,12 +710,12 @@ public void UpdateCalendarEntries(Dictionary entriesToBe ev = UpdateCalendarEntry(compare.Key, compare.Value, ref itemModified); } catch (System.Exception ex) { if (ex is ApplicationException) { - String summary = OutlookOgcs.Calendar.GetEventSummary("
Event update skipped.
" + ex.Message, compare.Key, out String anonSummary); + String summary = Outlook.Calendar.GetEventSummary("
Event update skipped.
" + ex.Message, compare.Key, out String anonSummary); Forms.Main.Instance.Console.Update(summary, anonSummary, Console.Markup.warning); if (ex.InnerException is Google.GoogleApiException) break; continue; } else { - String summary = OutlookOgcs.Calendar.GetEventSummary("
Event update failed.", compare.Key, out String anonSummary); + String summary = Outlook.Calendar.GetEventSummary("
Event update failed.", compare.Key, out String anonSummary); Forms.Main.Instance.Console.UpdateWithError(summary, ex, logEntry: anonSummary); if (ex is System.Runtime.InteropServices.COMException) throw; OGCSexception.Analyse(ex, true); @@ -732,7 +732,7 @@ public void UpdateCalendarEntries(Dictionary entriesToBe entriesUpdated++; eventExceptionCacheDirty = true; } catch (System.Exception ex) { - Forms.Main.Instance.Console.UpdateWithError(OutlookOgcs.Calendar.GetEventSummary("Updated event failed to save.", compare.Key, out String anonSummary, true), ex, logEntry: anonSummary); + Forms.Main.Instance.Console.UpdateWithError(Outlook.Calendar.GetEventSummary("Updated event failed to save.", compare.Key, out String anonSummary, true), ex, logEntry: anonSummary); OGCSexception.Analyse(ex, true); if (OgcsMessageBox.Show("Updated Google event failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; @@ -759,7 +759,7 @@ public void UpdateCalendarEntries(Dictionary entriesToBe UpdateCalendarEntry_save(ref ev); entriesToBeCompared[compare.Key] = ev; } catch (System.Exception ex) { - Forms.Main.Instance.Console.UpdateWithError(OutlookOgcs.Calendar.GetEventSummary("Updated event failed to save.", compare.Key, out String anonSummary, true), ex, logEntry: anonSummary); + Forms.Main.Instance.Console.UpdateWithError(Outlook.Calendar.GetEventSummary("Updated event failed to save.", compare.Key, out String anonSummary, true), ex, logEntry: anonSummary); OGCSexception.Analyse(ex, true); if (OgcsMessageBox.Show("Updated Google event failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; @@ -781,7 +781,7 @@ public Event UpdateCalendarEntry(AppointmentItem ai, Event ev, ref int itemModif if (ev.Updated > ai.LastModificationTime) return null; } else { - if (OutlookOgcs.CustomProperty.GetOGCSlastModified(ai).AddSeconds(5) >= ai.LastModificationTime) { + if (Outlook.CustomProperty.GetOGCSlastModified(ai).AddSeconds(5) >= ai.LastModificationTime) { log.Fine("Outlook last modified by OGCS."); return null; } @@ -791,7 +791,7 @@ public Event UpdateCalendarEntry(AppointmentItem ai, Event ev, ref int itemModif } } - String aiSummary = OutlookOgcs.Calendar.GetEventSummary(ai, out String anonSummary); + String aiSummary = Outlook.Calendar.GetEventSummary(ai, out String anonSummary); log.Debug("Processing >> " + (anonSummary ?? aiSummary)); if (!(ev.Creator.Self ?? (ev.Creator.Email == Settings.Instance.GaccountEmail)) && ev.Recurrence != null) { @@ -892,7 +892,7 @@ public Event UpdateCalendarEntry(AppointmentItem ai, Event ev, ref int itemModif if (ev.Start.DateTime != null) { String currentStartTZ = ev.Start.TimeZone; String currentEndTZ = ev.End.TimeZone; - ev = OutlookOgcs.Calendar.Instance.IOutlook.IANAtimezone_set(ev, ai); + ev = Outlook.Calendar.Instance.IOutlook.IANAtimezone_set(ev, ai); if (ev.Recurrence != null && ev.Start.TimeZone != ev.End.TimeZone) { log.Warn("Outlook recurring series has a different start and end timezone, which Google does not allow. Setting both to the start timezone."); ev.End.TimeZone = ev.Start.TimeZone; @@ -924,7 +924,7 @@ public Event UpdateCalendarEntry(AppointmentItem ai, Event ev, ref int itemModif ev.Description = bodyObfuscated; if (profile.AddGMeet) { - String outlookGMeet = OutlookOgcs.GMeet.RgxGmeetUrl().Match(ai.Body ?? "")?.Value; + String outlookGMeet = Outlook.GMeet.RgxGmeetUrl().Match(ai.Body ?? "")?.Value; if (Sync.Engine.CompareAttribute("Google Meet", Sync.Direction.OutlookToGoogle, ev.HangoutLink, outlookGMeet, sb, ref itemModified)) { try { GMeet.GoogleMeet(ev, outlookGMeet); @@ -983,7 +983,7 @@ public Event UpdateCalendarEntry(AppointmentItem ai, Event ev, ref int itemModif try { CompareRecipientsToAttendees(ai, ev, sb, ref itemModified); } catch (System.Exception ex) { - if (OutlookOgcs.Calendar.Instance.IOutlook.ExchangeConnectionMode().ToString().Contains("Disconnected")) { + if (Outlook.Calendar.Instance.IOutlook.ExchangeConnectionMode().ToString().Contains("Disconnected")) { Forms.Main.Instance.Console.Update("Outlook is currently disconnected from Exchange, so it's not possible to sync attendees.
" + "Please reconnect or do not sync attendees.", Console.Markup.error); throw new System.Exception("Outlook has disconnected from Exchange."); @@ -996,7 +996,7 @@ public Event UpdateCalendarEntry(AppointmentItem ai, Event ev, ref int itemModif #region Reminders if (profile.AddReminders) { - Boolean OKtoSyncReminder = OutlookOgcs.Calendar.Instance.IsOKtoSyncReminder(ai); + Boolean OKtoSyncReminder = Outlook.Calendar.Instance.IsOKtoSyncReminder(ai); if (ev.Reminders.Overrides != null && ev.Reminders.Overrides.Any(r => r.Method == "popup")) { //Find the popup reminder(s) in Google for (int r = ev.Reminders.Overrides.Count - 1; r >= 0; r--) { @@ -1270,7 +1270,7 @@ public void ReclaimOrphanCalendarEntries(ref List gEvents, ref List= 0; o--) { AppointmentItem ai = oAppointments[o]; - if (SignaturesMatch(sigEv, OutlookOgcs.Calendar.signature(ai))) { + if (SignaturesMatch(sigEv, Outlook.Calendar.signature(ai))) { try { Event originalEv = ev; CustomProperty.AddOutlookIDs(ref ev, ai); @@ -1280,9 +1280,9 @@ public void ReclaimOrphanCalendarEntries(ref List gEvents, ref List= 0; o--) { try { - if (log.IsUltraFineEnabled()) log.UltraFine("Checking " + OutlookOgcs.Calendar.GetEventSummary(outlook[o])); + if (log.IsUltraFineEnabled()) log.UltraFine("Checking " + Outlook.Calendar.GetEventSummary(outlook[o])); - if (SignaturesMatch(sigEv, OutlookOgcs.Calendar.signature(outlook[o]))) { + if (SignaturesMatch(sigEv, Outlook.Calendar.signature(outlook[o]))) { foundMatch = true; compare.Add(outlook[o], google[g]); outlook.Remove(outlook[o]); @@ -1401,7 +1401,7 @@ public void IdentifyEventDifferences_Simple( } catch (System.Exception ex) { if (!log.IsUltraFineEnabled()) { try { - log.Info(OutlookOgcs.Calendar.GetEventSummary(outlook[o])); + log.Info(Outlook.Calendar.GetEventSummary(outlook[o])); } catch { } } if (ex.Message == "An error occurred in the underlying security system. An internal error occurred.") { @@ -1441,12 +1441,12 @@ public void IdentifyEventDifferences_IDs( for (int o = outlook.Count - 1; o >= 0; o--) { try { - if (log.IsUltraFineEnabled()) log.UltraFine("Checking " + OutlookOgcs.Calendar.GetEventSummary(outlook[o])); + if (log.IsUltraFineEnabled()) log.UltraFine("Checking " + Outlook.Calendar.GetEventSummary(outlook[o])); String compare_oID; - if (outlookIDmissing && compare_gEntryID.StartsWith(OutlookOgcs.Calendar.GlobalIdPattern)) { + if (outlookIDmissing && compare_gEntryID.StartsWith(Outlook.Calendar.GlobalIdPattern)) { //compare_gEntryID actually holds GlobalID up to v2.3.2.3 - yes, confusing I know, but we're sorting this now - compare_oID = OutlookOgcs.Calendar.Instance.IOutlook.GetGlobalApptID(outlook[o]); + compare_oID = Outlook.Calendar.Instance.IOutlook.GetGlobalApptID(outlook[o]); } else { compare_oID = outlook[o].EntryID; } @@ -1473,7 +1473,7 @@ public void IdentifyEventDifferences_IDs( } catch (System.Exception ex) { if (!log.IsUltraFineEnabled()) { try { - log.Info(OutlookOgcs.Calendar.GetEventSummary(outlook[o])); + log.Info(Outlook.Calendar.GetEventSummary(outlook[o])); } catch { } } if (ex.Message == "An error occurred in the underlying security system. An internal error occurred.") { @@ -1529,11 +1529,11 @@ public void IdentifyEventDifferences( if (responseFiltered > 0) log.Info(responseFiltered + " Outlook items will not be created due to only syncing invites that have been responded to."); } - if (google.Count > 0 && OutlookOgcs.Calendar.Instance.ExcludedByCategory.Count > 0 && !profile.DeleteWhenCategoryExcluded) { + if (google.Count > 0 && Outlook.Calendar.Instance.ExcludedByCategory.Count > 0 && !profile.DeleteWhenCategoryExcluded) { //Check if Google items to be deleted were filtered out from Outlook for (int g = google.Count - 1; g >= 0; g--) { - if (OutlookOgcs.Calendar.Instance.ExcludedByCategory.ContainsValue(google[g].Id) || - OutlookOgcs.Calendar.Instance.ExcludedByCategory.ContainsKey(CustomProperty.Get(google[g], CustomProperty.MetadataId.oEntryId) ?? "")) { + if (Outlook.Calendar.Instance.ExcludedByCategory.ContainsValue(google[g].Id) || + Outlook.Calendar.Instance.ExcludedByCategory.ContainsKey(CustomProperty.Get(google[g], CustomProperty.MetadataId.oEntryId) ?? "")) { google.Remove(google[g]); } } @@ -1542,7 +1542,7 @@ public void IdentifyEventDifferences( //Check if Outlook items to be created were filtered out from Google for (int o = outlook.Count - 1; o >= 0; o--) { if (ExcludedByColour.ContainsValue(outlook[o].EntryID) || - ExcludedByColour.ContainsKey(OutlookOgcs.CustomProperty.Get(outlook[o], OutlookOgcs.CustomProperty.MetadataId.gEventID) ?? "")) { + ExcludedByColour.ContainsKey(Outlook.CustomProperty.Get(outlook[o], Outlook.CustomProperty.MetadataId.gEventID) ?? "")) { outlook.Remove(outlook[o]); } } @@ -1559,7 +1559,7 @@ public void IdentifyEventDifferences( if (profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id) { //Don't recreate any items that have been deleted in Google for (int o = outlook.Count - 1; o >= 0; o--) { - if (OutlookOgcs.CustomProperty.Exists(outlook[o], OutlookOgcs.CustomProperty.MetadataId.gEventID)) + if (Outlook.CustomProperty.Exists(outlook[o], Outlook.CustomProperty.MetadataId.gEventID)) outlook.Remove(outlook[o]); } //Don't delete any items that aren't yet in Outlook or just created in Outlook during this sync @@ -1571,7 +1571,7 @@ public void IdentifyEventDifferences( } if (Settings.Instance.CreateCSVFiles) { ExportToCSV("Events for deletion in Google", "google_delete.csv", google); - OutlookOgcs.Calendar.ExportToCSV("Appointments for creation in Google", "google_create.csv", outlook); + Outlook.Calendar.ExportToCSV("Appointments for creation in Google", "google_create.csv", outlook); } } @@ -1587,22 +1587,22 @@ public static Boolean ItemIDsMatch(ref Event ev, AppointmentItem ai) { if (CustomProperty.Exists(ev, CustomProperty.MetadataId.oGlobalApptId)) { String gCompareID = CustomProperty.Get(ev, CustomProperty.MetadataId.oGlobalApptId); - String oGlobalID = OutlookOgcs.Calendar.Instance.IOutlook.GetGlobalApptID(ai); + String oGlobalID = Outlook.Calendar.Instance.IOutlook.GetGlobalApptID(ai); //For items copied from someone elses calendar, it appears the Global ID is generated for each access?! (Creation Time changes) //I guess the copied item doesn't really have its "own" ID. So, we'll just compare //the "data" section of the byte array, which "ensures uniqueness" and doesn't include ID creation time - if ((OutlookOgcs.Factory.OutlookVersionName == OutlookOgcs.Factory.OutlookVersionNames.Outlook2003 && oGlobalID == gCompareID) //Actually simple compare of EntryId for O2003 + if ((Outlook.Factory.OutlookVersionName == Outlook.Factory.OutlookVersionNames.Outlook2003 && oGlobalID == gCompareID) //Actually simple compare of EntryId for O2003 || - (OutlookOgcs.Factory.OutlookVersionName != OutlookOgcs.Factory.OutlookVersionNames.Outlook2003 && + (Outlook.Factory.OutlookVersionName != Outlook.Factory.OutlookVersionNames.Outlook2003 && ( - (oGlobalID.StartsWith(OutlookOgcs.Calendar.GlobalIdPattern) && - gCompareID.StartsWith(OutlookOgcs.Calendar.GlobalIdPattern) && + (oGlobalID.StartsWith(Outlook.Calendar.GlobalIdPattern) && + gCompareID.StartsWith(Outlook.Calendar.GlobalIdPattern) && gCompareID.Substring(72) == oGlobalID.Substring(72)) //We've got bonafide Global IDs match || - (!oGlobalID.StartsWith(OutlookOgcs.Calendar.GlobalIdPattern) && - !gCompareID.StartsWith(OutlookOgcs.Calendar.GlobalIdPattern) && + (!oGlobalID.StartsWith(Outlook.Calendar.GlobalIdPattern) && + !gCompareID.StartsWith(Outlook.Calendar.GlobalIdPattern) && gCompareID.Remove(gCompareID.Length - 16) == oGlobalID.Remove(oGlobalID.Length - 16)) //Or it's really a Entry ID (failsafe match) ) )) @@ -1623,11 +1623,11 @@ public static Boolean ItemIDsMatch(ref Event ev, AppointmentItem ai) { //Worse still, both a locally copied item AND a rescheduled appointment by someone else //will have the MessageGlobalCounter bytes incremented (last 8-bytes) //The former is identified by ExplorerWatcher adding a special flag - if (OutlookOgcs.CustomProperty.Get(ai, OutlookOgcs.CustomProperty.MetadataId.locallyCopied) == true.ToString()) { + if (Outlook.CustomProperty.Get(ai, Outlook.CustomProperty.MetadataId.locallyCopied) == true.ToString()) { log.Fine("This appointment was copied by the user. Incorrect match avoided."); return false; } else { - if (profile.OutlookGalBlocked || ai.Organizer != OutlookOgcs.Calendar.Instance.IOutlook.CurrentUserName()) { + if (profile.OutlookGalBlocked || ai.Organizer != Outlook.Calendar.Instance.IOutlook.CurrentUserName()) { if (profile.OutlookGalBlocked) log.Warn("It looks like the organiser changed time of appointment, but due to GAL policy we can't check who they are."); else @@ -1643,7 +1643,7 @@ public static Boolean ItemIDsMatch(ref Event ev, AppointmentItem ai) { } else { log.Fine("EntryID has changed - invite accepted?"); - if (SignaturesMatch(signature(ev), OutlookOgcs.Calendar.signature(ai))) { + if (SignaturesMatch(signature(ev), Outlook.Calendar.signature(ai))) { CustomProperty.AddOutlookIDs(ref ev, ai); //update EntryID CustomProperty.Add(ref ev, CustomProperty.MetadataId.forceSave, "True"); return true; @@ -1652,11 +1652,11 @@ public static Boolean ItemIDsMatch(ref Event ev, AppointmentItem ai) { } } else if (profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id && - oGlobalID.StartsWith(OutlookOgcs.Calendar.GlobalIdPattern) && - gCompareID.StartsWith(OutlookOgcs.Calendar.GlobalIdPattern) && + oGlobalID.StartsWith(Outlook.Calendar.GlobalIdPattern) && + gCompareID.StartsWith(Outlook.Calendar.GlobalIdPattern) && gCompareID.Substring(72) != oGlobalID.Substring(72) && - OutlookOgcs.CustomProperty.Get(ai, OutlookOgcs.CustomProperty.MetadataId.gEventID) == ev.Id && - SignaturesMatch(signature(ev), OutlookOgcs.Calendar.signature(ai))) + Outlook.CustomProperty.Get(ai, Outlook.CustomProperty.MetadataId.gEventID) == ev.Id && + SignaturesMatch(signature(ev), Outlook.Calendar.signature(ai))) { //Apple iCloud completely recreates the GlobalID and zeros out the timestamp element! Issue #447. log.Warn("Appointment GlobalID has completely changed, but Google Event ID matches so relying on that!"); @@ -1688,7 +1688,7 @@ public Boolean CompareRecipientsToAttendees(AppointmentItem ai, Event ev, String bool foundAttendee = false; Recipient recipient = ai.Recipients[o]; log.Fine("Comparing Outlook recipient: " + recipient.Name); - String recipientSMTP = OutlookOgcs.Calendar.Instance.IOutlook.GetRecipientEmail(recipient); + String recipientSMTP = Outlook.Calendar.Instance.IOutlook.GetRecipientEmail(recipient); foreach (Google.Apis.Calendar.v3.Data.EventAttendee attendee in ev.Attendees ?? Enumerable.Empty()) { GoogleOgcs.EventAttendee ogcsAttendee = new GoogleOgcs.EventAttendee(attendee); if (ogcsAttendee.Email != null && (recipientSMTP.ToLower() == ogcsAttendee.Email.ToLower())) { @@ -1964,7 +1964,7 @@ public EventColour.Palette GetColour(OlCategoryColor categoryColour) { SettingsStore.Calendar profile = Settings.Profile.InPlay(); if (profile.ColourMaps.Count > 0) { - KeyValuePair kvp = profile.ColourMaps.FirstOrDefault(cm => OutlookOgcs.Calendar.Categories.OutlookColour(cm.Key) == categoryColour); + KeyValuePair kvp = profile.ColourMaps.FirstOrDefault(cm => Outlook.Calendar.Categories.OutlookColour(cm.Key) == categoryColour); if (kvp.Key != null) { gColour = ColourPalette.ActivePalette.FirstOrDefault(ap => ap.Id == kvp.Value); if (gColour != null) { @@ -1974,7 +1974,7 @@ public EventColour.Palette GetColour(OlCategoryColor categoryColour) { } } //Algorithmic closest colour matching - System.Drawing.Color color = OutlookOgcs.Categories.Map.RgbColour((OlCategoryColor)categoryColour); + System.Drawing.Color color = Outlook.Categories.Map.RgbColour((OlCategoryColor)categoryColour); EventColour.Palette closest = ColourPalette.GetClosestColour(color); return (closest.Id == "0") ? EventColour.Palette.NullPalette : closest; } @@ -1988,8 +1988,8 @@ private void getOutlookCategoryColour(String aiCategories, ref OlCategoryColor? if (!string.IsNullOrEmpty(aiCategories)) { log.Fine("Categories: " + aiCategories); try { - String category = aiCategories.Split(new[] { OutlookOgcs.Calendar.Categories.Delimiter }, StringSplitOptions.None).FirstOrDefault(); - categoryColour = OutlookOgcs.Calendar.Categories.OutlookColour(category); + String category = aiCategories.Split(new[] { Outlook.Calendar.Categories.Delimiter }, StringSplitOptions.None).FirstOrDefault(); + categoryColour = Outlook.Calendar.Categories.OutlookColour(category); } catch (System.Exception ex) { log.Error("Failed determining colour for Event from AppointmentItem categories: " + aiCategories); OGCSexception.Analyse(ex); @@ -2218,7 +2218,7 @@ public static Google.Apis.Calendar.v3.Data.EventAttendee CreateAttendee(Recipien GoogleOgcs.EventAttendee ea = new GoogleOgcs.EventAttendee(); log.Fine("Creating attendee " + recipient.Name); ea.DisplayName = recipient.Name; - ea.Email = OutlookOgcs.Calendar.Instance.IOutlook.GetRecipientEmail(recipient); + ea.Email = Outlook.Calendar.Instance.IOutlook.GetRecipientEmail(recipient); ea.Optional = (recipient.Type == (int)OlMeetingRecipientType.olOptional); if (isOrganiser) { //ea.Organizer = true; This is read-only. The best we can do is force them to have accepted the "invite" diff --git a/src/OutlookGoogleCalendarSync/NotificationTray.cs b/src/OutlookGoogleCalendarSync/NotificationTray.cs index 93323379..71dc6541 100644 --- a/src/OutlookGoogleCalendarSync/NotificationTray.cs +++ b/src/OutlookGoogleCalendarSync/NotificationTray.cs @@ -30,7 +30,7 @@ public NotificationTray(NotifyIcon icon) { this.icon.Text += (string.IsNullOrEmpty(Program.Title) ? "" : " - " + Program.Title); buildMenu(); - if (OutlookOgcs.Calendar.OOMsecurityInfo) { + if (Outlook.Calendar.OOMsecurityInfo) { ShowBubbleInfo("Your Outlook security settings may not be optimal.\r\n" + "Click here for further details.", ToolTipIcon.Warning, "OOMsecurity"); Telemetry.Send(Analytics.Category.ogcs, Analytics.Action.setting, "OOMsecurity;SyncCount=" + Settings.Instance.CompletedSyncs); diff --git a/src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookFactory.cs b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookFactory.cs similarity index 93% rename from src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookFactory.cs rename to src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookFactory.cs index 7c716096..da57f474 100644 --- a/src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookFactory.cs +++ b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookFactory.cs @@ -3,7 +3,7 @@ using System; using System.Linq; -namespace OutlookGoogleCalendarSync.OutlookOgcs { +namespace OutlookGoogleCalendarSync.Outlook { class Factory { private static readonly ILog log = LogManager.GetLogger(typeof(Factory)); private static String outlookVersionFull; @@ -62,7 +62,7 @@ public enum OutlookVersionNames : Int16 { private const Boolean testing2003 = false; - public static OutlookOgcs.Interface GetOutlookInterface() { + public static Interface GetOutlookInterface() { if (OutlookVersionName >= OutlookVersionNames.Outlook2007) { return new OutlookNew(); } else { @@ -73,7 +73,7 @@ public static OutlookOgcs.Interface GetOutlookInterface() { private static void getOutlookVersion() { //Attach just to get Outlook version - we don't know whether to provide New or Old interface yet Microsoft.Office.Interop.Outlook.Application oApp = null; - OutlookOgcs.Calendar.AttachToOutlook(ref oApp); + Outlook.Calendar.AttachToOutlook(ref oApp); try { int attempts = 1; int maxAttempts = 3; @@ -83,11 +83,11 @@ private static void getOutlookVersion() { outlookVersionFull = oApp.Version; attempts = maxAttempts + 1; } catch (System.Runtime.InteropServices.COMException ex) { - Ogcs.Outlook.Errors.ErrorType error = Ogcs.Outlook.Errors.HandleComError(ex); - if (error == Ogcs.Outlook.Errors.ErrorType.PermissionFailure || - error == Ogcs.Outlook.Errors.ErrorType.RpcRejected || - error == Ogcs.Outlook.Errors.ErrorType.RpcServerUnavailable || - error == Ogcs.Outlook.Errors.ErrorType.RpcFailed) // + Outlook.Errors.ErrorType error = Outlook.Errors.HandleComError(ex); + if (error == Outlook.Errors.ErrorType.PermissionFailure || + error == Outlook.Errors.ErrorType.RpcRejected || + error == Outlook.Errors.ErrorType.RpcServerUnavailable || + error == Outlook.Errors.ErrorType.RpcFailed) // { log.Warn(ex.Message + " Attempt " + attempts + "/" + maxAttempts); if (attempts == maxAttempts) { @@ -114,7 +114,7 @@ private static void getOutlookVersion() { getOutlookVersionName(outlookVersion, outlookVersionFull); } catch (System.Exception ex) { - OutlookOgcs.Calendar.PoorlyOfficeInstall(ex); + Outlook.Calendar.PoorlyOfficeInstall(ex); } finally { if (oApp != null) { System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oApp); diff --git a/src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookInterface.cs b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookInterface.cs similarity index 93% rename from src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookInterface.cs rename to src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookInterface.cs index 4f30be01..04fc146f 100644 --- a/src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookInterface.cs +++ b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookInterface.cs @@ -1,11 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using Google.Apis.Calendar.v3.Data; using Microsoft.Office.Interop.Outlook; -using Google.Apis.Calendar.v3.Data; +using System; +using System.Collections.Generic; -namespace OutlookGoogleCalendarSync.OutlookOgcs { +namespace OutlookGoogleCalendarSync.Outlook { public interface Interface { void Connect(); void Disconnect(Boolean onlyWhenNoGUI = false); diff --git a/src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookNew.cs b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookNew.cs similarity index 92% rename from src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookNew.cs rename to src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookNew.cs index 4a1d1a2a..e6b52de5 100644 --- a/src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookNew.cs +++ b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookNew.cs @@ -6,7 +6,7 @@ using System.Linq; using System.Windows.Forms; -namespace OutlookGoogleCalendarSync.OutlookOgcs { +namespace OutlookGoogleCalendarSync.Outlook { class OutlookNew : Interface { private static readonly ILog log = LogManager.GetLogger(typeof(OutlookNew)); @@ -20,9 +20,9 @@ class OutlookNew : Interface { private OlExchangeConnectionMode exchangeConnectionMode; public void Connect() { - if (!OutlookOgcs.Calendar.InstanceConnect) return; + if (!Outlook.Calendar.InstanceConnect) return; - OutlookOgcs.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: true, withSystemCall: false); + Outlook.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: true, withSystemCall: false); log.Debug("Setting up Outlook connection."); // Get the NameSpace and Logon information. @@ -89,7 +89,7 @@ public void Connect() { Forms.Main.Instance.cbOutlookCalendars.SelectedIndexChanged += Forms.Main.Instance.cbOutlookCalendar_SelectedIndexChanged; } - OutlookOgcs.Calendar.Categories = new OutlookOgcs.Categories(); + Outlook.Calendar.Categories = new Outlook.Categories(); Calendar.Categories.Get(oApp, useOutlookCalendar); //Set up event handlers @@ -105,7 +105,7 @@ public void Connect() { } finally { // Done. Log off. if (oNS != null) try { oNS.Logoff(); } catch { } - oNS = (NameSpace)OutlookOgcs.Calendar.ReleaseObject(oNS); + oNS = (NameSpace)Outlook.Calendar.ReleaseObject(oNS); } } public void Disconnect(Boolean onlyWhenNoGUI = false) { @@ -115,11 +115,11 @@ public void Disconnect(Boolean onlyWhenNoGUI = false) { { log.Debug("De-referencing all Outlook application objects."); try { - folders = (Folders)OutlookOgcs.Calendar.ReleaseObject(folders); - useOutlookCalendar = (MAPIFolder)OutlookOgcs.Calendar.ReleaseObject(useOutlookCalendar); + folders = (Folders)Outlook.Calendar.ReleaseObject(folders); + useOutlookCalendar = (MAPIFolder)Outlook.Calendar.ReleaseObject(useOutlookCalendar); for (int fld = calendarFolders.Count - 1; fld >= 0; fld--) { MAPIFolder mFld = calendarFolders.ElementAt(fld).Value; - mFld = (MAPIFolder)OutlookOgcs.Calendar.ReleaseObject(mFld); + mFld = (MAPIFolder)Outlook.Calendar.ReleaseObject(mFld); calendarFolders.Remove(calendarFolders.ElementAt(fld).Key); } calendarFolders = new Dictionary(); @@ -148,7 +148,7 @@ public Boolean NoGUIexists() { log.Fine("No running outlook.exe process found."); retVal = true; } else { - OutlookOgcs.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: false); + Outlook.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: false); try { explorers = oApp.Explorers; retVal = (explorers.Count == 0); @@ -158,7 +158,7 @@ public Boolean NoGUIexists() { } } } finally { - explorers = (Explorers)OutlookOgcs.Calendar.ReleaseObject(explorers); + explorers = (Explorers)Outlook.Calendar.ReleaseObject(explorers); } } if (retVal) log.Fine("No Outlook GUI detected."); @@ -190,11 +190,11 @@ public Boolean Offline() { oNS = oApp.GetNamespace("mapi"); return oNS.Offline; } catch { - OutlookOgcs.Calendar.Instance.Reset(); + Outlook.Calendar.Instance.Reset(); return false; } finally { if (oNS != null) oNS.Logoff(); - oNS = (NameSpace)OutlookOgcs.Calendar.ReleaseObject(oNS); + oNS = (NameSpace)Outlook.Calendar.ReleaseObject(oNS); } } public OlExchangeConnectionMode ExchangeConnectionMode() { @@ -219,7 +219,7 @@ public NameSpace GetCurrentUser(NameSpace oNS) { currentUser = oNS.CurrentUser; if (!Forms.Main.Instance.IsHandleCreated && (DateTime.Now - triggerOOMsecurity).TotalSeconds > 1) { log.Warn(">1s delay possibly due to Outlook security popup."); - OutlookOgcs.Calendar.OOMsecurityInfo = true; + Outlook.Calendar.OOMsecurityInfo = true; } } catch (System.Exception ex) { if (OGCSexception.GetErrorCode(ex) == "0x80004004") { //Access blocked @@ -231,9 +231,9 @@ public NameSpace GetCurrentUser(NameSpace oNS) { } OGCSexception.Analyse(ex); log.Warn("We seem to have a faux connection to Outlook! Forcing starting it with a system call :-/"); - oNS = (NameSpace)OutlookOgcs.Calendar.ReleaseObject(oNS); + oNS = (NameSpace)Outlook.Calendar.ReleaseObject(oNS); Disconnect(); - OutlookOgcs.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: true, withSystemCall: true); + Outlook.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: true, withSystemCall: true); oNS = oApp.GetNamespace("mapi"); int maxDelay = 5; @@ -262,7 +262,7 @@ public NameSpace GetCurrentUser(NameSpace oNS) { //Issue 402 log.Debug("Getting active window inspector"); Inspector inspector = oApp.ActiveInspector(); - inspector = (Inspector)OutlookOgcs.Calendar.ReleaseObject(inspector); + inspector = (Inspector)Outlook.Calendar.ReleaseObject(inspector); log.Debug("Done."); try { @@ -281,8 +281,8 @@ public NameSpace GetCurrentUser(NameSpace oNS) { profile.OutlookGalBlocked = false; } } finally { - currentUser = (Recipient)OutlookOgcs.Calendar.ReleaseObject(currentUser); - if (releaseNamespace) oNS = (NameSpace)OutlookOgcs.Calendar.ReleaseObject(oNS); + currentUser = (Recipient)Outlook.Calendar.ReleaseObject(currentUser); + if (releaseNamespace) oNS = (NameSpace)Outlook.Calendar.ReleaseObject(oNS); } return oNS; } @@ -290,7 +290,7 @@ public NameSpace GetCurrentUser(NameSpace oNS) { private MAPIFolder getCalendarStore(NameSpace oNS) { MAPIFolder defaultCalendar = null; SettingsStore.Calendar profile = Settings.Profile.InPlay(); - if (profile.OutlookService == OutlookOgcs.Calendar.Service.AlternativeMailbox && profile.MailboxName != "") { + if (profile.OutlookService == Outlook.Calendar.Service.AlternativeMailbox && profile.MailboxName != "") { log.Debug("Finding Alternative Mailbox calendar folders"); Folders binFolders = null; Store binStore = null; @@ -350,9 +350,9 @@ private MAPIFolder getCalendarStore(NameSpace oNS) { if (!(Forms.Main.Instance.Visible && Forms.Main.Instance.ActiveControl.Name == "rbOutlookAltMB")) throw new System.Exception("Failed to access alternate mailbox calendar '" + profile.MailboxName + "'", ex); } finally { - pa = (PropertyAccessor)OutlookOgcs.Calendar.ReleaseObject(pa); - binStore = (Store)OutlookOgcs.Calendar.ReleaseObject(binStore); - binFolders = (Folders)OutlookOgcs.Calendar.ReleaseObject(binFolders); + pa = (PropertyAccessor)Outlook.Calendar.ReleaseObject(pa); + binStore = (Store)Outlook.Calendar.ReleaseObject(binStore); + binFolders = (Folders)Outlook.Calendar.ReleaseObject(binFolders); mailboxNos++; } } while (calendarFolders.Count() == 0 && mailboxNos < Forms.Main.Instance.ddMailboxName.Items.Count); @@ -367,7 +367,7 @@ private MAPIFolder getCalendarStore(NameSpace oNS) { Forms.Main.Instance.ddMailboxName.Text = ""; } - } else if (profile.OutlookService == OutlookOgcs.Calendar.Service.SharedCalendar) { + } else if (profile.OutlookService == Outlook.Calendar.Service.SharedCalendar) { log.Debug("Finding shared calendar"); if (Forms.Main.Instance.Visible && profile.Equals(Forms.Main.Instance.ActiveCalendarProfile) && Forms.Main.Instance.ActiveControl?.Name == "rbOutlookSharedCal") { SelectNamesDialog snd; @@ -436,7 +436,7 @@ private MAPIFolder getSharedCalendar(NameSpace oNS, String sharedURI, Boolean in throw new System.Exception("Failed to access shared calendar.", ex); } } finally { - sharer = (Recipient)OutlookOgcs.Calendar.ReleaseObject(sharer); + sharer = (Recipient)Outlook.Calendar.ReleaseObject(sharer); } } @@ -449,7 +449,7 @@ private void getDefaultCalendar(NameSpace oNS, ref MAPIFolder defaultCalendar) { Forms.Main.Instance.rbOutlookDefaultMB.CheckedChanged -= Forms.Main.Instance.rbOutlookDefaultMB_CheckedChanged; Forms.Main.Instance.rbOutlookDefaultMB.Checked = true; } - profile.OutlookService = OutlookOgcs.Calendar.Service.DefaultMailbox; + profile.OutlookService = Outlook.Calendar.Service.DefaultMailbox; if (updateGUI) Forms.Main.Instance.rbOutlookDefaultMB.CheckedChanged += Forms.Main.Instance.rbOutlookDefaultMB_CheckedChanged; @@ -555,22 +555,22 @@ public List FilterItems(Items outlookItems, String filter) { public MAPIFolder GetFolderByID(String entryID) { NameSpace ns = null; try { - if (oApp == null) OutlookOgcs.Calendar.AttachToOutlook(ref oApp); + if (oApp == null) Outlook.Calendar.AttachToOutlook(ref oApp); ns = oApp.GetNamespace("mapi"); return ns.GetFolderFromID(entryID); } finally { - ns = (NameSpace)OutlookOgcs.Calendar.ReleaseObject(ns); + ns = (NameSpace)Outlook.Calendar.ReleaseObject(ns); } } public void GetAppointmentByID(String entryID, out AppointmentItem ai) { NameSpace ns = null; try { - if (oApp == null) OutlookOgcs.Calendar.AttachToOutlook(ref oApp); + if (oApp == null) Outlook.Calendar.AttachToOutlook(ref oApp); ns = oApp.GetNamespace("mapi"); ai = ns.GetItemFromID(entryID) as AppointmentItem; } finally { - ns = (NameSpace)OutlookOgcs.Calendar.ReleaseObject(ns); + ns = (NameSpace)Outlook.Calendar.ReleaseObject(ns); } } @@ -624,11 +624,11 @@ public String GetRecipientEmail(Recipient recipient) { log.Warn("Also failed to retrieve email from PropertyAccessor."); retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail); } finally { - pa = (Microsoft.Office.Interop.Outlook.PropertyAccessor)OutlookOgcs.Calendar.ReleaseObject(pa); + pa = (Microsoft.Office.Interop.Outlook.PropertyAccessor)Outlook.Calendar.ReleaseObject(pa); } } } finally { - eu = (ExchangeUser)OutlookOgcs.Calendar.ReleaseObject(eu); + eu = (ExchangeUser)Outlook.Calendar.ReleaseObject(eu); } } else if (addressEntry.AddressEntryUserType == OlAddressEntryUserType.olOutlookContactAddressEntry) { @@ -650,14 +650,14 @@ public String GetRecipientEmail(Recipient recipient) { pa = contact.PropertyAccessor; retEmail = pa.GetProperty(EMAIL1ADDRESS).ToString(); } finally { - pa = (Microsoft.Office.Interop.Outlook.PropertyAccessor)OutlookOgcs.Calendar.ReleaseObject(pa); + pa = (Microsoft.Office.Interop.Outlook.PropertyAccessor)Outlook.Calendar.ReleaseObject(pa); } } else { retEmail = contact.Email1Address; } } } finally { - contact = (ContactItem)OutlookOgcs.Calendar.ReleaseObject(contact); + contact = (ContactItem)Outlook.Calendar.ReleaseObject(contact); } } else { log.Fine("Exchange type: " + addressEntry.AddressEntryUserType.ToString()); @@ -667,7 +667,7 @@ public String GetRecipientEmail(Recipient recipient) { pa = recipient.PropertyAccessor; retEmail = pa.GetProperty(OutlookNew.PR_SMTP_ADDRESS).ToString(); } finally { - pa = (Microsoft.Office.Interop.Outlook.PropertyAccessor)OutlookOgcs.Calendar.ReleaseObject(pa); + pa = (Microsoft.Office.Interop.Outlook.PropertyAccessor)Outlook.Calendar.ReleaseObject(pa); } } @@ -708,7 +708,7 @@ public String GetRecipientEmail(Recipient recipient) { } return retEmail; } finally { - addressEntry = (AddressEntry)OutlookOgcs.Calendar.ReleaseObject(addressEntry); + addressEntry = (AddressEntry)Outlook.Calendar.ReleaseObject(addressEntry); } } @@ -726,12 +726,12 @@ public String GetGlobalApptID(AppointmentItem ai) { public void RefreshCategories() { log.Debug("Refreshing categories..."); try { - OutlookOgcs.Calendar.Categories.Get(oApp, useOutlookCalendar); + Outlook.Calendar.Categories.Get(oApp, useOutlookCalendar); } catch (System.Exception ex) { - Ogcs.Outlook.Errors.ErrorType error = Ogcs.Outlook.Errors.HandleComError(ex); - if (error == Ogcs.Outlook.Errors.ErrorType.RpcServerUnavailable || error == Ogcs.Outlook.Errors.ErrorType.WrongThread) { - OutlookOgcs.Calendar.Instance.Reset(); - OutlookOgcs.Calendar.Categories.Get(oApp, useOutlookCalendar); + Outlook.Errors.ErrorType error = Outlook.Errors.HandleComError(ex); + if (error == Outlook.Errors.ErrorType.RpcServerUnavailable || error == Outlook.Errors.ErrorType.WrongThread) { + Outlook.Calendar.Instance.Reset(); + Outlook.Calendar.Categories.Get(oApp, useOutlookCalendar); } } Extensions.OutlookColourPicker outlookColours = new Extensions.OutlookColourPicker(); @@ -739,7 +739,7 @@ public void RefreshCategories() { if (Settings.Profile.InPlay().Equals(Forms.Main.Instance.ActiveCalendarProfile)) { Forms.Main.Instance.ddOutlookColour = outlookColours; - foreach (OutlookOgcs.Categories.ColourInfo cInfo in Forms.Main.Instance.ddOutlookColour.Items) { + foreach (Outlook.Categories.ColourInfo cInfo in Forms.Main.Instance.ddOutlookColour.Items) { if (cInfo.OutlookCategory.ToString() == Forms.Main.Instance.ActiveCalendarProfile.SetEntriesColourValue && cInfo.Text == Forms.Main.Instance.ActiveCalendarProfile.SetEntriesColourName) { Forms.Main.Instance.ddOutlookColour.SelectedItem = cInfo; @@ -764,7 +764,7 @@ public Event IANAtimezone_set(Event ev, AppointmentItem ai) { pa = ai.PropertyAccessor; organiserTZname = pa.GetProperty(PR_ORGANISER_TIMEZONE).ToString(); } finally { - pa = (PropertyAccessor)OutlookOgcs.Calendar.ReleaseObject(pa); + pa = (PropertyAccessor)Outlook.Calendar.ReleaseObject(pa); } if (organiserTZname != ai.StartTimeZone.Name) { log.Fine("Appointment's timezone: " + ai.StartTimeZone.Name); @@ -780,7 +780,7 @@ public Event IANAtimezone_set(Event ev, AppointmentItem ai) { else organiserTZid = tzi.Id; } } catch (System.Exception ex) { - Forms.Main.Instance.Console.Update(OutlookOgcs.Calendar.GetEventSummary("
Could not determine the organiser's timezone. Google Event may have incorrect time.", ai, out String anonSummary), + Forms.Main.Instance.Console.Update(Outlook.Calendar.GetEventSummary("
Could not determine the organiser's timezone. Google Event may have incorrect time.", ai, out String anonSummary), anonSummary, Console.Markup.warning); if (ex.Data.Contains("OGCS")) log.Warn(ex.Message); else OGCSexception.Analyse(ex); @@ -840,8 +840,8 @@ public void WindowsTimeZone_get(AppointmentItem ai, out String startTz, out Stri startTz = _startTz.ID; endTz = _endTz.ID; } finally { - _startTz = (Microsoft.Office.Interop.Outlook.TimeZone)OutlookOgcs.Calendar.ReleaseObject(_startTz); - _endTz = (Microsoft.Office.Interop.Outlook.TimeZone)OutlookOgcs.Calendar.ReleaseObject(_endTz); + _startTz = (Microsoft.Office.Interop.Outlook.TimeZone)Outlook.Calendar.ReleaseObject(_startTz); + _endTz = (Microsoft.Office.Interop.Outlook.TimeZone)Outlook.Calendar.ReleaseObject(_endTz); } } @@ -986,7 +986,7 @@ public String GetEndTimeZoneID(AppointmentItem ai) { #endregion public void AddRtfBody(ref AppointmentItem ai, String RtfDocument) { - if (OutlookOgcs.Factory.OutlookVersionName != Factory.OutlookVersionNames.Outlook2007) { + if (Outlook.Factory.OutlookVersionName != Outlook.Factory.OutlookVersionNames.Outlook2007) { #if !DEVELOP_AGAINST_2007 if (String.IsNullOrEmpty(RtfDocument)) ai.RTFBody = " "; diff --git a/src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookOld.cs b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs similarity index 95% rename from src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookOld.cs rename to src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs index 1c7d7ae1..8b2de586 100644 --- a/src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookOld.cs +++ b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs @@ -7,7 +7,7 @@ using System.Runtime.InteropServices; using System.Windows.Forms; -namespace OutlookGoogleCalendarSync.OutlookOgcs { +namespace OutlookGoogleCalendarSync.Outlook { class OutlookOld : Interface { private static readonly ILog log = LogManager.GetLogger(typeof(OutlookOld)); @@ -20,9 +20,9 @@ class OutlookOld : Interface { private OlExchangeConnectionMode exchangeConnectionMode; public void Connect() { - if (!OutlookOgcs.Calendar.InstanceConnect) return; + if (!Outlook.Calendar.InstanceConnect) return; - OutlookOgcs.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: true, withSystemCall: false); + Outlook.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: true, withSystemCall: false); log.Debug("Setting up Outlook connection."); // Get the NameSpace and Logon information. @@ -79,12 +79,12 @@ public void Connect() { Forms.Main.Instance.cbOutlookCalendars.SelectedIndexChanged += Forms.Main.Instance.cbOutlookCalendar_SelectedIndexChanged; } - OutlookOgcs.Calendar.Categories = null; + Outlook.Calendar.Categories = null; } finally { // Done. Log off. if (oNS != null) try { oNS.Logoff(); } catch { } - oNS = (NameSpace)OutlookOgcs.Calendar.ReleaseObject(oNS); + oNS = (NameSpace)Outlook.Calendar.ReleaseObject(oNS); } } public void Disconnect(Boolean onlyWhenNoGUI = false) { @@ -94,11 +94,11 @@ public void Disconnect(Boolean onlyWhenNoGUI = false) { { log.Debug("De-referencing all Outlook application objects."); try { - folders = (Folders)OutlookOgcs.Calendar.ReleaseObject(folders); - useOutlookCalendar = (MAPIFolder)OutlookOgcs.Calendar.ReleaseObject(useOutlookCalendar); + folders = (Folders)Outlook.Calendar.ReleaseObject(folders); + useOutlookCalendar = (MAPIFolder)Outlook.Calendar.ReleaseObject(useOutlookCalendar); for (int fld = calendarFolders.Count - 1; fld >= 0; fld--) { MAPIFolder mFld = calendarFolders.ElementAt(fld).Value; - mFld = (MAPIFolder)OutlookOgcs.Calendar.ReleaseObject(mFld); + mFld = (MAPIFolder)Outlook.Calendar.ReleaseObject(mFld); calendarFolders.Remove(calendarFolders.ElementAt(fld).Key); } calendarFolders = new Dictionary(); @@ -125,7 +125,7 @@ public Boolean NoGUIexists() { log.Fine("No running outlook.exe process found."); retVal = true; } else { - OutlookOgcs.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: false); + Outlook.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: false); try { explorers = oApp.Explorers; retVal = (explorers.Count == 0); @@ -135,7 +135,7 @@ public Boolean NoGUIexists() { } } } finally { - explorers = (Explorers)OutlookOgcs.Calendar.ReleaseObject(explorers); + explorers = (Explorers)Outlook.Calendar.ReleaseObject(explorers); } } if (retVal) log.Fine("No Outlook GUI detected."); @@ -167,11 +167,11 @@ public Boolean Offline() { oNS = oApp.GetNamespace("mapi"); return oNS.Offline; } catch { - OutlookOgcs.Calendar.Instance.Reset(); + Outlook.Calendar.Instance.Reset(); return false; } finally { if (oNS != null) oNS.Logoff(); - oNS = (NameSpace)OutlookOgcs.Calendar.ReleaseObject(oNS); + oNS = (NameSpace)Outlook.Calendar.ReleaseObject(oNS); } } public OlExchangeConnectionMode ExchangeConnectionMode() { @@ -198,7 +198,7 @@ public NameSpace GetCurrentUser(NameSpace oNS) { currentUser = oNS.CurrentUser; if (!Forms.Main.Instance.IsHandleCreated && (DateTime.Now - triggerOOMsecurity).TotalSeconds > 1) { log.Warn(">1s delay possibly due to Outlook security popup."); - OutlookOgcs.Calendar.OOMsecurityInfo = true; + Outlook.Calendar.OOMsecurityInfo = true; } } catch (System.Exception ex) { OGCSexception.Analyse(ex); @@ -207,9 +207,9 @@ public NameSpace GetCurrentUser(NameSpace oNS) { return oNS; } log.Warn("We seem to have a faux connection to Outlook! Forcing starting it with a system call :-/"); - oNS = (NameSpace)OutlookOgcs.Calendar.ReleaseObject(oNS); + oNS = (NameSpace)Outlook.Calendar.ReleaseObject(oNS); Disconnect(); - OutlookOgcs.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: true, withSystemCall: true); + Outlook.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: true, withSystemCall: true); oNS = oApp.GetNamespace("mapi"); int maxDelay = 5; @@ -239,8 +239,8 @@ public NameSpace GetCurrentUser(NameSpace oNS) { currentUserSMTP = GetRecipientEmail(currentUser); currentUserName = currentUser.Name; } finally { - currentUser = (Recipient)OutlookOgcs.Calendar.ReleaseObject(currentUser); - if (releaseNamespace) oNS = (NameSpace)OutlookOgcs.Calendar.ReleaseObject(oNS); + currentUser = (Recipient)Outlook.Calendar.ReleaseObject(currentUser); + if (releaseNamespace) oNS = (NameSpace)Outlook.Calendar.ReleaseObject(oNS); } return oNS; } @@ -248,7 +248,7 @@ public NameSpace GetCurrentUser(NameSpace oNS) { private MAPIFolder getCalendarStore(NameSpace oNS) { MAPIFolder defaultCalendar = null; SettingsStore.Calendar profile = Settings.Profile.InPlay(); - if (profile.OutlookService == OutlookOgcs.Calendar.Service.DefaultMailbox) { + if (profile.OutlookService == Outlook.Calendar.Service.DefaultMailbox) { getDefaultCalendar(oNS, ref defaultCalendar); } log.Debug("Default Calendar folder: " + defaultCalendar.Name); @@ -280,7 +280,7 @@ private MAPIFolder getSharedCalendar(NameSpace oNS, String sharedURI) { MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return null; } finally { - sharer = (Recipient)OutlookOgcs.Calendar.ReleaseObject(sharer); + sharer = (Recipient)Outlook.Calendar.ReleaseObject(sharer); } } @@ -293,7 +293,7 @@ private void getDefaultCalendar(NameSpace oNS, ref MAPIFolder defaultCalendar) { Forms.Main.Instance.rbOutlookDefaultMB.CheckedChanged -= Forms.Main.Instance.rbOutlookDefaultMB_CheckedChanged; Forms.Main.Instance.rbOutlookDefaultMB.Checked = true; } - profile.OutlookService = OutlookOgcs.Calendar.Service.DefaultMailbox; + profile.OutlookService = Outlook.Calendar.Service.DefaultMailbox; if (updateGUI) Forms.Main.Instance.rbOutlookDefaultMB.CheckedChanged += Forms.Main.Instance.rbOutlookDefaultMB_CheckedChanged; @@ -419,18 +419,18 @@ public MAPIFolder GetFolderByID(String entryID) { ns = oApp.GetNamespace("mapi"); return ns.GetFolderFromID(entryID); } finally { - ns = (NameSpace)OutlookOgcs.Calendar.ReleaseObject(ns); + ns = (NameSpace)Outlook.Calendar.ReleaseObject(ns); } } public void GetAppointmentByID(String entryID, out AppointmentItem ai) { NameSpace ns = null; try { - if (oApp == null) OutlookOgcs.Calendar.AttachToOutlook(ref oApp); + if (oApp == null) Outlook.Calendar.AttachToOutlook(ref oApp); ns = oApp.GetNamespace("mapi"); ai = ns.GetItemFromID(entryID) as AppointmentItem; } finally { - ns = (NameSpace)OutlookOgcs.Calendar.ReleaseObject(ns); + ns = (NameSpace)Outlook.Calendar.ReleaseObject(ns); } } @@ -503,7 +503,7 @@ public String GetRecipientEmail(Recipient recipient) { } return retEmail; } finally { - addressEntry = (AddressEntry)OutlookOgcs.Calendar.ReleaseObject(addressEntry); + addressEntry = (AddressEntry)Outlook.Calendar.ReleaseObject(addressEntry); } } diff --git a/src/OutlookGoogleCalendarSync/OutlookOgcs/CustomProperty.cs b/src/OutlookGoogleCalendarSync/Outlook/CustomProperty.cs similarity index 91% rename from src/OutlookGoogleCalendarSync/OutlookOgcs/CustomProperty.cs rename to src/OutlookGoogleCalendarSync/Outlook/CustomProperty.cs index 732447ee..ceee5a4b 100644 --- a/src/OutlookGoogleCalendarSync/OutlookOgcs/CustomProperty.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/CustomProperty.cs @@ -6,7 +6,7 @@ using System.Linq; using System.Text.RegularExpressions; -namespace OutlookGoogleCalendarSync.OutlookOgcs { +namespace OutlookGoogleCalendarSync.Outlook { public class EphemeralProperties { private Dictionary> ephemeralProperties; @@ -125,11 +125,11 @@ private static String metadataIdKeyName(MetadataId Id) { int? returnVal = null; maxSet = 0; - if (OutlookOgcs.Calendar.Instance.EphemeralProperties.PropertyExists(ai, EphemeralProperty.PropertyName.KeySet) && - OutlookOgcs.Calendar.Instance.EphemeralProperties.PropertyExists(ai, EphemeralProperty.PropertyName.MaxSet)) + if (Calendar.Instance.EphemeralProperties.PropertyExists(ai, EphemeralProperty.PropertyName.KeySet) && + Calendar.Instance.EphemeralProperties.PropertyExists(ai, EphemeralProperty.PropertyName.MaxSet)) { - Object ep_keySet = OutlookOgcs.Calendar.Instance.EphemeralProperties.GetProperty(ai, EphemeralProperty.PropertyName.KeySet); - Object ep_maxSet = OutlookOgcs.Calendar.Instance.EphemeralProperties.GetProperty(ai, EphemeralProperty.PropertyName.MaxSet); + Object ep_keySet = Calendar.Instance.EphemeralProperties.GetProperty(ai, EphemeralProperty.PropertyName.KeySet); + Object ep_maxSet = Calendar.Instance.EphemeralProperties.GetProperty(ai, EphemeralProperty.PropertyName.MaxSet); maxSet = Convert.ToInt16(ep_maxSet ?? ep_keySet); if (ep_keySet != null) returnVal = Convert.ToInt16(ep_keySet); return returnVal; @@ -146,11 +146,11 @@ private static String metadataIdKeyName(MetadataId Id) { if (up.Name.StartsWith(calendarKeyName)) calendarKeys.Add(up.Name, up.Value.ToString()); } finally { - up = (UserProperty)OutlookOgcs.Calendar.ReleaseObject(up); + up = (UserProperty)Calendar.ReleaseObject(up); } } } finally { - ups = (UserProperties)OutlookOgcs.Calendar.ReleaseObject(ups); + ups = (UserProperties)Calendar.ReleaseObject(ups); } try { @@ -179,8 +179,8 @@ private static String metadataIdKeyName(MetadataId Id) { if (!string.IsNullOrEmpty(returnSet)) returnVal = Convert.ToInt16(returnSet); } finally { - OutlookOgcs.Calendar.Instance.EphemeralProperties.Add(ai, new EphemeralProperty(EphemeralProperty.PropertyName.KeySet, returnVal)); - OutlookOgcs.Calendar.Instance.EphemeralProperties.Add(ai, new EphemeralProperty(EphemeralProperty.PropertyName.MaxSet, maxSet)); + Calendar.Instance.EphemeralProperties.Add(ai, new EphemeralProperty(EphemeralProperty.PropertyName.KeySet, returnVal)); + Calendar.Instance.EphemeralProperties.Add(ai, new EphemeralProperty(EphemeralProperty.PropertyName.MaxSet, maxSet)); } return returnVal; } @@ -219,8 +219,8 @@ public static Boolean Exists(AppointmentItem ai, MetadataId searchId, out String } catch { return false; } finally { - prop = (UserProperty)OutlookOgcs.Calendar.ReleaseObject(prop); - ups = (UserProperties)OutlookOgcs.Calendar.ReleaseObject(ups); + prop = (UserProperty)Calendar.ReleaseObject(prop); + ups = (UserProperties)Calendar.ReleaseObject(ups); } } @@ -309,8 +309,8 @@ private static void add(ref AppointmentItem ai, MetadataId key, OlUserPropertyTy addkeyName = currentKeyName; //Might be suffixed with "-01" ups = ai.UserProperties; ups[addkeyName].Value = keyValue; - OutlookOgcs.Calendar.Instance.EphemeralProperties.Add(ai, new EphemeralProperty(EphemeralProperty.PropertyName.KeySet, keySet)); - OutlookOgcs.Calendar.Instance.EphemeralProperties.Add(ai, new EphemeralProperty(EphemeralProperty.PropertyName.MaxSet, keySet)); + Calendar.Instance.EphemeralProperties.Add(ai, new EphemeralProperty(EphemeralProperty.PropertyName.KeySet, keySet)); + Calendar.Instance.EphemeralProperties.Add(ai, new EphemeralProperty(EphemeralProperty.PropertyName.MaxSet, keySet)); log.Fine("Set userproperty " + addkeyName + "=" + keyValue.ToString()); } finally { @@ -332,8 +332,8 @@ public static String Get(AppointmentItem ai, MetadataId key) { retVal = prop.Value.ToString(); } } finally { - prop = (UserProperty)OutlookOgcs.Calendar.ReleaseObject(prop); - ups = (UserProperties)OutlookOgcs.Calendar.ReleaseObject(ups); + prop = (UserProperty)Calendar.ReleaseObject(prop); + ups = (UserProperties)Calendar.ReleaseObject(ups); } } return retVal; @@ -446,7 +446,7 @@ public static void LogProperties(AppointmentItem ai, log4net.Core.Level threshol UserProperties ups = null; UserProperty up = null; try { - log.Debug(OutlookOgcs.Calendar.GetEventSummary(ai)); + log.Debug(Calendar.GetEventSummary(ai)); ups = ai.UserProperties; for (int p = 1; p <= ups.Count; p++) { try { @@ -456,13 +456,13 @@ public static void LogProperties(AppointmentItem ai, log4net.Core.Level threshol else log.Debug(up.Name + "=" + up.Value.ToString()); } finally { - up = (UserProperty)OutlookOgcs.Calendar.ReleaseObject(up); + up = (UserProperty)Calendar.ReleaseObject(up); } } } catch (System.Exception ex) { OGCSexception.Analyse("Failed to log Appointment UserProperties", ex); } finally { - ups = (UserProperties)OutlookOgcs.Calendar.ReleaseObject(ups); + ups = (UserProperties)Calendar.ReleaseObject(ups); } } } diff --git a/src/OutlookGoogleCalendarSync/OutlookOgcs/ExplorerWatcher.cs b/src/OutlookGoogleCalendarSync/Outlook/ExplorerWatcher.cs similarity index 89% rename from src/OutlookGoogleCalendarSync/OutlookOgcs/ExplorerWatcher.cs rename to src/OutlookGoogleCalendarSync/Outlook/ExplorerWatcher.cs index fff1d96f..1555cc38 100644 --- a/src/OutlookGoogleCalendarSync/OutlookOgcs/ExplorerWatcher.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/ExplorerWatcher.cs @@ -2,9 +2,8 @@ using Microsoft.Office.Interop.Outlook; using System; using System.Collections.Generic; -using System.Linq; -namespace OutlookGoogleCalendarSync.OutlookOgcs { +namespace OutlookGoogleCalendarSync.Outlook { class ExplorerWatcher { private static readonly ILog log = LogManager.GetLogger(typeof(ExplorerWatcher)); @@ -74,11 +73,11 @@ private void beforeItemPaste(ref object ClipboardContent, MAPIFolder Target, ref } else { throw new ApplicationException("The item is not an appointment item."); } - log.Debug(OutlookOgcs.Calendar.GetEventSummary(copiedAi)); + log.Debug(Calendar.GetEventSummary(copiedAi)); String entryID = copiedAi.EntryID; - if (OutlookOgcs.CustomProperty.AnyStartsWith(copiedAi, OutlookOgcs.CustomProperty.MetadataId.gEventID)) { + if (CustomProperty.AnyStartsWith(copiedAi, CustomProperty.MetadataId.gEventID)) { Dictionary propertyBackup = cleanIDs(ref copiedAi); - OutlookOgcs.CustomProperty.Add(ref copiedAi, CustomProperty.MetadataId.originalStartDate, copiedAi.Start); + CustomProperty.Add(ref copiedAi, CustomProperty.MetadataId.originalStartDate, copiedAi.Start); copiedAi.Save(); System.Threading.Thread repopIDsThrd = new System.Threading.Thread(() => repopulateIDs(entryID, propertyBackup)); repopIDsThrd.Start(); @@ -86,7 +85,7 @@ private void beforeItemPaste(ref object ClipboardContent, MAPIFolder Target, ref } else { log.Debug("This item isn't managed by OGCS."); //But we still need to tag the pasted item as a "copied" item to avoid bad matches on Google events. - OutlookOgcs.CustomProperty.Add(ref copiedAi, OutlookOgcs.CustomProperty.MetadataId.locallyCopied, true.ToString()); + CustomProperty.Add(ref copiedAi, CustomProperty.MetadataId.locallyCopied, true.ToString()); copiedAi.Save(); //Untag the original copied item System.Threading.Thread untagAsCopiedThrd = new System.Threading.Thread(() => untagAsCopied(entryID)); @@ -101,7 +100,7 @@ private void beforeItemPaste(ref object ClipboardContent, MAPIFolder Target, ref OGCSexception.Analyse(ex); } finally { - copiedAi = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(copiedAi); + copiedAi = (AppointmentItem)Calendar.ReleaseObject(copiedAi); } } } catch (System.Exception ex) { @@ -130,18 +129,18 @@ private Dictionary cleanIDs(ref AppointmentItem copiedAi) { log.Fine("Property value: " + backupValue); propertyBackup.Add(metaDataId, backupValue); } finally { - up = (UserProperty)OutlookOgcs.Calendar.ReleaseObject(up); + up = (UserProperty)Calendar.ReleaseObject(up); } } - OutlookOgcs.CustomProperty.Extirpate(ref copiedAi); - OutlookOgcs.CustomProperty.Add(ref copiedAi, OutlookOgcs.CustomProperty.MetadataId.locallyCopied, true.ToString()); + CustomProperty.Extirpate(ref copiedAi); + CustomProperty.Add(ref copiedAi, CustomProperty.MetadataId.locallyCopied, true.ToString()); copiedAi.Save(); } catch (System.Exception ex) { log.Warn("Failed to clean OGCS properties from copied item."); OGCSexception.Analyse(ex); } finally { - ups = (UserProperties)OutlookOgcs.Calendar.ReleaseObject(ups); + ups = (UserProperties)Calendar.ReleaseObject(ups); } return propertyBackup; } @@ -154,12 +153,12 @@ private void repopulateIDs(String entryID, Dictionary propertyVa AppointmentItem copiedAi = null; try { untagAsCopied(entryID); - OutlookOgcs.Calendar.Instance.IOutlook.GetAppointmentByID(entryID, out copiedAi); + Calendar.Instance.IOutlook.GetAppointmentByID(entryID, out copiedAi); if (copiedAi == null) { throw new System.Exception("Could not find Outlook item with entryID " + entryID + " for post-processing."); } - log.Debug(OutlookOgcs.Calendar.GetEventSummary(copiedAi)); + log.Debug(Calendar.GetEventSummary(copiedAi)); foreach (KeyValuePair property in propertyValues) { if (property.Value is DateTime) addOutlookCustomProperty(ref copiedAi, property.Key, OlUserPropertyType.olDateTime, property.Value); @@ -167,7 +166,7 @@ private void repopulateIDs(String entryID, Dictionary propertyVa addOutlookCustomProperty(ref copiedAi, property.Key, OlUserPropertyType.olText, property.Value); } log.Fine("Restored properties:-"); - OutlookOgcs.CustomProperty.LogProperties(copiedAi, log4net.Core.Level.Debug); + CustomProperty.LogProperties(copiedAi, log4net.Core.Level.Debug); copiedAi.Save(); } catch (System.Exception ex) { @@ -180,7 +179,7 @@ private void repopulateIDs(String entryID, Dictionary propertyVa } OGCSexception.Analyse("Failed to repopulate OGCS properties back to copied item.", ex); } finally { - copiedAi = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(copiedAi); + copiedAi = (AppointmentItem)Calendar.ReleaseObject(copiedAi); } } @@ -191,13 +190,13 @@ private void untagAsCopied(String entryID) { AppointmentItem copiedAi = null; try { - OutlookOgcs.Calendar.Instance.IOutlook.GetAppointmentByID(entryID, out copiedAi); + Calendar.Instance.IOutlook.GetAppointmentByID(entryID, out copiedAi); if (copiedAi == null) { throw new System.Exception("Could not find Outlook item with entryID " + entryID + " for post-processing."); } - log.Debug(OutlookOgcs.Calendar.GetEventSummary(copiedAi)); - String deletedPropVal = deleteOutlookCustomProperty(ref copiedAi, OutlookOgcs.CustomProperty.MetadataId.locallyCopied.ToString()); - deletedPropVal = deleteOutlookCustomProperty(ref copiedAi, OutlookOgcs.CustomProperty.MetadataId.originalStartDate.ToString()); + log.Debug(Calendar.GetEventSummary(copiedAi)); + String deletedPropVal = deleteOutlookCustomProperty(ref copiedAi, CustomProperty.MetadataId.locallyCopied.ToString()); + deletedPropVal = deleteOutlookCustomProperty(ref copiedAi, CustomProperty.MetadataId.originalStartDate.ToString()); copiedAi.Save(); if (!String.IsNullOrEmpty(deletedPropVal)) { @@ -256,7 +255,7 @@ private void untagAsCopied(String entryID) { } OGCSexception.Analyse("Failed to remove OGCS 'copied' property on copied item.", ex); } finally { - copiedAi = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(copiedAi); + copiedAi = (AppointmentItem)Calendar.ReleaseObject(copiedAi); } } diff --git a/src/OutlookGoogleCalendarSync/OutlookOgcs/GMeet.cs b/src/OutlookGoogleCalendarSync/Outlook/GMeet.cs similarity index 99% rename from src/OutlookGoogleCalendarSync/OutlookOgcs/GMeet.cs rename to src/OutlookGoogleCalendarSync/Outlook/GMeet.cs index b82f1963..232b1dc5 100644 --- a/src/OutlookGoogleCalendarSync/OutlookOgcs/GMeet.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/GMeet.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Text.RegularExpressions; -namespace OutlookGoogleCalendarSync.OutlookOgcs { +namespace OutlookGoogleCalendarSync.Outlook { public class GMeetLogo { private static GMeetLogo instance; private static readonly ILog log = LogManager.GetLogger(typeof(GMeetLogo)); diff --git a/src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookCalendar.cs b/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs similarity index 96% rename from src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookCalendar.cs rename to src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs index bb424611..d283e837 100644 --- a/src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookCalendar.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs @@ -9,9 +9,9 @@ using System.Text; using System.Windows.Forms; -namespace OutlookGoogleCalendarSync.OutlookOgcs { +namespace OutlookGoogleCalendarSync.Outlook { /// - /// Description of OutlookOgcs.Calendar. + /// Class to target Outlook.Calendar for sync. /// public class Calendar { private static Calendar instance; @@ -52,14 +52,14 @@ public Folders Folders { public Dictionary CalendarFolders { get { return IOutlook.CalendarFolders(); } } - public static OutlookOgcs.Categories Categories; + public static Outlook.Categories Categories; public enum Service { DefaultMailbox, AlternativeMailbox, SharedCalendar } - public EphemeralProperties EphemeralProperties = new EphemeralProperties(); - + public Outlook.EphemeralProperties EphemeralProperties = new EphemeralProperties(); + /// Outlook Appointment excluded through user config public Dictionary ExcludedByCategory { get; private set; } @@ -103,8 +103,8 @@ public List GetCalendarEntriesInRange(SettingsStore.Calendar pr try { filtered = FilterCalendarEntries(profile, suppressAdvisories: suppressAdvisories); } catch (System.Runtime.InteropServices.InvalidComObjectException ex) { - if (Ogcs.Outlook.Errors.HandleComError(ex) == Ogcs.Outlook.Errors.ErrorType.ObjectSeparatedFromRcw) { - try { OutlookOgcs.Calendar.Instance.Reset(); } catch { } + if (Outlook.Errors.HandleComError(ex) == Outlook.Errors.ErrorType.ObjectSeparatedFromRcw) { + try { Outlook.Calendar.Instance.Reset(); } catch { } ex.Data.Add("OGCS", "Failed to access the Outlook calendar. Please try again."); throw; } @@ -118,7 +118,7 @@ public List GetCalendarEntriesInRange(SettingsStore.Calendar pr String wikiURL = "https://github.com/phw198/OutlookGoogleCalendarSync/wiki/Resolving-Outlook-Error-Messages#one-or-more-items-in-the-folder-you-synchronized-do-not-match"; ex.Data.Add("OGCS", ex.Message + "
Please view the wiki for suggestions on " + "how to resolve conflicts within your Outlook account."); - if (!suppressAdvisories && OgcsMessageBox.Show("Your Outlook calendar contains conflicts that need resolving in order to sync successfully.\r\nView the wiki for advice?", + if (!suppressAdvisories && OgcsMessageBox.Show("Your Outlook calendar contains conflicts that need resolving in order to sync successfully.\r\nView the wiki for advice?", "Outlook conflicts exist", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) Helper.OpenBrowser(wikiURL); } @@ -126,7 +126,7 @@ public List GetCalendarEntriesInRange(SettingsStore.Calendar pr } catch (System.ArgumentNullException ex) { OGCSexception.Analyse("It seems that Outlook has just been closed.", OGCSexception.LogAsFail(ex)); - OutlookOgcs.Calendar.Instance.Reset(); + Outlook.Calendar.Instance.Reset(); filtered = FilterCalendarEntries(profile, suppressAdvisories: suppressAdvisories); } catch (System.Exception) { @@ -357,7 +357,7 @@ private void createCalendarEntry(Event ev, ref AppointmentItem ai) { ai.Start = new DateTime(); ai.End = new DateTime(); ai.AllDayEvent = ev.AllDayEvent(); - ai = OutlookOgcs.Calendar.Instance.IOutlook.WindowsTimeZone_set(ai, ev); + ai = Outlook.Calendar.Instance.IOutlook.WindowsTimeZone_set(ai, ev); Recurrence.Instance.BuildOutlookPattern(ev, ai); ai.Subject = Obfuscate.ApplyRegex(Obfuscate.Property.Subject, ev.Summary, null, Sync.Direction.GoogleToOutlook); @@ -521,7 +521,7 @@ public Boolean UpdateCalendarEntry(ref AppointmentItem ai, Event ev, ref int ite String newStartTZ = "UTC"; String newEndTZ = "UTC"; IOutlook.WindowsTimeZone_get(ai, out currentStartTZ, out currentEndTZ); - ai = OutlookOgcs.Calendar.Instance.IOutlook.WindowsTimeZone_set(ai, ev, onlyTZattribute: true); + ai = Outlook.Calendar.Instance.IOutlook.WindowsTimeZone_set(ai, ev, onlyTZattribute: true); IOutlook.WindowsTimeZone_get(ai, out newStartTZ, out newEndTZ); Boolean startTzChange = Sync.Engine.CompareAttribute("Start Timezone", Sync.Direction.GoogleToOutlook, newStartTZ, currentStartTZ, sb, ref itemModified); Boolean endTzChange = Sync.Engine.CompareAttribute("End Timezone", Sync.Direction.GoogleToOutlook, newEndTZ, currentEndTZ, sb, ref itemModified); @@ -539,9 +539,9 @@ public Boolean UpdateCalendarEntry(ref AppointmentItem ai, Event ev, ref int ite if (startChange || endChange || startTzChange || endTzChange) { if (ai.RecurrenceState == OlRecurrenceState.olApptMaster) { if (startTzChange || endTzChange) { - oPattern = (RecurrencePattern)OutlookOgcs.Calendar.ReleaseObject(oPattern); + oPattern = (RecurrencePattern)Outlook.Calendar.ReleaseObject(oPattern); ai.ClearRecurrencePattern(); - ai = OutlookOgcs.Calendar.Instance.IOutlook.WindowsTimeZone_set(ai, ev, onlyTZattribute: false); + ai = Outlook.Calendar.Instance.IOutlook.WindowsTimeZone_set(ai, ev, onlyTZattribute: false); ai.Save(); Recurrence.Instance.BuildOutlookPattern(ev, ai); ai.Save(); //Explicit save required to make ai.IsRecurring true again @@ -557,7 +557,7 @@ public Boolean UpdateCalendarEntry(ref AppointmentItem ai, Event ev, ref int ite } } } else { - ai = OutlookOgcs.Calendar.Instance.IOutlook.WindowsTimeZone_set(ai, ev); + ai = Outlook.Calendar.Instance.IOutlook.WindowsTimeZone_set(ai, ev); } } @@ -637,8 +637,7 @@ public Boolean UpdateCalendarEntry(ref AppointmentItem ai, Event ev, ref int ite } if (ai.RecurrenceState == OlRecurrenceState.olApptMaster || - ai.RecurrenceState == OlRecurrenceState.olApptNotRecurring) - { + ai.RecurrenceState == OlRecurrenceState.olApptNotRecurring) { OlSensitivity gPrivacy = getPrivacy(ev.Visibility, ai.Sensitivity); if (Sync.Engine.CompareAttribute("Privacy", Sync.Direction.GoogleToOutlook, gPrivacy.ToString(), ai.Sensitivity.ToString(), sb, ref itemModified)) { ai.Sensitivity = gPrivacy; @@ -651,7 +650,7 @@ public Boolean UpdateCalendarEntry(ref AppointmentItem ai, Event ev, ref int ite if ((profile.AddColours || profile.SetEntriesColour) && ( ai.RecurrenceState == OlRecurrenceState.olApptMaster || - ai.RecurrenceState == OlRecurrenceState.olApptNotRecurring)) + ai.RecurrenceState == OlRecurrenceState.olApptNotRecurring)) // { log.Fine("Comparing colours/categories"); List aiCategories = new List(); @@ -726,7 +725,7 @@ public Boolean UpdateCalendarEntry(ref AppointmentItem ai, Event ev, ref int ite itemModified++; } } finally { - recipient = (Recipient)OutlookOgcs.Calendar.ReleaseObject(recipient); + recipient = (Recipient)Outlook.Calendar.ReleaseObject(recipient); } } foreach (EventAttendee gAttendee in addAttendees) { @@ -738,7 +737,7 @@ public Boolean UpdateCalendarEntry(ref AppointmentItem ai, Event ev, ref int ite itemModified++; } } finally { - recipients = (Recipients)OutlookOgcs.Calendar.ReleaseObject(recipients); + recipients = (Recipients)Outlook.Calendar.ReleaseObject(recipients); } } } @@ -816,7 +815,7 @@ public void DeleteCalendarEntries(List oAppointments) { try { doDelete = deleteCalendarEntry(ai); } catch (System.Exception ex) { - Forms.Main.Instance.Console.UpdateWithError(GetEventSummary("Appointment deletion failed.", ai, out String anonSummary, true), ex, logEntry:anonSummary); + Forms.Main.Instance.Console.UpdateWithError(GetEventSummary("Appointment deletion failed.", ai, out String anonSummary, true), ex, logEntry: anonSummary); OGCSexception.Analyse(ex, true); if (OgcsMessageBox.Show("Outlook appointment deletion failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; @@ -930,7 +929,7 @@ public void ReclaimOrphanCalendarEntries(ref List oAppointments log.Debug(unclaimedAi.Count + " unclaimed."); if (unclaimedAi.Count > 0 && (profile.SyncDirection.Id == Sync.Direction.GoogleToOutlook.Id || - profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id)) + profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id)) // { log.Info(unclaimedAi.Count + " unclaimed orphan appointments found."); if (profile.MergeItems || profile.DisableDelete || profile.ConfirmOnDelete) { @@ -969,7 +968,7 @@ private void createRecipient(EventAttendee gea, ref Recipients recipients) { recipient.Type = (int)(ea.Optional == null ? OlMeetingRecipientType.olRequired : ((bool)ea.Optional ? OlMeetingRecipientType.olOptional : OlMeetingRecipientType.olRequired)); //ReadOnly: ea.ResponseStatus } finally { - recipient = (Recipient)OutlookOgcs.Calendar.ReleaseObject(recipient); + recipient = (Recipient)Outlook.Calendar.ReleaseObject(recipient); } } } @@ -1013,10 +1012,10 @@ private OlSensitivity getPrivacy(String gVisibility, OlSensitivity? oSensitivity private OlBusyStatus getAvailability(String gTransparency, OlBusyStatus? oBusyStatus) { SettingsStore.Calendar profile = Sync.Engine.Calendar.Instance.Profile; List persistOutlookStatus = new List { OlBusyStatus.olTentative.ToString(), OlBusyStatus.olOutOfOffice.ToString(), "olWorkingElsewhere" }; - + if (!profile.SetEntriesAvailable) - return (gTransparency == "transparent") ? OlBusyStatus.olFree : - persistOutlookStatus.Contains(oBusyStatus.ToString()) ? (OlBusyStatus)oBusyStatus: OlBusyStatus.olBusy; + return (gTransparency == "transparent") ? OlBusyStatus.olFree : + persistOutlookStatus.Contains(oBusyStatus.ToString()) ? (OlBusyStatus)oBusyStatus : OlBusyStatus.olBusy; OlBusyStatus overrideFbStatus = OlBusyStatus.olFree; try { @@ -1058,13 +1057,13 @@ private String getColour(String gColourId, String oColour) { if (profile.SetEntriesColour) { if (profile.TargetCalendar.Id == Sync.Direction.OutlookToGoogle.Id) { //Colour forced to sync in other direction if (oColour == null) { //Creating item - OlCategoryColor outlookColour = OutlookOgcs.Categories.Map.Colours.Where(c => c.Key.ToString() == profile.SetEntriesColourValue).FirstOrDefault().Key; + OlCategoryColor outlookColour = Outlook.Categories.Map.Colours.Where(c => c.Key.ToString() == profile.SetEntriesColourValue).FirstOrDefault().Key; return Categories.FindName(outlookColour, profile.SetEntriesColourName); } else return oColour; } else { if (!profile.CreatedItemsOnly || (profile.CreatedItemsOnly && oColour == null)) { - OlCategoryColor outlookColour = OutlookOgcs.Categories.Map.Colours.Where(c => c.Key.ToString() == profile.SetEntriesColourValue).FirstOrDefault().Key; + OlCategoryColor outlookColour = Outlook.Categories.Map.Colours.Where(c => c.Key.ToString() == profile.SetEntriesColourValue).FirstOrDefault().Key; return Categories.FindName(outlookColour, profile.SetEntriesColourName); } else return oColour; } @@ -1080,7 +1079,7 @@ public String GetCategoryColour(String gColourId, Boolean createMissingCategory if (profile.ColourMaps.Count > 0) { KeyValuePair kvp = profile.ColourMaps.FirstOrDefault(cm => cm.Value == gColourId); if (kvp.Key != null) { - outlookColour = OutlookOgcs.Calendar.Categories.OutlookColour(kvp.Key); + outlookColour = Outlook.Calendar.Categories.OutlookColour(kvp.Key); if (outlookColour != null) { log.Debug("Colour mapping used: " + kvp.Value + ":" + GoogleOgcs.Calendar.Instance.ColourPalette.GetColour(gColourId).Name + " => " + kvp.Key); return kvp.Key; @@ -1105,7 +1104,7 @@ public static void AttachToOutlook(ref Microsoft.Office.Interop.Outlook.Applicat if (oApp == null) throw new ApplicationException("GetActiveObject() returned NULL without throwing an error."); } catch (System.Exception ex) { - if (Ogcs.Outlook.Errors.HandleComError(ex) == Ogcs.Outlook.Errors.ErrorType.Unavailable) { //MK_E_UNAVAILABLE + if (Outlook.Errors.HandleComError(ex) == Outlook.Errors.ErrorType.Unavailable) { //MK_E_UNAVAILABLE log.Warn("Attachment failed - Outlook is running without GUI for programmatic access."); } else { log.Warn("Attachment failed."); @@ -1162,7 +1161,7 @@ private static void openOutlook(ref Microsoft.Office.Interop.Outlook.Application while (maxWaits > 0 && oApp == null) { if (maxWaits % 2 == 0) log.Info("Waiting for Outlook to start..."); oProcess.WaitForInputIdle(15000); - OutlookOgcs.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: false); + Outlook.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: false); if (oApp == null) { log.Debug("Reattempting starting Outlook without system call."); try { oApp = new Microsoft.Office.Interop.Outlook.Application(); } catch (System.Exception ex) { log.Debug("Errored with: " + ex.Message); } @@ -1187,12 +1186,12 @@ public static void PoorlyOfficeInstall(System.Exception caughtException) { try { throw caughtException; } catch (System.Runtime.InteropServices.COMException ex) { - Ogcs.Outlook.Errors.ErrorType error = Ogcs.Outlook.Errors.HandleComError(ex, out String hResult); + Outlook.Errors.ErrorType error = Outlook.Errors.HandleComError(ex, out String hResult); - if (error == Ogcs.Outlook.Errors.ErrorType.RpcRejected || - error == Ogcs.Outlook.Errors.ErrorType.PermissionFailure || - error == Ogcs.Outlook.Errors.ErrorType.RpcServerUnavailable || - error == Ogcs.Outlook.Errors.ErrorType.RpcFailed) // + if (error == Outlook.Errors.ErrorType.RpcRejected || + error == Outlook.Errors.ErrorType.PermissionFailure || + error == Outlook.Errors.ErrorType.RpcServerUnavailable || + error == Outlook.Errors.ErrorType.RpcFailed) // { log.Warn(ex.Message); throw new ApplicationException("Outlook is busy.", ex); @@ -1246,7 +1245,7 @@ private static Boolean comErrorInWiki(System.Exception ex) { comGa4Ev.AddParameter("com_object", hResult); comGa4Ev.AddParameter(GA4.General.sync_count, Settings.Instance.CompletedSyncs); comGa4Ev.Send(); - + if (hResult == "0x80004002" && (ex is System.InvalidCastException || ex is System.Runtime.InteropServices.COMException)) { log.Warn(ex.Message); log.Debug("Extracting specific COM error code from Exception error message."); @@ -1263,7 +1262,7 @@ private static Boolean comErrorInWiki(System.Exception ex) { OGCSexception.Analyse("Parsing error message with regex failed.", ex2); } } - + if (!string.IsNullOrEmpty(hResult)) { try { String html = ""; @@ -1401,7 +1400,7 @@ private static string exportToCSV(AppointmentItem ai) { csv.Append("\"" + (ai.OptionalAttendees == null ? "" : ai.OptionalAttendees) + "\","); csv.Append(ai.ReminderSet + ","); csv.Append(ai.ReminderMinutesBeforeStart.ToString() + ","); - csv.Append(OutlookOgcs.Calendar.Instance.IOutlook.GetGlobalApptID(ai) + ","); + csv.Append(Outlook.Calendar.Instance.IOutlook.GetGlobalApptID(ai) + ","); csv.Append(ai.EntryID + "," + Sync.Engine.Calendar.Instance.Profile.UseOutlookCalendar.Id + ","); csv.Append((CustomProperty.Get(ai, CustomProperty.MetadataId.gEventID) ?? "") + ","); csv.Append((CustomProperty.Get(ai, CustomProperty.MetadataId.gCalendarId) ?? "") + ","); @@ -1464,7 +1463,7 @@ public static string GetEventSummary(AppointmentItem ai, out String eventSummary } eventSummary += " " + (ai.IsRecurring ? "(R) " : "") + "=> "; - if (Settings.Instance.AnonymiseLogs) + if (Settings.Instance.AnonymiseLogs) eventSummaryAnonymised = eventSummary + '"' + GoogleOgcs.Authenticator.GetMd5(ai.Subject, silent: true) + '"' + (onlyIfNotVerbose ? "
" : ""); eventSummary += '"' + ai.Subject + '"' + (onlyIfNotVerbose ? "
" : ""); @@ -1484,7 +1483,7 @@ public static string GetEventSummary(AppointmentItem ai, out String eventSummary public static void IdentifyEventDifferences( ref List google, //need creating ref List outlook, //need deleting - ref Dictionary compare) + ref Dictionary compare) // { log.Debug("Comparing Google events to Outlook items..."); Forms.Main.Instance.Console.Update("Matching calendar items...", verbose: true); @@ -1528,7 +1527,7 @@ public static void IdentifyEventDifferences( } } if (!foundMatch && profile.MergeItems && - OutlookOgcs.CustomProperty.Get(outlook[o], CustomProperty.MetadataId.gCalendarId) != profile.UseGoogleCalendar.Id) + Outlook.CustomProperty.Get(outlook[o], CustomProperty.MetadataId.gCalendarId) != profile.UseGoogleCalendar.Id) outlook.Remove(outlook[o]); } else if (profile.MergeItems) { @@ -1680,5 +1679,5 @@ private Boolean isOKtoSyncReminder(DateTime alarm) { } } #endregion + } } -} diff --git a/src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookCategories.cs b/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs similarity index 63% rename from src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookCategories.cs rename to src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs index 626b85aa..365ff241 100644 --- a/src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookCategories.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs @@ -5,17 +5,17 @@ using System.Drawing; using System.Linq; using System.Windows.Forms; -using Outlook = Microsoft.Office.Interop.Outlook; +using OutlookCOM = Microsoft.Office.Interop.Outlook; -namespace OutlookGoogleCalendarSync.OutlookOgcs { +namespace OutlookGoogleCalendarSync.Outlook { public class Categories { public class ColourInfo { public String Text { get; } - public Outlook.OlCategoryColor OutlookCategory { get; } + public OutlookCOM.OlCategoryColor OutlookCategory { get; } public Color Colour { get; } - public ColourInfo(Outlook.OlCategoryColor category, Color colour, String name = "") { - this.Text = string.IsNullOrEmpty(name) ? OutlookOgcs.Categories.FriendlyCategoryName(category) : name; + public ColourInfo(OutlookCOM.OlCategoryColor category, Color colour, String name = "") { + this.Text = string.IsNullOrEmpty(name) ? Categories.FriendlyCategoryName(category) : name; this.Colour = colour; this.OutlookCategory = category; } @@ -25,42 +25,42 @@ public class Map { private static readonly ILog log = LogManager.GetLogger(typeof(Map)); //Source: https://msdn.microsoft.com/en-us/library/ee203806%28v=exchg.80%29.aspx - public static Dictionary Colours { get; } + public static Dictionary Colours { get; } static Map() { - Colours = new Dictionary { - { Outlook.OlCategoryColor.olCategoryColorBlack, Color.FromArgb(28,28,28) }, - { Outlook.OlCategoryColor.olCategoryColorBlue, Color.FromArgb(50, 103, 184) }, - { Outlook.OlCategoryColor.olCategoryColorDarkBlue, Color.FromArgb(42, 81, 145 ) }, - { Outlook.OlCategoryColor.olCategoryColorDarkGray, Color.FromArgb(165, 165, 165) }, - { Outlook.OlCategoryColor.olCategoryColorDarkGreen, Color.FromArgb(53, 121, 43) }, - { Outlook.OlCategoryColor.olCategoryColorDarkMaroon, Color.FromArgb(130, 55, 95) }, - { Outlook.OlCategoryColor.olCategoryColorDarkOlive, Color.FromArgb(95, 108, 58) }, - { Outlook.OlCategoryColor.olCategoryColorDarkOrange, Color.FromArgb(177, 79, 13 ) }, - { Outlook.OlCategoryColor.olCategoryColorDarkPeach, Color.FromArgb(171, 123, 5 ) }, - { Outlook.OlCategoryColor.olCategoryColorDarkPurple, Color.FromArgb(80, 50, 143) }, - { Outlook.OlCategoryColor.olCategoryColorDarkRed, Color.FromArgb(175, 30, 37) }, - { Outlook.OlCategoryColor.olCategoryColorDarkSteel, Color.FromArgb(140, 156, 189) }, - { Outlook.OlCategoryColor.olCategoryColorDarkTeal, Color.FromArgb(46, 125, 100) }, - { Outlook.OlCategoryColor.olCategoryColorDarkYellow, Color.FromArgb(153, 148, 0) }, - { Outlook.OlCategoryColor.olCategoryColorGray, Color.FromArgb(196, 196, 196) }, - { Outlook.OlCategoryColor.olCategoryColorGreen, Color.FromArgb(74, 182, 63) }, - { Outlook.OlCategoryColor.olCategoryColorMaroon, Color.FromArgb(163, 78, 120) }, - { Outlook.OlCategoryColor.olCategoryColorNone, Color.FromArgb(255, 255, 255) }, - { Outlook.OlCategoryColor.olCategoryColorOlive, Color.FromArgb(133, 154, 82) }, - { Outlook.OlCategoryColor.olCategoryColorOrange, Color.FromArgb(240, 108, 21) }, - { Outlook.OlCategoryColor.olCategoryColorPeach, Color.FromArgb(255, 202, 76) }, - { Outlook.OlCategoryColor.olCategoryColorPurple, Color.FromArgb(97, 61, 180) }, - { Outlook.OlCategoryColor.olCategoryColorRed, Color.FromArgb(214, 37, 46) }, - { Outlook.OlCategoryColor.olCategoryColorSteel, Color.FromArgb(196, 204, 221) }, - { Outlook.OlCategoryColor.olCategoryColorTeal, Color.FromArgb(64, 189, 149) }, - { Outlook.OlCategoryColor.olCategoryColorYellow, Color.FromArgb(255, 254, 61) } + Colours = new Dictionary { + { OutlookCOM.OlCategoryColor.olCategoryColorBlack, Color.FromArgb(28,28,28) }, + { OutlookCOM.OlCategoryColor.olCategoryColorBlue, Color.FromArgb(50, 103, 184) }, + { OutlookCOM.OlCategoryColor.olCategoryColorDarkBlue, Color.FromArgb(42, 81, 145 ) }, + { OutlookCOM.OlCategoryColor.olCategoryColorDarkGray, Color.FromArgb(165, 165, 165) }, + { OutlookCOM.OlCategoryColor.olCategoryColorDarkGreen, Color.FromArgb(53, 121, 43) }, + { OutlookCOM.OlCategoryColor.olCategoryColorDarkMaroon, Color.FromArgb(130, 55, 95) }, + { OutlookCOM.OlCategoryColor.olCategoryColorDarkOlive, Color.FromArgb(95, 108, 58) }, + { OutlookCOM.OlCategoryColor.olCategoryColorDarkOrange, Color.FromArgb(177, 79, 13 ) }, + { OutlookCOM.OlCategoryColor.olCategoryColorDarkPeach, Color.FromArgb(171, 123, 5 ) }, + { OutlookCOM.OlCategoryColor.olCategoryColorDarkPurple, Color.FromArgb(80, 50, 143) }, + { OutlookCOM.OlCategoryColor.olCategoryColorDarkRed, Color.FromArgb(175, 30, 37) }, + { OutlookCOM.OlCategoryColor.olCategoryColorDarkSteel, Color.FromArgb(140, 156, 189) }, + { OutlookCOM.OlCategoryColor.olCategoryColorDarkTeal, Color.FromArgb(46, 125, 100) }, + { OutlookCOM.OlCategoryColor.olCategoryColorDarkYellow, Color.FromArgb(153, 148, 0) }, + { OutlookCOM.OlCategoryColor.olCategoryColorGray, Color.FromArgb(196, 196, 196) }, + { OutlookCOM.OlCategoryColor.olCategoryColorGreen, Color.FromArgb(74, 182, 63) }, + { OutlookCOM.OlCategoryColor.olCategoryColorMaroon, Color.FromArgb(163, 78, 120) }, + { OutlookCOM.OlCategoryColor.olCategoryColorNone, Color.FromArgb(255, 255, 255) }, + { OutlookCOM.OlCategoryColor.olCategoryColorOlive, Color.FromArgb(133, 154, 82) }, + { OutlookCOM.OlCategoryColor.olCategoryColorOrange, Color.FromArgb(240, 108, 21) }, + { OutlookCOM.OlCategoryColor.olCategoryColorPeach, Color.FromArgb(255, 202, 76) }, + { OutlookCOM.OlCategoryColor.olCategoryColorPurple, Color.FromArgb(97, 61, 180) }, + { OutlookCOM.OlCategoryColor.olCategoryColorRed, Color.FromArgb(214, 37, 46) }, + { OutlookCOM.OlCategoryColor.olCategoryColorSteel, Color.FromArgb(196, 204, 221) }, + { OutlookCOM.OlCategoryColor.olCategoryColorTeal, Color.FromArgb(64, 189, 149) }, + { OutlookCOM.OlCategoryColor.olCategoryColorYellow, Color.FromArgb(255, 254, 61) } }; } /// /// Convert from Outlook category colour to Color /// - public static Color RgbColour(Outlook.OlCategoryColor colour) { + public static Color RgbColour(OutlookCOM.OlCategoryColor colour) { log.Fine("Converting " + colour + " to RGB value."); return Colours[colour]; } @@ -79,7 +79,7 @@ public static Color RgbColour(String hexColour) { return colour; } - public static Outlook.OlCategoryColor GetClosestCategory(GoogleOgcs.EventColour.Palette basePalette) { + public static OutlookCOM.OlCategoryColor GetClosestCategory(GoogleOgcs.EventColour.Palette basePalette) { try { var colourDistance = Colours.Select(x => new { Value = x, Diff = GoogleOgcs.EventColour.GetDiff(x.Value, basePalette.RgbValue) }).ToList(); var minDistance = colourDistance.Min(x => x.Diff); @@ -87,15 +87,15 @@ public static Outlook.OlCategoryColor GetClosestCategory(GoogleOgcs.EventColour. } catch (System.Exception ex) { log.Warn("Failed to get closest Outlook category for " + basePalette.ToString()); OGCSexception.Analyse(ex); - return Outlook.OlCategoryColor.olCategoryColorNone; + return OutlookCOM.OlCategoryColor.olCategoryColorNone; } } } private static readonly ILog log = LogManager.GetLogger(typeof(Categories)); - private Outlook.Categories _categories; - private Outlook.Categories categories { + private OutlookCOM.Categories _categories; + private OutlookCOM.Categories categories { get { try { int? testAccess = this._categories?.Count; @@ -121,7 +121,7 @@ public Categories() { } public void Dispose() { - _categories = (Outlook.Categories)OutlookOgcs.Calendar.ReleaseObject(_categories); + _categories = (OutlookCOM.Categories)Calendar.ReleaseObject(_categories); } /// @@ -129,29 +129,29 @@ public void Dispose() { /// /// /// - public void Get(Outlook.Application oApp, Outlook.MAPIFolder calendar) { - Outlook.Store store = null; + public void Get(OutlookCOM.Application oApp, OutlookCOM.MAPIFolder calendar) { + OutlookCOM.Store store = null; try { - if (Settings.Profile.InPlay().OutlookService == OutlookOgcs.Calendar.Service.DefaultMailbox) + if (Settings.Profile.InPlay().OutlookService == Calendar.Service.DefaultMailbox) this.categories = oApp.Session.Categories; else { try { store = calendar.Store; - if (OutlookOgcs.Factory.OutlookVersionName == Factory.OutlookVersionNames.Outlook2007) { + if (Factory.OutlookVersionName == Factory.OutlookVersionNames.Outlook2007) { log.Debug("Accessing Outlook 2007 categories via reflection."); - this.categories = store.GetType().GetProperty("Categories").GetValue(store, null) as Outlook.Categories; + this.categories = store.GetType().GetProperty("Categories").GetValue(store, null) as OutlookCOM.Categories; } else { #if !DEVELOP_AGAINST_2007 log.Debug("Accessing categories through Outlook 2010 store."); this.categories = store.Categories; #else log.Debug("Accessing Outlook 2007 categories via reflection."); - this.categories = store.GetType().GetProperty("Categories").GetValue(store, null) as Outlook.Categories; + this.categories = store.GetType().GetProperty("Categories").GetValue(store, null) as OutlookCOM.Categories; #endif } } catch (System.Exception ex) { - Ogcs.Outlook.Errors.ErrorType error = Ogcs.Outlook.Errors.HandleComError(ex); - if (error == Ogcs.Outlook.Errors.ErrorType.RpcServerUnavailable || error == Ogcs.Outlook.Errors.ErrorType.WrongThread) + Outlook.Errors.ErrorType error = Outlook.Errors.HandleComError(ex); + if (error == Outlook.Errors.ErrorType.RpcServerUnavailable || error == Outlook.Errors.ErrorType.WrongThread) throw; log.Warn("Failed getting non-default mailbox categories. " + ex.Message); @@ -160,7 +160,7 @@ public void Get(Outlook.Application oApp, Outlook.MAPIFolder calendar) { } } } finally { - store = (Outlook.Store)Calendar.ReleaseObject(store); + store = (OutlookCOM.Store)Calendar.ReleaseObject(store); } } @@ -184,10 +184,10 @@ public void BuildPicker(ref System.Windows.Forms.CheckedListBox clb) { /// /// The user named Outlook category /// The Outlook category type - public Outlook.OlCategoryColor? OutlookColour(String categoryName) { + public OutlookCOM.OlCategoryColor? OutlookColour(String categoryName) { if (string.IsNullOrEmpty(categoryName)) log.Warn("Category name is empty."); - foreach (Outlook.Category category in this.categories) { + foreach (OutlookCOM.Category category in this.categories) { if (category.Name == categoryName.Trim()) return category.Color; } @@ -205,19 +205,19 @@ public void ValidateCategories() { OGCSexception.Analyse("Categories are not accessible!", OGCSexception.LogAsFail(ex)); this._categories = null; } - if (this._categories == null || OutlookOgcs.Calendar.Categories == null) { - OutlookOgcs.Calendar.Instance.IOutlook.RefreshCategories(); + if (this._categories == null || Calendar.Categories == null) { + Calendar.Instance.IOutlook.RefreshCategories(); } else { String catName = ""; try { - foreach (Outlook.Category cat in this._categories) { + foreach (OutlookCOM.Category cat in this._categories) { catName = cat.Name; - Outlook.OlCategoryColor catColour = cat.Color; + OutlookCOM.OlCategoryColor catColour = cat.Color; } } catch (System.Exception ex) { if (OGCSexception.GetErrorCode(ex, 0x0000FFFF) == "0x00004005" && ex.TargetSite.Name == "get_Color") { log.Warn("Outlook category '" + catName + "' seems to have changed!"); - OutlookOgcs.Calendar.Instance.IOutlook.RefreshCategories(); + Calendar.Instance.IOutlook.RefreshCategories(); } else { OGCSexception.Analyse("Could not access all the Outlook categories.", ex); this.categories = null; @@ -234,7 +234,7 @@ public void ValidateCategories() { private List getNames() { List names = new List(); if (this._categories != null) { - foreach (Outlook.Category category in this.categories) { + foreach (OutlookCOM.Category category in this.categories) { names.Add(category.Name); } } @@ -245,10 +245,10 @@ private List getNames() { /// Get the Outlook categories as List of ColourInfo /// /// List to be used in dropdown, for example - public List DropdownItems() { - List items = new List(); - foreach (Outlook.Category category in this.categories) { - items.Add(new OutlookOgcs.Categories.ColourInfo(category.Color, Categories.Map.RgbColour(category.Color), category.Name)); + public List DropdownItems() { + List items = new List(); + foreach (OutlookCOM.Category category in this.categories) { + items.Add(new Categories.ColourInfo(category.Color, Categories.Map.RgbColour(category.Color), category.Name)); } return items.OrderBy(i => i.Text).ToList(); } @@ -261,11 +261,11 @@ private List getNames() { /// Optional: The Outlook category name to also search by /// Optional: Create unused category colour? /// The matching category name - public String FindName(Outlook.OlCategoryColor? olCategory, String categoryName = null, Boolean createMissingCategory = true) { - if (olCategory == null || olCategory == Outlook.OlCategoryColor.olCategoryColorNone) return ""; + public String FindName(OutlookCOM.OlCategoryColor? olCategory, String categoryName = null, Boolean createMissingCategory = true) { + if (olCategory == null || olCategory == OutlookCOM.OlCategoryColor.olCategoryColorNone) return ""; - Outlook.Category failSafeCategory = null; - foreach (Outlook.Category category in this.categories) { + OutlookCOM.Category failSafeCategory = null; + foreach (OutlookCOM.Category category in this.categories) { try { if (category.Color == olCategory) { if (categoryName == null) { @@ -279,7 +279,7 @@ public String FindName(Outlook.OlCategoryColor? olCategory, String categoryName } catch (System.Runtime.InteropServices.COMException ex) { if (OGCSexception.GetErrorCode(ex, 0x0000FFFF) == "0x00004005") { //The operation failed. log.Warn("It seems a category has been manually removed in Outlook."); - OutlookOgcs.Calendar.Instance.IOutlook.RefreshCategories(); + Calendar.Instance.IOutlook.RefreshCategories(); } else throw; } } @@ -297,14 +297,14 @@ public String FindName(Outlook.OlCategoryColor? olCategory, String categoryName "Create new Outlook category?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes; } if (createMissingCategory) { - Outlook.Category newCategory = categories.Add(newCategoryName, olCategory); + OutlookCOM.Category newCategory = categories.Add(newCategoryName, olCategory); log.Info("Added new Outlook category \"" + newCategory.Name + "\" for " + newCategory.Color.ToString()); return newCategory.Name; } return ""; } - public static String FriendlyCategoryName(Outlook.OlCategoryColor? olCategory) { + public static String FriendlyCategoryName(OutlookCOM.OlCategoryColor? olCategory) { return olCategory.ToString().Replace("olCategoryColor", "").Replace("Dark", "Dark "); } } diff --git a/src/OutlookGoogleCalendarSync/Ogcs.Outlook/OutlookErrors.cs b/src/OutlookGoogleCalendarSync/Outlook/OutlookErrors.cs similarity index 98% rename from src/OutlookGoogleCalendarSync/Ogcs.Outlook/OutlookErrors.cs rename to src/OutlookGoogleCalendarSync/Outlook/OutlookErrors.cs index 4df69c7c..6dcf7afe 100644 --- a/src/OutlookGoogleCalendarSync/Ogcs.Outlook/OutlookErrors.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/OutlookErrors.cs @@ -1,7 +1,7 @@ using log4net; using System; -namespace OutlookGoogleCalendarSync.Ogcs.Outlook { +namespace OutlookGoogleCalendarSync.Outlook { public class Errors { private static readonly ILog log = LogManager.GetLogger(typeof(Errors)); diff --git a/src/OutlookGoogleCalendarSync/OutlookGoogleCalendarSync.csproj b/src/OutlookGoogleCalendarSync/OutlookGoogleCalendarSync.csproj index cc457c3a..f5768527 100644 --- a/src/OutlookGoogleCalendarSync/OutlookGoogleCalendarSync.csproj +++ b/src/OutlookGoogleCalendarSync/OutlookGoogleCalendarSync.csproj @@ -327,14 +327,20 @@ - + + + + - - - + + + + + + @@ -353,7 +359,6 @@ - @@ -376,11 +381,6 @@ MainForm.cs - - - - - diff --git a/src/OutlookGoogleCalendarSync/Program.cs b/src/OutlookGoogleCalendarSync/Program.cs index fc385491..a6239e3c 100644 --- a/src/OutlookGoogleCalendarSync/Program.cs +++ b/src/OutlookGoogleCalendarSync/Program.cs @@ -117,7 +117,7 @@ private static void Main(string[] args) { } finally { log.Debug("Shutting down application."); - OutlookOgcs.Calendar.Disconnect(); + Outlook.Calendar.Disconnect(); Forms.Splash.CloseMe(); GC.Collect(); GC.WaitForPendingFinalizers(); diff --git a/src/OutlookGoogleCalendarSync/Recurrence.cs b/src/OutlookGoogleCalendarSync/Recurrence.cs index 78a76ae2..140aa3f3 100644 --- a/src/OutlookGoogleCalendarSync/Recurrence.cs +++ b/src/OutlookGoogleCalendarSync/Recurrence.cs @@ -37,12 +37,12 @@ public List BuildGooglePattern(AppointmentItem ai, Event ev) { if (ai.AllDayEvent) utcEnd = rp.PatternEndDate; else { - DateTime localEnd = rp.PatternEndDate + OutlookOgcs.Calendar.Instance.IOutlook.GetEndInEndTimeZone(ai).TimeOfDay; - utcEnd = TimeZoneInfo.ConvertTimeToUtc(localEnd, TimeZoneInfo.FindSystemTimeZoneById(OutlookOgcs.Calendar.Instance.IOutlook.GetEndTimeZoneID(ai))); + DateTime localEnd = rp.PatternEndDate + Outlook.Calendar.Instance.IOutlook.GetEndInEndTimeZone(ai).TimeOfDay; + utcEnd = TimeZoneInfo.ConvertTimeToUtc(localEnd, TimeZoneInfo.FindSystemTimeZoneById(Outlook.Calendar.Instance.IOutlook.GetEndTimeZoneID(ai))); } gPattern.Add("RRULE:" + buildRrule(rp, utcEnd)); } finally { - rp = (RecurrencePattern)OutlookOgcs.Calendar.ReleaseObject(rp); + rp = (RecurrencePattern)Outlook.Calendar.ReleaseObject(rp); } log.Debug(string.Join("\r\n", gPattern.ToArray())); return gPattern; @@ -51,7 +51,7 @@ public List BuildGooglePattern(AppointmentItem ai, Event ev) { public void BuildOutlookPattern(Event ev, AppointmentItem ai) { RecurrencePattern ignore; buildOutlookPattern(ev, ai, out ignore); - ignore = (RecurrencePattern)OutlookOgcs.Calendar.ReleaseObject(ignore); + ignore = (RecurrencePattern)Outlook.Calendar.ReleaseObject(ignore); } private void buildOutlookPattern(Event ev, AppointmentItem ai, out RecurrencePattern oPattern) { @@ -130,7 +130,7 @@ private void buildOutlookPattern(Event ev, AppointmentItem ai, out RecurrencePat #endregion #region RANGE - ai = OutlookOgcs.Calendar.Instance.IOutlook.WindowsTimeZone_set(ai, ev); + ai = Outlook.Calendar.Instance.IOutlook.WindowsTimeZone_set(ai, ev); oPattern.PatternStartDate = ev.Start.SafeDateTime(); if (ruleBook.ContainsKey("INTERVAL") && Convert.ToInt16(ruleBook["INTERVAL"]) > 1 && ruleBook["FREQ"] != "YEARLY") oPattern.Interval = Convert.ToInt16(ruleBook["INTERVAL"]); @@ -169,7 +169,7 @@ public void CompareOutlookPattern(Event ev, ref RecurrencePattern aiOpattern, Sy if (ev.Recurrence == null) return; log.Fine("Building a temporary recurrent Appointment generated from Event"); - AppointmentItem evAI = OutlookOgcs.Calendar.Instance.IOutlook.UseOutlookCalendar().Items.Add() as AppointmentItem; + AppointmentItem evAI = Outlook.Calendar.Instance.IOutlook.UseOutlookCalendar().Items.Add() as AppointmentItem; evAI.Start = ev.Start.SafeDateTime(); RecurrencePattern evOpattern = null; @@ -213,9 +213,9 @@ public void CompareOutlookPattern(Event ev, ref RecurrencePattern aiOpattern, Sy aiOpattern.Occurrences = evOpattern.Occurrences; } } finally { - evOpattern = (RecurrencePattern)OutlookOgcs.Calendar.ReleaseObject(evOpattern); + evOpattern = (RecurrencePattern)Outlook.Calendar.ReleaseObject(evOpattern); evAI.Delete(); - evAI = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(evAI); + evAI = (AppointmentItem)Outlook.Calendar.ReleaseObject(evAI); } } @@ -456,7 +456,7 @@ private Event getGoogleInstance(Microsoft.Office.Interop.Outlook.Exception oExcp ai = oExcp.AppointmentItem; log.Debug(" Current date: " + ai.Start.ToString("dd/MM/yyyy")); } finally { - ai = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(ai); + ai = (AppointmentItem)Outlook.Calendar.ReleaseObject(ai); } } if (dirtyCache) { @@ -499,12 +499,12 @@ private Event getGoogleInstance(Microsoft.Office.Interop.Outlook.Exception oExcp } public Event GetGoogleMasterEvent(AppointmentItem ai) { - log.Fine("Found a master Outlook recurring item outside sync date range: " + OutlookOgcs.Calendar.GetEventSummary(ai)); + log.Fine("Found a master Outlook recurring item outside sync date range: " + Outlook.Calendar.GetEventSummary(ai)); List events = new List(); Boolean haveMatchingEv = false; - if (OutlookOgcs.CustomProperty.Exists(ai, OutlookOgcs.CustomProperty.MetadataId.gEventID)) { - String googleIdValue = OutlookOgcs.CustomProperty.Get(ai, OutlookOgcs.CustomProperty.MetadataId.gEventID); - String googleCalValue = OutlookOgcs.CustomProperty.Get(ai, OutlookOgcs.CustomProperty.MetadataId.gCalendarId); + if (Outlook.CustomProperty.Exists(ai, Outlook.CustomProperty.MetadataId.gEventID)) { + String googleIdValue = Outlook.CustomProperty.Get(ai, Outlook.CustomProperty.MetadataId.gEventID); + String googleCalValue = Outlook.CustomProperty.Get(ai, Outlook.CustomProperty.MetadataId.gCalendarId); if (googleCalValue == null || googleCalValue == Sync.Engine.Calendar.Instance.Profile.UseGoogleCalendar.Id) { Event ev = GoogleOgcs.Calendar.Instance.GetCalendarEntry(googleIdValue); if (ev != null) { @@ -531,8 +531,8 @@ public Event GetGoogleMasterEvent(AppointmentItem ai) { } if (GoogleOgcs.CustomProperty.OutlookIdMissing(ev)) { String compare_oID; - if (!string.IsNullOrEmpty(gEntryID) && gEntryID.StartsWith(OutlookOgcs.Calendar.GlobalIdPattern)) { //We got a Global ID, not Entry ID - compare_oID = OutlookOgcs.Calendar.Instance.IOutlook.GetGlobalApptID(ai); + if (!string.IsNullOrEmpty(gEntryID) && gEntryID.StartsWith(Outlook.Calendar.GlobalIdPattern)) { //We got a Global ID, not Entry ID + compare_oID = Outlook.Calendar.Instance.IOutlook.GetGlobalApptID(ai); } else { compare_oID = ai.EntryID; } @@ -552,13 +552,13 @@ public Event GetGoogleMasterEvent(AppointmentItem ai) { } } else { log.Debug("Event \"" + ev.Summary + "\" does not have Outlook EntryID stored."); - if (GoogleOgcs.Calendar.SignaturesMatch(GoogleOgcs.Calendar.signature(ev), OutlookOgcs.Calendar.signature(ai))) { + if (GoogleOgcs.Calendar.SignaturesMatch(GoogleOgcs.Calendar.signature(ev), Outlook.Calendar.signature(ai))) { log.Debug("Master event matched on simple signatures."); return ev; } } } - log.Warn("Failed to find master Google event for: " + OutlookOgcs.Calendar.GetEventSummary(ai)); + log.Warn("Failed to find master Google event for: " + Outlook.Calendar.GetEventSummary(ai)); return null; } @@ -618,7 +618,7 @@ public static void CreateGoogleExceptions(AppointmentItem ai, String recurringEv } catch (System.Exception ex) { OGCSexception.Analyse(ex); } finally { - ai2 = (Microsoft.Office.Interop.Outlook.AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(ai2); + ai2 = (Microsoft.Office.Interop.Outlook.AppointmentItem)Outlook.Calendar.ReleaseObject(ai2); } } } catch (System.Exception ex) { @@ -651,15 +651,15 @@ public static void CreateGoogleExceptions(AppointmentItem ai, String recurringEv } } } finally { - oExcp = (Microsoft.Office.Interop.Outlook.Exception)OutlookOgcs.Calendar.ReleaseObject(oExcp); + oExcp = (Microsoft.Office.Interop.Outlook.Exception)Outlook.Calendar.ReleaseObject(oExcp); } } } finally { for (int e = 1; e <= excps.Count; e++) { - Microsoft.Office.Interop.Outlook.Exception garbage = (Microsoft.Office.Interop.Outlook.Exception)OutlookOgcs.Calendar.ReleaseObject(excps[e]); + Microsoft.Office.Interop.Outlook.Exception garbage = (Microsoft.Office.Interop.Outlook.Exception)Outlook.Calendar.ReleaseObject(excps[e]); } - excps = (Exceptions)OutlookOgcs.Calendar.ReleaseObject(excps); - rp = (RecurrencePattern)OutlookOgcs.Calendar.ReleaseObject(rp); + excps = (Exceptions)Outlook.Calendar.ReleaseObject(excps); + rp = (RecurrencePattern)Outlook.Calendar.ReleaseObject(rp); } } @@ -671,7 +671,7 @@ public static void UpdateGoogleExceptions(AppointmentItem ai, Event ev, Boolean rp = ai.GetRecurrencePattern(); excps = rp.Exceptions; if (excps.Count > 0) { - log.Debug(OutlookOgcs.Calendar.GetEventSummary(ai)); + log.Debug(Outlook.Calendar.GetEventSummary(ai)); log.Debug("This is a recurring appointment with " + excps.Count + " exceptions that will now be iteratively compared."); for (int e = 1; e <= excps.Count; e++) { Microsoft.Office.Interop.Outlook.Exception oExcp = null; @@ -690,7 +690,7 @@ public static void UpdateGoogleExceptions(AppointmentItem ai, Event ev, Boolean } else { aiExcp = oExcp.AppointmentItem; oExcp_currDate = aiExcp.Start; - aiExcp = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(aiExcp); + aiExcp = (AppointmentItem)Outlook.Calendar.ReleaseObject(aiExcp); } if (oExcp_currDate < Sync.Engine.Calendar.Instance.Profile.SyncStart.Date || oExcp_currDate > Sync.Engine.Calendar.Instance.Profile.SyncEnd.Date) { log.Fine("Exception is" + logDeleted + " outside date range being synced: " + oExcp_currDate.Date.ToString("dd/MM/yyyy")); @@ -709,7 +709,7 @@ public static void UpdateGoogleExceptions(AppointmentItem ai, Event ev, Boolean log.Warn("Outlook is NOT deleted though - a mismatch has occurred somehow!"); String syncDirectionTip = (Sync.Engine.Calendar.Instance.Profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id) ? "
Ensure you first set OGCS to one-way sync O->G." : ""; Forms.Main.Instance.Console.Update( - OutlookOgcs.Calendar.GetEventSummary("
" + + Outlook.Calendar.GetEventSummary("
" + "The occurrence on " + oExcp.OriginalDate.ToShortDateString() + " does not exist in Google, but does in Outlook.
" + "This can happen if, for example, you declined the occurrence (which is synced to Google) and proposed a new time that is subsequently accepted by the organiser.
" + "Suggested fix: delete the entire series in Google and let OGCS recreate it." + syncDirectionTip, ai, out String anonSummary) @@ -721,7 +721,7 @@ public static void UpdateGoogleExceptions(AppointmentItem ai, Event ev, Boolean log.Fine("Checking if we have another Google instance that /is/ cancelled on " + movedToStartDate.ToString("dd-MMM-yyyy") + " that this one has been moved to."); Event duplicate = Recurrence.Instance.getGoogleInstance(gExcp.RecurringEventId, movedToStartDate); DialogResult dr = DialogResult.Yes; - String summary = OutlookOgcs.Calendar.GetEventSummary(ai, out String anonSummary); + String summary = Outlook.Calendar.GetEventSummary(ai, out String anonSummary); if (duplicate?.Status == "cancelled") { log.Warn("Another deleted occurrence on the same date " + movedToStartDate.ToString("dd-MMM-yyyy") + " found, so this Google item that has moved to that date cannot be safely deleted automatically."); String msg = summary + "\r\n\r\nAn occurrence on " + movedToStartDate.ToString("dd-MMM-yyyy") + " was previously deleted, before another occurrence on " + oExcp.OriginalDate.ToString("dd-MMM-yyyy") + @@ -776,14 +776,14 @@ public static void UpdateGoogleExceptions(AppointmentItem ai, Event ev, Boolean if (oIsDeleted == DeletionState.Deleted) log.Debug("The Outlook appointment is deleted, so not a problem."); } } finally { - aiExcp = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(aiExcp); - oExcp = (Microsoft.Office.Interop.Outlook.Exception)OutlookOgcs.Calendar.ReleaseObject(oExcp); + aiExcp = (AppointmentItem)Outlook.Calendar.ReleaseObject(aiExcp); + oExcp = (Microsoft.Office.Interop.Outlook.Exception)Outlook.Calendar.ReleaseObject(oExcp); } } } } finally { - excps = (Exceptions)OutlookOgcs.Calendar.ReleaseObject(excps); - rp = (RecurrencePattern)OutlookOgcs.Calendar.ReleaseObject(rp); + excps = (Exceptions)Outlook.Calendar.ReleaseObject(excps); + rp = (RecurrencePattern)Outlook.Calendar.ReleaseObject(rp); } } } @@ -798,8 +798,8 @@ public static Boolean HasExceptions(AppointmentItem ai) { excps = rp.Exceptions; return excps.Count != 0; } finally { - excps = (Exceptions)OutlookOgcs.Calendar.ReleaseObject(excps); - rp = (RecurrencePattern)OutlookOgcs.Calendar.ReleaseObject(rp); + excps = (Exceptions)Outlook.Calendar.ReleaseObject(excps); + rp = (RecurrencePattern)Outlook.Calendar.ReleaseObject(rp); } } @@ -819,7 +819,7 @@ private static DeletionState exceptionIsDeleted(Microsoft.Office.Interop.Outlook } return DeletionState.Inaccessible; } finally { - ai = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(ai); + ai = (AppointmentItem)Outlook.Calendar.ReleaseObject(ai); } } @@ -874,16 +874,16 @@ private void processOutlookExceptions(ref AppointmentItem ai, List evExce } if (gExcp.Status == "cancelled") { - Forms.Main.Instance.Console.Update(OutlookOgcs.Calendar.GetEventSummary("
Occurrence deleted.", newAiExcp, out String anonSummary), anonSummary, Console.Markup.calendar, verbose: true); + Forms.Main.Instance.Console.Update(Outlook.Calendar.GetEventSummary("
Occurrence deleted.", newAiExcp, out String anonSummary), anonSummary, Console.Markup.calendar, verbose: true); newAiExcp.Delete(); } else if (Sync.Engine.Calendar.Instance.Profile.ExcludeDeclinedInvites && gExcp.Attendees != null && gExcp.Attendees.Count(a => a.Self == true && a.ResponseStatus == "declined") == 1) { - Forms.Main.Instance.Console.Update(OutlookOgcs.Calendar.GetEventSummary("
Occurrence declined.", newAiExcp, out String anonSummary), anonSummary, Console.Markup.calendar, verbose: true); + Forms.Main.Instance.Console.Update(Outlook.Calendar.GetEventSummary("
Occurrence declined.", newAiExcp, out String anonSummary), anonSummary, Console.Markup.calendar, verbose: true); newAiExcp.Delete(); } else { int itemModified = 0; - OutlookOgcs.Calendar.Instance.UpdateCalendarEntry(ref newAiExcp, gExcp, ref itemModified, + Outlook.Calendar.Instance.UpdateCalendarEntry(ref newAiExcp, gExcp, ref itemModified, forceCompare || gExcp.Start.SafeDateTime().Date != newAiExcp.Start.Date); if (itemModified > 0) { try { @@ -892,7 +892,7 @@ private void processOutlookExceptions(ref AppointmentItem ai, List evExce OGCSexception.Analyse(ex); if (ex.Message == "Cannot save this item.") { Forms.Main.Instance.Console.Update( - OutlookOgcs.Calendar.GetEventSummary("Uh oh! Outlook wasn't able to save this recurrence exception! " + + Outlook.Calendar.GetEventSummary("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.", newAiExcp, out String anonSummary, true) , anonSummary, Console.Markup.warning); } @@ -900,11 +900,11 @@ private void processOutlookExceptions(ref AppointmentItem ai, List evExce } } } finally { - newAiExcp = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(newAiExcp); + newAiExcp = (AppointmentItem)Outlook.Calendar.ReleaseObject(newAiExcp); } } } finally { - oPattern = (RecurrencePattern)OutlookOgcs.Calendar.ReleaseObject(oPattern); + oPattern = (RecurrencePattern)Outlook.Calendar.ReleaseObject(oPattern); } } @@ -947,11 +947,11 @@ private static void getOutlookInstance(RecurrencePattern oPattern, DateTime inst return; } } finally { - oExcp = (Microsoft.Office.Interop.Outlook.Exception)OutlookOgcs.Calendar.ReleaseObject(oExcp); + oExcp = (Microsoft.Office.Interop.Outlook.Exception)Outlook.Calendar.ReleaseObject(oExcp); } } } finally { - oExcps = (Exceptions)OutlookOgcs.Calendar.ReleaseObject(oExcps); + oExcps = (Exceptions)Outlook.Calendar.ReleaseObject(oExcps); } //Finally check if the occurrence is not an exception, or an exception has moved to the same date as a deleted exception diff --git a/src/OutlookGoogleCalendarSync/SettingsStore/Calendar.cs b/src/OutlookGoogleCalendarSync/SettingsStore/Calendar.cs index 2f269d8b..ac36367f 100644 --- a/src/OutlookGoogleCalendarSync/SettingsStore/Calendar.cs +++ b/src/OutlookGoogleCalendarSync/SettingsStore/Calendar.cs @@ -33,7 +33,7 @@ private void setDefaults() { _ProfileName = "Default"; //Outlook - OutlookService = OutlookOgcs.Calendar.Service.DefaultMailbox; + OutlookService = Outlook.Calendar.Service.DefaultMailbox; MailboxName = ""; SharedCalendar = ""; UseOutlookCalendar = new OutlookCalendarListEntry(); @@ -110,7 +110,7 @@ private void setDefaults() { public enum RestrictBy { Include, Exclude } - [DataMember] public OutlookOgcs.Calendar.Service OutlookService { get; set; } + [DataMember] public Outlook.Calendar.Service OutlookService { get; set; } [DataMember] public string MailboxName { get; set; } [DataMember] public string SharedCalendar { get; set; } [DataMember] public OutlookCalendarListEntry UseOutlookCalendar { get; set; } @@ -270,7 +270,7 @@ public void LogSettings() { log.Info("OUTLOOK SETTINGS:-"); log.Info(" Service: " + OutlookService.ToString()); - if (OutlookService == OutlookOgcs.Calendar.Service.SharedCalendar) { + if (OutlookService == Outlook.Calendar.Service.SharedCalendar) { log.Info(" Shared Calendar: " + SharedCalendar); } else { log.Info(" Mailbox/FolderStore Name: " + MailboxName); @@ -309,10 +309,10 @@ public void LogSettings() { } if (ColourMaps.Count > 0) { log.Info(" Custom Colour/Category Mapping:-"); - if (OutlookOgcs.Factory.OutlookVersionName == OutlookOgcs.Factory.OutlookVersionNames.Outlook2003) + if (Outlook.Factory.OutlookVersionName == Outlook.Factory.OutlookVersionNames.Outlook2003) log.Fail(" Using Outlook2003 - categories not supported, although mapping exists"); else - ColourMaps.ToList().ForEach(c => log.Info(" " + OutlookOgcs.Calendar.Categories.OutlookColour(c.Key) + ":" + c.Key + " <=> " + + ColourMaps.ToList().ForEach(c => log.Info(" " + Outlook.Calendar.Categories.OutlookColour(c.Key) + ":" + c.Key + " <=> " + c.Value + ":" + GoogleOgcs.EventColour.Palette.GetColourName(c.Value))); } log.Info(" SingleCategoryOnly: " + SingleCategoryOnly); diff --git a/src/OutlookGoogleCalendarSync/Sync/Calendar.cs b/src/OutlookGoogleCalendarSync/Sync/Calendar.cs index 6105db10..9a5fc14b 100644 --- a/src/OutlookGoogleCalendarSync/Sync/Calendar.cs +++ b/src/OutlookGoogleCalendarSync/Sync/Calendar.cs @@ -68,7 +68,7 @@ public void StartSync(Boolean manualIgnition, Boolean updateSyncSchedule = true) } //Check if Outlook is Online try { - if (OutlookOgcs.Calendar.Instance.IOutlook.Offline() && this.Profile.AddAttendees) { + if (Outlook.Calendar.Instance.IOutlook.Offline() && this.Profile.AddAttendees) { mainFrm.Console.Update("

You have selected to sync attendees but Outlook is currently offline.

" + "

Either put Outlook online or do not sync attendees.

", Console.Markup.error, notifyBubble: true); this.setNextSync(false, updateSyncSchedule); @@ -141,18 +141,18 @@ public void StartSync(Boolean manualIgnition, Boolean updateSyncSchedule = true) } } - Ogcs.Outlook.Errors.ErrorType error = Ogcs.Outlook.Errors.HandleComError(ex); - if (error == Ogcs.Outlook.Errors.ErrorType.RpcServerUnavailable || - error == Ogcs.Outlook.Errors.ErrorType.RpcFailed || - error == Ogcs.Outlook.Errors.ErrorType.InvokedObjectDisconnectedFromClients) // + Outlook.Errors.ErrorType error = Outlook.Errors.HandleComError(ex); + if (error == Outlook.Errors.ErrorType.RpcServerUnavailable || + error == Outlook.Errors.ErrorType.RpcFailed || + error == Outlook.Errors.ErrorType.InvokedObjectDisconnectedFromClients) // { OGCSexception.Analyse(OGCSexception.LogAsFail(ex)); String message = "It looks like Outlook was closed during the sync."; - if (error == Ogcs.Outlook.Errors.ErrorType.RpcFailed) message = "It looks like Outlook has been restarted and is not yet responsive."; + if (error == Outlook.Errors.ErrorType.RpcFailed) message = "It looks like Outlook has been restarted and is not yet responsive."; mainFrm.Console.Update(message + "
Will retry syncing in a few seconds...", Console.Markup.fail, newLine: false); syncResult = SyncResult.ReconnectThenRetry; - } else if (error == Ogcs.Outlook.Errors.ErrorType.OperationFailed) { + } else if (error == Outlook.Errors.ErrorType.OperationFailed) { mainFrm.Console.Update(ex.Message, Console.Markup.fail, newLine: false); syncResult = SyncResult.ReconnectThenRetry; @@ -180,7 +180,7 @@ public void StartSync(Boolean manualIgnition, Boolean updateSyncSchedule = true) } mainFrm.Console.Update("Attempting to reconnect to Outlook..."); try { - OutlookOgcs.Calendar.Instance.Reset(); + Outlook.Calendar.Instance.Reset(); } catch (System.Exception ex) { mainFrm.Console.UpdateWithError("A problem was encountered reconnecting to Outlook.
Further syncs aborted.", ex, notifyBubble: true); syncResult = SyncResult.Abandon; @@ -226,7 +226,7 @@ public void StartSync(Boolean manualIgnition, Boolean updateSyncSchedule = true) //Release Outlook reference if GUI not available. //Otherwise, tasktray shows "another program is using outlook" and it doesn't send and receive emails - OutlookOgcs.Calendar.Disconnect(onlyWhenNoGUI: true); + Outlook.Calendar.Disconnect(onlyWhenNoGUI: true); } } @@ -262,7 +262,7 @@ private void setNextSync(Boolean syncedOk, Boolean updateSyncSchedule) { private void skipCorruptedItem(ref List outlookEntries, AppointmentItem cai, String errMsg) { try { - String itemSummary = OutlookOgcs.Calendar.GetEventSummary(cai, out String anonSummary); + String itemSummary = Outlook.Calendar.GetEventSummary(cai, out String anonSummary); if (string.IsNullOrEmpty(itemSummary)) { try { itemSummary = cai.Start.Date.ToShortDateString() + " => " + cai.Subject; @@ -294,13 +294,13 @@ private SyncResult synchronize() { List googleEntries = null; if (!GoogleOgcs.Calendar.IsInstanceNull) GoogleOgcs.Calendar.Instance.EphemeralProperties.Clear(); - OutlookOgcs.Calendar.Instance.EphemeralProperties.Clear(); + Outlook.Calendar.Instance.EphemeralProperties.Clear(); try { #region Read Outlook items console.Update("Scanning Outlook calendar..."); - OutlookOgcs.Calendar.Instance.IOutlook.UseOutlookCalendar(OutlookOgcs.Calendar.Instance.IOutlook.GetFolderByID(Sync.Engine.Calendar.Instance.Profile.UseOutlookCalendar.Id)); - outlookEntries = OutlookOgcs.Calendar.Instance.GetCalendarEntriesInRange(Sync.Engine.Calendar.Instance.Profile, false); + Outlook.Calendar.Instance.IOutlook.UseOutlookCalendar(Outlook.Calendar.Instance.IOutlook.GetFolderByID(Sync.Engine.Calendar.Instance.Profile.UseOutlookCalendar.Id)); + outlookEntries = Outlook.Calendar.Instance.GetCalendarEntriesInRange(Sync.Engine.Calendar.Instance.Profile, false); console.Update(outlookEntries.Count + " Outlook calendar entries found.", Console.Markup.sectionEnd, newLine: false); if (Sync.Engine.Instance.CancellationPending) return SyncResult.UserCancelled; @@ -381,9 +381,9 @@ private SyncResult synchronize() { } } catch (System.Exception ex) { OGCSexception.Analyse("Encountered error casting calendar object to AppointmentItem - cannot sync it. ExchangeMode=" + - OutlookOgcs.Calendar.Instance.IOutlook.ExchangeConnectionMode().ToString(), ex); + Outlook.Calendar.Instance.IOutlook.ExchangeConnectionMode().ToString(), ex); skipCorruptedItem(ref outlookEntries, outlookEntries[o], ex.Message); - ai = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(ai); + ai = (AppointmentItem)Outlook.Calendar.ReleaseObject(ai); continue; } @@ -406,21 +406,21 @@ private SyncResult synchronize() { } else { log.Debug($"EntryID: {entryID}; Start: {checkStartDate}; End: {checkEndDate}"); OGCSexception.Analyse("Calendar item does not have a proper date range - cannot sync it. ExchangeMode=" + - OutlookOgcs.Calendar.Instance.IOutlook.ExchangeConnectionMode().ToString(), ex); + Outlook.Calendar.Instance.IOutlook.ExchangeConnectionMode().ToString(), ex); skipCorruptedItem(ref outlookEntries, outlookEntries[o], ex.Message); } - ai = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(ai); + ai = (AppointmentItem)Outlook.Calendar.ReleaseObject(ai); continue; } if (ai.IsRecurring && ai.Start.Date < this.Profile.SyncStart && ai.End.Date < this.Profile.SyncStart) { if (!Sync.Engine.Instance.ManualForceCompare && Profile.SyncDirection.Id == Sync.Direction.GoogleToOutlook.Id && Profile.MergeItems && - OutlookOgcs.CustomProperty.AnyStartsWith(ai, OutlookOgcs.CustomProperty.MetadataId.gCalendarId) && - OutlookOgcs.CustomProperty.Get(ai, OutlookOgcs.CustomProperty.MetadataId.gCalendarId) != this.Profile.UseGoogleCalendar.Id) + Outlook.CustomProperty.AnyStartsWith(ai, Outlook.CustomProperty.MetadataId.gCalendarId) && + Outlook.CustomProperty.Get(ai, Outlook.CustomProperty.MetadataId.gCalendarId) != this.Profile.UseGoogleCalendar.Id) { log.Fine("Outlook recurring master, outside sync window, originates from a different Google calendar than that being synced. Will not attempt to find matching Google master event."); outlookEntries.Remove(ai); - ai = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(ai); + ai = (AppointmentItem)Outlook.Calendar.ReleaseObject(ai); continue; } //We won't bother getting Google master event if appointment is yearly reoccurring in a month outside of sync range @@ -458,18 +458,18 @@ private SyncResult synchronize() { console.Update("Failed to retrieve master for Google recurring event outside of sync range.", OGCSexception.LoggingAsFail(ex) ? Console.Markup.fail : Console.Markup.error); throw; } finally { - oPattern = (RecurrencePattern)OutlookOgcs.Calendar.ReleaseObject(oPattern); + oPattern = (RecurrencePattern)Outlook.Calendar.ReleaseObject(oPattern); } } //Completely dereference object and retrieve afresh (due to GetRecurrencePattern earlier) - ai = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(ai); - OutlookOgcs.Calendar.Instance.IOutlook.GetAppointmentByID(entryID, out ai); + ai = (AppointmentItem)Outlook.Calendar.ReleaseObject(ai); + Outlook.Calendar.Instance.IOutlook.GetAppointmentByID(entryID, out ai); outlookEntries[o] = ai; } console.Update("Outlook " + outlookEntries.Count + ", Google " + googleEntries.Count); GoogleOgcs.Calendar.ExportToCSV("Outputting all Events.", "google_events.csv", googleEntries); - OutlookOgcs.Calendar.ExportToCSV("Outputting all Appointments.", "outlook_appointments.csv", outlookEntries); + Outlook.Calendar.ExportToCSV("Outputting all Appointments.", "outlook_appointments.csv", outlookEntries); if (Sync.Engine.Instance.CancellationPending) return SyncResult.UserCancelled; #endregion @@ -483,15 +483,15 @@ private SyncResult synchronize() { GoogleOgcs.Calendar.Instance.ReclaimOrphanCalendarEntries(ref googleEntries, ref outlookEntries); if (Sync.Engine.Instance.CancellationPending) return SyncResult.UserCancelled; - OutlookOgcs.Calendar.Instance.ReclaimOrphanCalendarEntries(ref outlookEntries, ref googleEntries); + Outlook.Calendar.Instance.ReclaimOrphanCalendarEntries(ref outlookEntries, ref googleEntries); if (Sync.Engine.Instance.CancellationPending) return SyncResult.UserCancelled; if (this.Profile.AddColours || this.Profile.SetEntriesColour) { - OutlookOgcs.Calendar.Categories.ValidateCategories(); + Outlook.Calendar.Categories.ValidateCategories(); if (this.Profile.ColourMaps.Count > 0) { this.Profile.ColourMaps.ToList().ForEach(c => { - if (OutlookOgcs.Calendar.Categories.OutlookColour(c.Key) == null) { + if (Outlook.Calendar.Categories.OutlookColour(c.Key) == null) { if (OgcsMessageBox.Show("There is a problem with your colour mapping configuration.\r\nColours may not get synced as intended.\r\nReview maps now for missing Outlook colours?", "Invalid colour map", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Error) == DialogResult.Yes) new Forms.ColourMap().ShowDialog(); @@ -523,7 +523,7 @@ private SyncResult synchronize() { } finally { if (outlookEntries != null) { for (int o = outlookEntries.Count() - 1; o >= 0; o--) { - outlookEntries[o] = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(outlookEntries[o]); + outlookEntries[o] = (AppointmentItem)Outlook.Calendar.ReleaseObject(outlookEntries[o]); outlookEntries.RemoveAt(o); } } @@ -645,7 +645,7 @@ private Boolean outlookToGoogle(List outlookEntries, List 0) { - OutlookOgcs.Calendar.ReleaseObject(entriesToBeCompared.Keys.Last()); + Outlook.Calendar.ReleaseObject(entriesToBeCompared.Keys.Last()); entriesToBeCompared.Remove(entriesToBeCompared.Keys.Last()); } } @@ -665,7 +665,7 @@ private Boolean googleToOutlook(List googleEntries, List Console console = Forms.Main.Instance.Console; try { - OutlookOgcs.Calendar.IdentifyEventDifferences(ref outlookEntriesToBeCreated, ref outlookEntriesToBeDeleted, ref entriesToBeCompared); + Outlook.Calendar.IdentifyEventDifferences(ref outlookEntriesToBeCreated, ref outlookEntriesToBeDeleted, ref entriesToBeCompared); if (Sync.Engine.Instance.CancellationPending) return false; } catch (System.Exception) { console.Update("Unable to identify differences in Outlook calendar.", Console.Markup.error); @@ -686,7 +686,7 @@ private Boolean googleToOutlook(List googleEntries, List MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No) { while (outlookEntriesToBeDeleted.Count() > 0) { - OutlookOgcs.Calendar.ReleaseObject(outlookEntriesToBeDeleted.Last()); + Outlook.Calendar.ReleaseObject(outlookEntriesToBeDeleted.Last()); outlookEntriesToBeDeleted.Remove(outlookEntriesToBeDeleted.Last()); } } @@ -698,7 +698,7 @@ private Boolean googleToOutlook(List googleEntries, List if (outlookEntriesToBeDeleted.Count > 0) { console.Update("Deleting " + outlookEntriesToBeDeleted.Count + " Outlook calendar entries", Console.Markup.h2, newLine: false); try { - OutlookOgcs.Calendar.Instance.DeleteCalendarEntries(outlookEntriesToBeDeleted); + Outlook.Calendar.Instance.DeleteCalendarEntries(outlookEntriesToBeDeleted); } catch (UserCancelledSyncException ex) { log.Info(ex.Message); return false; @@ -716,7 +716,7 @@ private Boolean googleToOutlook(List googleEntries, List if (outlookEntriesToBeCreated.Count > 0) { console.Update("Creating " + outlookEntriesToBeCreated.Count + " Outlook calendar entries", Console.Markup.h2, newLine: false); try { - OutlookOgcs.Calendar.Instance.CreateCalendarEntries(outlookEntriesToBeCreated); + Outlook.Calendar.Instance.CreateCalendarEntries(outlookEntriesToBeCreated); } catch (UserCancelledSyncException ex) { log.Info(ex.Message); return false; @@ -734,7 +734,7 @@ private Boolean googleToOutlook(List googleEntries, List if (entriesToBeCompared.Count > 0) { console.Update("Comparing " + entriesToBeCompared.Count + " existing Outlook calendar entries", Console.Markup.h2, newLine: false); try { - OutlookOgcs.Calendar.Instance.UpdateCalendarEntries(entriesToBeCompared, ref entriesUpdated); + Outlook.Calendar.Instance.UpdateCalendarEntries(entriesToBeCompared, ref entriesUpdated); } catch (UserCancelledSyncException ex) { log.Info(ex.Message); return false; @@ -753,15 +753,15 @@ private Boolean googleToOutlook(List googleEntries, List outlookEntriesToBeDeleted.Count + " deleted; " + entriesUpdated + " updated"; while (outlookEntriesToBeCreated.Count() > 0) { - OutlookOgcs.Calendar.ReleaseObject(outlookEntriesToBeCreated.Last()); + Outlook.Calendar.ReleaseObject(outlookEntriesToBeCreated.Last()); outlookEntriesToBeCreated.Remove(outlookEntriesToBeCreated.Last()); } while (outlookEntriesToBeDeleted.Count() > 0) { - OutlookOgcs.Calendar.ReleaseObject(outlookEntriesToBeDeleted.Last()); + Outlook.Calendar.ReleaseObject(outlookEntriesToBeDeleted.Last()); outlookEntriesToBeDeleted.Remove(outlookEntriesToBeDeleted.Last()); } while (entriesToBeCompared.Count() > 0) { - OutlookOgcs.Calendar.ReleaseObject(entriesToBeCompared.Keys.Last()); + Outlook.Calendar.ReleaseObject(entriesToBeCompared.Keys.Last()); entriesToBeCompared.Remove(entriesToBeCompared.Keys.Last()); } } @@ -777,13 +777,13 @@ private SyncResult extirpateCustomProperties(List outlookEntrie AppointmentItem ai = null; try { ai = outlookEntries[o]; - OutlookOgcs.CustomProperty.LogProperties(ai, log4net.Core.Level.Debug); - if (OutlookOgcs.CustomProperty.Extirpate(ref ai)) { - console.Update(OutlookOgcs.Calendar.GetEventSummary(ai, out String anonSummary), anonSummary, Console.Markup.calendar); + Outlook.CustomProperty.LogProperties(ai, log4net.Core.Level.Debug); + if (Outlook.CustomProperty.Extirpate(ref ai)) { + console.Update(Outlook.Calendar.GetEventSummary(ai, out String anonSummary), anonSummary, Console.Markup.calendar); ai.Save(); } } finally { - ai = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(ai); + ai = (AppointmentItem)Outlook.Calendar.ReleaseObject(ai); } if (Sync.Engine.Instance.CancellationPending) return SyncResult.UserCancelled; } diff --git a/src/OutlookGoogleCalendarSync/Sync/Timer.cs b/src/OutlookGoogleCalendarSync/Sync/Timer.cs index e20297ab..0a21a1f1 100644 --- a/src/OutlookGoogleCalendarSync/Sync/Timer.cs +++ b/src/OutlookGoogleCalendarSync/Sync/Timer.cs @@ -159,7 +159,7 @@ public void ResetLastRun() { this.lastRunTime = DateTime.Now; try { log.Fine("Updating calendar item count following Push Sync."); - this.lastRunItemCount = OutlookOgcs.Calendar.Instance.GetCalendarEntriesInRange(this.owningProfile as SettingsStore.Calendar, true).Count; + this.lastRunItemCount = Outlook.Calendar.Instance.GetCalendarEntriesInRange(this.owningProfile as SettingsStore.Calendar, true).Count; } catch (System.Exception ex) { OGCSexception.Analyse("Failed to update item count following a Push Sync.", ex); } @@ -177,9 +177,9 @@ private void ogcsPushTimer_Tick(object sender, EventArgs e) { //Force in the push sync profile Sync.Engine.Calendar.Instance.Profile = profile; - if (OutlookOgcs.Calendar.Instance.IOutlook.NoGUIexists()) return; + if (Outlook.Calendar.Instance.IOutlook.NoGUIexists()) return; log.Fine("Push sync triggered for profile: " + Settings.Profile.Name(profile)); - System.Collections.Generic.List items = OutlookOgcs.Calendar.Instance.GetCalendarEntriesInRange(profile, true); + System.Collections.Generic.List items = Outlook.Calendar.Instance.GetCalendarEntriesInRange(profile, true); if (items.Count < this.lastRunItemCount || items.FindAll(x => x.LastModificationTime > this.lastRunTime).Count > 0) { log.Debug("Changes found for Push sync."); @@ -192,13 +192,13 @@ private void ogcsPushTimer_Tick(object sender, EventArgs e) { failures++; log.Warn("Push Sync failed " + failures + " times to check for changed items."); - Ogcs.Outlook.Errors.ErrorType error = Ogcs.Outlook.Errors.HandleComError(ex); - if (error == Ogcs.Outlook.Errors.ErrorType.RpcServerUnavailable || - error == Ogcs.Outlook.Errors.ErrorType.InvokedObjectDisconnectedFromClients || - error == Ogcs.Outlook.Errors.ErrorType.RpcFailed) // + Outlook.Errors.ErrorType error = Outlook.Errors.HandleComError(ex); + if (error == Outlook.Errors.ErrorType.RpcServerUnavailable || + error == Outlook.Errors.ErrorType.InvokedObjectDisconnectedFromClients || + error == Outlook.Errors.ErrorType.RpcFailed) // { try { - OutlookOgcs.Calendar.Instance.Reset(); + Outlook.Calendar.Instance.Reset(); } catch (System.Exception ex2) { OGCSexception.Analyse("Failed resetting Outlook connection.", ex2); } diff --git a/src/OutlookGoogleCalendarSync/Telemetry.cs b/src/OutlookGoogleCalendarSync/Telemetry.cs index f8a932e5..d1cc2c35 100644 --- a/src/OutlookGoogleCalendarSync/Telemetry.cs +++ b/src/OutlookGoogleCalendarSync/Telemetry.cs @@ -114,7 +114,7 @@ public static void TrackVersions() { if (Program.InDeveloperMode) return; //OUTLOOK CLIENT - Send(Analytics.Category.outlook, Analytics.Action.version, OutlookOgcs.Factory.OutlookVersionNameFull.Replace("Outlook", "")); + Send(Analytics.Category.outlook, Analytics.Action.version, Outlook.Factory.OutlookVersionNameFull.Replace("Outlook", "")); //OGCS APPLICATION Send(Analytics.Category.ogcs, Analytics.Action.version, System.Windows.Forms.Application.ProductVersion); From fad048845c035ab6c7ed79edb7ec1c168d0c8db8 Mon Sep 17 00:00:00 2001 From: Paul Woolcock <11843015+phw198@users.noreply.github.com> Date: Sun, 28 Apr 2024 12:00:44 +0100 Subject: [PATCH 2/8] Code refactor under OutlookGoogleCalendarSync.Google namespace Added "Ogcs" alias for application namespace. --- .../Console/Console.cs | 5 +- .../Extensions/ColourPicker.cs | 37 +++--- .../Extensions/Exception.cs | 16 +-- .../Extensions/ILogExtension.cs | 17 +-- .../Forms/ColourMap.cs | 11 +- .../Forms/MainForm.cs | 61 +++++----- src/OutlookGoogleCalendarSync/Forms/Splash.cs | 9 +- .../{GoogleOgcs => Google}/ApiKeyring.cs | 7 +- .../{GoogleOgcs => Google}/Authenticator.cs | 45 +++---- .../{GoogleOgcs => Google}/CustomProperty.cs | 25 ++-- .../{GoogleOgcs => Google}/ErrorReporting.cs | 3 +- .../{GoogleOgcs => Google}/EventAttendee.cs | 8 +- .../{GoogleOgcs => Google}/EventColour.cs | 30 ++--- .../{GoogleOgcs => Google}/GMeet.cs | 2 +- .../{GoogleOgcs => Google}/GoogleCalendar.cs | 111 +++++++++--------- .../Outlook/OutlookCalendar.cs | 77 ++++++------ .../Outlook/OutlookCategories.cs | 5 +- .../OutlookGoogleCalendarSync.csproj | 16 +-- src/OutlookGoogleCalendarSync/Program.cs | 17 +-- src/OutlookGoogleCalendarSync/Recurrence.cs | 57 ++++----- .../SettingsStore/Calendar.cs | 5 +- .../SettingsStore/Settings.cs | 12 +- .../Sync/Calendar.cs | 43 +++---- src/OutlookGoogleCalendarSync/Sync/Engine.cs | 5 +- src/OutlookGoogleCalendarSync/Telemetry.cs | 10 +- 25 files changed, 325 insertions(+), 309 deletions(-) rename src/OutlookGoogleCalendarSync/{GoogleOgcs => Google}/ApiKeyring.cs (98%) rename src/OutlookGoogleCalendarSync/{GoogleOgcs => Google}/Authenticator.cs (92%) rename src/OutlookGoogleCalendarSync/{GoogleOgcs => Google}/CustomProperty.cs (92%) rename src/OutlookGoogleCalendarSync/{GoogleOgcs => Google}/ErrorReporting.cs (98%) rename src/OutlookGoogleCalendarSync/{GoogleOgcs => Google}/EventAttendee.cs (82%) rename src/OutlookGoogleCalendarSync/{GoogleOgcs => Google}/EventColour.cs (91%) rename src/OutlookGoogleCalendarSync/{GoogleOgcs => Google}/GMeet.cs (98%) rename src/OutlookGoogleCalendarSync/{GoogleOgcs => Google}/GoogleCalendar.cs (96%) diff --git a/src/OutlookGoogleCalendarSync/Console/Console.cs b/src/OutlookGoogleCalendarSync/Console/Console.cs index 7b42f96b..cd201abe 100644 --- a/src/OutlookGoogleCalendarSync/Console/Console.cs +++ b/src/OutlookGoogleCalendarSync/Console/Console.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using Microsoft.Win32; using System; using System.Linq; @@ -412,7 +413,7 @@ public void FormatEventChanges(StringBuilder sb, String anonymised) { if (Settings.Instance.AnonymiseLogs) { MatchCollection matches = Regex.Matches(anonymised, @"^Subject:\s(.*?)\s=>\s(.*?)$", RegexOptions.Multiline); if (matches.Count > 0) { - anonymised = anonymised.Replace(matches[0].Value, "Subject: " + GoogleOgcs.Authenticator.GetMd5(matches[0].Groups[1].Value) + " => " + GoogleOgcs.Authenticator.GetMd5(matches[0].Groups[2].Value.TrimEnd("\r".ToCharArray()))); + anonymised = anonymised.Replace(matches[0].Value, "Subject: " + Ogcs.Google.Authenticator.GetMd5(matches[0].Groups[1].Value) + " => " + Ogcs.Google.Authenticator.GetMd5(matches[0].Groups[2].Value.TrimEnd("\r".ToCharArray()))); } } Update(lines[0] + "
" + table.ToString(), anonymised, verbose: true, newLine: false); diff --git a/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs b/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs index c780c8c1..cabe2f3e 100644 --- a/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs +++ b/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs @@ -1,4 +1,5 @@ -using Microsoft.Office.Interop.Outlook; +using Ogcs = OutlookGoogleCalendarSync; +using Microsoft.Office.Interop.Outlook; using System; using System.Collections.Generic; using System.Drawing; @@ -66,9 +67,9 @@ public GoogleColourPicker() { /// Add all the available Google colours /// public void AddPaletteColours(Boolean connectToGoogle = false) { - if (GoogleOgcs.Calendar.IsInstanceNull && !connectToGoogle) return; + if (Ogcs.Google.Calendar.IsInstanceNull && !connectToGoogle) return; - foreach (GoogleOgcs.EventColour.Palette palette in GoogleOgcs.Calendar.Instance.ColourPalette.ActivePalette) { + foreach (Ogcs.Google.EventColour.Palette palette in Ogcs.Google.Calendar.Instance.ColourPalette.ActivePalette) { Items.Add(palette); } } @@ -79,12 +80,12 @@ public void ColourPicker_DrawItem(object sender, System.Windows.Forms.DrawItemEv return; // Get the colour - GoogleOgcs.EventColour.Palette colour = (GoogleOgcs.EventColour.Palette)Items[e.Index]; + Ogcs.Google.EventColour.Palette colour = (Ogcs.Google.EventColour.Palette)Items[e.Index]; ColourCombobox.DrawComboboxItemColour(cbColour, new SolidBrush(colour.RgbValue), colour.Name, e); } - public new GoogleOgcs.EventColour.Palette SelectedItem { - get { return (GoogleOgcs.EventColour.Palette)base.SelectedItem; } + public new Ogcs.Google.EventColour.Palette SelectedItem { + get { return (Ogcs.Google.EventColour.Palette)base.SelectedItem; } set { base.SelectedItem = value; } } @@ -96,26 +97,26 @@ private void ColourPicker_Enter(object sender, EventArgs e) { ToolTip loading = new ToolTip(); try { - GoogleOgcs.EventColour.Palette currentSelection = null; + Ogcs.Google.EventColour.Palette currentSelection = null; - if (GoogleOgcs.Calendar.IsInstanceNull || !GoogleOgcs.Calendar.Instance.ColourPalette.IsCached()) { + if (Ogcs.Google.Calendar.IsInstanceNull || !Ogcs.Google.Calendar.Instance.ColourPalette.IsCached()) { loading.SetToolTip(this, "Retrieving colours from Google..."); loading.ShowAlways = true; loading.InitialDelay = 0; loading.Show("Retrieving colours from Google...", this, this.FindForm().PointToClient(this.Parent.PointToScreen(this.Location))); - GoogleOgcs.Calendar.Instance.ColourPalette.Get(); - currentSelection = (GoogleOgcs.EventColour.Palette)SelectedItem; + Ogcs.Google.Calendar.Instance.ColourPalette.Get(); + currentSelection = (Ogcs.Google.EventColour.Palette)SelectedItem; loading.Hide(this); } - if (Items.Count != GoogleOgcs.Calendar.Instance.ColourPalette.ActivePalette.Count) { + if (Items.Count != Ogcs.Google.Calendar.Instance.ColourPalette.ActivePalette.Count) { while (Items.Count > 0) Items.RemoveAt(0); AddPaletteColours(true); } - foreach (GoogleOgcs.EventColour.Palette pInfo in Items) { + foreach (Ogcs.Google.EventColour.Palette pInfo in Items) { if (pInfo.Id == currentSelection?.Id) { SelectedItem = pInfo; break; @@ -253,7 +254,7 @@ public override void InitializeEditingControl(int rowIndex, object initialFormat ctl.PopulateDropdownItems(); if (!string.IsNullOrEmpty(currentText)) this.Value = currentText; - foreach (GoogleOgcs.EventColour.Palette p in Forms.ColourMap.GoogleComboBox.Items) { + foreach (Ogcs.Google.EventColour.Palette p in Forms.ColourMap.GoogleComboBox.Items) { if (p.Name == (String)this.Value) { ctl.SelectedValue = p; break; @@ -271,7 +272,7 @@ public override Type EditType { public override Type ValueType { get { - return typeof(GoogleOgcs.EventColour.Palette); + return typeof(Ogcs.Google.EventColour.Palette); } } @@ -289,7 +290,7 @@ protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.R if (rowIndex < 0) return; - foreach (GoogleOgcs.EventColour.Palette ci in Forms.ColourMap.GoogleComboBox.Items) { + foreach (Ogcs.Google.EventColour.Palette ci in Forms.ColourMap.GoogleComboBox.Items) { if (ci.Name == this.Value?.ToString()) { Brush boxBrush = new SolidBrush(ci.RgbValue); Brush textBrush = SystemBrushes.WindowText; @@ -502,8 +503,8 @@ public GoogleColourCombobox() { } public void PopulateDropdownItems() { - Dictionary cbItems = new Dictionary(); - foreach (GoogleOgcs.EventColour.Palette ci in Forms.ColourMap.GoogleComboBox.Items) { + Dictionary cbItems = new Dictionary(); + foreach (Ogcs.Google.EventColour.Palette ci in Forms.ColourMap.GoogleComboBox.Items) { cbItems.Add(ci, ci.Name); } this.DataSource = new BindingSource(cbItems, null); @@ -516,7 +517,7 @@ void ComboboxColor_DrawItem(object sender, DrawItemEventArgs e) { if (e.Index < 0 || e.Index >= cbColour.Items.Count) return; - KeyValuePair kvp = (KeyValuePair)cbColour.Items[e.Index]; + KeyValuePair kvp = (KeyValuePair)cbColour.Items[e.Index]; if (kvp.Key != null) { // Get the colour Brush brush = new SolidBrush(kvp.Key.RgbValue); diff --git a/src/OutlookGoogleCalendarSync/Extensions/Exception.cs b/src/OutlookGoogleCalendarSync/Extensions/Exception.cs index f5b26c1f..61ec3bd4 100644 --- a/src/OutlookGoogleCalendarSync/Extensions/Exception.cs +++ b/src/OutlookGoogleCalendarSync/Extensions/Exception.cs @@ -76,14 +76,14 @@ public static void AnalyseAggregate(AggregateException agex, Boolean throwError if (!String.IsNullOrEmpty(ex.Message)) Forms.Main.Instance.Console.UpdateWithError(null, ex); else log.Error(agex.Message); - } else if (ex is Google.Apis.Auth.OAuth2.Responses.TokenResponseException) { - AnalyseTokenResponse(ex as Google.Apis.Auth.OAuth2.Responses.TokenResponseException, throwError); + } else if (ex is global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException) { + AnalyseTokenResponse(ex as global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException, throwError); } else Analyse(ex); } } - public static void AnalyseTokenResponse(Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex, Boolean throwError = true) { + public static void AnalyseTokenResponse(global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex, Boolean throwError = true) { String instructions = "On the Settings > Google tab, please disconnect and re-authenticate your account."; log.Warn("Token response error: " + ex.Message); @@ -107,14 +107,14 @@ public static void AnalyseTokenResponse(Google.Apis.Auth.OAuth2.Responses.TokenR } public static String FriendlyMessage(System.Exception ex) { - if (ex is Google.GoogleApiException) { - Google.GoogleApiException gaex = ex as Google.GoogleApiException; + if (ex is global::Google.GoogleApiException) { + global::Google.GoogleApiException gaex = ex as global::Google.GoogleApiException; if (gaex.Error != null) return gaex.Error.Message + " [" + gaex.Error.Code + "=" + gaex.HttpStatusCode + "]"; else return gaex.Message + " [" + gaex.HttpStatusCode + "]"; } else { - return ex.Message + (ex.InnerException != null && !(ex.InnerException is Google.GoogleApiException) ? "
" + ex.InnerException.Message : ""); + return ex.Message + (ex.InnerException != null && !(ex.InnerException is global::Google.GoogleApiException) ? "
" + ex.InnerException.Message : ""); } } @@ -175,7 +175,7 @@ public static void LogAsFail(ref System.NullReferenceException ex) { } /// Capture this exception as log4net FAIL (not ERROR) when logged - public static void LogAsFail(ref Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { + public static void LogAsFail(ref global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { if (ex.Data.Contains(LogAs)) ex.Data[LogAs] = OGCSexception.LogLevel.FAIL; else @@ -183,7 +183,7 @@ public static void LogAsFail(ref Google.Apis.Auth.OAuth2.Responses.TokenResponse } /// Capture this exception as log4net FAIL (not ERROR) when logged - public static void LogAsFail(ref Google.GoogleApiException ex) { + public static void LogAsFail(ref global::Google.GoogleApiException ex) { if (ex.Data.Contains(LogAs)) ex.Data[LogAs] = OGCSexception.LogLevel.FAIL; else diff --git a/src/OutlookGoogleCalendarSync/Extensions/ILogExtension.cs b/src/OutlookGoogleCalendarSync/Extensions/ILogExtension.cs index 7825b0a8..e084c8ca 100644 --- a/src/OutlookGoogleCalendarSync/Extensions/ILogExtension.cs +++ b/src/OutlookGoogleCalendarSync/Extensions/ILogExtension.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using log4net.Core; using System; using System.Collections.Generic; @@ -72,19 +73,19 @@ public class ErrorFlagAppender : log4net.Appender.AppenderSkeleton { /// When an error is logged, check if user has chosen to upload logs or not /// protected override void Append(LoggingEvent loggingEvent) { - if (!GoogleOgcs.ErrorReporting.Initialised || GoogleOgcs.ErrorReporting.ErrorOccurred) return; - GoogleOgcs.ErrorReporting.ErrorOccurred = true; + if (!Ogcs.Google.ErrorReporting.Initialised || Ogcs.Google.ErrorReporting.ErrorOccurred) return; + Ogcs.Google.ErrorReporting.ErrorOccurred = true; String configSetting = null; if (Settings.AreLoaded) configSetting = Settings.Instance.CloudLogging.ToString(); else configSetting = XMLManager.ImportElement("CloudLogging", Settings.ConfigFile); if (!string.IsNullOrEmpty(configSetting)) { - if (Convert.ToBoolean(configSetting) && GoogleOgcs.ErrorReporting.GetThreshold().ToString().ToUpper() != "ALL") { - GoogleOgcs.ErrorReporting.SetThreshold(true); + if (Convert.ToBoolean(configSetting) && Ogcs.Google.ErrorReporting.GetThreshold().ToString().ToUpper() != "ALL") { + Ogcs.Google.ErrorReporting.SetThreshold(true); replayLogs(); - } else if (!Convert.ToBoolean(configSetting) && GoogleOgcs.ErrorReporting.GetThreshold().ToString().ToUpper() != "OFF") { - GoogleOgcs.ErrorReporting.SetThreshold(false); + } else if (!Convert.ToBoolean(configSetting) && Ogcs.Google.ErrorReporting.GetThreshold().ToString().ToUpper() != "OFF") { + Ogcs.Google.ErrorReporting.SetThreshold(false); } return; } @@ -93,7 +94,7 @@ protected override void Append(LoggingEvent loggingEvent) { Forms.ErrorReporting frm = Forms.ErrorReporting.Instance; DialogResult dr = frm.ShowDialog(); if (dr == DialogResult.Cancel) { - GoogleOgcs.ErrorReporting.ErrorOccurred = false; + Ogcs.Google.ErrorReporting.ErrorOccurred = false; return; } Boolean confirmative = dr == DialogResult.Yes; diff --git a/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs b/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs index 20841140..35537458 100644 --- a/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs +++ b/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using System; using System.Collections.Generic; using System.Linq; @@ -45,7 +46,7 @@ private void loadConfig() { try { if (Forms.Main.Instance.ActiveCalendarProfile.ColourMaps.Count > 0) colourGridView.Rows.Clear(); foreach (KeyValuePair colourMap in Forms.Main.Instance.ActiveCalendarProfile.ColourMaps) { - addRow(colourMap.Key, GoogleOgcs.EventColour.Palette.GetColourName(colourMap.Value)); + addRow(colourMap.Key, Ogcs.Google.EventColour.Palette.GetColourName(colourMap.Value)); } ddOutlookColour.AddCategoryColours(); if (ddOutlookColour.Items.Count > 0) @@ -136,7 +137,7 @@ private void btOK_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in colourGridView.Rows) { if (string.IsNullOrEmpty(row.Cells["OutlookColour"].Value?.ToString()?.Trim()) || string.IsNullOrEmpty(row.Cells["GoogleColour"].Value?.ToString()?.Trim())) continue; try { - profile.ColourMaps.Add(row.Cells["OutlookColour"].Value.ToString(), GoogleOgcs.EventColour.Palette.GetColourId(row.Cells["GoogleColour"].Value.ToString())); + profile.ColourMaps.Add(row.Cells["OutlookColour"].Value.ToString(), Ogcs.Google.EventColour.Palette.GetColourId(row.Cells["GoogleColour"].Value.ToString())); } catch (System.ArgumentException ex) { if (OGCSexception.GetErrorCode(ex) == "0x80070057") { //An item with the same key has already been added @@ -243,13 +244,13 @@ private void ddOutlookColour_SelectedIndexChanged(object sender, EventArgs e) { foreach (DataGridViewRow row in colourGridView.Rows) { if (row.Cells["OutlookColour"].Value.ToString() == ddOutlookColour.SelectedItem.Text && !string.IsNullOrEmpty(row.Cells["GoogleColour"].Value?.ToString())) { - String colourId = GoogleOgcs.EventColour.Palette.GetColourId(row.Cells["GoogleColour"].Value.ToString()); + String colourId = Ogcs.Google.EventColour.Palette.GetColourId(row.Cells["GoogleColour"].Value.ToString()); ddGoogleColour.SelectedIndex = Convert.ToInt16(colourId); return; } } - ddGoogleColour.SelectedIndex = Convert.ToInt16(GoogleOgcs.Calendar.Instance.GetColour(ddOutlookColour.SelectedItem.OutlookCategory).Id); + ddGoogleColour.SelectedIndex = Convert.ToInt16(Ogcs.Google.Calendar.Instance.GetColour(ddOutlookColour.SelectedItem.OutlookCategory).Id); } catch (System.Exception ex) { OGCSexception.Analyse("ddOutlookColour_SelectedIndexChanged(): Could not update ddGoogleColour.", ex); diff --git a/src/OutlookGoogleCalendarSync/Forms/MainForm.cs b/src/OutlookGoogleCalendarSync/Forms/MainForm.cs index d5712c67..63edb3d4 100644 --- a/src/OutlookGoogleCalendarSync/Forms/MainForm.cs +++ b/src/OutlookGoogleCalendarSync/Forms/MainForm.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using Microsoft.Office.Interop.Outlook; using System; using System.Collections.Generic; @@ -125,7 +126,7 @@ private void updateGUIsettings() { "Only sync attendees if total fewer than this number. Google allows up to 200 attendees."); ToolTips.SetToolTip(cbCloakEmail, "Google has been known to send meeting updates to attendees without your consent.\n" + - "This option safeguards against that by appending '" + GoogleOgcs.EventAttendee.EmailCloak + "' to their email address."); + "This option safeguards against that by appending '" + Ogcs.Google.EventAttendee.EmailCloak + "' to their email address."); ToolTips.SetToolTip(cbSingleCategoryOnly, "Only allow a single Outlook category - ie 1:1 sync with Google.\n" + "Otherwise, for multiple categories and only one synced with OGCS, manually prefix the category name(s) with \"OGCS \"."); @@ -221,7 +222,7 @@ private void updateGUIsettings() { dgAbout.Rows[r].Cells[1].Value = Settings.ConfigFile; dgAbout.Rows.Add(); r++; dgAbout.Rows[r].Cells[0].Value = "Subscription"; - dgAbout.Rows[r].Cells[1].Value = (Settings.Instance.Subscribed <= GoogleOgcs.Authenticator.SubscribedBefore) ? "N/A" : Settings.Instance.Subscribed.ToShortDateString(); + dgAbout.Rows[r].Cells[1].Value = (Settings.Instance.Subscribed <= Ogcs.Google.Authenticator.SubscribedBefore) ? "N/A" : Settings.Instance.Subscribed.ToShortDateString(); dgAbout.Rows.Add(); r++; dgAbout.Rows[r].Cells[0].Value = "Timezone DB"; dgAbout.Rows[r].Cells[1].Value = TimezoneDB.Instance.Version; @@ -445,11 +446,11 @@ public void UpdateGUIsettings_Profile() { } cbColourFilter.SelectedItem = profile.ColoursRestrictBy == SettingsStore.Calendar.RestrictBy.Include ? "Include" : "Exclude"; - GoogleOgcs.Calendar.BuildOfflineColourPicker(clbColours); + Ogcs.Google.Calendar.BuildOfflineColourPicker(clbColours); cbDeleteWhenColourExcl.Checked = profile.DeleteWhenColourExcluded; cbExcludeDeclinedInvites.Checked = profile.ExcludeDeclinedInvites; cbExcludeGoals.Checked = profile.ExcludeGoals; - cbExcludeGoals.Enabled = GoogleOgcs.Calendar.IsDefaultCalendar() ?? true; + cbExcludeGoals.Enabled = Ogcs.Google.Calendar.IsDefaultCalendar() ?? true; cbAddGMeet.Checked = profile.AddGMeet; if (Settings.Instance.UsingPersonalAPIkeys()) { @@ -1082,8 +1083,8 @@ private void tbSyncNote_Click(object sender, EventArgs e) { "Would you like to do that now?", "Proceed with authorisation?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (authorise == DialogResult.Yes) { log.Debug("Resetting Google account access."); - GoogleOgcs.Calendar.Instance.Authenticator.Reset(); - GoogleOgcs.Calendar.Instance.Authenticator.UserSubscriptionCheck(); + Ogcs.Google.Calendar.Instance.Authenticator.Reset(); + Ogcs.Google.Calendar.Instance.Authenticator.UserSubscriptionCheck(); } } else { if (tbSyncNote.Tag.ToString().Contains("OGCS Premium renewal")) { @@ -1531,17 +1532,17 @@ private void llMultipleOGCS_LinkClicked(object sender, LinkLabelLinkClickedEvent private void GetMyGoogleCalendars_Click(object sender, EventArgs e) { if (bGetGoogleCalendars.Text == "Cancel retrieval") { log.Warn("User cancelled retrieval of Google calendars."); - GoogleOgcs.Calendar.Instance.Authenticator.CancelTokenSource.Cancel(); + Ogcs.Google.Calendar.Instance.Authenticator.CancelTokenSource.Cancel(); return; } log.Debug("Retrieving Google calendar list."); this.bGetGoogleCalendars.Text = "Cancel retrieval"; try { - GoogleOgcs.Calendar.Instance.GetCalendars(); + Ogcs.Google.Calendar.Instance.GetCalendars(); } catch (AggregateException agex) { OGCSexception.AnalyseAggregate(agex, false); - } catch (Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { + } catch (global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { OGCSexception.AnalyseTokenResponse(ex, false); } catch (OperationCanceledException) { } catch (System.Exception ex) { @@ -1551,7 +1552,7 @@ private void GetMyGoogleCalendars_Click(object sender, EventArgs e) { MessageBoxButtons.OK, MessageBoxIcon.Error); StringBuilder sb = new StringBuilder(); console.BuildOutput("Unable to get the list of Google calendars. The following error occurred:", ref sb, false); - if (ex is ApplicationException && ex.InnerException != null && ex.InnerException is Google.GoogleApiException) { + if (ex is ApplicationException && ex.InnerException != null && ex.InnerException is global::Google.GoogleApiException) { console.BuildOutput(ex.Message, ref sb, false); console.Update(sb, Console.Markup.fail, logit: true); } else { @@ -1576,10 +1577,10 @@ private void GetMyGoogleCalendars_Click(object sender, EventArgs e) { } private void cbGoogleCalendars_BuildList() { - if (GoogleOgcs.Calendar.Instance.CalendarList.Count > 0) { + if (Ogcs.Google.Calendar.Instance.CalendarList.Count > 0) { cbGoogleCalendars.Items.Clear(); - GoogleOgcs.Calendar.Instance.CalendarList.Sort((x, y) => (x.Sorted()).CompareTo(y.Sorted())); - foreach (GoogleCalendarListEntry mcle in GoogleOgcs.Calendar.Instance.CalendarList) { + Ogcs.Google.Calendar.Instance.CalendarList.Sort((x, y) => (x.Sorted()).CompareTo(y.Sorted())); + foreach (GoogleCalendarListEntry mcle in Ogcs.Google.Calendar.Instance.CalendarList) { if (!cbListHiddenGcals.Checked && mcle.Hidden) continue; cbGoogleCalendars.Items.Add(mcle); if (cbGoogleCalendars.SelectedIndex == -1 && mcle.Id == ActiveCalendarProfile.UseGoogleCalendar?.Id) @@ -1602,7 +1603,7 @@ private void cbGoogleCalendars_SelectedIndexChanged(object sender, EventArgs e) "Please review your calendar selection.", "Read-only Sync", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); this.tabAppSettings.SelectedTab = this.tabAppSettings.TabPages["tabGoogle"]; } - cbExcludeGoals.Enabled = GoogleOgcs.Calendar.IsDefaultCalendar() ?? true; + cbExcludeGoals.Enabled = Ogcs.Google.Calendar.IsDefaultCalendar() ?? true; if (sender != null) log.Warn("Google calendar selection changed to: " + ActiveCalendarProfile.UseGoogleCalendar.ToString(true)); } @@ -1616,13 +1617,13 @@ private void btResetGCal_Click(object sender, EventArgs e) { this.cbGoogleCalendars.Items.Clear(); this.tbClientID.ReadOnly = false; this.tbClientSecret.ReadOnly = false; - if (!GoogleOgcs.Calendar.IsInstanceNull && GoogleOgcs.Calendar.Instance.Authenticator != null) - GoogleOgcs.Calendar.Instance.Authenticator.Reset(reauthorise: false); + if (!Ogcs.Google.Calendar.IsInstanceNull && Ogcs.Google.Calendar.Instance.Authenticator != null) + Ogcs.Google.Calendar.Instance.Authenticator.Reset(reauthorise: false); else { Settings.Instance.AssignedClientIdentifier = ""; Settings.Instance.GaccountEmail = ""; tbConnectedAcc.Text = "Not connected"; - System.IO.File.Delete(System.IO.Path.Combine(Program.UserFilePath, GoogleOgcs.Authenticator.TokenFile)); + System.IO.File.Delete(System.IO.Path.Combine(Program.UserFilePath, Ogcs.Google.Authenticator.TokenFile)); } } } @@ -1657,8 +1658,8 @@ private void clbColours_SelectedIndexChanged(object sender, EventArgs e) { } private void refreshColours() { - GoogleOgcs.Calendar.Instance.ColourPalette.Get(); - GoogleOgcs.Calendar.Instance.ColourPalette.BuildPicker(clbColours); + Ogcs.Google.Calendar.Instance.ColourPalette.Get(); + Ogcs.Google.Calendar.Instance.ColourPalette.BuildPicker(clbColours); } private void miColourRefresh_Click(object sender, EventArgs e) { refreshColours(); @@ -1666,7 +1667,7 @@ private void miColourRefresh_Click(object sender, EventArgs e) { /// Shim function to work around x-thread call of BuildPicker() public void miColourBuildPicker_Click(object sender, EventArgs e) { CheckedListBox clb = GetControlThreadSafe(clbColours) as CheckedListBox; - GoogleOgcs.Calendar.Instance.ColourPalette.BuildPicker(clb); + Ogcs.Google.Calendar.Instance.ColourPalette.BuildPicker(clb); SetControlPropertyThreadSafe(clbColours, "Items", clb.Items); } private void miColourSelectNone_Click(object sender, EventArgs e) { @@ -1956,13 +1957,13 @@ private void ddOutlookColour_SelectedIndexChanged(object sender, EventArgs e) { try { ddGoogleColour.SelectedIndexChanged -= ddGoogleColour_SelectedIndexChanged; - GoogleOgcs.EventColour.Palette palette = GoogleOgcs.EventColour.Palette.NullPalette; - if (GoogleOgcs.Calendar.IsColourPaletteNull || !GoogleOgcs.Calendar.Instance.ColourPalette.IsCached()) + Ogcs.Google.EventColour.Palette palette = Ogcs.Google.EventColour.Palette.NullPalette; + if (Ogcs.Google.Calendar.IsColourPaletteNull || !Ogcs.Google.Calendar.Instance.ColourPalette.IsCached()) offlineAddGoogleColour(); else { - if (ddGoogleColour.Items.Count != GoogleOgcs.Calendar.Instance.ColourPalette.ActivePalette.Count) + if (ddGoogleColour.Items.Count != Ogcs.Google.Calendar.Instance.ColourPalette.ActivePalette.Count) ddGoogleColour.AddPaletteColours(); - palette = GoogleOgcs.Calendar.Instance.GetColour(ddOutlookColour.SelectedItem.OutlookCategory); + palette = Ogcs.Google.Calendar.Instance.GetColour(ddOutlookColour.SelectedItem.OutlookCategory); ddGoogleColour.SelectedIndex = Convert.ToInt16(palette.Id); } @@ -1988,7 +1989,7 @@ private void ddGoogleColour_SelectedIndexChanged(object sender, EventArgs e) { ddOutlookColour.SelectedIndexChanged -= ddOutlookColour_SelectedIndexChanged; String oCatName = null; - if (GoogleOgcs.Calendar.IsColourPaletteNull || !GoogleOgcs.Calendar.Instance.ColourPalette.IsCached()) + if (Ogcs.Google.Calendar.IsColourPaletteNull || !Ogcs.Google.Calendar.Instance.ColourPalette.IsCached()) oCatName = ActiveCalendarProfile.SetEntriesColourName; else oCatName = Outlook.Calendar.Instance.GetCategoryColour(ddGoogleColour.SelectedItem.Id); @@ -2016,14 +2017,14 @@ private void ddGoogleColour_SelectedIndexChanged(object sender, EventArgs e) { /// Avoid connecting to Google simply to add correct profile colour to dropdown /// private void offlineAddGoogleColour() { - GoogleOgcs.EventColour.Palette localPalette = new GoogleOgcs.EventColour.Palette( - GoogleOgcs.EventColour.Palette.Type.Event, ActiveCalendarProfile.SetEntriesColourGoogleId, null, Color.Transparent); - if (!ddGoogleColour.Items.Cast().Any(cbi => cbi.Id == localPalette.Id)) { + Ogcs.Google.EventColour.Palette localPalette = new Ogcs.Google.EventColour.Palette( + Ogcs.Google.EventColour.Palette.Type.Event, ActiveCalendarProfile.SetEntriesColourGoogleId, null, Color.Transparent); + if (!ddGoogleColour.Items.Cast().Any(cbi => cbi.Id == localPalette.Id)) { ddGoogleColour.Items.Add(localPalette); ddGoogleColour.SelectedItem = localPalette; return; } - foreach (GoogleOgcs.EventColour.Palette item in ddGoogleColour.Items) { + foreach (Ogcs.Google.EventColour.Palette item in ddGoogleColour.Items) { if (item.Id == localPalette.Id) { ddGoogleColour.SelectedItem = item; break; diff --git a/src/OutlookGoogleCalendarSync/Forms/Splash.cs b/src/OutlookGoogleCalendarSync/Forms/Splash.cs index a88899d2..3dbf9d53 100644 --- a/src/OutlookGoogleCalendarSync/Forms/Splash.cs +++ b/src/OutlookGoogleCalendarSync/Forms/Splash.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using System; using System.Threading; using System.Windows.Forms; @@ -48,13 +49,13 @@ private static void doShowSplash() { String subscribedDate = XMLManager.ImportElement("Subscribed", Settings.ConfigFile); if (!string.IsNullOrEmpty(subscribedDate)) subscribed = DateTime.Parse(subscribedDate); - else subscribed = GoogleOgcs.Authenticator.SubscribedNever; + else subscribed = Ogcs.Google.Authenticator.SubscribedNever; Boolean hideSplash = (XMLManager.ImportElement("HideSplashScreen", Settings.ConfigFile) ?? "false") == "true"; initialised = true; splash.cbHideSplash.Checked = hideSplash; - if (subscribed == GoogleOgcs.Authenticator.SubscribedNever && !donor) { + if (subscribed == Ogcs.Google.Authenticator.SubscribedNever && !donor) { ToolTips = new ToolTip { AutoPopDelay = 10000, InitialDelay = 500, @@ -115,7 +116,7 @@ private void Splash_Shown(object sender, EventArgs e) { private void cbHideSplash_CheckedChanged(object sender, EventArgs e) { if (!this.Visible) return; - if (subscribed == GoogleOgcs.Authenticator.SubscribedNever && !donor) { + if (subscribed == Ogcs.Google.Authenticator.SubscribedNever && !donor) { this.cbHideSplash.CheckedChanged -= cbHideSplash_CheckedChanged; cbHideSplash.Checked = false; this.cbHideSplash.CheckedChanged += cbHideSplash_CheckedChanged; diff --git a/src/OutlookGoogleCalendarSync/GoogleOgcs/ApiKeyring.cs b/src/OutlookGoogleCalendarSync/Google/ApiKeyring.cs similarity index 98% rename from src/OutlookGoogleCalendarSync/GoogleOgcs/ApiKeyring.cs rename to src/OutlookGoogleCalendarSync/Google/ApiKeyring.cs index dac9ef11..fb1a2703 100644 --- a/src/OutlookGoogleCalendarSync/GoogleOgcs/ApiKeyring.cs +++ b/src/OutlookGoogleCalendarSync/Google/ApiKeyring.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using System; using System.Collections.Generic; using System.Linq; @@ -12,7 +13,7 @@ * sync engine, so that's for another day! */ -namespace OutlookGoogleCalendarSync.GoogleOgcs { +namespace OutlookGoogleCalendarSync.Google { public class ApiKeyring { private static readonly ILog log = LogManager.GetLogger(typeof(ApiKeyring)); private const String keyringURL = "https://github.com/phw198/OutlookGoogleCalendarSync/raw/master/docs/keyring.md"; @@ -152,7 +153,7 @@ public static void ChangeKeys() { System.Windows.Forms.OgcsMessageBox.Show("Your Google authorisation token needs updating.\r\n" + "The process to reauthorise access to your Google account will now begin...", "Authorisation token invalid", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); - GoogleOgcs.Calendar.Instance.Authenticator.Reset(); + Ogcs.Google.Calendar.Instance.Authenticator.Reset(); } private static MatchCollection findText(string source, string pattern) { diff --git a/src/OutlookGoogleCalendarSync/GoogleOgcs/Authenticator.cs b/src/OutlookGoogleCalendarSync/Google/Authenticator.cs similarity index 92% rename from src/OutlookGoogleCalendarSync/GoogleOgcs/Authenticator.cs rename to src/OutlookGoogleCalendarSync/Google/Authenticator.cs index 18790f17..14385c82 100644 --- a/src/OutlookGoogleCalendarSync/GoogleOgcs/Authenticator.cs +++ b/src/OutlookGoogleCalendarSync/Google/Authenticator.cs @@ -1,4 +1,5 @@ -using Google.Apis.Auth.OAuth2; +using Ogcs = OutlookGoogleCalendarSync; +using Google.Apis.Auth.OAuth2; using Google.Apis.Calendar.v3; using Google.Apis.Calendar.v3.Data; using Google.Apis.Util.Store; @@ -11,14 +12,14 @@ using System.Threading.Tasks; using System.Windows.Forms; -namespace OutlookGoogleCalendarSync.GoogleOgcs { +namespace OutlookGoogleCalendarSync.Google { public class Authenticator { private static readonly ILog log = LogManager.GetLogger(typeof(Authenticator)); private Boolean authenticated = false; public Boolean Authenticated { get { return authenticated; } } - public const String TokenFile = "Google.Apis.Auth.OAuth2.Responses.TokenResponse-user"; + public const String TokenFile = "global::Google.Apis.Auth.OAuth2.Responses.TokenResponse-user"; private String tokenFullPath; private Boolean tokenFileExists { get { return File.Exists(tokenFullPath); } } @@ -111,7 +112,7 @@ private async Task getAuthenticated(ClientSecrets cs) { if (tokenFileExists) log.Debug("User has provided Google authorisation and credential file saved."); - } catch (Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { + } catch (global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { //OGCSexception.AnalyseTokenResponse(ex); if (ex.Error.Error == "access_denied") { String noAuthGiven = "Sorry, but this application will not work if you don't allow it access to your Google Calendar :("; @@ -137,9 +138,9 @@ private async Task getAuthenticated(ClientSecrets cs) { log.Debug("Access token expires " + credential.Token.IssuedUtc.AddSeconds(credential.Token.ExpiresInSeconds.Value).ToLocalTime().ToString()); } - GoogleOgcs.Calendar.Instance.Service = new CalendarService(new Google.Apis.Services.BaseClientService.Initializer() { HttpClientInitializer = credential }); + Ogcs.Google.Calendar.Instance.Service = new CalendarService(new global::Google.Apis.Services.BaseClientService.Initializer() { HttpClientInitializer = credential }); if (Settings.Instance.Proxy.Type == "Custom") - GoogleOgcs.Calendar.Instance.Service.HttpClient.DefaultRequestHeaders.Add("user-agent", Settings.Instance.Proxy.BrowserUserAgent); + Ogcs.Google.Calendar.Instance.Service.HttpClient.DefaultRequestHeaders.Add("user-agent", Settings.Instance.Proxy.BrowserUserAgent); if (credential.Token.IssuedUtc.AddSeconds(credential.Token.ExpiresInSeconds.Value) < DateTime.UtcNow.AddMinutes(1)) { log.Debug("Access token needs refreshing."); @@ -148,9 +149,9 @@ private async Task getAuthenticated(ClientSecrets cs) { int backoff = 0; while (backoff < Calendar.BackoffLimit) { try { - GoogleOgcs.Calendar.Instance.Service.Settings.Get("useKeyboardShortcuts").Execute(); + Ogcs.Google.Calendar.Instance.Service.Settings.Get("useKeyboardShortcuts").Execute(); break; - } catch (Google.GoogleApiException ex) { + } catch (global::Google.GoogleApiException ex) { switch (Calendar.HandleAPIlimits(ref ex, null)) { case Calendar.ApiException.throwException: throw; case Calendar.ApiException.freeAPIexhausted: @@ -174,8 +175,8 @@ private async Task getAuthenticated(ClientSecrets cs) { } } catch (System.Exception ex) { - if (ex is Google.Apis.Auth.OAuth2.Responses.TokenResponseException) - OGCSexception.AnalyseTokenResponse(ex as Google.Apis.Auth.OAuth2.Responses.TokenResponseException, false); + if (ex is global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException) + OGCSexception.AnalyseTokenResponse(ex as global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException, false); else { OGCSexception.Analyse(ex); Forms.Main.Instance.Console.Update("Unable to communicate with Google services. " + (ex.InnerException != null ? ex.InnerException.Message : ex.Message), Console.Markup.warning); @@ -200,12 +201,12 @@ public void Reset(Boolean reauthorise = true) { Forms.Main.Instance.SetControlPropertyThreadSafe(Forms.Main.Instance.tbConnectedAcc, "Text", "Not connected"); authenticated = false; if (tokenFileExists) File.Delete(tokenFullPath); - if (!GoogleOgcs.Calendar.IsInstanceNull) { - GoogleOgcs.Calendar.Instance.Authenticator = null; - GoogleOgcs.Calendar.Instance.Service = null; + if (!Ogcs.Google.Calendar.IsInstanceNull) { + Ogcs.Google.Calendar.Instance.Authenticator = null; + Ogcs.Google.Calendar.Instance.Service = null; if (reauthorise) { - GoogleOgcs.Calendar.Instance.Authenticator = new Authenticator(); - GoogleOgcs.Calendar.Instance.Authenticator.GetAuthenticated(); + Ogcs.Google.Calendar.Instance.Authenticator = new Authenticator(); + Ogcs.Google.Calendar.Instance.Authenticator.GetAuthenticated(); } } } @@ -333,7 +334,7 @@ public Boolean UserSubscriptionCheck() { log.Debug("Retrieving all subscribers from past year."); try { do { - EventsResource.ListRequest lr = GoogleOgcs.Calendar.Instance.Service.Events.List("hahospj0gkekqentakho0vv224@group.calendar.google.com"); + EventsResource.ListRequest lr = Ogcs.Google.Calendar.Instance.Service.Events.List("hahospj0gkekqentakho0vv224@group.calendar.google.com"); lr.PageToken = pageToken; lr.SingleEvents = true; @@ -353,18 +354,18 @@ public Boolean UserSubscriptionCheck() { log.Warn("User's Google account username is not present - cannot check if they have subscribed."); return false; } - } catch (Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { + } catch (global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { OGCSexception.AnalyseTokenResponse(ex); - } catch (Google.GoogleApiException ex) { - switch (GoogleOgcs.Calendar.HandleAPIlimits(ref ex, null)) { + } catch (global::Google.GoogleApiException ex) { + switch (Ogcs.Google.Calendar.HandleAPIlimits(ref ex, null)) { case Calendar.ApiException.throwException: throw; case Calendar.ApiException.freeAPIexhausted: OGCSexception.LogAsFail(ref ex); OGCSexception.Analyse(ex); - System.ApplicationException aex = new System.ApplicationException(GoogleOgcs.Calendar.Instance.SubscriptionInvite, ex); + System.ApplicationException aex = new System.ApplicationException(Ogcs.Google.Calendar.Instance.SubscriptionInvite, ex); OGCSexception.LogAsFail(ref aex); - GoogleOgcs.Calendar.Instance.Service = null; + Ogcs.Google.Calendar.Instance.Service = null; throw aex; } @@ -428,7 +429,7 @@ private Boolean userDonationCheck() { log.Debug("Retrieving all donors."); try { do { - EventsResource.ListRequest lr = GoogleOgcs.Calendar.Instance.Service.Events.List("toiqu5lfdklneh5aqq509jhhk8@group.calendar.google.com"); + EventsResource.ListRequest lr = Ogcs.Google.Calendar.Instance.Service.Events.List("toiqu5lfdklneh5aqq509jhhk8@group.calendar.google.com"); lr.PageToken = pageToken; lr.SingleEvents = true; diff --git a/src/OutlookGoogleCalendarSync/GoogleOgcs/CustomProperty.cs b/src/OutlookGoogleCalendarSync/Google/CustomProperty.cs similarity index 92% rename from src/OutlookGoogleCalendarSync/GoogleOgcs/CustomProperty.cs rename to src/OutlookGoogleCalendarSync/Google/CustomProperty.cs index 19e4d09c..c243172b 100644 --- a/src/OutlookGoogleCalendarSync/GoogleOgcs/CustomProperty.cs +++ b/src/OutlookGoogleCalendarSync/Google/CustomProperty.cs @@ -1,4 +1,5 @@ -using Google.Apis.Calendar.v3.Data; +using Ogcs = OutlookGoogleCalendarSync; +using Google.Apis.Calendar.v3.Data; using log4net; using Microsoft.Office.Interop.Outlook; using System; @@ -6,7 +7,7 @@ using System.Linq; using System.Text.RegularExpressions; -namespace OutlookGoogleCalendarSync.GoogleOgcs { +namespace OutlookGoogleCalendarSync.Google { public class EphemeralProperties { private Dictionary> ephemeralProperties; @@ -126,11 +127,11 @@ private static String metadataIdKeyName(MetadataId id) { int? returnVal = null; maxSet = 0; - if (GoogleOgcs.Calendar.Instance.EphemeralProperties.PropertyExists(ev, EphemeralProperty.PropertyName.KeySet) && - GoogleOgcs.Calendar.Instance.EphemeralProperties.PropertyExists(ev, EphemeralProperty.PropertyName.MaxSet)) + if (Ogcs.Google.Calendar.Instance.EphemeralProperties.PropertyExists(ev, EphemeralProperty.PropertyName.KeySet) && + Ogcs.Google.Calendar.Instance.EphemeralProperties.PropertyExists(ev, EphemeralProperty.PropertyName.MaxSet)) { - Object ep_keySet = GoogleOgcs.Calendar.Instance.EphemeralProperties.GetProperty(ev, EphemeralProperty.PropertyName.KeySet); - Object ep_maxSet = GoogleOgcs.Calendar.Instance.EphemeralProperties.GetProperty(ev, EphemeralProperty.PropertyName.MaxSet); + Object ep_keySet = Ogcs.Google.Calendar.Instance.EphemeralProperties.GetProperty(ev, EphemeralProperty.PropertyName.KeySet); + Object ep_maxSet = Ogcs.Google.Calendar.Instance.EphemeralProperties.GetProperty(ev, EphemeralProperty.PropertyName.MaxSet); maxSet = Convert.ToInt16(ep_maxSet ?? ep_keySet); if (ep_keySet != null) returnVal = Convert.ToInt16(ep_keySet); return returnVal; @@ -164,8 +165,8 @@ private static String metadataIdKeyName(MetadataId id) { if (!string.IsNullOrEmpty(returnSet)) returnVal = Convert.ToInt16(returnSet); } finally { - GoogleOgcs.Calendar.Instance.EphemeralProperties.Add(ev, new EphemeralProperty(EphemeralProperty.PropertyName.KeySet, returnVal)); - GoogleOgcs.Calendar.Instance.EphemeralProperties.Add(ev, new EphemeralProperty(EphemeralProperty.PropertyName.MaxSet, maxSet)); + Ogcs.Google.Calendar.Instance.EphemeralProperties.Add(ev, new EphemeralProperty(EphemeralProperty.PropertyName.KeySet, returnVal)); + Ogcs.Google.Calendar.Instance.EphemeralProperties.Add(ev, new EphemeralProperty(EphemeralProperty.PropertyName.MaxSet, maxSet)); } return returnVal; } @@ -180,7 +181,7 @@ public static Boolean OutlookIdMissing(Event ev) { if (!Exists(ev, MetadataId.oCalendarId)) missingIds += metadataIdKeyName(MetadataId.oCalendarId) + "|"; if (!Exists(ev, MetadataId.oEntryId)) missingIds += metadataIdKeyName(MetadataId.oEntryId) + "|"; if (!string.IsNullOrEmpty(missingIds)) - log.Warn("Found Google item missing Outlook IDs (" + missingIds.TrimEnd('|') + "). " + GoogleOgcs.Calendar.GetEventSummary(ev)); + log.Warn("Found Google item missing Outlook IDs (" + missingIds.TrimEnd('|') + "). " + Ogcs.Google.Calendar.GetEventSummary(ev)); return !string.IsNullOrEmpty(missingIds); } @@ -253,8 +254,8 @@ private static void add(ref Event ev, String keyName, String keyValue, int? keyS else ev.ExtendedProperties.Private__.Add(keyName, keyValue); - GoogleOgcs.Calendar.Instance.EphemeralProperties.Add(ev, new EphemeralProperty(EphemeralProperty.PropertyName.KeySet, keySet)); - GoogleOgcs.Calendar.Instance.EphemeralProperties.Add(ev, new EphemeralProperty(EphemeralProperty.PropertyName.MaxSet, keySet)); + Ogcs.Google.Calendar.Instance.EphemeralProperties.Add(ev, new EphemeralProperty(EphemeralProperty.PropertyName.KeySet, keySet)); + Ogcs.Google.Calendar.Instance.EphemeralProperties.Add(ev, new EphemeralProperty(EphemeralProperty.PropertyName.MaxSet, keySet)); log.Fine("Set extendedproperty " + keyName + "=" + keyValue); } @@ -342,7 +343,7 @@ public static void LogProperties(Event ev, log4net.Core.Level thresholdLevel) { try { if (ev.ExtendedProperties != null && ev.ExtendedProperties.Private__ != null) { - log.Debug(GoogleOgcs.Calendar.GetEventSummary(ev)); + log.Debug(Ogcs.Google.Calendar.GetEventSummary(ev)); foreach (KeyValuePair prop in ev.ExtendedProperties.Private__.OrderBy(k => k.Key)) { log.Debug(prop.Key + "=" + prop.Value); } diff --git a/src/OutlookGoogleCalendarSync/GoogleOgcs/ErrorReporting.cs b/src/OutlookGoogleCalendarSync/Google/ErrorReporting.cs similarity index 98% rename from src/OutlookGoogleCalendarSync/GoogleOgcs/ErrorReporting.cs rename to src/OutlookGoogleCalendarSync/Google/ErrorReporting.cs index 7ad98cb2..ec7af9ff 100644 --- a/src/OutlookGoogleCalendarSync/GoogleOgcs/ErrorReporting.cs +++ b/src/OutlookGoogleCalendarSync/Google/ErrorReporting.cs @@ -3,10 +3,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Management; using System.Text.RegularExpressions; -namespace OutlookGoogleCalendarSync.GoogleOgcs { +namespace OutlookGoogleCalendarSync.Google { class ErrorReporting { private static readonly ILog log = LogManager.GetLogger(typeof(ErrorReporting)); diff --git a/src/OutlookGoogleCalendarSync/GoogleOgcs/EventAttendee.cs b/src/OutlookGoogleCalendarSync/Google/EventAttendee.cs similarity index 82% rename from src/OutlookGoogleCalendarSync/GoogleOgcs/EventAttendee.cs rename to src/OutlookGoogleCalendarSync/Google/EventAttendee.cs index 2f7063a2..b3afe4e2 100644 --- a/src/OutlookGoogleCalendarSync/GoogleOgcs/EventAttendee.cs +++ b/src/OutlookGoogleCalendarSync/Google/EventAttendee.cs @@ -2,15 +2,15 @@ using System; using System.Reflection; -namespace OutlookGoogleCalendarSync.GoogleOgcs { - class EventAttendee : Google.Apis.Calendar.v3.Data.EventAttendee { +namespace OutlookGoogleCalendarSync.Google { + class EventAttendee : global::Google.Apis.Calendar.v3.Data.EventAttendee { private static readonly ILog log = LogManager.GetLogger(typeof(EventAttendee)); public const String EmailCloak = ".ogcs"; - private Google.Apis.Calendar.v3.Data.EventAttendee parent { get; set; } + private global::Google.Apis.Calendar.v3.Data.EventAttendee parent { get; set; } public EventAttendee() { } - public EventAttendee(Google.Apis.Calendar.v3.Data.EventAttendee baseAttendee) { + public EventAttendee(global::Google.Apis.Calendar.v3.Data.EventAttendee baseAttendee) { parent = baseAttendee; foreach (PropertyInfo prop in parent.GetType().GetProperties()) { try { diff --git a/src/OutlookGoogleCalendarSync/GoogleOgcs/EventColour.cs b/src/OutlookGoogleCalendarSync/Google/EventColour.cs similarity index 91% rename from src/OutlookGoogleCalendarSync/GoogleOgcs/EventColour.cs rename to src/OutlookGoogleCalendarSync/Google/EventColour.cs index 79b310a0..ba58103e 100644 --- a/src/OutlookGoogleCalendarSync/GoogleOgcs/EventColour.cs +++ b/src/OutlookGoogleCalendarSync/Google/EventColour.cs @@ -1,12 +1,12 @@ -using Google.Apis.Calendar.v3.Data; +using Ogcs = OutlookGoogleCalendarSync; +using Google.Apis.Calendar.v3.Data; using log4net; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; - -namespace OutlookGoogleCalendarSync.GoogleOgcs { +namespace OutlookGoogleCalendarSync.Google { public class EventColour { public class Palette { private Boolean UseWebAppColours = true; @@ -183,8 +183,8 @@ public List ActivePalette { if (profile.UseGoogleCalendar?.Id == null) return activePalette; if (profile.UseGoogleCalendar.ColourId == "0") { - GoogleOgcs.Calendar.Instance.GetCalendars(); - profile.UseGoogleCalendar.ColourId = GoogleOgcs.Calendar.Instance.CalendarList.Find(c => c.Id == profile.UseGoogleCalendar.Id)?.ColourId ?? "0"; + Ogcs.Google.Calendar.Instance.GetCalendars(); + profile.UseGoogleCalendar.ColourId = Ogcs.Google.Calendar.Instance.CalendarList.Find(c => c.Id == profile.UseGoogleCalendar.Id)?.ColourId ?? "0"; } //Palette currentCal = calendarPalette.Find(p => p.Id == profile.UseGoogleCalendar.ColourId); @@ -217,22 +217,22 @@ public void Get() { eventPalette = new List(); int backoff = 0; try { - while (backoff < GoogleOgcs.Calendar.BackoffLimit) { + while (backoff < Ogcs.Google.Calendar.BackoffLimit) { try { - colours = GoogleOgcs.Calendar.Instance.Service.Colors.Get().Execute(); + colours = Ogcs.Google.Calendar.Instance.Service.Colors.Get().Execute(); break; - } catch (Google.GoogleApiException ex) { - switch (GoogleOgcs.Calendar.HandleAPIlimits(ref ex, null)) { - case GoogleOgcs.Calendar.ApiException.throwException: throw; - case GoogleOgcs.Calendar.ApiException.freeAPIexhausted: + } catch (global::Google.GoogleApiException ex) { + switch (Ogcs.Google.Calendar.HandleAPIlimits(ref ex, null)) { + case Ogcs.Google.Calendar.ApiException.throwException: throw; + case Ogcs.Google.Calendar.ApiException.freeAPIexhausted: OGCSexception.LogAsFail(ref ex); OGCSexception.Analyse(ex); - System.ApplicationException aex = new System.ApplicationException(GoogleOgcs.Calendar.Instance.SubscriptionInvite, ex); + System.ApplicationException aex = new System.ApplicationException(Ogcs.Google.Calendar.Instance.SubscriptionInvite, ex); OGCSexception.LogAsFail(ref aex); throw aex; - case GoogleOgcs.Calendar.ApiException.backoffThenRetry: + case Ogcs.Google.Calendar.ApiException.backoffThenRetry: backoff++; - if (backoff == GoogleOgcs.Calendar.BackoffLimit) { + if (backoff == Ogcs.Google.Calendar.BackoffLimit) { log.Error("API limit backoff was not successful. Retrieve Event colours failed."); throw; } else { @@ -270,7 +270,7 @@ public void BuildPicker(System.Windows.Forms.CheckedListBox clb) { clb.BeginUpdate(); clb.Items.Clear(); clb.Items.Add(""); - foreach (Palette colour in GoogleOgcs.Calendar.Instance.ColourPalette.eventPalette) { + foreach (Palette colour in Ogcs.Google.Calendar.Instance.ColourPalette.eventPalette) { clb.Items.Add(colour.Name); } foreach (String colour in Forms.Main.Instance.ActiveCalendarProfile.Colours) { diff --git a/src/OutlookGoogleCalendarSync/GoogleOgcs/GMeet.cs b/src/OutlookGoogleCalendarSync/Google/GMeet.cs similarity index 98% rename from src/OutlookGoogleCalendarSync/GoogleOgcs/GMeet.cs rename to src/OutlookGoogleCalendarSync/Google/GMeet.cs index 294a184e..393c10bd 100644 --- a/src/OutlookGoogleCalendarSync/GoogleOgcs/GMeet.cs +++ b/src/OutlookGoogleCalendarSync/Google/GMeet.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Linq; -namespace OutlookGoogleCalendarSync.GoogleOgcs { +namespace OutlookGoogleCalendarSync.Google { static class GMeet { private static readonly ILog log = LogManager.GetLogger(typeof(GMeet)); diff --git a/src/OutlookGoogleCalendarSync/GoogleOgcs/GoogleCalendar.cs b/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs similarity index 96% rename from src/OutlookGoogleCalendarSync/GoogleOgcs/GoogleCalendar.cs rename to src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs index c4819eda..bbc656d3 100644 --- a/src/OutlookGoogleCalendarSync/GoogleOgcs/GoogleCalendar.cs +++ b/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs @@ -1,4 +1,5 @@ -using Google.Apis.Calendar.v3; +using Ogcs = OutlookGoogleCalendarSync; +using Google.Apis.Calendar.v3; using Google.Apis.Calendar.v3.Data; using log4net; using Microsoft.Office.Interop.Outlook; @@ -10,9 +11,9 @@ using System.Text.RegularExpressions; using System.Windows.Forms; -namespace OutlookGoogleCalendarSync.GoogleOgcs { +namespace OutlookGoogleCalendarSync.Google { /// - /// Description of GoogleOgcs.Calendar. + /// Description of Ogcs.Google.Calendar. /// public class Calendar { private static readonly ILog log = LogManager.GetLogger(typeof(Calendar)); @@ -22,8 +23,8 @@ public class Calendar { public static Calendar Instance { get { if (instance == null) { - instance = new GoogleOgcs.Calendar { - Authenticator = new GoogleOgcs.Authenticator() + instance = new Ogcs.Google.Calendar { + Authenticator = new Ogcs.Google.Authenticator() }; instance.Authenticator.GetAuthenticated(); if (instance.Authenticator.Authenticated) { @@ -42,15 +43,15 @@ public static Calendar Instance { } public Calendar() { } private Boolean openedIssue1593 = false; - public GoogleOgcs.Authenticator Authenticator; + public Ogcs.Google.Authenticator Authenticator; /// Google Events excluded through user config public Dictionary ExcludedByColour { get; private set; } - private GoogleOgcs.EventColour colourPalette; + private Ogcs.Google.EventColour colourPalette; public static Boolean IsColourPaletteNull { get { return instance?.colourPalette == null; } } - public GoogleOgcs.EventColour ColourPalette { + public Ogcs.Google.EventColour ColourPalette { get { if (colourPalette == null) colourPalette = new EventColour(); @@ -65,7 +66,7 @@ public CalendarService Service { get { if (service == null) { log.Debug("Google service not yet instantiated."); - Authenticator = new GoogleOgcs.Authenticator(); + Authenticator = new Ogcs.Google.Authenticator(); Authenticator.GetAuthenticated(); if (Authenticator.Authenticated) Authenticator.OgcsUserStatus(); @@ -124,7 +125,7 @@ public void GetCalendars() { lr.ShowHidden = true; request = lr.Execute(); break; - } catch (Google.GoogleApiException ex) { + } catch (global::Google.GoogleApiException ex) { switch (HandleAPIlimits(ref ex, null)) { case ApiException.throwException: throw; case ApiException.freeAPIexhausted: @@ -179,7 +180,7 @@ public List GetCalendarEntriesInRecurrence(String recurringEventId) { request = ir.Execute(); log.Debug("Page " + pageNum + " received."); break; - } catch (Google.GoogleApiException ex) { + } catch (global::Google.GoogleApiException ex) { switch (HandleAPIlimits(ref ex, null)) { case ApiException.throwException: throw; case ApiException.freeAPIexhausted: @@ -230,7 +231,7 @@ public Event GetCalendarEntry(String eventId) { try { request = gr.Execute(); break; - } catch (Google.GoogleApiException ex) { + } catch (global::Google.GoogleApiException ex) { if (ex.Error.Code == 404) { //Not found log.Fail("Could not find Google Event with specified ID " + eventId); return null; @@ -300,7 +301,7 @@ public List GetCalendarEntriesInRange(DateTime from, DateTime to) { request = lr.Execute(); log.Debug("Page " + pageNum + " received."); break; - } catch (Google.GoogleApiException ex) { + } catch (global::Google.GoogleApiException ex) { switch (HandleAPIlimits(ref ex, null)) { case ApiException.throwException: throw; case ApiException.freeAPIexhausted: @@ -463,7 +464,7 @@ private Event patchEvent(Event ev, String patchId = null) { } return pr.Execute(); - } catch (Google.GoogleApiException ex) { + } catch (global::Google.GoogleApiException ex) { switch (HandleAPIlimits(ref ex, ev)) { case ApiException.throwException: throw; case ApiException.freeAPIexhausted: @@ -502,7 +503,7 @@ public void CreateCalendarEntries(List appointments) { if (ex is ApplicationException) { String summary = Outlook.Calendar.GetEventSummary("Event creation skipped.
" + ex.Message, ai, out String anonSummary); Forms.Main.Instance.Console.Update(summary, anonSummary, Console.Markup.warning); - if (ex.InnerException is Google.GoogleApiException) break; + if (ex.InnerException is global::Google.GoogleApiException) break; continue; } else { String summary = Outlook.Calendar.GetEventSummary("Event creation failed.", ai, out String anonSummary); @@ -577,7 +578,7 @@ private Event createCalendarEntry(AppointmentItem ai) { ev.Transparency = getAvailability(ai.BusyStatus, null); ev.ColorId = getColour(ai.Categories, null)?.Id ?? EventColour.Palette.NullPalette.Id; - ev.Attendees = new List(); + ev.Attendees = new List(); if (profile.AddAttendees && ai.Recipients.Count > 1 && !APIlimitReached_attendee) { //Don't add attendees if there's only 1 (me) if (ai.Recipients.Count > profile.MaxAttendees) { log.Warn("This Outlook appointment has " + ai.Recipients.Count + " attendees, more than the user configured maximum."); @@ -587,7 +588,7 @@ private Event createCalendarEntry(AppointmentItem ai) { } } else { foreach (Microsoft.Office.Interop.Outlook.Recipient recipient in ai.Recipients) { - Google.Apis.Calendar.v3.Data.EventAttendee ea = GoogleOgcs.Calendar.CreateAttendee(recipient, ai.Organizer == recipient.Name); + global::Google.Apis.Calendar.v3.Data.EventAttendee ea = Ogcs.Google.Calendar.CreateAttendee(recipient, ai.Organizer == recipient.Name); ev.Attendees.Add(ea); } } @@ -642,7 +643,7 @@ private Event createCalendarEntry_save(Event ev, AppointmentItem ai) { Settings.Instance.APIlimit_inEffect = false; } break; - } catch (Google.GoogleApiException ex) { + } catch (global::Google.GoogleApiException ex) { switch (HandleAPIlimits(ref ex, ev)) { case ApiException.throwException: throw; case ApiException.freeAPIexhausted: @@ -677,7 +678,7 @@ private Event createCalendarEntry_save(Event ev, AppointmentItem ai) { if (profile.AddGMeet && Outlook.GMeet.BodyHasGmeetUrl(ai)) { log.Info("Adding GMeet conference details."); String outlookGMeet = Outlook.GMeet.RgxGmeetUrl().Match(ai.Body).Value; - GMeet.GoogleMeet(createdEvent, outlookGMeet); + Ogcs.Google.GMeet.GoogleMeet(createdEvent, outlookGMeet); createdEvent = patchEvent(createdEvent) ?? createdEvent; log.Fine("Conference data added."); } @@ -687,7 +688,7 @@ private Event createCalendarEntry_save(Event ev, AppointmentItem ai) { // Forms.Main.Instance.Console.Update("Add #" + i, verbose: true); // Event result = service.Events.Insert(ev, Settings.Instance.UseGoogleCalendar.Id).Execute(); // System.Threading.Thread.Sleep(300); - // GoogleOgcs.Calendar.Instance.deleteCalendarEntry_save(result); + // Ogcs.Google.Calendar.Instance.deleteCalendarEntry_save(result); // System.Threading.Thread.Sleep(300); //} #endregion @@ -712,7 +713,7 @@ public void UpdateCalendarEntries(Dictionary entriesToBe if (ex is ApplicationException) { String summary = Outlook.Calendar.GetEventSummary("
Event update skipped.
" + ex.Message, compare.Key, out String anonSummary); Forms.Main.Instance.Console.Update(summary, anonSummary, Console.Markup.warning); - if (ex.InnerException is Google.GoogleApiException) break; + if (ex.InnerException is global::Google.GoogleApiException) break; continue; } else { String summary = Outlook.Calendar.GetEventSummary("
Event update failed.", compare.Key, out String anonSummary); @@ -927,7 +928,7 @@ public Event UpdateCalendarEntry(AppointmentItem ai, Event ev, ref int itemModif String outlookGMeet = Outlook.GMeet.RgxGmeetUrl().Match(ai.Body ?? "")?.Value; if (Sync.Engine.CompareAttribute("Google Meet", Sync.Direction.OutlookToGoogle, ev.HangoutLink, outlookGMeet, sb, ref itemModified)) { try { - GMeet.GoogleMeet(ev, outlookGMeet); + Ogcs.Google.GMeet.GoogleMeet(ev, outlookGMeet); ev = patchEvent(ev) ?? ev; log.Fine("Conference data change successfully saved."); } catch (System.Exception ex) { @@ -1088,7 +1089,7 @@ public void UpdateCalendarEntry_save(ref Event ev) { Settings.Instance.APIlimit_inEffect = false; } break; - } catch (Google.GoogleApiException ex) { + } catch (global::Google.GoogleApiException ex) { ApiException handled = HandleAPIlimits(ref ex, ev); switch (handled) { case ApiException.throwException: throw; @@ -1145,7 +1146,7 @@ public void DeleteCalendarEntries(List events) { try { doDelete = deleteCalendarEntry(ev); } catch (System.Exception ex) { - Forms.Main.Instance.Console.UpdateWithError(GoogleOgcs.Calendar.GetEventSummary("Event deletion failed.", ev, out String anonSummary, true), ex, logEntry: anonSummary); + Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("Event deletion failed.", ev, out String anonSummary, true), ex, logEntry: anonSummary); OGCSexception.Analyse(ex, true); if (OgcsMessageBox.Show("Google event deletion failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; @@ -1158,8 +1159,8 @@ public void DeleteCalendarEntries(List events) { if (doDelete) deleteCalendarEntry_save(ev); else events.Remove(ev); } catch (System.Exception ex) { - if (ex is Google.GoogleApiException) { - Google.GoogleApiException gex = ex as Google.GoogleApiException; + if (ex is global::Google.GoogleApiException) { + global::Google.GoogleApiException gex = ex as global::Google.GoogleApiException; if (gex.Error != null && gex.Error.Code == 410) { //Resource has been deleted log.Fail("This event is already deleted! Ignoring failed request to delete."); continue; @@ -1168,7 +1169,7 @@ public void DeleteCalendarEntries(List events) { if (ex is ApplicationException) { String summary = GetEventSummary("
Event deletion skipped.
" + ex.Message, ev, out String anonSummary); Forms.Main.Instance.Console.Update(summary, anonSummary, Console.Markup.warning); - if (ex.InnerException is Google.GoogleApiException) break; + if (ex.InnerException is global::Google.GoogleApiException) break; continue; } else { String summary = GetEventSummary("
Event deletion failed.", ev, out String anonSummary); @@ -1213,7 +1214,7 @@ private void deleteCalendarEntry_save(Event ev) { request.SendUpdates = EventsResource.DeleteRequest.SendUpdatesEnum.None; string result = request.Execute(); break; - } catch (Google.GoogleApiException ex) { + } catch (global::Google.GoogleApiException ex) { switch (HandleAPIlimits(ref ex, ev)) { case ApiException.throwException: throw; case ApiException.freeAPIexhausted: @@ -1377,7 +1378,7 @@ public void IdentifyEventDifferences_Simple( // Count backwards so that we can remove found items without affecting the order of remaining items for (int g = google.Count - 1; g >= 0; g--) { if (Sync.Engine.Instance.CancellationPending) return; - log.Fine("Checking " + GoogleOgcs.Calendar.GetEventSummary(google[g])); + log.Fine("Checking " + Ogcs.Google.Calendar.GetEventSummary(google[g])); //Use simple matching on start,end,subject,location to pair events String sigEv = signature(google[g]); @@ -1432,7 +1433,7 @@ public void IdentifyEventDifferences_IDs( int metadataEnhanced = 0; for (int g = google.Count - 1; g >= 0; g--) { if (Sync.Engine.Instance.CancellationPending) return; - log.Fine("Checking " + GoogleOgcs.Calendar.GetEventSummary(google[g])); + log.Fine("Checking " + Ogcs.Google.Calendar.GetEventSummary(google[g])); if (CustomProperty.Exists(google[g], CustomProperty.MetadataId.oEntryId)) { String compare_gEntryID = CustomProperty.Get(google[g], CustomProperty.MetadataId.oEntryId); @@ -1485,7 +1486,7 @@ public void IdentifyEventDifferences_IDs( } } if (!foundMatch && profile.MergeItems && - GoogleOgcs.CustomProperty.Get(google[g], CustomProperty.MetadataId.oCalendarId) != profile.UseOutlookCalendar.Id) + Ogcs.Google.CustomProperty.Get(google[g], CustomProperty.MetadataId.oCalendarId) != profile.UseOutlookCalendar.Id) google.Remove(google[g]); } else if (profile.MergeItems) { @@ -1538,7 +1539,7 @@ public void IdentifyEventDifferences( } } } - if (outlook.Count > 0 && GoogleOgcs.Calendar.Instance.ExcludedByColour.Count > 0) { + if (outlook.Count > 0 && Ogcs.Google.Calendar.Instance.ExcludedByColour.Count > 0) { //Check if Outlook items to be created were filtered out from Google for (int o = outlook.Count - 1; o >= 0; o--) { if (ExcludedByColour.ContainsValue(outlook[o].EntryID) || @@ -1679,8 +1680,8 @@ public static Boolean ItemIDsMatch(ref Event ev, AppointmentItem ai) { public Boolean CompareRecipientsToAttendees(AppointmentItem ai, Event ev, StringBuilder sb, ref int itemModified) { log.Fine("Comparing Recipients"); //Build a list of Google attendees. Any remaining at the end of the diff must be deleted. - List removeAttendee = new List(); - foreach (Google.Apis.Calendar.v3.Data.EventAttendee ea in ev.Attendees ?? Enumerable.Empty()) { + List removeAttendee = new List(); + foreach (global::Google.Apis.Calendar.v3.Data.EventAttendee ea in ev.Attendees ?? Enumerable.Empty()) { removeAttendee.Add(ea); } if (ai.Recipients.Count > 1) { @@ -1689,8 +1690,8 @@ public Boolean CompareRecipientsToAttendees(AppointmentItem ai, Event ev, String Recipient recipient = ai.Recipients[o]; log.Fine("Comparing Outlook recipient: " + recipient.Name); String recipientSMTP = Outlook.Calendar.Instance.IOutlook.GetRecipientEmail(recipient); - foreach (Google.Apis.Calendar.v3.Data.EventAttendee attendee in ev.Attendees ?? Enumerable.Empty()) { - GoogleOgcs.EventAttendee ogcsAttendee = new GoogleOgcs.EventAttendee(attendee); + foreach (global::Google.Apis.Calendar.v3.Data.EventAttendee attendee in ev.Attendees ?? Enumerable.Empty()) { + Ogcs.Google.EventAttendee ogcsAttendee = new Ogcs.Google.EventAttendee(attendee); if (ogcsAttendee.Email != null && (recipientSMTP.ToLower() == ogcsAttendee.Email.ToLower())) { foundAttendee = true; removeAttendee.Remove(attendee); @@ -1759,15 +1760,15 @@ public Boolean CompareRecipientsToAttendees(AppointmentItem ai, Event ev, String if (!foundAttendee) { log.Fine("Attendee added: " + recipient.Name); sb.AppendLine("Attendee added: " + recipient.Name); - if (ev.Attendees == null) ev.Attendees = new List(); - ev.Attendees.Add(GoogleOgcs.Calendar.CreateAttendee(recipient, ai.Organizer == recipient.Name)); + if (ev.Attendees == null) ev.Attendees = new List(); + ev.Attendees.Add(Ogcs.Google.Calendar.CreateAttendee(recipient, ai.Organizer == recipient.Name)); itemModified++; } } } //more than just 1 (me) recipients - foreach (Google.Apis.Calendar.v3.Data.EventAttendee gea in removeAttendee) { - GoogleOgcs.EventAttendee ea = new GoogleOgcs.EventAttendee(gea); + foreach (global::Google.Apis.Calendar.v3.Data.EventAttendee gea in removeAttendee) { + Ogcs.Google.EventAttendee ea = new Ogcs.Google.EventAttendee(gea); log.Fine("Attendee removed: " + (ea.DisplayName ?? ea.Email), ea.Email); sb.AppendLine("Attendee removed: " + (ea.DisplayName ?? ea.Email)); ev.Attendees.Remove(gea); @@ -1791,7 +1792,7 @@ public void GetSettings() { stage = "retrieve settings for synced Google calendar"; getCalendarSettings(); break; - } catch (Google.GoogleApiException ex) { + } catch (global::Google.GoogleApiException ex) { switch (HandleAPIlimits(ref ex, null)) { case ApiException.throwException: throw; case ApiException.freeAPIexhausted: @@ -1827,7 +1828,7 @@ private void getCalendarSettings() { CalendarListEntry cal; try { cal = request.Execute(); - } catch (Google.GoogleApiException ex) { + } catch (global::Google.GoogleApiException ex) { if (ex.InnerException is Newtonsoft.Json.JsonReaderException && ex.InnerException.Message.Contains("Unexpected character encountered while parsing value: <") && Settings.Instance.Proxy.Type != "None") { log.Warn("Call to CalendarList API endpoint failed. Retrying with trailing '/' in case of poorly configured proxy."); //The URI ends with "@group.calendar.google.com", which seemingly can cause confusion - see issue #1745 @@ -2113,7 +2114,7 @@ private static String exportToCSV(Event ev) { System.Text.StringBuilder required = new System.Text.StringBuilder(); System.Text.StringBuilder optional = new System.Text.StringBuilder(); if (ev.Attendees != null) { - foreach (Google.Apis.Calendar.v3.Data.EventAttendee ea in ev.Attendees) { + foreach (global::Google.Apis.Calendar.v3.Data.EventAttendee ea in ev.Attendees) { if (ea.Optional != null && (bool)ea.Optional) { optional.Append(ea.DisplayName + ";"); } else { required.Append(ea.DisplayName + ";"); } } @@ -2214,8 +2215,8 @@ public static String GetEventSummary(Event ev, out String eventSummaryAnonymised return eventSummary; } - public static Google.Apis.Calendar.v3.Data.EventAttendee CreateAttendee(Recipient recipient, Boolean isOrganiser) { - GoogleOgcs.EventAttendee ea = new GoogleOgcs.EventAttendee(); + public static global::Google.Apis.Calendar.v3.Data.EventAttendee CreateAttendee(Recipient recipient, Boolean isOrganiser) { + Ogcs.Google.EventAttendee ea = new Ogcs.Google.EventAttendee(); log.Fine("Creating attendee " + recipient.Name); ea.DisplayName = recipient.Name; ea.Email = Outlook.Calendar.Instance.IOutlook.GetRecipientEmail(recipient); @@ -2234,7 +2235,7 @@ public static Google.Apis.Calendar.v3.Data.EventAttendee CreateAttendee(Recipien return ea; } - public static ApiException HandleAPIlimits(ref Google.GoogleApiException ex, Event ev) { + public static ApiException HandleAPIlimits(ref global::Google.GoogleApiException ex, Event ev) { //https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors log.Fail(ex.Message); @@ -2269,7 +2270,7 @@ public static ApiException HandleAPIlimits(ref Google.GoogleApiException ex, Eve } else if (ex.Error?.Code == 403 && ex.Error.Errors?.First().Domain == "usageLimits") { if (ex.Message.Contains("Calendar usage limits exceeded") && profile.AddAttendees && ev != null) { - //"Google.Apis.Requests.RequestError\r\nCalendar usage limits exceeded. [403]\r\nErrors [\r\n\tMessage[Calendar usage limits exceeded.] Location[ - ] Reason[quotaExceeded] Domain[usageLimits]\r\n]\r\n" + //"global::Google.Apis.Requests.RequestError\r\nCalendar usage limits exceeded. [403]\r\nErrors [\r\n\tMessage[Calendar usage limits exceeded.] Location[ - ] Reason[quotaExceeded] Domain[usageLimits]\r\n]\r\n" //This happens because too many attendees have been added in a short period of time. //See https://support.google.com/a/answer/2905486?hl=en-uk&hlrm=en @@ -2280,7 +2281,7 @@ public static ApiException HandleAPIlimits(ref Google.GoogleApiException ex, Eve Settings.Instance.APIlimit_inEffect = true; Settings.Instance.APIlimit_lastHit = DateTime.Now; - ev.Attendees = new List(); + ev.Attendees = new List(); return ApiException.backoffThenRetry; } else if (ex.Error.Errors.First().Reason == "rateLimitExceeded") { @@ -2335,8 +2336,8 @@ public static ApiException HandleAPIlimits(ref Google.GoogleApiException ex, Eve log.Warn("The Event has changed since it was last retrieved - attempting to force an overwrite."); EventsResource.UpdateRequest request; try { - request = GoogleOgcs.Calendar.Instance.Service.Events.Update(ev, profile.UseGoogleCalendar.Id, ev.Id); - request.ETagAction = Google.Apis.ETagAction.Ignore; + request = Ogcs.Google.Calendar.Instance.Service.Events.Update(ev, profile.UseGoogleCalendar.Id, ev.Id); + request.ETagAction = global::Google.Apis.ETagAction.Ignore; request.SendUpdates = EventsResource.UpdateRequest.SendUpdatesEnum.None; ev = request.Execute(); log.Debug("Successfully forced save by ignoring eTag values."); @@ -2347,14 +2348,14 @@ public static ApiException HandleAPIlimits(ref Google.GoogleApiException ex, Eve log.Fine("Current Updated: " + ev.UpdatedRaw); log.Fine("Current Sequence: " + ev.Sequence); log.Debug("Refetching event from Google."); - Event remoteEv = GoogleOgcs.Calendar.Instance.GetCalendarEntry(ev.Id); + Event remoteEv = Ogcs.Google.Calendar.Instance.GetCalendarEntry(ev.Id); log.Fine("Remote eTag: " + remoteEv.ETag); log.Fine("Remote Updated: " + remoteEv.UpdatedRaw); log.Fine("Remote Sequence: " + remoteEv.Sequence); log.Warn("Attempting trample of remote version..."); ev.ETag = remoteEv.ETag; ev.Sequence = remoteEv.Sequence; - request = GoogleOgcs.Calendar.Instance.Service.Events.Update(ev, profile.UseGoogleCalendar.Id, ev.Id); + request = Ogcs.Google.Calendar.Instance.Service.Events.Update(ev, profile.UseGoogleCalendar.Id, ev.Id); request.SendUpdates = EventsResource.UpdateRequest.SendUpdatesEnum.None; ev = request.Execute(); log.Debug("Successful!"); @@ -2409,9 +2410,9 @@ public static void BuildOfflineColourPicker(System.Windows.Forms.CheckedListBox /// This is solely for purposefully causing an error to assist when developing /// public void ThrowApiException() { - Google.GoogleApiException ex = new Google.GoogleApiException("Service", "Rate Limit Exceeded"); - Google.Apis.Requests.SingleError err = new Google.Apis.Requests.SingleError { Domain = "usageLimits", Reason = "rateLimitExceeded" }; - ex.Error = new Google.Apis.Requests.RequestError { Errors = new List(), Code = 403 }; + global::Google.GoogleApiException ex = new global::Google.GoogleApiException("Service", "Rate Limit Exceeded"); + global::Google.Apis.Requests.SingleError err = new global::Google.Apis.Requests.SingleError { Domain = "usageLimits", Reason = "rateLimitExceeded" }; + ex.Error = new global::Google.Apis.Requests.RequestError { Errors = new List(), Code = 403 }; ex.Error.Errors.Add(err); throw ex; } diff --git a/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs b/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs index d283e837..6d35bc25 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs @@ -1,4 +1,5 @@ -using Google.Apis.Calendar.v3.Data; +using Ogcs = OutlookGoogleCalendarSync; +using Google.Apis.Calendar.v3.Data; using log4net; using Microsoft.Office.Interop.Outlook; using System; @@ -312,10 +313,10 @@ public void CreateCalendarEntries(List events) { createCalendarEntry(ev, ref newAi); } catch (System.Exception ex) { if (ex.GetType() == typeof(ApplicationException)) { - Forms.Main.Instance.Console.Update(GoogleOgcs.Calendar.GetEventSummary("Appointment creation skipped: " + ex.Message, ev, out String anonSummary, true), anonSummary, Console.Markup.warning); + Forms.Main.Instance.Console.Update(Ogcs.Google.Calendar.GetEventSummary("Appointment creation skipped: " + ex.Message, ev, out String anonSummary, true), anonSummary, Console.Markup.warning); continue; } else { - Forms.Main.Instance.Console.UpdateWithError(GoogleOgcs.Calendar.GetEventSummary("Appointment creation failed.", ev, out String anonSummary, true), ex, logEntry: anonSummary); + Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("Appointment creation failed.", ev, out String anonSummary, true), ex, logEntry: anonSummary); OGCSexception.Analyse(ex, true); if (OgcsMessageBox.Show("Outlook appointment creation failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; @@ -328,7 +329,7 @@ public void CreateCalendarEntries(List events) { createCalendarEntry_save(newAi, ref ev); events[g] = ev; } catch (System.Exception ex) { - Forms.Main.Instance.Console.UpdateWithError(GoogleOgcs.Calendar.GetEventSummary("New appointment failed to save.", ev, out String anonSummary, true), ex, logEntry: anonSummary); + Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("New appointment failed to save.", ev, out String anonSummary, true), ex, logEntry: anonSummary); OGCSexception.Analyse(ex, true); if (OgcsMessageBox.Show("New Outlook appointment failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; @@ -348,7 +349,7 @@ public void CreateCalendarEntries(List events) { } private void createCalendarEntry(Event ev, ref AppointmentItem ai) { - string itemSummary = GoogleOgcs.Calendar.GetEventSummary(ev, out String anonItemSummary); + string itemSummary = Ogcs.Google.Calendar.GetEventSummary(ev, out String anonItemSummary); log.Debug("Processing >> " + (anonItemSummary ?? itemSummary)); Forms.Main.Instance.Console.Update(itemSummary, anonItemSummary, Console.Markup.calendar, verbose: true); @@ -389,9 +390,9 @@ private void createCalendarEntry(Event ev, ref AppointmentItem ai) { } catch (System.Exception ex) { OGCSexception.Analyse("Failed setting Outlook reminder for final popup Google notification.", ex); } - } else if ((ev.Reminders?.UseDefault ?? false) && GoogleOgcs.Calendar.Instance.MinDefaultReminder != int.MinValue) { + } else if ((ev.Reminders?.UseDefault ?? false) && Ogcs.Google.Calendar.Instance.MinDefaultReminder != int.MinValue) { ai.ReminderSet = true; - ai.ReminderMinutesBeforeStart = GoogleOgcs.Calendar.Instance.MinDefaultReminder; + ai.ReminderMinutesBeforeStart = Ogcs.Google.Calendar.Instance.MinDefaultReminder; } else { ai.ReminderSet = profile.UseOutlookDefaultReminder; } @@ -414,10 +415,10 @@ private static void createCalendarEntry_save(AppointmentItem ai, ref Event ev) { ai.Save(); - if (profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id || GoogleOgcs.CustomProperty.ExistAnyOutlookIDs(ev)) { + if (profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id || Ogcs.Google.CustomProperty.ExistAnyOutlookIDs(ev)) { log.Debug("Storing the Outlook appointment IDs in Google event."); - GoogleOgcs.CustomProperty.AddOutlookIDs(ref ev, ai); - GoogleOgcs.Calendar.Instance.UpdateCalendarEntry_save(ref ev); + Ogcs.Google.CustomProperty.AddOutlookIDs(ref ev, ai); + Ogcs.Google.Calendar.Instance.UpdateCalendarEntry_save(ref ev); } } #endregion @@ -436,7 +437,7 @@ public void UpdateCalendarEntries(Dictionary entriesToBe try { needsUpdating = UpdateCalendarEntry(ref ai, compare.Value, ref itemModified); } catch (System.Exception ex) { - Forms.Main.Instance.Console.UpdateWithError(GoogleOgcs.Calendar.GetEventSummary("
Appointment update failed.", compare.Value, out String anonSummary), ex, logEntry: anonSummary); + Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("
Appointment update failed.", compare.Value, out String anonSummary), ex, logEntry: anonSummary); OGCSexception.Analyse(ex, true); if (OgcsMessageBox.Show("Outlook appointment update failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; @@ -449,7 +450,7 @@ public void UpdateCalendarEntries(Dictionary entriesToBe updateCalendarEntry_save(ref ai); entriesUpdated++; } catch (System.Exception ex) { - Forms.Main.Instance.Console.UpdateWithError(GoogleOgcs.Calendar.GetEventSummary("Updated appointment failed to save.", compare.Value, out String anonSummary, true), ex, logEntry: anonSummary); + Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("Updated appointment failed to save.", compare.Value, out String anonSummary, true), ex, logEntry: anonSummary); OGCSexception.Analyse(ex, true); if (OgcsMessageBox.Show("Updated Outlook appointment failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; @@ -464,7 +465,7 @@ public void UpdateCalendarEntries(Dictionary entriesToBe } else { if (ai.RecurrenceState == OlRecurrenceState.olApptMaster && compare.Value.Recurrence != null && compare.Value.RecurringEventId == null) { - log.Debug(GoogleOgcs.Calendar.GetEventSummary(compare.Value)); + log.Debug(Ogcs.Google.Calendar.GetEventSummary(compare.Value)); Recurrence.Instance.UpdateOutlookExceptions(ref ai, compare.Value, forceCompare: false); } else if (needsUpdating || CustomProperty.Exists(ai, CustomProperty.MetadataId.forceSave)) { @@ -490,7 +491,7 @@ public Boolean UpdateCalendarEntry(ref AppointmentItem ai, Event ev, ref int ite if (ai.LastModificationTime > ev.Updated) return false; } else { - if (GoogleOgcs.CustomProperty.GetOGCSlastModified(ev).AddSeconds(5) >= ev.Updated) + if (Ogcs.Google.CustomProperty.GetOGCSlastModified(ev).AddSeconds(5) >= ev.Updated) //Google last modified by OGCS return false; if (ai.LastModificationTime > ev.Updated) @@ -501,7 +502,7 @@ public Boolean UpdateCalendarEntry(ref AppointmentItem ai, Event ev, ref int ite if (ai.RecurrenceState == OlRecurrenceState.olApptMaster || ai.RecurrenceState == OlRecurrenceState.olApptException) log.Debug("Processing recurring " + (ai.RecurrenceState == OlRecurrenceState.olApptMaster ? "master" : "exception") + " appointment."); - String evSummary = GoogleOgcs.Calendar.GetEventSummary(ev, out String anonSummary); + String evSummary = Ogcs.Google.Calendar.GetEventSummary(ev, out String anonSummary); log.Debug("Processing >> " + (anonSummary ?? evSummary)); StringBuilder sb = new StringBuilder(); @@ -699,7 +700,7 @@ public Boolean UpdateCalendarEntry(ref AppointmentItem ai, Event ev, ref int ite String recipientSMTP = IOutlook.GetRecipientEmail(recipient); for (int g = (ev.Attendees == null ? -1 : ev.Attendees.Count - 1); g >= 0; g--) { - GoogleOgcs.EventAttendee attendee = new GoogleOgcs.EventAttendee(ev.Attendees[g]); + Ogcs.Google.EventAttendee attendee = new Ogcs.Google.EventAttendee(ev.Attendees[g]); if (recipientSMTP.ToLower() == attendee.Email.ToLower()) { foundAttendee = true; @@ -729,7 +730,7 @@ public Boolean UpdateCalendarEntry(ref AppointmentItem ai, Event ev, ref int ite } } foreach (EventAttendee gAttendee in addAttendees) { - GoogleOgcs.EventAttendee attendee = new GoogleOgcs.EventAttendee(gAttendee); + Ogcs.Google.EventAttendee attendee = new Ogcs.Google.EventAttendee(gAttendee); if ((attendee.DisplayName ?? attendee.Email) == ai.Organizer) continue; //Attendee in Google is owner in Outlook, so can't also be added as a recipient) sb.AppendLine("Recipient added: " + (attendee.DisplayName ?? attendee.Email)); @@ -752,7 +753,7 @@ public Boolean UpdateCalendarEntry(ref AppointmentItem ai, Event ev, ref int ite EventReminder reminder = ev.Reminders.Overrides.Where(r => r.Method == "popup").OrderBy(r => r.Minutes).First(); reminderMins = (int)reminder.Minutes; } else if (ev.Reminders?.UseDefault ?? false) { - reminderMins = GoogleOgcs.Calendar.Instance.MinDefaultReminder; + reminderMins = Ogcs.Google.Calendar.Instance.MinDefaultReminder; } if (reminderMins != int.MinValue) { @@ -895,13 +896,13 @@ public void ReclaimOrphanCalendarEntries(ref List oAppointments for (int g = gEvents.Count - 1; g >= 0; g--) { Event ev = gEvents[g]; - String sigEv = GoogleOgcs.Calendar.signature(ev); + String sigEv = Ogcs.Google.Calendar.signature(ev); if (String.IsNullOrEmpty(sigEv)) { gEvents.Remove(ev); continue; } - if (GoogleOgcs.Calendar.SignaturesMatch(sigEv, sigAi)) { + if (Ogcs.Google.Calendar.SignaturesMatch(sigEv, sigAi)) { CustomProperty.AddGoogleIDs(ref ai, ev); updateCalendarEntry_save(ref ai); unclaimedAi.Remove(ai); @@ -910,10 +911,10 @@ public void ReclaimOrphanCalendarEntries(ref List oAppointments Forms.Main.Instance.Console.Update(GetEventSummary("Reclaimed: ", ai, out String anonSummary, appendContext: false), anonSummary, verbose: true); oAppointments[o] = ai; - if (profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id || GoogleOgcs.CustomProperty.ExistAnyOutlookIDs(ev)) { + if (profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id || Ogcs.Google.CustomProperty.ExistAnyOutlookIDs(ev)) { log.Debug("Updating the Outlook appointment IDs in Google event."); - GoogleOgcs.CustomProperty.AddOutlookIDs(ref ev, ai); - GoogleOgcs.Calendar.Instance.UpdateCalendarEntry_save(ref ev); + Ogcs.Google.CustomProperty.AddOutlookIDs(ref ev, ai); + Ogcs.Google.Calendar.Instance.UpdateCalendarEntry_save(ref ev); gEvents[g] = ev; } break; @@ -958,7 +959,7 @@ public void ReclaimOrphanCalendarEntries(ref List oAppointments } private void createRecipient(EventAttendee gea, ref Recipients recipients) { - GoogleOgcs.EventAttendee ea = new GoogleOgcs.EventAttendee(gea); + Ogcs.Google.EventAttendee ea = new Ogcs.Google.EventAttendee(gea); if (IOutlook.CurrentUserSMTP().ToLower() != ea.Email) { Recipient recipient = null; try { @@ -1081,15 +1082,15 @@ public String GetCategoryColour(String gColourId, Boolean createMissingCategory if (kvp.Key != null) { outlookColour = Outlook.Calendar.Categories.OutlookColour(kvp.Key); if (outlookColour != null) { - log.Debug("Colour mapping used: " + kvp.Value + ":" + GoogleOgcs.Calendar.Instance.ColourPalette.GetColour(gColourId).Name + " => " + kvp.Key); + log.Debug("Colour mapping used: " + kvp.Value + ":" + Ogcs.Google.Calendar.Instance.ColourPalette.GetColour(gColourId).Name + " => " + kvp.Key); return kvp.Key; } } } //Algorithmic closest colour matching - GoogleOgcs.EventColour.Palette pallete = GoogleOgcs.Calendar.Instance.ColourPalette.GetColour(gColourId); - if (pallete == GoogleOgcs.EventColour.Palette.NullPalette) return null; + Ogcs.Google.EventColour.Palette pallete = Ogcs.Google.Calendar.Instance.ColourPalette.GetColour(gColourId); + if (pallete == Ogcs.Google.EventColour.Palette.NullPalette) return null; outlookColour = Categories.Map.GetClosestCategory(pallete); return Categories.FindName(outlookColour, createMissingCategory: createMissingCategory); @@ -1464,7 +1465,7 @@ public static string GetEventSummary(AppointmentItem ai, out String eventSummary eventSummary += " " + (ai.IsRecurring ? "(R) " : "") + "=> "; if (Settings.Instance.AnonymiseLogs) - eventSummaryAnonymised = eventSummary + '"' + GoogleOgcs.Authenticator.GetMd5(ai.Subject, silent: true) + '"' + (onlyIfNotVerbose ? "
" : ""); + eventSummaryAnonymised = eventSummary + '"' + Ogcs.Google.Authenticator.GetMd5(ai.Subject, silent: true) + '"' + (onlyIfNotVerbose ? "
" : ""); eventSummary += '"' + ai.Subject + '"' + (onlyIfNotVerbose ? "
" : ""); } catch (System.Runtime.InteropServices.COMException ex) { @@ -1505,7 +1506,7 @@ public static void IdentifyEventDifferences( Boolean foundMatch = false; for (int g = google.Count - 1; g >= 0; g--) { - log.UltraFine("Checking " + GoogleOgcs.Calendar.GetEventSummary(google[g])); + log.UltraFine("Checking " + Ogcs.Google.Calendar.GetEventSummary(google[g])); if (compare_oEventID == google[g].Id.ToString()) { if (googleIDmissing == null) googleIDmissing = CustomProperty.GoogleIdMissing(outlook[o]); @@ -1549,11 +1550,11 @@ public static void IdentifyEventDifferences( if (responseFiltered > 0) log.Info(responseFiltered + " Outlook items will not be deleted due to only syncing invites that have been responded to."); } - if (outlook.Count > 0 && GoogleOgcs.Calendar.Instance.ExcludedByColour.Count > 0 && !profile.DeleteWhenColourExcluded) { + if (outlook.Count > 0 && Ogcs.Google.Calendar.Instance.ExcludedByColour.Count > 0 && !profile.DeleteWhenColourExcluded) { //Check if Outlook items to be deleted were filtered out from Google for (int o = outlook.Count - 1; o >= 0; o--) { - if (GoogleOgcs.Calendar.Instance.ExcludedByColour.ContainsValue(outlook[o].EntryID) || - GoogleOgcs.Calendar.Instance.ExcludedByColour.ContainsKey(CustomProperty.Get(outlook[o], CustomProperty.MetadataId.gEventID) ?? "")) { + if (Ogcs.Google.Calendar.Instance.ExcludedByColour.ContainsValue(outlook[o].EntryID) || + Ogcs.Google.Calendar.Instance.ExcludedByColour.ContainsKey(CustomProperty.Get(outlook[o], CustomProperty.MetadataId.gEventID) ?? "")) { outlook.Remove(outlook[o]); } } @@ -1562,7 +1563,7 @@ public static void IdentifyEventDifferences( //Check if Google items to be created were filtered out from Outlook for (int g = google.Count - 1; g >= 0; g--) { if (Instance.ExcludedByCategory.ContainsValue(google[g].Id) || - Instance.ExcludedByCategory.ContainsKey(GoogleOgcs.CustomProperty.Get(google[g], GoogleOgcs.CustomProperty.MetadataId.oEntryId) ?? "")) { + Instance.ExcludedByCategory.ContainsKey(Ogcs.Google.CustomProperty.Get(google[g], Ogcs.Google.CustomProperty.MetadataId.oEntryId) ?? "")) { google.Remove(google[g]); } } @@ -1579,7 +1580,7 @@ public static void IdentifyEventDifferences( if (profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id) { //Don't recreate any items that have been deleted in Outlook for (int g = google.Count - 1; g >= 0; g--) { - if (GoogleOgcs.CustomProperty.Exists(google[g], GoogleOgcs.CustomProperty.MetadataId.oEntryId)) + if (Ogcs.Google.CustomProperty.Exists(google[g], Ogcs.Google.CustomProperty.MetadataId.oEntryId)) google.Remove(google[g]); } //Don't delete any items that aren't yet in Google or just created in Google during this sync @@ -1591,7 +1592,7 @@ public static void IdentifyEventDifferences( } if (Settings.Instance.CreateCSVFiles) { ExportToCSV("Appointments for deletion in Outlook", "outlook_delete.csv", outlook); - GoogleOgcs.Calendar.ExportToCSV("Events for creation in Outlook", "outlook_create.csv", google); + Ogcs.Google.Calendar.ExportToCSV("Events for creation in Outlook", "outlook_create.csv", google); } } @@ -1639,9 +1640,9 @@ public Boolean IsOKtoSyncReminder(AppointmentItem ai) { if (ai.ReminderSet) alarm = ai.Start.AddMinutes(-ai.ReminderMinutesBeforeStart); else { - if (profile.UseGoogleDefaultReminder && GoogleOgcs.Calendar.Instance.MinDefaultReminder != int.MinValue) { - log.Fine("Using default Google reminder value: " + GoogleOgcs.Calendar.Instance.MinDefaultReminder); - alarm = ai.Start.AddMinutes(-GoogleOgcs.Calendar.Instance.MinDefaultReminder); + if (profile.UseGoogleDefaultReminder && Ogcs.Google.Calendar.Instance.MinDefaultReminder != int.MinValue) { + log.Fine("Using default Google reminder value: " + Ogcs.Google.Calendar.Instance.MinDefaultReminder); + alarm = ai.Start.AddMinutes(-Ogcs.Google.Calendar.Instance.MinDefaultReminder); } else return false; } diff --git a/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs b/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs index 365ff241..57816f5f 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs @@ -1,4 +1,5 @@ ///#define DEVELOP_AGAINST_2007 //Develop as for Outlook 2007 for greatest compatiblity +using Ogcs = OutlookGoogleCalendarSync; using log4net; using System; using System.Collections.Generic; @@ -79,9 +80,9 @@ public static Color RgbColour(String hexColour) { return colour; } - public static OutlookCOM.OlCategoryColor GetClosestCategory(GoogleOgcs.EventColour.Palette basePalette) { + public static OutlookCOM.OlCategoryColor GetClosestCategory(Ogcs.Google.EventColour.Palette basePalette) { try { - var colourDistance = Colours.Select(x => new { Value = x, Diff = GoogleOgcs.EventColour.GetDiff(x.Value, basePalette.RgbValue) }).ToList(); + var colourDistance = Colours.Select(x => new { Value = x, Diff = Ogcs.Google.EventColour.GetDiff(x.Value, basePalette.RgbValue) }).ToList(); var minDistance = colourDistance.Min(x => x.Diff); return colourDistance.Find(x => x.Diff == minDistance).Value.Key; } catch (System.Exception ex) { diff --git a/src/OutlookGoogleCalendarSync/OutlookGoogleCalendarSync.csproj b/src/OutlookGoogleCalendarSync/OutlookGoogleCalendarSync.csproj index f5768527..5bc0f0e5 100644 --- a/src/OutlookGoogleCalendarSync/OutlookGoogleCalendarSync.csproj +++ b/src/OutlookGoogleCalendarSync/OutlookGoogleCalendarSync.csproj @@ -326,14 +326,18 @@ TimezoneMap.cs
- + + + + + + + + - - - @@ -354,11 +358,8 @@ UpdateInfo.cs - - - @@ -373,7 +374,6 @@ Splash.cs - Form diff --git a/src/OutlookGoogleCalendarSync/Program.cs b/src/OutlookGoogleCalendarSync/Program.cs index a6239e3c..433c7dd8 100644 --- a/src/OutlookGoogleCalendarSync/Program.cs +++ b/src/OutlookGoogleCalendarSync/Program.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using log4net.Config; using System; using System.Collections.Generic; @@ -56,7 +57,7 @@ private static void Main(string[] args) { try { setSecurityProtocols(); - GoogleOgcs.ErrorReporting.Initialise(); + Ogcs.Google.ErrorReporting.Initialise(); RoamingProfileOGCS = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Application.ProductName); parseArgumentsAndInitialise(args); @@ -153,11 +154,11 @@ private static void parseArgumentsAndInitialise(string[] args) { log.Info("Storing user files in directory: " + MaskFilePath(UserFilePath)); //Before settings have been loaded, early config of cloud logging - GoogleOgcs.ErrorReporting.UpdateLogUuId(); + Ogcs.Google.ErrorReporting.UpdateLogUuId(); Boolean cloudLogSetting = false; String cloudLogXmlSetting = XMLManager.ImportElement("CloudLogging", Settings.ConfigFile); if (!string.IsNullOrEmpty(cloudLogXmlSetting)) cloudLogSetting = Boolean.Parse(cloudLogXmlSetting); - GoogleOgcs.ErrorReporting.SetThreshold(cloudLogSetting); + Ogcs.Google.ErrorReporting.SetThreshold(cloudLogSetting); if (!StartedWithFileArgs) { //Now let's confirm files are actually in the right place @@ -239,14 +240,14 @@ private static void initialiseLogger(string logFilename, string logPath = null, log4net.LogManager.GetRepository().LevelMap.Add(MyFineLevel); log4net.LogManager.GetRepository().LevelMap.Add(MyUltraFineLevel); - GoogleOgcs.ErrorReporting.LogId = "v" + Application.ProductVersion; - GoogleOgcs.ErrorReporting.UpdateLogUuId(); + Ogcs.Google.ErrorReporting.LogId = "v" + Application.ProductVersion; + Ogcs.Google.ErrorReporting.UpdateLogUuId(); XmlConfigurator.Configure(new System.IO.FileInfo( Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), logSettingsFile) )); - GoogleOgcs.ErrorReporting.SetThreshold(false); + Ogcs.Google.ErrorReporting.SetThreshold(false); if (bootstrap) { log.Info("Program started: v" + Application.ProductVersion); @@ -464,7 +465,7 @@ private static void moveFiles(string srcDir, string dstDir) { WorkingFilesDirectory = dstDir; foreach (string file in Directory.GetFiles(srcDir)) { - if (Path.GetFileName(file).StartsWith("OGcalsync.log") || file.EndsWith(".csv") || file.EndsWith(".json") || file == GoogleOgcs.Authenticator.TokenFile) { + if (Path.GetFileName(file).StartsWith("OGcalsync.log") || file.EndsWith(".csv") || file.EndsWith(".json") || file == Ogcs.Google.Authenticator.TokenFile) { dstFile = Path.Combine(dstDir, Path.GetFileName(file)); File.Delete(dstFile); log.Debug(" " + Path.GetFileName(file)); diff --git a/src/OutlookGoogleCalendarSync/Recurrence.cs b/src/OutlookGoogleCalendarSync/Recurrence.cs index 140aa3f3..6ccd0a1e 100644 --- a/src/OutlookGoogleCalendarSync/Recurrence.cs +++ b/src/OutlookGoogleCalendarSync/Recurrence.cs @@ -1,4 +1,5 @@ -using Google.Apis.Calendar.v3.Data; +using Ogcs = OutlookGoogleCalendarSync; +using Google.Apis.Calendar.v3.Data; using log4net; using Microsoft.Office.Interop.Outlook; using System; @@ -151,7 +152,7 @@ private void buildOutlookPattern(Event ev, AppointmentItem ai, out RecurrencePat if (endDate < oPattern.PatternStartDate) { log.Debug("PatternStartDate: " + oPattern.PatternStartDate.ToString("yyyyMMddHHmmss")); log.Debug("PatternEndDate: " + ruleBook["UNTIL"].ToString()); - String summary = GoogleOgcs.Calendar.GetEventSummary("The recurring Google event has an end date before the start date, which Outlook doesn't allow.
" + + String summary = Ogcs.Google.Calendar.GetEventSummary("The recurring Google event has an end date before the start date, which Outlook doesn't allow.
" + "The synced Outlook recurrence has been changed to a single occurrence.", ev, out String anonSummary, onlyIfNotVerbose: true); Forms.Main.Instance.Console.Update(summary, anonSummary, Console.Markup.warning); oPattern.Occurrences = 1; @@ -399,7 +400,7 @@ public Boolean HasExceptions(Event ev, Boolean checkLocalCacheOnly = false) { //Therefore, you'd have to GetCalendarEntriesInRange() with no date range, then filter to the recurringEventId - not efficient! //So...will make it only sync exceptions within the sync date range, which we have cached already //if (!checkLocalCacheOnly) { - // List gInstances = GoogleOgcs.Calendar.Instance.GetCalendarEntriesInRecurrence(ev.RecurringEventId ?? ev.Id); + // List gInstances = Ogcs.Google.Calendar.Instance.GetCalendarEntriesInRecurrence(ev.RecurringEventId ?? ev.Id); // //Add any new exceptions to local cache // googleExceptions = googleExceptions.Union(gInstances.Where(exp => exp.Sequence > 0)).ToList(); //} @@ -478,7 +479,7 @@ private Event getGoogleInstance(Microsoft.Office.Interop.Outlook.Exception oExcp } log.Debug("Google exception event is not cached. Retrieving all recurring instances..."); } - List gInstances = GoogleOgcs.Calendar.Instance.GetCalendarEntriesInRecurrence(gRecurringEventID); + List gInstances = Ogcs.Google.Calendar.Instance.GetCalendarEntriesInRecurrence(gRecurringEventID); if (gInstances == null) return null; //Add any new exceptions to local cache @@ -506,7 +507,7 @@ public Event GetGoogleMasterEvent(AppointmentItem ai) { String googleIdValue = Outlook.CustomProperty.Get(ai, Outlook.CustomProperty.MetadataId.gEventID); String googleCalValue = Outlook.CustomProperty.Get(ai, Outlook.CustomProperty.MetadataId.gCalendarId); if (googleCalValue == null || googleCalValue == Sync.Engine.Calendar.Instance.Profile.UseGoogleCalendar.Id) { - Event ev = GoogleOgcs.Calendar.Instance.GetCalendarEntry(googleIdValue); + Event ev = Ogcs.Google.Calendar.Instance.GetCalendarEntry(googleIdValue); if (ev != null) { events.Add(ev); haveMatchingEv = true; @@ -515,21 +516,21 @@ public Event GetGoogleMasterEvent(AppointmentItem ai) { } } if (!haveMatchingEv) { - events = GoogleOgcs.Calendar.Instance.GetCalendarEntriesInRange(ai.Start.Date, ai.Start.Date.AddDays(1)); + events = Ogcs.Google.Calendar.Instance.GetCalendarEntriesInRange(ai.Start.Date, ai.Start.Date.AddDays(1)); if (Sync.Engine.Calendar.Instance.Profile.SyncDirection.Id != Sync.Direction.GoogleToOutlook.Id) { List ais = new List(); ais.Add(ai); - GoogleOgcs.Calendar.Instance.ReclaimOrphanCalendarEntries(ref events, ref ais, neverDelete: true); + Ogcs.Google.Calendar.Instance.ReclaimOrphanCalendarEntries(ref events, ref ais, neverDelete: true); } } for (int g = 0; g < events.Count(); g++) { Event ev = events[g]; - String gEntryID = GoogleOgcs.CustomProperty.Get(ev, GoogleOgcs.CustomProperty.MetadataId.oEntryId); + String gEntryID = Ogcs.Google.CustomProperty.Get(ev, Ogcs.Google.CustomProperty.MetadataId.oEntryId); if (haveMatchingEv || !string.IsNullOrEmpty(gEntryID)) { if (haveMatchingEv && string.IsNullOrEmpty(gEntryID)) { return ev; } - if (GoogleOgcs.CustomProperty.OutlookIdMissing(ev)) { + if (Ogcs.Google.CustomProperty.OutlookIdMissing(ev)) { String compare_oID; if (!string.IsNullOrEmpty(gEntryID) && gEntryID.StartsWith(Outlook.Calendar.GlobalIdPattern)) { //We got a Global ID, not Entry ID compare_oID = Outlook.Calendar.Instance.IOutlook.GetGlobalApptID(ai); @@ -538,21 +539,21 @@ public Event GetGoogleMasterEvent(AppointmentItem ai) { } if (haveMatchingEv || gEntryID == compare_oID) { log.Info("Adding Outlook IDs to Master Google Event..."); - GoogleOgcs.CustomProperty.AddOutlookIDs(ref ev, ai); + Ogcs.Google.CustomProperty.AddOutlookIDs(ref ev, ai); try { - GoogleOgcs.Calendar.Instance.UpdateCalendarEntry_save(ref ev); + Ogcs.Google.Calendar.Instance.UpdateCalendarEntry_save(ref ev); } catch (System.Exception ex) { OGCSexception.Analyse("Failed saving Outlook IDs to Google Event.", ex, true); } return ev; } - } else if (GoogleOgcs.Calendar.ItemIDsMatch(ref ev, ai)) { + } else if (Ogcs.Google.Calendar.ItemIDsMatch(ref ev, ai)) { log.Fine("Found master event."); return ev; } } else { log.Debug("Event \"" + ev.Summary + "\" does not have Outlook EntryID stored."); - if (GoogleOgcs.Calendar.SignaturesMatch(GoogleOgcs.Calendar.signature(ev), Outlook.Calendar.signature(ai))) { + if (Ogcs.Google.Calendar.SignaturesMatch(Ogcs.Google.Calendar.signature(ev), Outlook.Calendar.signature(ai))) { log.Debug("Master event matched on simple signatures."); return ev; } @@ -566,7 +567,7 @@ public static void CreateGoogleExceptions(AppointmentItem ai, String recurringEv if (!ai.IsRecurring) return; log.Debug("Creating Google recurrence exceptions."); - List gRecurrences = GoogleOgcs.Calendar.Instance.GetCalendarEntriesInRecurrence(recurringEventId); + List gRecurrences = Ogcs.Google.Calendar.Instance.GetCalendarEntriesInRecurrence(recurringEventId); if (gRecurrences == null) return; RecurrencePattern rp = null; @@ -603,7 +604,7 @@ public static void CreateGoogleExceptions(AppointmentItem ai, String recurringEv ai2 = oExcp2.AppointmentItem; if (oExcp.OriginalDate.Date == oExcp2.OriginalDate.Date && oExcp.OriginalDate.Date != ai2.Start.Date) { //It's an additional exception which has the same original start date, but was moved - log.Warn(GoogleOgcs.Calendar.GetEventSummary(ev)); + log.Warn(Ogcs.Google.Calendar.GetEventSummary(ev)); log.Warn("This item is not really deleted, but moved to another date in Outlook on "+ ai2.Start.Date.ToString("dd-MMM-yyyy")); skipDelete = true; log.Fine("Now checking if there is a Google item on that date - we don't want a duplicate."); @@ -611,7 +612,7 @@ public static void CreateGoogleExceptions(AppointmentItem ai, String recurringEv if (duplicate != null) { log.Warn("Determined a 'duplicate' exists on that date - this will be deleted."); duplicate.Status = "cancelled"; - GoogleOgcs.Calendar.Instance.UpdateCalendarEntry_save(ref duplicate); + Ogcs.Google.Calendar.Instance.UpdateCalendarEntry_save(ref duplicate); } break; } @@ -627,22 +628,22 @@ public static void CreateGoogleExceptions(AppointmentItem ai, String recurringEv } if (!skipDelete) { log.Fine("None found."); - Forms.Main.Instance.Console.Update(GoogleOgcs.Calendar.GetEventSummary("
Occurrence deleted.", ev, out String anonSummary), anonSummary, Console.Markup.calendar, verbose: true); + Forms.Main.Instance.Console.Update(Ogcs.Google.Calendar.GetEventSummary("
Occurrence deleted.", ev, out String anonSummary), anonSummary, Console.Markup.calendar, verbose: true); ev.Status = "cancelled"; - GoogleOgcs.Calendar.Instance.UpdateCalendarEntry_save(ref ev); + Ogcs.Google.Calendar.Instance.UpdateCalendarEntry_save(ref ev); } } else { int exceptionItemsModified = 0; - Event modifiedEv = GoogleOgcs.Calendar.Instance.UpdateCalendarEntry(oExcp.AppointmentItem, ev, ref exceptionItemsModified, forceCompare: true); + Event modifiedEv = Ogcs.Google.Calendar.Instance.UpdateCalendarEntry(oExcp.AppointmentItem, ev, ref exceptionItemsModified, forceCompare: true); if (exceptionItemsModified > 0) { - GoogleOgcs.Calendar.Instance.UpdateCalendarEntry_save(ref modifiedEv); + Ogcs.Google.Calendar.Instance.UpdateCalendarEntry_save(ref modifiedEv); if (oExcp.OriginalDate.Date != oExcp.AppointmentItem.Start.Date) { log.Fine("Double checking there is no other Google item on " + oExcp.AppointmentItem.Start.Date.ToString("dd-MMM-yyyy") + " that " + oExcp.OriginalDate.Date.ToString("dd-MMM-yyyy") + " was moved to - we don't want a duplicate."); Event duplicate = gRecurrences.FirstOrDefault(g => oExcp.AppointmentItem.Start.Date == g.OriginalStartTime.SafeDateTime().Date); if (duplicate != null && duplicate.Status != "cancelled") { log.Warn("Determined a 'duplicate' exists on that date - this will be deleted."); duplicate.Status = "cancelled"; - GoogleOgcs.Calendar.Instance.UpdateCalendarEntry_save(ref duplicate); + Ogcs.Google.Calendar.Instance.UpdateCalendarEntry_save(ref duplicate); } } } @@ -730,7 +731,7 @@ public static void UpdateGoogleExceptions(AppointmentItem ai, Event ev, Boolean dr = OgcsMessageBox.Show(msg, "Confirm deletion of recurring series occurrence", MessageBoxButtons.YesNo, MessageBoxIcon.Question, msg.Replace(summary, anonSummary)); } if (dr == DialogResult.Yes) { - Forms.Main.Instance.Console.Update(GoogleOgcs.Calendar.GetEventSummary("
Occurrence deleted.", gExcp, out String anonSummary2), anonSummary2, Console.Markup.calendar, verbose: true); + Forms.Main.Instance.Console.Update(Ogcs.Google.Calendar.GetEventSummary("
Occurrence deleted.", gExcp, out String anonSummary2), anonSummary2, Console.Markup.calendar, verbose: true); gExcp.Status = "cancelled"; log.Debug("Exception deleted."); excp_itemModified++; @@ -742,12 +743,12 @@ public static void UpdateGoogleExceptions(AppointmentItem ai, Event ev, Boolean TimeSpan modifiedDiff = (TimeSpan)(gExcp.Updated - aiExcp.LastModificationTime); log.Fine("Modification time difference (in days) between G and O exception: " + modifiedDiff); Boolean forceCompare = modifiedDiff < TimeSpan.FromDays(1); - GoogleOgcs.Calendar.Instance.UpdateCalendarEntry(aiExcp, gExcp, ref excp_itemModified, forceCompare); + Ogcs.Google.Calendar.Instance.UpdateCalendarEntry(aiExcp, gExcp, ref excp_itemModified, forceCompare); if (forceCompare && excp_itemModified == 0 && DateTime.Now > aiExcp.LastModificationTime.AddDays(1)) { - GoogleOgcs.CustomProperty.SetOGCSlastModified(ref gExcp); + Ogcs.Google.CustomProperty.SetOGCSlastModified(ref gExcp); try { log.Debug("Doing a dummy update in order to update the last modified date of Google recurring series exception."); - GoogleOgcs.Calendar.Instance.UpdateCalendarEntry_save(ref gExcp); + Ogcs.Google.Calendar.Instance.UpdateCalendarEntry_save(ref gExcp); } catch (System.Exception ex) { OGCSexception.Analyse("Dummy update of unchanged exception for Google recurring series failed.", ex); } @@ -760,9 +761,9 @@ public static void UpdateGoogleExceptions(AppointmentItem ai, Event ev, Boolean } if (excp_itemModified > 0) { try { - GoogleOgcs.Calendar.Instance.UpdateCalendarEntry_save(ref gExcp); + Ogcs.Google.Calendar.Instance.UpdateCalendarEntry_save(ref gExcp); } catch (System.Exception ex) { - Forms.Main.Instance.Console.UpdateWithError(GoogleOgcs.Calendar.GetEventSummary("Updated event exception failed to save.", gExcp, out String anonSummary, true), ex, logEntry: anonSummary); + Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("Updated event exception failed to save.", gExcp, out String anonSummary, true), ex, logEntry: anonSummary); OGCSexception.Analyse(ex, true); if (OgcsMessageBox.Show("Updated Google event exception failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; @@ -864,7 +865,7 @@ private void processOutlookExceptions(ref AppointmentItem ai, List evExce log.Warn("Unable to find Outlook exception for " + gExcpOrigDate.ToString() + " now on " + gExcpCurrDate?.Date.ToString()); log.Warn("Google is NOT deleted though - a mismatch has occurred somehow!"); String syncDirectionTip = (Sync.Engine.Calendar.Instance.Profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id) ? "
Ensure you first set OGCS to one-way sync G->O." : ""; - Forms.Main.Instance.Console.Update(GoogleOgcs.Calendar.GetEventSummary( + Forms.Main.Instance.Console.Update(Ogcs.Google.Calendar.GetEventSummary( "
This occurrence cannot be found in Outlook.
" + "This can happen if, for example, the occurrence has been rearranged to different days more than once.
" + "Suggested fix: delete the entire series in Google and let OGCS recreate it." + syncDirectionTip, gExcp, out String anonSummary), diff --git a/src/OutlookGoogleCalendarSync/SettingsStore/Calendar.cs b/src/OutlookGoogleCalendarSync/SettingsStore/Calendar.cs index ac36367f..eb420b16 100644 --- a/src/OutlookGoogleCalendarSync/SettingsStore/Calendar.cs +++ b/src/OutlookGoogleCalendarSync/SettingsStore/Calendar.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using System; using System.Collections.Generic; using System.Linq; @@ -313,7 +314,7 @@ public void LogSettings() { log.Fail(" Using Outlook2003 - categories not supported, although mapping exists"); else ColourMaps.ToList().ForEach(c => log.Info(" " + Outlook.Calendar.Categories.OutlookColour(c.Key) + ":" + c.Key + " <=> " + - c.Value + ":" + GoogleOgcs.EventColour.Palette.GetColourName(c.Value))); + c.Value + ":" + Ogcs.Google.EventColour.Palette.GetColourName(c.Value))); } log.Info(" SingleCategoryOnly: " + SingleCategoryOnly); log.Info(" Obfuscate Words: " + Obfuscation.Enabled); diff --git a/src/OutlookGoogleCalendarSync/SettingsStore/Settings.cs b/src/OutlookGoogleCalendarSync/SettingsStore/Settings.cs index 88ac5d28..e6c3d9b9 100644 --- a/src/OutlookGoogleCalendarSync/SettingsStore/Settings.cs +++ b/src/OutlookGoogleCalendarSync/SettingsStore/Settings.cs @@ -1,7 +1,7 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using System; using System.Collections.Generic; -using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.Serialization; @@ -114,7 +114,7 @@ public void SetDefaults() { alphaReleases = !System.Windows.Forms.Application.ProductVersion.EndsWith("0.0"); SkipVersion = null; - subscribed = GoogleOgcs.Authenticator.SubscribedNever; + subscribed = Ogcs.Google.Authenticator.SubscribedNever; donor = false; hideSplashScreen = null; suppressSocialPopup = false; @@ -242,8 +242,8 @@ [DataMember] public bool? CloudLogging { get { return cloudLogging; } set { cloudLogging = value; - GoogleOgcs.ErrorReporting.SetThreshold(value ?? false); - if (value == null) GoogleOgcs.ErrorReporting.ErrorOccurred = false; + Ogcs.Google.ErrorReporting.SetThreshold(value ?? false); + if (value == null) Ogcs.Google.ErrorReporting.ErrorOccurred = false; if (!Loading()) XMLManager.ExportElement(this, "CloudLogging", value, ConfigFile); } } @@ -271,7 +271,7 @@ [DataMember] public bool AlphaReleases { } } public Boolean UserIsBenefactor() { - return Subscribed != GoogleOgcs.Authenticator.SubscribedNever || donor; + return Subscribed != Ogcs.Google.Authenticator.SubscribedNever || donor; } [DataMember] public DateTime Subscribed { get { return subscribed; } diff --git a/src/OutlookGoogleCalendarSync/Sync/Calendar.cs b/src/OutlookGoogleCalendarSync/Sync/Calendar.cs index 9a5fc14b..73cf9f6e 100644 --- a/src/OutlookGoogleCalendarSync/Sync/Calendar.cs +++ b/src/OutlookGoogleCalendarSync/Sync/Calendar.cs @@ -1,4 +1,5 @@ -using Google.Apis.Calendar.v3.Data; +using Ogcs = OutlookGoogleCalendarSync; +using Google.Apis.Calendar.v3.Data; using log4net; using Microsoft.Office.Interop.Outlook; using System; @@ -79,7 +80,7 @@ public void StartSync(Boolean manualIgnition, Boolean updateSyncSchedule = true) OGCSexception.Analyse(ex, true); return; } - GoogleOgcs.Calendar.APIlimitReached_attendee = false; + Ogcs.Google.Calendar.APIlimitReached_attendee = false; this.Profile.OgcsTimer.NextSyncDateText = "In progress..."; @@ -266,10 +267,10 @@ private void skipCorruptedItem(ref List outlookEntries, Appoint if (string.IsNullOrEmpty(itemSummary)) { try { itemSummary = cai.Start.Date.ToShortDateString() + " => " + cai.Subject; - anonSummary = cai.Start.Date.ToShortDateString() + " => " + GoogleOgcs.Authenticator.GetMd5(cai.Subject); + anonSummary = cai.Start.Date.ToShortDateString() + " => " + Ogcs.Google.Authenticator.GetMd5(cai.Subject); } catch { itemSummary = cai.Subject; - anonSummary = GoogleOgcs.Authenticator.GetMd5(cai.Subject); + anonSummary = Ogcs.Google.Authenticator.GetMd5(cai.Subject); } } String message = "

" + itemSummary + "

There is problem with this item - it will not be synced.

" + errMsg + "

"; @@ -292,8 +293,8 @@ private SyncResult synchronize() { List outlookEntries = null; List googleEntries = null; - if (!GoogleOgcs.Calendar.IsInstanceNull) - GoogleOgcs.Calendar.Instance.EphemeralProperties.Clear(); + if (!Ogcs.Google.Calendar.IsInstanceNull) + Ogcs.Google.Calendar.Instance.EphemeralProperties.Clear(); Outlook.Calendar.Instance.EphemeralProperties.Clear(); try { @@ -309,11 +310,11 @@ private SyncResult synchronize() { #region Read Google items console.Update("Scanning Google calendar..."); try { - GoogleOgcs.Calendar.Instance.GetSettings(); - googleEntries = GoogleOgcs.Calendar.Instance.GetCalendarEntriesInRange(); + Ogcs.Google.Calendar.Instance.GetSettings(); + googleEntries = Ogcs.Google.Calendar.Instance.GetCalendarEntriesInRange(); } catch (AggregateException agex) { OGCSexception.AnalyseAggregate(agex); - } catch (Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { + } catch (global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { OGCSexception.AnalyseTokenResponse(ex, false); return SyncResult.Fail; } catch (System.Net.Http.HttpRequestException ex) { @@ -324,7 +325,7 @@ private SyncResult synchronize() { ex.Data.Add("OGCS", "ERROR: Unable to connect to the Google calendar. Please try again. " + ((ex.InnerException != null) ? ex.InnerException.Message : ex.Message)); throw; } catch (System.ApplicationException ex) { - if (ex.InnerException != null && ex.InnerException is Google.GoogleApiException && + if (ex.InnerException != null && ex.InnerException is global::Google.GoogleApiException && (ex.Message.Contains("daily Calendar quota has been exhausted") || OGCSexception.GetErrorCode(ex.InnerException) == "0x80131500")) { Forms.Main.Instance.Console.Update(ex.Message, Console.Markup.warning); DateTime newQuota = DateTime.UtcNow.Date.AddHours(8); @@ -468,7 +469,7 @@ private SyncResult synchronize() { } console.Update("Outlook " + outlookEntries.Count + ", Google " + googleEntries.Count); - GoogleOgcs.Calendar.ExportToCSV("Outputting all Events.", "google_events.csv", googleEntries); + Ogcs.Google.Calendar.ExportToCSV("Outputting all Events.", "google_events.csv", googleEntries); Outlook.Calendar.ExportToCSV("Outputting all Appointments.", "outlook_appointments.csv", outlookEntries); if (Sync.Engine.Instance.CancellationPending) return SyncResult.UserCancelled; #endregion @@ -480,7 +481,7 @@ private SyncResult synchronize() { } //Reclaim orphans - GoogleOgcs.Calendar.Instance.ReclaimOrphanCalendarEntries(ref googleEntries, ref outlookEntries); + Ogcs.Google.Calendar.Instance.ReclaimOrphanCalendarEntries(ref googleEntries, ref outlookEntries); if (Sync.Engine.Instance.CancellationPending) return SyncResult.UserCancelled; Outlook.Calendar.Instance.ReclaimOrphanCalendarEntries(ref outlookEntries, ref googleEntries); @@ -544,7 +545,7 @@ private Boolean outlookToGoogle(List outlookEntries, List outlookEntries, List outlookEntries, List 0) { console.Update("Deleting " + googleEntriesToBeDeleted.Count + " Google calendar entries", Console.Markup.h2, newLine: false); try { - GoogleOgcs.Calendar.Instance.DeleteCalendarEntries(googleEntriesToBeDeleted); + Ogcs.Google.Calendar.Instance.DeleteCalendarEntries(googleEntriesToBeDeleted); } catch (UserCancelledSyncException ex) { log.Info(ex.Message); return false; @@ -607,7 +608,7 @@ private Boolean outlookToGoogle(List outlookEntries, List 0) { console.Update("Creating " + googleEntriesToBeCreated.Count + " Google calendar entries", Console.Markup.h2, newLine: false); try { - GoogleOgcs.Calendar.Instance.CreateCalendarEntries(googleEntriesToBeCreated); + Ogcs.Google.Calendar.Instance.CreateCalendarEntries(googleEntriesToBeCreated); } catch (UserCancelledSyncException ex) { log.Info(ex.Message); return false; @@ -625,7 +626,7 @@ private Boolean outlookToGoogle(List outlookEntries, List 0) { console.Update("Comparing " + entriesToBeCompared.Count + " existing Google calendar entries", Console.Markup.h2, newLine: false); try { - GoogleOgcs.Calendar.Instance.UpdateCalendarEntries(entriesToBeCompared, ref entriesUpdated); + Ogcs.Google.Calendar.Instance.UpdateCalendarEntries(entriesToBeCompared, ref entriesUpdated); } catch (UserCancelledSyncException ex) { log.Info(ex.Message); return false; @@ -791,10 +792,10 @@ private SyncResult extirpateCustomProperties(List outlookEntrie console.Update("Cleansing OGCS metadata from Google items...", Console.Markup.h2, newLine: false); for (int g = 0; g < googleEntries.Count; g++) { Event ev = googleEntries[g]; - GoogleOgcs.CustomProperty.LogProperties(ev, log4net.Core.Level.Debug); - if (GoogleOgcs.CustomProperty.Extirpate(ref ev)) { - console.Update(GoogleOgcs.Calendar.GetEventSummary(ev, out String anonSummary), anonSummary, Console.Markup.calendar); - GoogleOgcs.Calendar.Instance.UpdateCalendarEntry_save(ref ev); + Ogcs.Google.CustomProperty.LogProperties(ev, log4net.Core.Level.Debug); + if (Ogcs.Google.CustomProperty.Extirpate(ref ev)) { + console.Update(Ogcs.Google.Calendar.GetEventSummary(ev, out String anonSummary), anonSummary, Console.Markup.calendar); + Ogcs.Google.Calendar.Instance.UpdateCalendarEntry_save(ref ev); } if (Sync.Engine.Instance.CancellationPending) return SyncResult.UserCancelled; } diff --git a/src/OutlookGoogleCalendarSync/Sync/Engine.cs b/src/OutlookGoogleCalendarSync/Sync/Engine.cs index 357e4a36..fb823b4e 100644 --- a/src/OutlookGoogleCalendarSync/Sync/Engine.cs +++ b/src/OutlookGoogleCalendarSync/Sync/Engine.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using System; using System.Collections.Generic; using System.Linq; @@ -174,7 +175,7 @@ public void Sync_Requested(object sender = null, EventArgs e = null) { Start(manualIgnition: true, updateSyncSchedule: false); } else if (Forms.Main.Instance.bSyncNow.Text == "Stop Sync") { - GoogleOgcs.Calendar.Instance.Authenticator.CancelTokenSource.Cancel(); + Ogcs.Google.Calendar.Instance.Authenticator.CancelTokenSource.Cancel(); if (!SyncingNow) return; if (!bwSync.CancellationPending) { diff --git a/src/OutlookGoogleCalendarSync/Telemetry.cs b/src/OutlookGoogleCalendarSync/Telemetry.cs index d1cc2c35..8af3a20a 100644 --- a/src/OutlookGoogleCalendarSync/Telemetry.cs +++ b/src/OutlookGoogleCalendarSync/Telemetry.cs @@ -1,9 +1,9 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using System; using System.Collections.Generic; using System.Management; using System.Net; -using System.Text.RegularExpressions; using System.Threading.Tasks; namespace OutlookGoogleCalendarSync { @@ -31,7 +31,7 @@ public String UpdateAnonymousUniqueUserId() { try { if (Settings.AreLoaded && !string.IsNullOrEmpty(Settings.Instance.GaccountEmail)) { log.Debug("Settings have been loaded, which contains Gmail account."); - uuId = GoogleOgcs.Authenticator.GetMd5(Settings.Instance.GaccountEmail, true); + uuId = Ogcs.Google.Authenticator.GetMd5(Settings.Instance.GaccountEmail, true); } else { log.Debug("Settings not loaded; checking if the raw settings file has Gmail account set."); @@ -42,7 +42,7 @@ public String UpdateAnonymousUniqueUserId() { if (!string.IsNullOrEmpty(gmailAccount)) { log.Fine("Gmail account found in settings files."); - uuId = GoogleOgcs.Authenticator.GetMd5(gmailAccount, true); + uuId = Ogcs.Google.Authenticator.GetMd5(gmailAccount, true); } else { log.Warn("No Gmail account found, building custom thumbprint instead."); String customThumbprint = ""; @@ -61,7 +61,7 @@ public String UpdateAnonymousUniqueUserId() { String volumeSerial = dsk["VolumeSerialNumber"].ToString(); customThumbprint += ";" + volumeSerial; - uuId = GoogleOgcs.Authenticator.GetMd5(customThumbprint); + uuId = Ogcs.Google.Authenticator.GetMd5(customThumbprint); } } From eca639797360704dc53dad3085d6b492e557e442 Mon Sep 17 00:00:00 2001 From: Paul Woolcock <11843015+phw198@users.noreply.github.com> Date: Sun, 28 Apr 2024 12:26:52 +0100 Subject: [PATCH 3/8] Code refactor under OutlookGoogleCalendarSync.Exception namespace --- .../Console/Console.cs | 12 +- src/OutlookGoogleCalendarSync/EmailAddress.cs | 5 +- .../Extensions/ColourPicker.cs | 10 +- .../Extensions/Exception.cs | 33 +++--- .../Extensions/ILogExtension.cs | 2 +- .../Extensions/NumericUpDown.cs | 5 +- .../Forms/ColourMap.cs | 28 ++--- .../Forms/ErrorReporting.cs | 5 +- .../Forms/MainForm.cs | 52 ++++---- .../Forms/ProfileManage.cs | 16 +-- .../Forms/TimezoneMap.cs | 15 +-- .../Forms/UpdateInfo.cs | 7 +- .../Google/ApiKeyring.cs | 4 +- .../Google/Authenticator.cs | 32 ++--- .../Google/CustomProperty.cs | 2 +- .../Google/ErrorReporting.cs | 9 +- .../Google/EventAttendee.cs | 5 +- .../Google/EventColour.cs | 16 +-- src/OutlookGoogleCalendarSync/Google/GMeet.cs | 5 +- .../Google/GoogleCalendar.cs | 112 +++++++++--------- src/OutlookGoogleCalendarSync/Helper.cs | 7 +- .../NotificationTray.cs | 15 +-- .../Outlook.Factory/OutlookFactory.cs | 9 +- .../Outlook.Factory/OutlookNew.cs | 41 +++---- .../Outlook.Factory/OutlookOld.cs | 23 ++-- .../Outlook/CustomProperty.cs | 11 +- .../Outlook/ExplorerWatcher.cs | 27 +++-- .../Outlook/GMeet.cs | 5 +- .../Outlook/OutlookCalendar.cs | 70 +++++------ .../Outlook/OutlookCategories.cs | 14 +-- .../Outlook/OutlookErrors.cs | 7 +- src/OutlookGoogleCalendarSync/Program.cs | 18 +-- src/OutlookGoogleCalendarSync/Recurrence.cs | 20 ++-- .../SettingsStore/Proxy.cs | 13 +- .../SettingsStore/Settings.cs | 2 +- .../SettingsStore/Upgrade.cs | 13 +- .../Sync/Calendar.cs | 40 +++---- src/OutlookGoogleCalendarSync/Sync/Engine.cs | 4 +- src/OutlookGoogleCalendarSync/Sync/Timer.cs | 9 +- src/OutlookGoogleCalendarSync/Telemetry.cs | 6 +- src/OutlookGoogleCalendarSync/TimezoneDB.cs | 15 +-- src/OutlookGoogleCalendarSync/Updater.cs | 39 +++--- src/OutlookGoogleCalendarSync/XMLManager.cs | 31 ++--- 43 files changed, 416 insertions(+), 398 deletions(-) diff --git a/src/OutlookGoogleCalendarSync/Console/Console.cs b/src/OutlookGoogleCalendarSync/Console/Console.cs index cd201abe..a3ddacd0 100644 --- a/src/OutlookGoogleCalendarSync/Console/Console.cs +++ b/src/OutlookGoogleCalendarSync/Console/Console.cs @@ -310,7 +310,7 @@ public void Update(String moreOutput, Markup? markupPrefix = null, bool newLine } else this.wb.DocumentText = content; } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } while (navigationStatus != NavigationStatus.completed) { @@ -328,9 +328,9 @@ public void Update(String moreOutput, Markup? markupPrefix = null, bool newLine public void UpdateWithError(String moreOutput, System.Exception ex, bool notifyBubble = false, String logEntry = null) { Markup emoji = Markup.error; - if (OGCSexception.LoggingAsFail(ex)) + if (Ogcs.Exception.LoggingAsFail(ex)) emoji = Markup.fail; - Update(moreOutput + (!string.IsNullOrEmpty(moreOutput) ? "
" : "") + OGCSexception.FriendlyMessage(ex), logEntry, emoji, notifyBubble: notifyBubble); + Update(moreOutput + (!string.IsNullOrEmpty(moreOutput) ? "
" : "") + Ogcs.Exception.FriendlyMessage(ex), logEntry, emoji, notifyBubble: notifyBubble); } /// Log the output sans HTML tags. @@ -389,7 +389,7 @@ private String parseEmoji(String output, Markup? markupPrefix = null) { } catch (System.Exception ex) { log.Error("Failed parsing for emoji."); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } return output; } @@ -471,7 +471,7 @@ public static void MuteClicks(Boolean mute) { log.Warn("Could not find default navigation sound registry key."); } } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } #endregion @@ -486,7 +486,7 @@ public void CallGappScript() { System.Threading.Thread.Sleep(100); } } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } log.Debug("Done"); */ diff --git a/src/OutlookGoogleCalendarSync/EmailAddress.cs b/src/OutlookGoogleCalendarSync/EmailAddress.cs index e453431f..2e8b8e90 100644 --- a/src/OutlookGoogleCalendarSync/EmailAddress.cs +++ b/src/OutlookGoogleCalendarSync/EmailAddress.cs @@ -1,4 +1,5 @@ -using System; +using Ogcs = OutlookGoogleCalendarSync; +using System; using System.Globalization; using System.Text.RegularExpressions; using log4net; @@ -75,7 +76,7 @@ public static String MaskAddressWithinText(String sourceContainingEmailAddress) return sourceContainingEmailAddress.Replace(emailAddress, masked); } } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } return sourceContainingEmailAddress; } diff --git a/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs b/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs index cabe2f3e..4bb7999d 100644 --- a/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs +++ b/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs @@ -123,7 +123,7 @@ private void ColourPicker_Enter(object sender, EventArgs e) { } } } catch (System.Exception ex) { - OGCSexception.Analyse("ColourPicker_Enter()", ex); + Ogcs.Exception.Analyse("ColourPicker_Enter()", ex); } finally { loading.Hide(this); loading.RemoveAll(); @@ -234,7 +234,7 @@ protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.R } } } catch (System.Exception ex) { - OGCSexception.Analyse("OutlookColourComboboxCell.Paint()", ex); + Ogcs.Exception.Analyse("OutlookColourComboboxCell.Paint()", ex); } } } @@ -299,7 +299,7 @@ protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.R } } } catch (System.Exception ex) { - OGCSexception.Analyse("GoogleColourComboboxCell.Paint()", ex); + Ogcs.Exception.Analyse("GoogleColourComboboxCell.Paint()", ex); } } } @@ -425,7 +425,7 @@ public static void DrawComboboxItemColour(ComboBox cbColour, Brush boxColour, St if ((e.State & DrawItemState.NoFocusRect) == DrawItemState.None) e.DrawFocusRectangle(); } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } @@ -448,7 +448,7 @@ public static void DrawComboboxItemColour(Boolean comboEnabled, Brush boxColour, cellBounds.Y + ((cellBounds.Height - Control.DefaultFont.Height) / 2)); } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } } diff --git a/src/OutlookGoogleCalendarSync/Extensions/Exception.cs b/src/OutlookGoogleCalendarSync/Extensions/Exception.cs index 61ec3bd4..ecce03cd 100644 --- a/src/OutlookGoogleCalendarSync/Extensions/Exception.cs +++ b/src/OutlookGoogleCalendarSync/Extensions/Exception.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using System; using System.ComponentModel; using System.Linq; @@ -10,8 +11,8 @@ public UserCancelledSyncException(string message) : base(message) { } public UserCancelledSyncException(string message, System.Exception inner) : base(message, inner) { } } - class OGCSexception { - private static readonly ILog log = LogManager.GetLogger(typeof(OGCSexception)); + class Exception { + private static readonly ILog log = LogManager.GetLogger(typeof(Ogcs.Exception)); public static void Analyse(String warnDetail, System.Exception ex, Boolean includeStackTrace = false) { log.Warn(warnDetail); @@ -30,7 +31,7 @@ public static void Analyse(System.Exception ex, Boolean includeStackTrace = fals errorLocation += ex.TargetSite.Name + "() in "; System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(ex, true); String[] frameBits = st.GetFrame(0).ToString().Split('\\'); - if (frameBits.Count() == 1) throw new Exception(); + if (frameBits.Count() == 1) throw new System.Exception(); errorLocation += frameBits.LastOrDefault().Trim(); } catch { errorLocation += ""; @@ -132,9 +133,9 @@ private enum LogLevel { /// public static void LogAsFail(ref System.Exception ex) { if (ex.Data.Contains(LogAs)) - ex.Data[LogAs] = OGCSexception.LogLevel.FAIL; + ex.Data[LogAs] = Ogcs.Exception.LogLevel.FAIL; else - ex.Data.Add(LogAs, OGCSexception.LogLevel.FAIL); + ex.Data.Add(LogAs, Ogcs.Exception.LogLevel.FAIL); } /// /// Capture this exception as log4net FAIL (not ERROR) when logged @@ -149,9 +150,9 @@ public static System.Exception LogAsFail(System.Exception ex) { /// public static void LogAsFail(ref System.ApplicationException ex) { if (ex.Data.Contains(LogAs)) - ex.Data[LogAs] = OGCSexception.LogLevel.FAIL; + ex.Data[LogAs] = Ogcs.Exception.LogLevel.FAIL; else - ex.Data.Add(LogAs, OGCSexception.LogLevel.FAIL); + ex.Data.Add(LogAs, Ogcs.Exception.LogLevel.FAIL); } /// @@ -159,9 +160,9 @@ public static void LogAsFail(ref System.ApplicationException ex) { /// public static void LogAsFail(ref System.Runtime.InteropServices.COMException ex) { if (ex.Data.Contains(LogAs)) - ex.Data[LogAs] = OGCSexception.LogLevel.FAIL; + ex.Data[LogAs] = Ogcs.Exception.LogLevel.FAIL; else - ex.Data.Add(LogAs, OGCSexception.LogLevel.FAIL); + ex.Data.Add(LogAs, Ogcs.Exception.LogLevel.FAIL); } /// @@ -169,25 +170,25 @@ public static void LogAsFail(ref System.Runtime.InteropServices.COMException ex) /// public static void LogAsFail(ref System.NullReferenceException ex) { if (ex.Data.Contains(LogAs)) - ex.Data[LogAs] = OGCSexception.LogLevel.FAIL; + ex.Data[LogAs] = Ogcs.Exception.LogLevel.FAIL; else - ex.Data.Add(LogAs, OGCSexception.LogLevel.FAIL); + ex.Data.Add(LogAs, Ogcs.Exception.LogLevel.FAIL); } /// Capture this exception as log4net FAIL (not ERROR) when logged public static void LogAsFail(ref global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { if (ex.Data.Contains(LogAs)) - ex.Data[LogAs] = OGCSexception.LogLevel.FAIL; + ex.Data[LogAs] = Ogcs.Exception.LogLevel.FAIL; else - ex.Data.Add(LogAs, OGCSexception.LogLevel.FAIL); + ex.Data.Add(LogAs, Ogcs.Exception.LogLevel.FAIL); } /// Capture this exception as log4net FAIL (not ERROR) when logged public static void LogAsFail(ref global::Google.GoogleApiException ex) { if (ex.Data.Contains(LogAs)) - ex.Data[LogAs] = OGCSexception.LogLevel.FAIL; + ex.Data[LogAs] = Ogcs.Exception.LogLevel.FAIL; else - ex.Data.Add(LogAs, OGCSexception.LogLevel.FAIL); + ex.Data.Add(LogAs, Ogcs.Exception.LogLevel.FAIL); } /// diff --git a/src/OutlookGoogleCalendarSync/Extensions/ILogExtension.cs b/src/OutlookGoogleCalendarSync/Extensions/ILogExtension.cs index e084c8ca..0bd93a51 100644 --- a/src/OutlookGoogleCalendarSync/Extensions/ILogExtension.cs +++ b/src/OutlookGoogleCalendarSync/Extensions/ILogExtension.cs @@ -144,7 +144,7 @@ private void replayLogs() { } } catch (System.Exception ex) { log.Warn("Failed to replay logs."); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } } diff --git a/src/OutlookGoogleCalendarSync/Extensions/NumericUpDown.cs b/src/OutlookGoogleCalendarSync/Extensions/NumericUpDown.cs index 390165ab..8069f54b 100644 --- a/src/OutlookGoogleCalendarSync/Extensions/NumericUpDown.cs +++ b/src/OutlookGoogleCalendarSync/Extensions/NumericUpDown.cs @@ -1,4 +1,5 @@ -using System.Windows.Forms; +using Ogcs = OutlookGoogleCalendarSync; +using System.Windows.Forms; namespace OutlookGoogleCalendarSync.Extensions { public partial class OgcsNumericUpDown : NumericUpDown { @@ -34,7 +35,7 @@ private void checkLimit() { this.tooltip.RemoveAll(); } } catch (System.Exception ex) { - OGCSexception.Analyse(this.Name, ex); + Ogcs.Exception.Analyse(this.Name, ex); } } } diff --git a/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs b/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs index 35537458..4190f09f 100644 --- a/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs +++ b/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs @@ -57,7 +57,7 @@ private void loadConfig() { ddGoogleColour.SelectedIndex = 0; } catch (System.Exception ex) { - OGCSexception.Analyse("Populating gridview cells from Settings.", ex); + Ogcs.Exception.Analyse("Populating gridview cells from Settings.", ex); } } @@ -78,7 +78,7 @@ private void addRow(String outlookColour, String googleColour) { colourGridView.NotifyCurrentCellDirty(false); } catch (System.Exception ex) { - OGCSexception.Analyse("Adding colour/category map row #" + lastRow, ex); + Ogcs.Exception.Analyse("Adding colour/category map row #" + lastRow, ex); } } @@ -96,7 +96,7 @@ private void newRowNeeded() { colourGridView.CurrentCell = lastCell; } } catch (System.Exception ex) { - OGCSexception.Analyse("newRowNeeded(): Adding colour/category map row #" + lastRow, ex); + Ogcs.Exception.Analyse("newRowNeeded(): Adding colour/category map row #" + lastRow, ex); } finally { colourGridView.NotifyCurrentCellDirty(true); colourGridView.NotifyCurrentCellDirty(false); @@ -126,7 +126,7 @@ private void btOK_Click(object sender, EventArgs e) { return; } } catch (System.Exception ex) { - OGCSexception.Analyse("Failed looking for duplicating mappings before storing in Settings.", ex); + Ogcs.Exception.Analyse("Failed looking for duplicating mappings before storing in Settings.", ex); OgcsMessageBox.Show("An error was encountered storing your custom mappings.", "Cannot save mappings", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } @@ -139,13 +139,13 @@ private void btOK_Click(object sender, EventArgs e) { try { profile.ColourMaps.Add(row.Cells["OutlookColour"].Value.ToString(), Ogcs.Google.EventColour.Palette.GetColourId(row.Cells["GoogleColour"].Value.ToString())); } catch (System.ArgumentException ex) { - if (OGCSexception.GetErrorCode(ex) == "0x80070057") { + if (Ogcs.Exception.GetErrorCode(ex) == "0x80070057") { //An item with the same key has already been added } else throw; } } } catch (System.Exception ex) { - OGCSexception.Analyse("Could not save colour/category mappings to Settings.", ex); + Ogcs.Exception.Analyse("Could not save colour/category mappings to Settings.", ex); } finally { this.Close(); } @@ -157,7 +157,7 @@ private void btRemoveRow_Click(object sender, EventArgs e) { colourGridView.Rows.Remove(colourGridView.CurrentRow); } } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } @@ -172,7 +172,7 @@ private void colourGridView_CellClick(object sender, DataGridViewCellEventArgs e ((ComboBox)colourGridView.EditingControl).DroppedDown = true; } } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } @@ -192,7 +192,7 @@ private void colourGridView_EditingControlShowing(object sender, DataGridViewEdi } } } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } @@ -207,7 +207,7 @@ private void colourGridView_CellValueChanged(object sender, DataGridViewCellEven newRowNeeded(); } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } @@ -217,7 +217,7 @@ private void colourGridView_CellEnter(object sender, DataGridViewCellEventArgs e newRowNeeded(); } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } @@ -232,7 +232,7 @@ private void colourGridView_SelectionChanged(object sender, EventArgs e) { colourGridView.Rows[selectedRow].Selected = false; } } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } @@ -253,7 +253,7 @@ private void ddOutlookColour_SelectedIndexChanged(object sender, EventArgs e) { ddGoogleColour.SelectedIndex = Convert.ToInt16(Ogcs.Google.Calendar.Instance.GetColour(ddOutlookColour.SelectedItem.OutlookCategory).Id); } catch (System.Exception ex) { - OGCSexception.Analyse("ddOutlookColour_SelectedIndexChanged(): Could not update ddGoogleColour.", ex); + Ogcs.Exception.Analyse("ddOutlookColour_SelectedIndexChanged(): Could not update ddGoogleColour.", ex); } finally { ddGoogleColour.SelectedIndexChanged += ddGoogleColour_SelectedIndexChanged; } @@ -299,7 +299,7 @@ private void ddGoogleColour_SelectedIndexChanged(object sender, EventArgs e) { ddOutlookColour.SelectedIndex = 0; } catch (System.Exception ex) { - OGCSexception.Analyse("ddGoogleColour_SelectedIndexChanged(): Could not update ddOutlookColour.", ex); + Ogcs.Exception.Analyse("ddGoogleColour_SelectedIndexChanged(): Could not update ddOutlookColour.", ex); } finally { ddOutlookColour.SelectedIndexChanged += ddOutlookColour_SelectedIndexChanged; } diff --git a/src/OutlookGoogleCalendarSync/Forms/ErrorReporting.cs b/src/OutlookGoogleCalendarSync/Forms/ErrorReporting.cs index 5bc7e976..5f7164c6 100644 --- a/src/OutlookGoogleCalendarSync/Forms/ErrorReporting.cs +++ b/src/OutlookGoogleCalendarSync/Forms/ErrorReporting.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using System; using System.Collections.Generic; using System.IO; @@ -64,7 +65,7 @@ private void CloudLogging_Shown(object sender, EventArgs e) { btYes.Focus(); } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } diff --git a/src/OutlookGoogleCalendarSync/Forms/MainForm.cs b/src/OutlookGoogleCalendarSync/Forms/MainForm.cs index 63edb3d4..cf0090d5 100644 --- a/src/OutlookGoogleCalendarSync/Forms/MainForm.cs +++ b/src/OutlookGoogleCalendarSync/Forms/MainForm.cs @@ -323,7 +323,7 @@ public void UpdateGUIsettings_Profile() { folderIDs[theFolder.Name].Add(theFolder.EntryID); } } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to get EntryID for folder: " + theFolder.Name, OGCSexception.LogAsFail(ex)); + Ogcs.Exception.Analyse("Failed to get EntryID for folder: " + theFolder.Name, Ogcs.Exception.LogAsFail(ex)); } finally { theFolder = (MAPIFolder)Outlook.Calendar.ReleaseObject(theFolder); } @@ -595,7 +595,7 @@ public void UpdateGUIsettings_Profile() { #endregion #endregion } catch (System.Exception ex) { - OGCSexception.Analyse("Unable to set GUI profile.", ex); + Ogcs.Exception.Analyse("Unable to set GUI profile.", ex); throw; } finally { this.LoadingProfileConfig = false; @@ -610,7 +610,7 @@ public void FeaturesBlockedByCorpPolicy(Boolean isTrue) { ToolTips.SetToolTip(cbAddDescription, isTrue ? tooltip : ""); ToolTips.SetToolTip(rbOutlookSharedCal, isTrue ? tooltip : ""); } catch (System.InvalidOperationException ex) { - if (OGCSexception.GetErrorCode(ex) == "0x80131509") { //Cross-thread operation + if (Ogcs.Exception.GetErrorCode(ex) == "0x80131509") { //Cross-thread operation log.Warn("Can't set form tooltips from sync thread."); //Won't worry too much - will work fine on OGCS startup, and will only arrive here if GAL has been blocked *after* startup. Should be very unlikely. } @@ -706,13 +706,13 @@ private void buildAvailabilityDropdown() { ddAvailabilty.DataSource = new BindingSource(availability, null); ddAvailabilty.Enabled = profile.SetEntriesAvailable; } catch (System.Exception ex) { - OGCSexception.Analyse("Failed building availability dropdown values.", ex); + Ogcs.Exception.Analyse("Failed building availability dropdown values.", ex); return; } try { ddAvailabilty.SelectedValue = Enum.Parse(typeof(OlBusyStatus), profile.AvailabilityStatus); } catch (System.Exception ex) { - OGCSexception.Analyse("Failed selecting availability dropdown value from Settings.", ex); + Ogcs.Exception.Analyse("Failed selecting availability dropdown value from Settings.", ex); } finally { if (ddAvailabilty.SelectedIndex == -1 && ddAvailabilty.Items.Count > 0) ddAvailabilty.SelectedIndex = 0; @@ -724,14 +724,14 @@ public void Sync_Click(object sender, EventArgs e) { try { Sync.Engine.Instance.Sync_Requested(sender, e); } catch (System.AggregateException ex) { - OGCSexception.AnalyseAggregate(ex, false); + Ogcs.Exception.AnalyseAggregate(ex, false); } catch (System.ApplicationException ex) { if (ex.Message.ToLower().Contains("try again") && sender != null) { Sync_Click(null, null); } } catch (System.Exception ex) { console.UpdateWithError("Problem encountered during synchronisation.", ex); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); } finally { if (!Sync.Engine.Instance.SyncingNow) { bSyncNow.Text = "Start Sync"; @@ -972,7 +972,7 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { } catch (System.Exception ex) { log.Warn("Failed to process captured F1 key."); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); System.Diagnostics.Process.Start(Program.OgcsWebsite + "/guide"); return true; } @@ -980,7 +980,7 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { } catch (System.Exception ex) { log.Warn("Failed to process captured command key."); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } return base.ProcessCmdKey(ref msg, keyData); @@ -1048,7 +1048,7 @@ private void Console_KeyDown(object sender, PreviewKeyDownEventArgs e) { notLogFile(); } } catch (System.Exception ex) { - OGCSexception.Analyse("Console_KeyDown detected.", OGCSexception.LogAsFail(ex)); + Ogcs.Exception.Analyse("Console_KeyDown detected.", Ogcs.Exception.LogAsFail(ex)); } } @@ -1217,7 +1217,7 @@ private void ddProfile_SelectedIndexChanged(object sender, EventArgs e) { this.panelObscure.Visible = true; } } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } cal.SetActive(); break; @@ -1267,7 +1267,7 @@ private void miDeleteProfile_Click(object sender, EventArgs e) { Settings.Instance.Save(); } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to delete profile '" + profileName + "'.", ex); + Ogcs.Exception.Analyse("Failed to delete profile '" + profileName + "'.", ex); throw; } } @@ -1503,7 +1503,7 @@ private void btTestOutlookFilter_Click(object sender, EventArgs e) { log.Info(msg); OgcsMessageBox.Show(msg, "Date-Time Format Results", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (System.Exception ex) { - OGCSexception.Analyse("Profile '" + Settings.Profile.Name(ActiveCalendarProfile) + "', calendar ID " + ActiveCalendarProfile.UseOutlookCalendar.Id, ex); + Ogcs.Exception.Analyse("Profile '" + Settings.Profile.Name(ActiveCalendarProfile) + "', calendar ID " + ActiveCalendarProfile.UseOutlookCalendar.Id, ex); OgcsMessageBox.Show(ex.Message, "Unable to perform test", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -1541,12 +1541,12 @@ private void GetMyGoogleCalendars_Click(object sender, EventArgs e) { try { Ogcs.Google.Calendar.Instance.GetCalendars(); } catch (AggregateException agex) { - OGCSexception.AnalyseAggregate(agex, false); + Ogcs.Exception.AnalyseAggregate(agex, false); } catch (global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { - OGCSexception.AnalyseTokenResponse(ex, false); + Ogcs.Exception.AnalyseTokenResponse(ex, false); } catch (OperationCanceledException) { } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); OgcsMessageBox.Show("Failed to retrieve Google calendars.\r\n" + "Please check the output on the Sync tab for more details.", "Google calendar retrieval failed", MessageBoxButtons.OK, MessageBoxIcon.Error); @@ -1556,7 +1556,7 @@ private void GetMyGoogleCalendars_Click(object sender, EventArgs e) { console.BuildOutput(ex.Message, ref sb, false); console.Update(sb, Console.Markup.fail, logit: true); } else { - console.BuildOutput(OGCSexception.FriendlyMessage(ex), ref sb, false); + console.BuildOutput(Ogcs.Exception.FriendlyMessage(ex), ref sb, false); console.Update(sb, Console.Markup.error, logit: true); if (Settings.Instance.Proxy.Type == "IE") { if (OgcsMessageBox.Show("Please ensure you can access the internet with Internet Explorer.\r\n" + @@ -1973,7 +1973,7 @@ private void ddOutlookColour_SelectedIndexChanged(object sender, EventArgs e) { ddGoogleColour_SelectedIndexChanged(null, null); } catch (System.Exception ex) { - OGCSexception.Analyse("ddOutlookColour_SelectedIndexChanged(): Could not update ddGoogleColour.", ex); + Ogcs.Exception.Analyse("ddOutlookColour_SelectedIndexChanged(): Could not update ddGoogleColour.", ex); } finally { ddGoogleColour.SelectedIndexChanged += ddGoogleColour_SelectedIndexChanged; } @@ -2007,7 +2007,7 @@ private void ddGoogleColour_SelectedIndexChanged(object sender, EventArgs e) { ddOutlookColour_SelectedIndexChanged(null, null); } catch (System.Exception ex) { - OGCSexception.Analyse("ddGoogleColour_SelectedIndexChanged(): Could not update ddOutlookColour.", ex); + Ogcs.Exception.Analyse("ddGoogleColour_SelectedIndexChanged(): Could not update ddOutlookColour.", ex); } finally { ddOutlookColour.SelectedIndexChanged += ddOutlookColour_SelectedIndexChanged; } @@ -2269,7 +2269,7 @@ private void btColourMap_Click(object sender, EventArgs e) { colourForm.ShowDialog(); } } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } private void cbSingleCategoryOnly_CheckedChanged(object sender, EventArgs e) { @@ -2311,8 +2311,8 @@ private void cbStartOnStartup_CheckedChanged(object sender, EventArgs e) { try { Program.ManageStartupRegKey(); } 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(s).", ex); + if (ex is System.Security.SecurityException) Ogcs.Exception.LogAsFail(ref ex); //User doesn't have rights to access registry + Ogcs.Exception.Analyse("Failed accessing registry for startup key(s).", ex); if (this.Visible) { OgcsMessageBox.Show("You do not have permissions to access the system registry.\nThis setting cannot be used.", "Registry access denied", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); @@ -2329,8 +2329,8 @@ private void cbStartOnStartupAllUsers_CheckedChanged(object sender, EventArgs e) try { Program.ManageStartupRegKey(); } 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 HKLM startup key.", ex); + if (ex is System.Security.SecurityException) Ogcs.Exception.LogAsFail(ref ex); //User doesn't have rights to access registry + Ogcs.Exception.Analyse("Failed accessing registry for HKLM startup key.", ex); if (this.Visible) { OgcsMessageBox.Show("You do not have permissions to access the system registry.\nThis setting cannot be used.", "Registry access denied", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); @@ -2479,7 +2479,7 @@ private void btCheckBrowserAgent_Click(object sender, EventArgs e) { try { Helper.OpenBrowser(Program.OgcsWebsite + "/browseruseragent"); } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to check browser's user agent.", ex); + Ogcs.Exception.Analyse("Failed to check browser's user agent.", ex); } } @@ -2615,7 +2615,7 @@ public void CheckSyncMilestone() { } } catch (System.Exception ex) { log.Warn("Failed checking sync milestone."); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } diff --git a/src/OutlookGoogleCalendarSync/Forms/ProfileManage.cs b/src/OutlookGoogleCalendarSync/Forms/ProfileManage.cs index 0817879e..4654b6d8 100644 --- a/src/OutlookGoogleCalendarSync/Forms/ProfileManage.cs +++ b/src/OutlookGoogleCalendarSync/Forms/ProfileManage.cs @@ -1,13 +1,7 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; +using Ogcs = OutlookGoogleCalendarSync; using log4net; +using System; +using System.Windows.Forms; namespace OutlookGoogleCalendarSync.Forms { public partial class ProfileManage : Form { @@ -56,7 +50,7 @@ private void ProfileManage_FormClosing(object sender, FormClosingEventArgs e) { newCalendar.InitialiseTimer(); newCalendar.RegisterForPushSync(); } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to add new profile.", ex); + Ogcs.Exception.Analyse("Failed to add new profile.", ex); throw; } @@ -75,7 +69,7 @@ private void ProfileManage_FormClosing(object sender, FormClosingEventArgs e) { log.Info("Renamed calendar settings from '" + currentProfileName + "' to '" + newProfileName + "'."); } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to rename profile from '" + currentProfileName + "' to '" + newProfileName + "'.", ex); + Ogcs.Exception.Analyse("Failed to rename profile from '" + currentProfileName + "' to '" + newProfileName + "'.", ex); throw; } Forms.Main.Instance.NotificationTray.RenameProfileItem(currentProfileName, newProfileName); diff --git a/src/OutlookGoogleCalendarSync/Forms/TimezoneMap.cs b/src/OutlookGoogleCalendarSync/Forms/TimezoneMap.cs index 99d9bdc5..54456b37 100644 --- a/src/OutlookGoogleCalendarSync/Forms/TimezoneMap.cs +++ b/src/OutlookGoogleCalendarSync/Forms/TimezoneMap.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using System; using System.Collections.Generic; using System.Linq; @@ -60,7 +61,7 @@ private void initialiseDataGridView() { loadConfig(); } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } @@ -73,7 +74,7 @@ private void loadConfig() { } } catch (System.Exception ex) { - OGCSexception.Analyse("Populating gridview cells from Settings.", ex); + Ogcs.Exception.Analyse("Populating gridview cells from Settings.", ex); } } @@ -94,7 +95,7 @@ private void addRow(String organiserTz, String systemTz) { tzGridView.NotifyCurrentCellDirty(false); } catch (System.Exception ex) { - OGCSexception.Analyse("Adding timezone map row #" + lastRow, ex); + Ogcs.Exception.Analyse("Adding timezone map row #" + lastRow, ex); } } @@ -119,13 +120,13 @@ private void btOK_Click(object sender, EventArgs e) { try { Settings.Instance.TimezoneMaps.Add(row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString()); } catch (System.ArgumentException ex) { - if (OGCSexception.GetErrorCode(ex) == "0x80070057") { + if (Ogcs.Exception.GetErrorCode(ex) == "0x80070057") { //An item with the same key has already been added } else throw; } } } catch (System.Exception ex) { - OGCSexception.Analyse("Could not save timezone mappings to Settings.", ex); + Ogcs.Exception.Analyse("Could not save timezone mappings to Settings.", ex); } finally { this.Close(); Forms.Main.Instance.SetControlPropertyThreadSafe(Forms.Main.Instance.btCustomTzMap, "Visible", Settings.Instance.TimezoneMaps.Count != 0); @@ -146,7 +147,7 @@ private void tzGridView_DataError(object sender, DataGridViewDataErrorEventArgs log.Debug("Cell[" + cell.RowIndex + "][" + cell.ColumnIndex + "] caused error."); } catch { } finally { - OGCSexception.Analyse("Bad cell value in timezone data grid.", e.Exception); + Ogcs.Exception.Analyse("Bad cell value in timezone data grid.", e.Exception); } } } diff --git a/src/OutlookGoogleCalendarSync/Forms/UpdateInfo.cs b/src/OutlookGoogleCalendarSync/Forms/UpdateInfo.cs index 7a55017e..4438ad5f 100644 --- a/src/OutlookGoogleCalendarSync/Forms/UpdateInfo.cs +++ b/src/OutlookGoogleCalendarSync/Forms/UpdateInfo.cs @@ -1,6 +1,7 @@ -using System; -using System.Windows.Forms; +using Ogcs = OutlookGoogleCalendarSync; using log4net; +using System; +using System.Windows.Forms; namespace OutlookGoogleCalendarSync.Forms { public partial class UpdateInfo : Form { @@ -50,7 +51,7 @@ public UpdateInfo(String releaseVersion, String releaseType, String html, out Di } catch (System.Exception ex) { log.Debug("A problem was encountered showing the release notes."); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); dr = OgcsMessageBox.Show("A new " + (releaseType == "alpha" ? "alpha " : "") + "release of OGCS is available.\nWould you like to upgrade to v" + releaseVersion + " now?", "OGCS Update Available", MessageBoxButtons.YesNo, MessageBoxIcon.Information); } diff --git a/src/OutlookGoogleCalendarSync/Google/ApiKeyring.cs b/src/OutlookGoogleCalendarSync/Google/ApiKeyring.cs index fb1a2703..e5257988 100644 --- a/src/OutlookGoogleCalendarSync/Google/ApiKeyring.cs +++ b/src/OutlookGoogleCalendarSync/Google/ApiKeyring.cs @@ -96,7 +96,7 @@ public void PickKey(KeyType keyType) { } catch (System.Exception ex) { log.Fail("Failed picking "+ keyType.ToString() +" API key. clientID=" + Settings.Instance.AssignedClientIdentifier); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); log.Debug("Reverting to default key."); Key = new ApiKey.DefaultKey(keyType); } @@ -184,7 +184,7 @@ public ApiKey(String type, String projectName, String projectId, String status, this.ClientSecret = clientSecret; } catch (System.Exception ex) { log.Error("Failed creating API key."); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); throw; } } diff --git a/src/OutlookGoogleCalendarSync/Google/Authenticator.cs b/src/OutlookGoogleCalendarSync/Google/Authenticator.cs index 14385c82..c12f1824 100644 --- a/src/OutlookGoogleCalendarSync/Google/Authenticator.cs +++ b/src/OutlookGoogleCalendarSync/Google/Authenticator.cs @@ -66,7 +66,7 @@ private void spawnOauth() { } catch (System.OperationCanceledException) { Forms.Main.Instance.Console.Update("Authorisation to allow OGCS to manage your Google calendar was cancelled.", Console.Markup.warning); } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } catch (System.Exception ex) { log.Fail("Problem encountered in getCalendarClientSecrets()"); @@ -113,7 +113,7 @@ private async Task getAuthenticated(ClientSecrets cs) { log.Debug("User has provided Google authorisation and credential file saved."); } catch (global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { - //OGCSexception.AnalyseTokenResponse(ex); + //Ogcs.Exception.AnalyseTokenResponse(ex); if (ex.Error.Error == "access_denied") { String noAuthGiven = "Sorry, but this application will not work if you don't allow it access to your Google Calendar :("; log.Warn("User did not provide authorisation code. Sync will not be able to work."); @@ -127,7 +127,7 @@ private async Task getAuthenticated(ClientSecrets cs) { Forms.Main.Instance.Console.Update("Unable to authenticate with Google. The operation was cancelled.", Console.Markup.warning); } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); Forms.Main.Instance.Console.UpdateWithError("Unable to authenticate with Google. The following error occurred:", ex); } @@ -155,10 +155,10 @@ private async Task getAuthenticated(ClientSecrets cs) { switch (Calendar.HandleAPIlimits(ref ex, null)) { case Calendar.ApiException.throwException: throw; case Calendar.ApiException.freeAPIexhausted: - OGCSexception.LogAsFail(ref ex); - OGCSexception.Analyse(ex); + Ogcs.Exception.LogAsFail(ref ex); + Ogcs.Exception.Analyse(ex); System.ApplicationException aex = new System.ApplicationException(Calendar.Instance.SubscriptionInvite, ex); - OGCSexception.LogAsFail(ref aex); + Ogcs.Exception.LogAsFail(ref aex); authenticated = false; return authenticated; case Calendar.ApiException.backoffThenRetry: @@ -176,9 +176,9 @@ private async Task getAuthenticated(ClientSecrets cs) { } catch (System.Exception ex) { if (ex is global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException) - OGCSexception.AnalyseTokenResponse(ex as global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException, false); + Ogcs.Exception.AnalyseTokenResponse(ex as global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException, false); else { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); Forms.Main.Instance.Console.Update("Unable to communicate with Google services. " + (ex.InnerException != null ? ex.InnerException.Message : ex.Message), Console.Markup.warning); } authenticated = false; @@ -238,7 +238,7 @@ private void getGaccountEmail(String accessToken) { System.IO.StreamReader sr = new System.IO.StreamReader(stream); log.Error(sr.ReadToEnd()); } - if (OGCSexception.GetErrorCode(ex) == "0x80131509") { + if (Ogcs.Exception.GetErrorCode(ex) == "0x80131509") { log.Warn(ex.Message); System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(@"\b(403|Forbidden|Prohibited|Insufficient Permission)\b", System.Text.RegularExpressions.RegexOptions.IgnoreCase); @@ -268,7 +268,7 @@ private void getGaccountEmail(String accessToken) { throw; } } - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); if (ex.Message.ToLower().Contains("access denied")) { Forms.Main.Instance.Console.Update("Failed to obtain Calendar access from Google - it's possible your access has been revoked." + "
Try disconnecting your Google account and reauthorising OGCS.", Console.Markup.error); @@ -280,7 +280,7 @@ private void getGaccountEmail(String accessToken) { } catch (System.Exception ex) { log.Debug("JSON: " + jsonString); log.Error("Failed to retrieve Google account username."); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); log.Debug("Using previously retrieved username: " + Settings.Instance.GaccountEmail_masked()); } } @@ -301,7 +301,7 @@ public static String GetMd5(String input, Boolean isEmailAddress = false, Boolea } } catch (System.Exception ex) { log.Error("Failed to create MD5" + (silent ? "." : " for '" + (isEmailAddress ? EmailAddress.MaskAddress(input) : input) + "'.")); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } return sb.ToString(); } @@ -355,16 +355,16 @@ public Boolean UserSubscriptionCheck() { return false; } } catch (global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { - OGCSexception.AnalyseTokenResponse(ex); + Ogcs.Exception.AnalyseTokenResponse(ex); } catch (global::Google.GoogleApiException ex) { switch (Ogcs.Google.Calendar.HandleAPIlimits(ref ex, null)) { case Calendar.ApiException.throwException: throw; case Calendar.ApiException.freeAPIexhausted: - OGCSexception.LogAsFail(ref ex); - OGCSexception.Analyse(ex); + Ogcs.Exception.LogAsFail(ref ex); + Ogcs.Exception.Analyse(ex); System.ApplicationException aex = new System.ApplicationException(Ogcs.Google.Calendar.Instance.SubscriptionInvite, ex); - OGCSexception.LogAsFail(ref aex); + Ogcs.Exception.LogAsFail(ref aex); Ogcs.Google.Calendar.Instance.Service = null; throw aex; } diff --git a/src/OutlookGoogleCalendarSync/Google/CustomProperty.cs b/src/OutlookGoogleCalendarSync/Google/CustomProperty.cs index c243172b..4baeb138 100644 --- a/src/OutlookGoogleCalendarSync/Google/CustomProperty.cs +++ b/src/OutlookGoogleCalendarSync/Google/CustomProperty.cs @@ -349,7 +349,7 @@ public static void LogProperties(Event ev, log4net.Core.Level thresholdLevel) { } } } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to log Event ExtendedProperties", ex); + Ogcs.Exception.Analyse("Failed to log Event ExtendedProperties", ex); } } } diff --git a/src/OutlookGoogleCalendarSync/Google/ErrorReporting.cs b/src/OutlookGoogleCalendarSync/Google/ErrorReporting.cs index ec7af9ff..32b030a6 100644 --- a/src/OutlookGoogleCalendarSync/Google/ErrorReporting.cs +++ b/src/OutlookGoogleCalendarSync/Google/ErrorReporting.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using System; using System.Collections.Generic; using System.IO; @@ -64,7 +65,7 @@ public static void Initialise() { try { File.WriteAllLines(credFile, newLines.ToArray()); } catch (System.IO.IOException ex) { - if (OGCSexception.GetErrorCode(ex) == "0x80070020") + if (Ogcs.Exception.GetErrorCode(ex) == "0x80070020") log.Warn("ErrorReporting.json is being used by another process (perhaps multiple instances of OGCS are being started on system startup?)"); else throw; @@ -79,7 +80,7 @@ public static void Initialise() { //Logging isn't initialised yet, so don't catch this error - let it crash out so user is aware and hopefully reports it! //System.Windows.Forms.OgcsMessageBox.Show(ex.Message); //log.Debug("Failed to initialise error reporting."); - //OGCSexception.Analyse(ex); + //Ogcs.Exception.Analyse(ex); } } @@ -143,7 +144,7 @@ public static void SetThreshold(Boolean cloudLoggingEnabled) { } catch (System.Exception ex) { log.Error("Failed to configure error reporting appender."); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } } diff --git a/src/OutlookGoogleCalendarSync/Google/EventAttendee.cs b/src/OutlookGoogleCalendarSync/Google/EventAttendee.cs index b3afe4e2..dba7f544 100644 --- a/src/OutlookGoogleCalendarSync/Google/EventAttendee.cs +++ b/src/OutlookGoogleCalendarSync/Google/EventAttendee.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using System; using System.Reflection; @@ -17,7 +18,7 @@ public EventAttendee(global::Google.Apis.Calendar.v3.Data.EventAttendee baseAtte prop.SetValue(this, prop.GetValue(baseAttendee)); } catch (System.Exception ex) { log.Warn("Failed to set property " + prop.Name); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } } diff --git a/src/OutlookGoogleCalendarSync/Google/EventColour.cs b/src/OutlookGoogleCalendarSync/Google/EventColour.cs index ba58103e..78f794a4 100644 --- a/src/OutlookGoogleCalendarSync/Google/EventColour.cs +++ b/src/OutlookGoogleCalendarSync/Google/EventColour.cs @@ -58,7 +58,7 @@ public String Name { try { name = GetColourName(Id); } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); name = HexValue; } return name; @@ -141,7 +141,7 @@ public static String GetColourId(String name) { try { id = eventColourNames.First(n => (n.Value as Metadata).Name == name).Key.ToString(); } catch (System.Exception ex) { - OGCSexception.Analyse("Could not find colour ID for '" + name + "'.", ex); + Ogcs.Exception.Analyse("Could not find colour ID for '" + name + "'.", ex); } return id; } @@ -162,7 +162,7 @@ public static String GetColourName(String id) { else log.Error("GetColourName(): ID '" + id + "' not found."); } catch (System.Exception ex) { - OGCSexception.Analyse("Could not find colour name for '" + id + "'.", ex); + Ogcs.Exception.Analyse("Could not find colour name for '" + id + "'.", ex); } return name; } @@ -225,10 +225,10 @@ public void Get() { switch (Ogcs.Google.Calendar.HandleAPIlimits(ref ex, null)) { case Ogcs.Google.Calendar.ApiException.throwException: throw; case Ogcs.Google.Calendar.ApiException.freeAPIexhausted: - OGCSexception.LogAsFail(ref ex); - OGCSexception.Analyse(ex); + Ogcs.Exception.LogAsFail(ref ex); + Ogcs.Exception.Analyse(ex); System.ApplicationException aex = new System.ApplicationException(Ogcs.Google.Calendar.Instance.SubscriptionInvite, ex); - OGCSexception.LogAsFail(ref aex); + Ogcs.Exception.LogAsFail(ref aex); throw aex; case Ogcs.Google.Calendar.ApiException.backoffThenRetry: backoff++; @@ -246,7 +246,7 @@ public void Get() { } } catch (System.Exception ex) { log.Error("Failed retrieving calendar Event colours."); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); throw; } @@ -304,7 +304,7 @@ public Palette GetClosestColour(Color baseColour) { return colourDistance.Find(x => x.Diff == minDistance).Value; } catch (System.Exception ex) { log.Warn("Failed to get closest Event colour for " + baseColour.Name); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); return Palette.NullPalette; } } diff --git a/src/OutlookGoogleCalendarSync/Google/GMeet.cs b/src/OutlookGoogleCalendarSync/Google/GMeet.cs index 393c10bd..71de85d8 100644 --- a/src/OutlookGoogleCalendarSync/Google/GMeet.cs +++ b/src/OutlookGoogleCalendarSync/Google/GMeet.cs @@ -1,4 +1,5 @@ -using Google.Apis.Calendar.v3.Data; +using Ogcs = OutlookGoogleCalendarSync; +using Google.Apis.Calendar.v3.Data; using log4net; using System; using System.Collections.Generic; @@ -51,7 +52,7 @@ public static void GoogleMeet(this Event ev, String outlookGMeetUrl) { } } catch (System.Exception ex) { - OGCSexception.Analyse("Could not alter Event conference data.", ex); + Ogcs.Exception.Analyse("Could not alter Event conference data.", ex); } } } diff --git a/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs b/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs index bbc656d3..b7f630b2 100644 --- a/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs +++ b/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs @@ -129,10 +129,10 @@ public void GetCalendars() { switch (HandleAPIlimits(ref ex, null)) { case ApiException.throwException: throw; case ApiException.freeAPIexhausted: - OGCSexception.LogAsFail(ref ex); - OGCSexception.Analyse(ex); + Ogcs.Exception.LogAsFail(ref ex); + Ogcs.Exception.Analyse(ex); System.ApplicationException aex = new System.ApplicationException(SubscriptionInvite, ex); - OGCSexception.LogAsFail(ref aex); + Ogcs.Exception.LogAsFail(ref aex); throw aex; case ApiException.backoffThenRetry: backoff++; @@ -184,10 +184,10 @@ public List GetCalendarEntriesInRecurrence(String recurringEventId) { switch (HandleAPIlimits(ref ex, null)) { case ApiException.throwException: throw; case ApiException.freeAPIexhausted: - OGCSexception.LogAsFail(ref ex); - OGCSexception.Analyse(ex); + Ogcs.Exception.LogAsFail(ref ex); + Ogcs.Exception.Analyse(ex); System.ApplicationException aex = new System.ApplicationException(SubscriptionInvite, ex); - OGCSexception.LogAsFail(ref aex); + Ogcs.Exception.LogAsFail(ref aex); throw aex; case ApiException.backoffThenRetry: backoff++; @@ -214,8 +214,8 @@ public List GetCalendarEntriesInRecurrence(String recurringEventId) { return result; } catch (System.Exception ex) { - Forms.Main.Instance.Console.UpdateWithError("Failed to retrieve recurring events.", OGCSexception.LogAsFail(ex)); - OGCSexception.Analyse("recurringEventId: " + recurringEventId, ex); + Forms.Main.Instance.Console.UpdateWithError("Failed to retrieve recurring events.", Ogcs.Exception.LogAsFail(ex)); + Ogcs.Exception.Analyse("recurringEventId: " + recurringEventId, ex); return null; } } @@ -239,10 +239,10 @@ public Event GetCalendarEntry(String eventId) { switch (HandleAPIlimits(ref ex, null)) { case ApiException.throwException: throw; case ApiException.freeAPIexhausted: - OGCSexception.LogAsFail(ref ex); - OGCSexception.Analyse(ex); + Ogcs.Exception.LogAsFail(ref ex); + Ogcs.Exception.Analyse(ex); System.ApplicationException aex = new System.ApplicationException(SubscriptionInvite, ex); - OGCSexception.LogAsFail(ref aex); + Ogcs.Exception.LogAsFail(ref aex); throw aex; case ApiException.backoffThenRetry: backoff++; @@ -305,17 +305,17 @@ public List GetCalendarEntriesInRange(DateTime from, DateTime to) { switch (HandleAPIlimits(ref ex, null)) { case ApiException.throwException: throw; case ApiException.freeAPIexhausted: - OGCSexception.LogAsFail(ref ex); - OGCSexception.Analyse(ex); + Ogcs.Exception.LogAsFail(ref ex); + Ogcs.Exception.Analyse(ex); System.ApplicationException aex = new System.ApplicationException(SubscriptionInvite, ex); - OGCSexception.LogAsFail(ref aex); + Ogcs.Exception.LogAsFail(ref aex); throw aex; case ApiException.backoffThenRetry: backoff++; if (backoff == BackoffLimit) { log.Error("API limit backoff was not successful. Retrieve failed."); aex = new System.ApplicationException(SubscriptionInvite, ex); - OGCSexception.LogAsFail(ref aex); + Ogcs.Exception.LogAsFail(ref aex); throw aex; } else { int backoffDelay = (int)Math.Pow(2, backoff); @@ -468,10 +468,10 @@ private Event patchEvent(Event ev, String patchId = null) { switch (HandleAPIlimits(ref ex, ev)) { case ApiException.throwException: throw; case ApiException.freeAPIexhausted: - OGCSexception.LogAsFail(ref ex); - OGCSexception.Analyse(ex); + Ogcs.Exception.LogAsFail(ref ex); + Ogcs.Exception.Analyse(ex); System.ApplicationException aex = new System.ApplicationException(SubscriptionInvite, ex); - OGCSexception.LogAsFail(ref aex); + Ogcs.Exception.LogAsFail(ref aex); throw aex; case ApiException.justContinue: break; case ApiException.backoffThenRetry: @@ -508,7 +508,7 @@ public void CreateCalendarEntries(List appointments) { } else { String summary = Outlook.Calendar.GetEventSummary("Event creation failed.", ai, out String anonSummary); Forms.Main.Instance.Console.UpdateWithError(summary, ex, logEntry: anonSummary); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); if (OgcsMessageBox.Show("Google event creation failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else @@ -525,7 +525,7 @@ public void CreateCalendarEntries(List appointments) { return; } Forms.Main.Instance.Console.UpdateWithError(Outlook.Calendar.GetEventSummary("New event failed to save.", ai, out String anonSummary, true), ex, logEntry: anonSummary); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); if (OgcsMessageBox.Show("New Google event failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else @@ -566,7 +566,7 @@ private Event createCalendarEntry(AppointmentItem ai) { try { ev.Description = Obfuscate.ApplyRegex(Obfuscate.Property.Description, ai.Body, null, Sync.Direction.OutlookToGoogle); } catch (System.Exception ex) { - if (OGCSexception.GetErrorCode(ex) == "0x80004004") { + if (Ogcs.Exception.GetErrorCode(ex) == "0x80004004") { Forms.Main.Instance.Console.Update("You do not have the rights to programmatically access Outlook appointment descriptions.
" + "It may be best to stop syncing the Description attribute.", Console.Markup.warning); } else throw; @@ -647,10 +647,10 @@ private Event createCalendarEntry_save(Event ev, AppointmentItem ai) { switch (HandleAPIlimits(ref ex, ev)) { case ApiException.throwException: throw; case ApiException.freeAPIexhausted: - OGCSexception.LogAsFail(ref ex); - OGCSexception.Analyse(ex); + Ogcs.Exception.LogAsFail(ref ex); + Ogcs.Exception.Analyse(ex); System.ApplicationException aex = new System.ApplicationException(SubscriptionInvite, ex); - OGCSexception.LogAsFail(ref aex); + Ogcs.Exception.LogAsFail(ref aex); throw aex; case ApiException.justContinue: break; case ApiException.backoffThenRetry: @@ -719,7 +719,7 @@ public void UpdateCalendarEntries(Dictionary entriesToBe String summary = Outlook.Calendar.GetEventSummary("
Event update failed.", compare.Key, out String anonSummary); Forms.Main.Instance.Console.UpdateWithError(summary, ex, logEntry: anonSummary); if (ex is System.Runtime.InteropServices.COMException) throw; - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); if (OgcsMessageBox.Show("Google event update failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else @@ -734,7 +734,7 @@ public void UpdateCalendarEntries(Dictionary entriesToBe eventExceptionCacheDirty = true; } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(Outlook.Calendar.GetEventSummary("Updated event failed to save.", compare.Key, out String anonSummary, true), ex, logEntry: anonSummary); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); if (OgcsMessageBox.Show("Updated Google event failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else @@ -761,7 +761,7 @@ public void UpdateCalendarEntries(Dictionary entriesToBe entriesToBeCompared[compare.Key] = ev; } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(Outlook.Calendar.GetEventSummary("Updated event failed to save.", compare.Key, out String anonSummary, true), ex, logEntry: anonSummary); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); if (OgcsMessageBox.Show("Updated Google event failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else @@ -932,7 +932,7 @@ public Event UpdateCalendarEntry(AppointmentItem ai, Event ev, ref int itemModif ev = patchEvent(ev) ?? ev; log.Fine("Conference data change successfully saved."); } catch (System.Exception ex) { - OGCSexception.Analyse("Could not update conference data in existing Event.", ex); + Ogcs.Exception.Analyse("Could not update conference data in existing Event.", ex); } } } @@ -1094,10 +1094,10 @@ public void UpdateCalendarEntry_save(ref Event ev) { switch (handled) { case ApiException.throwException: throw; case ApiException.freeAPIexhausted: - OGCSexception.LogAsFail(ref ex); - OGCSexception.Analyse(ex); + Ogcs.Exception.LogAsFail(ref ex); + Ogcs.Exception.Analyse(ex); System.ApplicationException aex = new System.ApplicationException(SubscriptionInvite, ex); - OGCSexception.LogAsFail(ref aex); + Ogcs.Exception.LogAsFail(ref aex); throw aex; case ApiException.backoffThenRetry: backoff++; @@ -1147,7 +1147,7 @@ public void DeleteCalendarEntries(List events) { doDelete = deleteCalendarEntry(ev); } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("Event deletion failed.", ev, out String anonSummary, true), ex, logEntry: anonSummary); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); if (OgcsMessageBox.Show("Google event deletion failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else { @@ -1174,7 +1174,7 @@ public void DeleteCalendarEntries(List events) { } else { String summary = GetEventSummary("
Event deletion failed.", ev, out String anonSummary); Forms.Main.Instance.Console.UpdateWithError(summary, ex, logEntry: anonSummary); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); if (OgcsMessageBox.Show("Google event deletion failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else @@ -1218,10 +1218,10 @@ private void deleteCalendarEntry_save(Event ev) { switch (HandleAPIlimits(ref ex, ev)) { case ApiException.throwException: throw; case ApiException.freeAPIexhausted: - OGCSexception.LogAsFail(ref ex); - OGCSexception.Analyse(ex); + Ogcs.Exception.LogAsFail(ref ex); + Ogcs.Exception.Analyse(ex); System.ApplicationException aex = new System.ApplicationException(SubscriptionInvite, ex); - OGCSexception.LogAsFail(ref aex); + Ogcs.Exception.LogAsFail(ref aex); throw aex; case ApiException.backoffThenRetry: backoff++; @@ -1360,7 +1360,7 @@ public void CleanDuplicateEntries(ref List google) { lastSeenDuplicateSet = ev.Created; } } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } @@ -1796,10 +1796,10 @@ public void GetSettings() { switch (HandleAPIlimits(ref ex, null)) { case ApiException.throwException: throw; case ApiException.freeAPIexhausted: - OGCSexception.LogAsFail(ref ex); - OGCSexception.Analyse("Not able to " + stage, ex); + Ogcs.Exception.LogAsFail(ref ex); + Ogcs.Exception.Analyse("Not able to " + stage, ex); System.ApplicationException aex = new System.ApplicationException(SubscriptionInvite, ex); - OGCSexception.LogAsFail(ref aex); + Ogcs.Exception.LogAsFail(ref aex); throw aex; case ApiException.backoffThenRetry: backoff++; @@ -1813,11 +1813,11 @@ public void GetSettings() { } break; } - OGCSexception.Analyse("Not able to " + stage, ex); + Ogcs.Exception.Analyse("Not able to " + stage, ex); throw new System.ApplicationException("Unable to " + stage + ".", ex); } catch (System.Exception ex) { - OGCSexception.Analyse("Not able to " + stage, ex); + Ogcs.Exception.Analyse("Not able to " + stage, ex); throw; } } @@ -1839,7 +1839,7 @@ private void getCalendarSettings() { String responseBody = response.Content.ReadAsStringAsync().Result; cal = Newtonsoft.Json.JsonConvert.DeserializeObject(responseBody); } catch (System.Exception ex2) { - OGCSexception.Analyse("Failed retrieving calendarList via HttpRequestMessage.", ex2); + Ogcs.Exception.Analyse("Failed retrieving calendarList via HttpRequestMessage.", ex2); throw; } } else throw; @@ -1904,7 +1904,7 @@ private String getAvailability(OlBusyStatus oBusyStatus, String gTransparency) { if (fbStatus != OlBusyStatus.olFree) overrideTransparency = "opaque"; } catch (System.Exception ex) { - OGCSexception.Analyse("Could not convert string '" + profile.AvailabilityStatus + "' to OlBusyStatus type. Defaulting override to available.", ex); + Ogcs.Exception.Analyse("Could not convert string '" + profile.AvailabilityStatus + "' to OlBusyStatus type. Defaulting override to available.", ex); } if (profile.SyncDirection.Id != Sync.Direction.Bidirectional.Id) { @@ -1993,7 +1993,7 @@ private void getOutlookCategoryColour(String aiCategories, ref OlCategoryColor? categoryColour = Outlook.Calendar.Categories.OutlookColour(category); } catch (System.Exception ex) { log.Error("Failed determining colour for Event from AppointmentItem categories: " + aiCategories); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } } @@ -2052,7 +2052,7 @@ public static void ExportToCSV(String action, String filename, List event log.Debug("Previous export renamed to " + backupFilename); } } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to backup previous CSV file.", ex); + Ogcs.Exception.Analyse("Failed to backup previous CSV file.", ex); } Stream stream = null; @@ -2063,7 +2063,7 @@ public static void ExportToCSV(String action, String filename, List event tw = new StreamWriter(stream, Encoding.UTF8); } catch (System.Exception ex) { Forms.Main.Instance.Console.Update("Failed to create CSV file '" + filename + "'.", Console.Markup.error); - OGCSexception.Analyse("Error opening file '" + filename + "' for writing.", ex); + Ogcs.Exception.Analyse("Error opening file '" + filename + "' for writing.", ex); return; } try { @@ -2080,12 +2080,12 @@ public static void ExportToCSV(String action, String filename, List event tw.WriteLine(exportToCSV(ev)); } catch (System.Exception ex) { Forms.Main.Instance.Console.Update(GetEventSummary("Failed to output following Google event to CSV:-
", ev, out String anonSummary, appendContext: false), anonSummary, Console.Markup.warning); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); } } } catch (System.Exception ex) { Forms.Main.Instance.Console.Update("Failed to output Google events to CSV.", Console.Markup.error); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } finally { if (tw != null) tw.Close(); @@ -2249,7 +2249,7 @@ public static ApiException HandleAPIlimits(ref global::Google.GoogleApiException apiGa4Ev.AddParameter("message", ex.Error?.Errors?.First().Message); apiGa4Ev.Send(); } catch (System.Exception gaEx) { - OGCSexception.Analyse(gaEx); + Ogcs.Exception.Analyse(gaEx); } SettingsStore.Calendar profile = Sync.Engine.Calendar.Instance.Profile; @@ -2286,8 +2286,8 @@ public static ApiException HandleAPIlimits(ref global::Google.GoogleApiException } else if (ex.Error.Errors.First().Reason == "rateLimitExceeded") { if (ex.Message.Contains("limit 'Queries per minute'")) { - log.Fail(OGCSexception.FriendlyMessage(ex)); - OGCSexception.LogAsFail(ref ex); + log.Fail(Ogcs.Exception.FriendlyMessage(ex)); + Ogcs.Exception.LogAsFail(ref ex); return ApiException.backoffThenRetry; } else if (ex.Message.Contains("limit 'Queries per day'") || ex.Message.Contains("Daily Limit Exceeded")) { @@ -2343,7 +2343,7 @@ public static ApiException HandleAPIlimits(ref global::Google.GoogleApiException log.Debug("Successfully forced save by ignoring eTag values."); } catch (System.Exception ex2) { try { - OGCSexception.Analyse("Failed forcing save with ETagAction.Ignore", OGCSexception.LogAsFail(ex2)); + Ogcs.Exception.Analyse("Failed forcing save with ETagAction.Ignore", Ogcs.Exception.LogAsFail(ex2)); log.Fine("Current eTag: " + ev.ETag); log.Fine("Current Updated: " + ev.UpdatedRaw); log.Fine("Current Sequence: " + ev.Sequence); @@ -2366,8 +2366,8 @@ public static ApiException HandleAPIlimits(ref global::Google.GoogleApiException return ApiException.justContinue; } else if (ex.Error?.Code == 500) { - log.Fail(OGCSexception.FriendlyMessage(ex)); - OGCSexception.LogAsFail(ref ex); + log.Fail(Ogcs.Exception.FriendlyMessage(ex)); + Ogcs.Exception.LogAsFail(ref ex); return ApiException.backoffThenRetry; } @@ -2383,7 +2383,7 @@ public static ApiException HandleAPIlimits(ref global::Google.GoogleApiException return profile.UseGoogleCalendar.Id == Settings.Instance.GaccountEmail; } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); return null; } } diff --git a/src/OutlookGoogleCalendarSync/Helper.cs b/src/OutlookGoogleCalendarSync/Helper.cs index 88dc6926..a83540e3 100644 --- a/src/OutlookGoogleCalendarSync/Helper.cs +++ b/src/OutlookGoogleCalendarSync/Helper.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using Microsoft.Win32; using System; @@ -11,7 +12,7 @@ public static void OpenBrowser(String url) { System.Diagnostics.Process.Start(url); return; } catch (System.Exception ex) { - OGCSexception.Analyse("Could not open default browser.", OGCSexception.LogAsFail(ex)); + Ogcs.Exception.Analyse("Could not open default browser.", Ogcs.Exception.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! @@ -65,7 +66,7 @@ private static String getDefaultBrowserPath() { return browserPath; } } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); return ""; } } diff --git a/src/OutlookGoogleCalendarSync/NotificationTray.cs b/src/OutlookGoogleCalendarSync/NotificationTray.cs index 71dc6541..666d1f0a 100644 --- a/src/OutlookGoogleCalendarSync/NotificationTray.cs +++ b/src/OutlookGoogleCalendarSync/NotificationTray.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using System; using System.Drawing; using System.Linq; @@ -57,8 +58,8 @@ public NotificationTray(NotifyIcon icon) { animatedIconFrames[i] = Icon.FromHandle(bmp.GetHicon()); } animatedIconFrame = 0; - } catch (Exception ex) { - OGCSexception.Analyse("Could not set up animated system tray icon.", ex); + } catch (System.Exception ex) { + Ogcs.Exception.Analyse("Could not set up animated system tray icon.", ex); } } @@ -132,7 +133,7 @@ public void UpdateItem(String itemName, String itemText = null, Boolean enabled } } catch (System.Exception ex) { if (Forms.Main.Instance.IsDisposed) return; - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); } } @@ -155,7 +156,7 @@ public void AddProfileItem(String itemText) { } catch (System.Exception ex) { if (Forms.Main.Instance.IsDisposed) return; - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); } } public void RenameProfileItem(String currentText, String newText) { @@ -174,7 +175,7 @@ public void RenameProfileItem(String currentText, String newText) { } catch (System.Exception ex) { if (Forms.Main.Instance.IsDisposed) return; - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); } } public void RemoveProfileItem(String itemText) { @@ -193,7 +194,7 @@ public void RemoveProfileItem(String itemText) { } catch (System.Exception ex) { if (Forms.Main.Instance.IsDisposed) return; - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); } } diff --git a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookFactory.cs b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookFactory.cs index da57f474..85024b64 100644 --- a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookFactory.cs +++ b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookFactory.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using Microsoft.Win32; using System; using System.Linq; @@ -131,7 +132,7 @@ private static void getOutlookVersionName(Int16 version, String versionFull) { outlookVersionName = (OutlookVersionNames)version; outlookVersionNameFull = outlookVersionName.ToString(); } catch (System.Exception ex) { - OGCSexception.Analyse("Failed determining Outlook client version.", ex); + Ogcs.Exception.Analyse("Failed determining Outlook client version.", ex); outlookVersionNameFull = "Failed-" + versionFull; outlookVersionName = OutlookVersionNames.Failed; } @@ -181,12 +182,12 @@ private static void getOutlookVersionName(Int16 version, String versionFull) { log.Error("Could not determine exact Outlook version with codebase v16."); } catch (System.Exception ex) { - OGCSexception.Analyse("Failed determining Click-to-Run release.", ex); + Ogcs.Exception.Analyse("Failed determining Click-to-Run release.", ex); } } } } catch (System.Exception ex) { - OGCSexception.Analyse("Failed determining Outlook release name from registry for codebase v16.", ex); + Ogcs.Exception.Analyse("Failed determining Outlook release name from registry for codebase v16.", ex); } } finally { log.Info("Outlook product name: " + outlookVersionNameFull); diff --git a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookNew.cs b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookNew.cs index e6b52de5..9b50a640 100644 --- a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookNew.cs +++ b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookNew.cs @@ -1,4 +1,5 @@ -using Google.Apis.Calendar.v3.Data; +using Ogcs = OutlookGoogleCalendarSync; +using Google.Apis.Calendar.v3.Data; using log4net; using Microsoft.Office.Interop.Outlook; using System; @@ -96,7 +97,7 @@ public void Connect() { explorerWatcher = new ExplorerWatcher(oApp); } catch (System.Runtime.InteropServices.COMException ex) { - if (OGCSexception.GetErrorCode(ex) == "0x84120009") { //Cannot complete the operation. You are not connected. [Issue #514, occurs on GetNamespace("mapi")] + if (Ogcs.Exception.GetErrorCode(ex) == "0x84120009") { //Cannot complete the operation. You are not connected. [Issue #514, occurs on GetNamespace("mapi")] log.Warn(ex.Message); throw new ApplicationException("A problem was encountered with your Office install.\r\n" + "Please perform an Office Repair or reinstall Outlook and then try running OGCS again."); @@ -222,14 +223,14 @@ public NameSpace GetCurrentUser(NameSpace oNS) { Outlook.Calendar.OOMsecurityInfo = true; } } catch (System.Exception ex) { - if (OGCSexception.GetErrorCode(ex) == "0x80004004") { //Access blocked + if (Ogcs.Exception.GetErrorCode(ex) == "0x80004004") { //Access blocked if (profile.OutlookGalBlocked) { //Fail fast log.Debug("Corporate policy is still blocking access to GAL."); return oNS; } - OGCSexception.LogAsFail(ref ex); + Ogcs.Exception.LogAsFail(ref ex); } - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); log.Warn("We seem to have a faux connection to Outlook! Forcing starting it with a system call :-/"); oNS = (NameSpace)Outlook.Calendar.ReleaseObject(oNS); Disconnect(); @@ -246,14 +247,14 @@ public NameSpace GetCurrentUser(NameSpace oNS) { delay = maxDelay; } catch (System.Exception ex2) { if (delay == maxDelay) { - if (OGCSexception.GetErrorCode(ex2) == "0x80004004") { //E_ABORT + if (Ogcs.Exception.GetErrorCode(ex2) == "0x80004004") { //E_ABORT log.Warn("Corporate policy or possibly anti-virus is blocking access to GAL."); - } else OGCSexception.Analyse(ex2); + } else Ogcs.Exception.Analyse(ex2); log.Warn("OGCS is unable to obtain CurrentUser from Outlook."); profile.OutlookGalBlocked = true; return oNS; } - OGCSexception.Analyse(ex2); + Ogcs.Exception.Analyse(ex2); } delay++; } @@ -270,9 +271,9 @@ public NameSpace GetCurrentUser(NameSpace oNS) { currentUserName = currentUser.Name; } catch (System.Exception ex) { log.Warn("OGCS is unable to interogate CurrentUser from Outlook."); - if (OGCSexception.GetErrorCode(ex) == "0x80004004") { //E_ABORT + if (Ogcs.Exception.GetErrorCode(ex) == "0x80004004") { //E_ABORT log.Warn("Corporate policy or possibly anti-virus is blocking access to GAL."); - } else OGCSexception.Analyse(OGCSexception.LogAsFail(ex)); + } else Ogcs.Exception.Analyse(Ogcs.Exception.LogAsFail(ex)); profile.OutlookGalBlocked = true; return oNS; } @@ -333,7 +334,7 @@ private MAPIFolder getCalendarStore(NameSpace oNS) { object bin = pa.GetProperty(PR_IPM_WASTEBASKET_ENTRYID); excludeDeletedFolder = pa.BinaryToString(bin); //EntryID } catch (System.Exception ex) { - OGCSexception.Analyse("Could not access 'Deleted Items' folder property.", OGCSexception.LogAsFail(ex)); + Ogcs.Exception.Analyse("Could not access 'Deleted Items' folder property.", Ogcs.Exception.LogAsFail(ex)); } Boolean updateGUI = profile.Equals(Forms.Main.Instance.ActiveCalendarProfile); if (updateGUI) { @@ -346,7 +347,7 @@ private MAPIFolder getCalendarStore(NameSpace oNS) { Forms.Main.Instance.lOutlookCalendar.Text = "Select calendar"; } } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to find calendar folders in alternate mailbox '" + profile.MailboxName + "'.", ex, true); + Ogcs.Exception.Analyse("Failed to find calendar folders in alternate mailbox '" + profile.MailboxName + "'.", ex, true); if (!(Forms.Main.Instance.Visible && Forms.Main.Instance.ActiveControl.Name == "rbOutlookAltMB")) throw new System.Exception("Failed to access alternate mailbox calendar '" + profile.MailboxName + "'", ex); } finally { @@ -469,7 +470,7 @@ private void getDefaultCalendar(NameSpace oNS, ref MAPIFolder defaultCalendar) { Forms.Main.Instance.SetControlPropertyThreadSafe(Forms.Main.Instance.lOutlookCalendar, "Text", "Select calendar"); } } catch (System.Exception ex) { - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); throw; } } @@ -500,14 +501,14 @@ private void findCalendars(Folders folders, Dictionary calen } } catch (System.Exception ex) { if (oApp?.Session.ExchangeConnectionMode.ToString().Contains("Disconnected") ?? false || - OGCSexception.GetErrorCode(ex) == "0xC204011D" || ex.Message.StartsWith("Network problems are preventing connection to Microsoft Exchange.") || - OGCSexception.GetErrorCode(ex, 0x000FFFFF) == "0x00040115") { + Ogcs.Exception.GetErrorCode(ex) == "0xC204011D" || ex.Message.StartsWith("Network problems are preventing connection to Microsoft Exchange.") || + Ogcs.Exception.GetErrorCode(ex, 0x000FFFFF) == "0x00040115") { log.Warn(ex.Message); log.Info("Currently disconnected from Exchange - unable to retrieve MAPI folders."); Forms.Main.Instance.ToolTips.SetToolTip(Forms.Main.Instance.cbOutlookCalendars, "The Outlook calendar to synchonize with.\nSome may not be listed as you are currently disconnected."); } else { - OGCSexception.Analyse("Failed to recurse MAPI folders.", ex); + Ogcs.Exception.Analyse("Failed to recurse MAPI folders.", ex); OgcsMessageBox.Show("A problem was encountered when searching for Outlook calendar folders.\r\n" + ex.Message, "Calendar Folders", MessageBoxButtons.OK, MessageBoxIcon.Warning); } @@ -529,7 +530,7 @@ private void calendarFolderAdd(String name, MAPIFolder folder, MAPIFolder parent try { calendarFolders.Add(name, folder); } catch (System.ArgumentException ex) { - if (OGCSexception.GetErrorCode(ex) == "0x80070057") { + if (Ogcs.Exception.GetErrorCode(ex) == "0x80070057") { //An item with the same key has already been added. //Let's recurse up to the parent folder, looking to make it unique object parentObj = (parentFolder != null ? parentFolder.Parent : folder.Parent); @@ -609,7 +610,7 @@ public String GetRecipientEmail(Recipient recipient) { try { retEmail = eu.PrimarySmtpAddress; } catch (System.Exception ex) { - OGCSexception.Analyse("Could not access Exchange users's primary SMTP.", OGCSexception.LogAsFail(ex)); + Ogcs.Exception.Analyse("Could not access Exchange users's primary SMTP.", Ogcs.Exception.LogAsFail(ex)); } } if (eu == null || string.IsNullOrEmpty(retEmail)) { @@ -783,7 +784,7 @@ public Event IANAtimezone_set(Event ev, AppointmentItem ai) { Forms.Main.Instance.Console.Update(Outlook.Calendar.GetEventSummary("
Could not determine the organiser's timezone. Google Event may have incorrect time.", ai, out String anonSummary), anonSummary, Console.Markup.warning); if (ex.Data.Contains("OGCS")) log.Warn(ex.Message); - else OGCSexception.Analyse(ex); + else Ogcs.Exception.Analyse(ex); organiserTZname = null; organiserTZid = null; } @@ -971,7 +972,7 @@ private TimeZoneInfo getWindowsTimezoneFromDescription(String tzDescription) { } catch (System.Exception ex) { log.Warn("Failed to get the organiser's timezone ID for " + tzDescription); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } return null; } diff --git a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs index 8b2de586..14a5b353 100644 --- a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs +++ b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs @@ -1,4 +1,5 @@ -using Google.Apis.Calendar.v3.Data; +using Ogcs = OutlookGoogleCalendarSync; +using Google.Apis.Calendar.v3.Data; using log4net; using Microsoft.Office.Interop.Outlook; using System; @@ -201,7 +202,7 @@ public NameSpace GetCurrentUser(NameSpace oNS) { Outlook.Calendar.OOMsecurityInfo = true; } } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); if (profile.OutlookGalBlocked) { //Fail fast log.Debug("Corporate policy is still blocking access to GAL."); return oNS; @@ -223,13 +224,13 @@ public NameSpace GetCurrentUser(NameSpace oNS) { } catch (System.Exception ex2) { if (delay == maxDelay) { log.Warn("OGCS is unable to obtain CurrentUser from Outlook."); - if (OGCSexception.GetErrorCode(ex2) == "0x80004004") { //E_ABORT + if (Ogcs.Exception.GetErrorCode(ex2) == "0x80004004") { //E_ABORT log.Warn("Corporate policy or possibly anti-virus is blocking access to GAL."); - } else OGCSexception.Analyse(OGCSexception.LogAsFail(ex2)); + } else Ogcs.Exception.Analyse(Ogcs.Exception.LogAsFail(ex2)); profile.OutlookGalBlocked = true; return oNS; } - OGCSexception.Analyse(ex2); + Ogcs.Exception.Analyse(ex2); } delay++; } @@ -311,7 +312,7 @@ private void getDefaultCalendar(NameSpace oNS, ref MAPIFolder defaultCalendar) { Forms.Main.Instance.SetControlPropertyThreadSafe(Forms.Main.Instance.lOutlookCalendar, "Text", "Select calendar"); } } catch (System.Exception ex) { - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); throw; } } @@ -342,14 +343,14 @@ private void findCalendars(Folders folders, Dictionary calen } } catch (System.Exception ex) { if (oApp.Session.ExchangeConnectionMode.ToString().Contains("Disconnected") || - OGCSexception.GetErrorCode(ex) == "0xC204011D" || ex.Message.StartsWith("Network problems are preventing connection to Microsoft Exchange.") || - OGCSexception.GetErrorCode(ex, 0x000FFFFF) == "0x00040115") { + Ogcs.Exception.GetErrorCode(ex) == "0xC204011D" || ex.Message.StartsWith("Network problems are preventing connection to Microsoft Exchange.") || + Ogcs.Exception.GetErrorCode(ex, 0x000FFFFF) == "0x00040115") { log.Warn(ex.Message); log.Info("Currently disconnected from Exchange - unable to retrieve MAPI folders."); Forms.Main.Instance.ToolTips.SetToolTip(Forms.Main.Instance.cbOutlookCalendars, "The Outlook calendar to synchonize with.\nSome may not be listed as you are currently disconnected."); } else { - OGCSexception.Analyse("Failed to recurse MAPI folders.", ex); + Ogcs.Exception.Analyse("Failed to recurse MAPI folders.", ex); OgcsMessageBox.Show("A problem was encountered when searching for Outlook calendar folders.\r\n" + ex.Message, "Calendar Folders", MessageBoxButtons.OK, MessageBoxIcon.Warning); } @@ -371,7 +372,7 @@ private void calendarFolderAdd(String name, MAPIFolder folder, MAPIFolder parent try { calendarFolders.Add(name, folder); } catch (System.ArgumentException ex) { - if (OGCSexception.GetErrorCode(ex) == "0x80070057") { + if (Ogcs.Exception.GetErrorCode(ex) == "0x80070057") { //An item with the same key has already been added. //Let's recurse up to the parent folder, looking to make it unique object parentObj = (parentFolder != null ? parentFolder.Parent : folder.Parent); @@ -406,7 +407,7 @@ public List FilterItems(Items outlookItems, String filter) { } log.Info(o2003recurring.Count + " recurring items successfully kept for Outlook 2003."); } catch (System.Exception ex) { - OGCSexception.Analyse("Unable to iterate Outlook items.", ex); + Ogcs.Exception.Analyse("Unable to iterate Outlook items.", ex); } restrictedItems.AddRange(o2003recurring); diff --git a/src/OutlookGoogleCalendarSync/Outlook/CustomProperty.cs b/src/OutlookGoogleCalendarSync/Outlook/CustomProperty.cs index ceee5a4b..eb6ff534 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/CustomProperty.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/CustomProperty.cs @@ -1,4 +1,5 @@ -using Google.Apis.Calendar.v3.Data; +using Ogcs = OutlookGoogleCalendarSync; +using Google.Apis.Calendar.v3.Data; using log4net; using Microsoft.Office.Interop.Outlook; using System; @@ -300,7 +301,7 @@ private static void add(ref AppointmentItem ai, MetadataId key, OlUserPropertyTy ups = ai.UserProperties; ups.Add(addkeyName, keyType); } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); ups.Add(addkeyName, keyType, false); } finally { ups = (UserProperties)Calendar.ReleaseObject(ups); @@ -356,7 +357,7 @@ private static DateTime get_datetime(AppointmentItem ai, MetadataId key) { retVal = (DateTime)prop.Value; } catch (System.Exception ex) { log.Error("Failed to retrieve DateTime value for property " + searchKey); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } } finally { @@ -460,7 +461,7 @@ public static void LogProperties(AppointmentItem ai, log4net.Core.Level threshol } } } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to log Appointment UserProperties", ex); + Ogcs.Exception.Analyse("Failed to log Appointment UserProperties", ex); } finally { ups = (UserProperties)Calendar.ReleaseObject(ups); } @@ -475,7 +476,7 @@ public static OlBodyFormat BodyFormat(this AppointmentItem ai) { try { format = (OlBodyFormat)ai.GetType().InvokeMember("BodyFormat", System.Reflection.BindingFlags.GetProperty, null, ai, null); } catch (System.Exception ex) { - OGCSexception.Analyse("Unable to determine AppointmentItem body format.", ex); + Ogcs.Exception.Analyse("Unable to determine AppointmentItem body format.", ex); } return format; } diff --git a/src/OutlookGoogleCalendarSync/Outlook/ExplorerWatcher.cs b/src/OutlookGoogleCalendarSync/Outlook/ExplorerWatcher.cs index 1555cc38..e9c93264 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/ExplorerWatcher.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/ExplorerWatcher.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using Microsoft.Office.Interop.Outlook; using System; using System.Collections.Generic; @@ -97,14 +98,14 @@ private void beforeItemPaste(ref object ClipboardContent, MAPIFolder Target, ref } catch (System.Exception ex) { log.Warn("Not able to process copy and pasted event."); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } finally { copiedAi = (AppointmentItem)Calendar.ReleaseObject(copiedAi); } } } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } @@ -138,7 +139,7 @@ private Dictionary cleanIDs(ref AppointmentItem copiedAi) { } catch (System.Exception ex) { log.Warn("Failed to clean OGCS properties from copied item."); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } finally { ups = (UserProperties)Calendar.ReleaseObject(ups); } @@ -171,13 +172,13 @@ private void repopulateIDs(String entryID, Dictionary propertyVa } catch (System.Exception ex) { if (ex is System.Runtime.InteropServices.COMException && ( - OGCSexception.GetErrorCode(ex) == "0x8004010F" || //The message you specified cannot be found - OGCSexception.GetErrorCode(ex) == "0x8004010A")) //The operation cannot be performed because the object has been deleted + Ogcs.Exception.GetErrorCode(ex) == "0x8004010F" || //The message you specified cannot be found + Ogcs.Exception.GetErrorCode(ex) == "0x8004010A")) //The operation cannot be performed because the object has been deleted { log.Warn("Could not find Outlook item with entryID " + entryID + " for post-processing."); - OGCSexception.LogAsFail(ref ex); + Ogcs.Exception.LogAsFail(ref ex); } - OGCSexception.Analyse("Failed to repopulate OGCS properties back to copied item.", ex); + Ogcs.Exception.Analyse("Failed to repopulate OGCS properties back to copied item.", ex); } finally { copiedAi = (AppointmentItem)Calendar.ReleaseObject(copiedAi); } @@ -247,13 +248,13 @@ private void untagAsCopied(String entryID) { } catch (System.Exception ex) { if (ex is System.Runtime.InteropServices.COMException && ( - OGCSexception.GetErrorCode(ex) == "0x8004010F" || //The message you specified cannot be found - OGCSexception.GetErrorCode(ex) == "0x8004010A")) //The operation cannot be performed because the object has been deleted + Ogcs.Exception.GetErrorCode(ex) == "0x8004010F" || //The message you specified cannot be found + Ogcs.Exception.GetErrorCode(ex) == "0x8004010A")) //The operation cannot be performed because the object has been deleted { log.Warn("Could not find Outlook item with entryID " + entryID + " for post-processing."); - OGCSexception.LogAsFail(ref ex); + Ogcs.Exception.LogAsFail(ref ex); } - OGCSexception.Analyse("Failed to remove OGCS 'copied' property on copied item.", ex); + Ogcs.Exception.Analyse("Failed to remove OGCS 'copied' property on copied item.", ex); } finally { copiedAi = (AppointmentItem)Calendar.ReleaseObject(copiedAi); } @@ -267,7 +268,7 @@ private void addOutlookCustomProperty(ref AppointmentItem copiedAi, String addKe try { ups.Add(addKeyName, keyType); } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); ups.Add(addKeyName, keyType, false); } } diff --git a/src/OutlookGoogleCalendarSync/Outlook/GMeet.cs b/src/OutlookGoogleCalendarSync/Outlook/GMeet.cs index 232b1dc5..91a3e5ad 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/GMeet.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/GMeet.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using Microsoft.Office.Interop.Outlook; using System; using System.Linq; @@ -30,7 +31,7 @@ private String base64encode(System.Drawing.Image img) { return Convert.ToBase64String(imgBytes); } catch (System.Exception ex) { - OGCSexception.Analyse("Could not load GMeet logo.", ex); + Ogcs.Exception.Analyse("Could not load GMeet logo.", ex); return ""; } } diff --git a/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs b/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs index 6d35bc25..fb07f155 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs @@ -35,8 +35,8 @@ public static Calendar Instance { } catch (System.ApplicationException) { throw; } catch (System.Exception ex) { - if (ex is System.Runtime.InteropServices.COMException) OGCSexception.LogAsFail(ref ex); - OGCSexception.Analyse(ex); + if (ex is System.Runtime.InteropServices.COMException) Ogcs.Exception.LogAsFail(ref ex); + Ogcs.Exception.Analyse(ex); log.Info("It appears Outlook has been closed/restarted after OGCS was started. Reconnecting..."); instance = new Calendar(); instance.IOutlook.Connect(); @@ -86,7 +86,7 @@ public static void Disconnect(Boolean onlyWhenNoGUI = false) { InstanceConnect = false; Instance.IOutlook.Disconnect(onlyWhenNoGUI); } catch (System.Exception ex) { - OGCSexception.Analyse("Could not disconnect from Outlook.", OGCSexception.LogAsFail(ex)); + Ogcs.Exception.Analyse("Could not disconnect from Outlook.", Ogcs.Exception.LogAsFail(ex)); } finally { GC.Collect(); GC.WaitForPendingFinalizers(); @@ -110,12 +110,12 @@ public List GetCalendarEntriesInRange(SettingsStore.Calendar pr throw; } } catch (System.Runtime.InteropServices.COMException ex) { - if (OGCSexception.GetErrorCode(ex, 0x0000FFFF) == "0x00004005" && ex.TargetSite.Name == "get_LastModificationTime") { //You must specify a time. - OGCSexception.LogAsFail(ref ex); + if (Ogcs.Exception.GetErrorCode(ex, 0x0000FFFF) == "0x00004005" && ex.TargetSite.Name == "get_LastModificationTime") { //You must specify a time. + Ogcs.Exception.LogAsFail(ref ex); ex.Data.Add("OGCS", "Corrupted item(s) with no start/end date exist in your Outlook calendar that need fixing or removing before a sync can run.
" + "Switch the calendar folder to List View, sort by date and look for entries with no start and/or end date."); - } else if (OGCSexception.GetErrorCode(ex, 0x000FFFFF) == "0x00020009" && ex.TargetSite.Name == "get_Categories") { //One or more items in the folder you synchronized do not match. - OGCSexception.LogAsFail(ref ex); + } else if (Ogcs.Exception.GetErrorCode(ex, 0x000FFFFF) == "0x00020009" && ex.TargetSite.Name == "get_Categories") { //One or more items in the folder you synchronized do not match. + Ogcs.Exception.LogAsFail(ref ex); String wikiURL = "https://github.com/phw198/OutlookGoogleCalendarSync/wiki/Resolving-Outlook-Error-Messages#one-or-more-items-in-the-folder-you-synchronized-do-not-match"; ex.Data.Add("OGCS", ex.Message + "
Please view the wiki for suggestions on " + "how to resolve conflicts within your Outlook account."); @@ -126,7 +126,7 @@ public List GetCalendarEntriesInRange(SettingsStore.Calendar pr throw; } catch (System.ArgumentNullException ex) { - OGCSexception.Analyse("It seems that Outlook has just been closed.", OGCSexception.LogAsFail(ex)); + Ogcs.Exception.Analyse("It seems that Outlook has just been closed.", Ogcs.Exception.LogAsFail(ex)); Outlook.Calendar.Instance.Reset(); filtered = FilterCalendarEntries(profile, suppressAdvisories: suppressAdvisories); @@ -207,7 +207,7 @@ public List FilterCalendarEntries(SettingsStore.Calendar profil continue; } catch (System.Exception ex) { - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); log.Debug("Unable to get End date for: " + GetEventSummary(ai)); continue; } @@ -317,7 +317,7 @@ public void CreateCalendarEntries(List events) { continue; } else { Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("Appointment creation failed.", ev, out String anonSummary, true), ex, logEntry: anonSummary); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); if (OgcsMessageBox.Show("Outlook appointment creation failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else @@ -330,7 +330,7 @@ public void CreateCalendarEntries(List events) { events[g] = ev; } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("New appointment failed to save.", ev, out String anonSummary, true), ex, logEntry: anonSummary); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); if (OgcsMessageBox.Show("New Outlook appointment failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else @@ -388,7 +388,7 @@ private void createCalendarEntry(Event ev, ref AppointmentItem ai) { EventReminder reminder = ev.Reminders.Overrides.Where(r => r.Method == "popup").OrderBy(x => x.Minutes).First(); ai.ReminderMinutesBeforeStart = (int)reminder.Minutes; } catch (System.Exception ex) { - OGCSexception.Analyse("Failed setting Outlook reminder for final popup Google notification.", ex); + Ogcs.Exception.Analyse("Failed setting Outlook reminder for final popup Google notification.", ex); } } else if ((ev.Reminders?.UseDefault ?? false) && Ogcs.Google.Calendar.Instance.MinDefaultReminder != int.MinValue) { ai.ReminderSet = true; @@ -438,7 +438,7 @@ public void UpdateCalendarEntries(Dictionary entriesToBe needsUpdating = UpdateCalendarEntry(ref ai, compare.Value, ref itemModified); } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("
Appointment update failed.", compare.Value, out String anonSummary), ex, logEntry: anonSummary); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); if (OgcsMessageBox.Show("Outlook appointment update failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else @@ -451,7 +451,7 @@ public void UpdateCalendarEntries(Dictionary entriesToBe entriesUpdated++; } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("Updated appointment failed to save.", compare.Value, out String anonSummary, true), ex, logEntry: anonSummary); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); if (OgcsMessageBox.Show("Updated Outlook appointment failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else @@ -769,7 +769,7 @@ public Boolean UpdateCalendarEntry(ref AppointmentItem ai, Event ev, ref int ite itemModified++; } } catch (System.Exception ex) { - OGCSexception.Analyse("Failed setting Outlook reminder for final popup Google notification.", ex); + Ogcs.Exception.Analyse("Failed setting Outlook reminder for final popup Google notification.", ex); } } @@ -817,7 +817,7 @@ public void DeleteCalendarEntries(List oAppointments) { doDelete = deleteCalendarEntry(ai); } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(GetEventSummary("Appointment deletion failed.", ai, out String anonSummary, true), ex, logEntry: anonSummary); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); if (OgcsMessageBox.Show("Outlook appointment deletion failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else @@ -829,7 +829,7 @@ public void DeleteCalendarEntries(List oAppointments) { else oAppointments.Remove(ai); } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(GetEventSummary("Deleted appointment failed to remove.", ai, out String anonSummary, true), ex, logEntry: anonSummary); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); if (OgcsMessageBox.Show("Deleted Outlook appointment failed to remove. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else @@ -1022,7 +1022,7 @@ private OlBusyStatus getAvailability(String gTransparency, OlBusyStatus? oBusySt try { Enum.TryParse(profile.AvailabilityStatus, out overrideFbStatus); } catch (System.Exception ex) { - OGCSexception.Analyse("Could not convert string '" + profile.AvailabilityStatus + "' to OlBusyStatus type. Defaulting override to available.", ex); + Ogcs.Exception.Analyse("Could not convert string '" + profile.AvailabilityStatus + "' to OlBusyStatus type. Defaulting override to available.", ex); } if (profile.SyncDirection.Id != Sync.Direction.Bidirectional.Id) { @@ -1109,7 +1109,7 @@ public static void AttachToOutlook(ref Microsoft.Office.Interop.Outlook.Applicat log.Warn("Attachment failed - Outlook is running without GUI for programmatic access."); } else { log.Warn("Attachment failed."); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } if (openOutlookOnFail) openOutlookHandler(ref oApp, withSystemCall); } @@ -1197,18 +1197,18 @@ public static void PoorlyOfficeInstall(System.Exception caughtException) { log.Warn(ex.Message); throw new ApplicationException("Outlook is busy.", ex); - } else if (OGCSexception.GetErrorCode(ex, 0x000FFFFF) == "0x00040115") { + } else if (Ogcs.Exception.GetErrorCode(ex, 0x000FFFFF) == "0x00040115") { log.Warn(ex.Message); log.Debug("OGCS is not able to run as Outlook is not properly connected to the Exchange server?"); throw new ApplicationException("Outlook is busy.", ex); - } else if (OGCSexception.GetErrorCode(ex, 0x000FFFFF) == "0x000702E4") { + } else if (Ogcs.Exception.GetErrorCode(ex, 0x000FFFFF) == "0x000702E4") { log.Warn(ex.Message); throw new ApplicationException("Outlook and OGCS are running in different security elevations.\n" + "Both must be running in Standard or Administrator mode."); } else if (!comErrorInWiki(ex)) { - OGCSexception.Analyse("COM error not in wiki.", ex); + Ogcs.Exception.Analyse("COM error not in wiki.", ex); if (!alreadyRedirectedToWikiForComError.Contains(hResult)) { Helper.OpenBrowser("https://github.com/phw198/OutlookGoogleCalendarSync/wiki/FAQs---COM-Errors"); alreadyRedirectedToWikiForComError.Add(hResult); @@ -1221,14 +1221,14 @@ public static void PoorlyOfficeInstall(System.Exception caughtException) { if (!comErrorInWiki(ex)) throw; } catch (System.UnauthorizedAccessException ex) { - if (OGCSexception.GetErrorCode(ex) == "0x80070005") { // E_ACCESSDENIED + if (Ogcs.Exception.GetErrorCode(ex) == "0x80070005") { // E_ACCESSDENIED log.Warn(ex.Message); throw new ApplicationException("OGCS was not permitted to start Outlook.\r\n" + "Please manually start Outlook and then restart OGCS again."); } } catch (System.Exception ex) { - OGCSexception.Analyse("Early binding to Outlook appears to have failed.", ex, true); + Ogcs.Exception.Analyse("Early binding to Outlook appears to have failed.", ex, true); log.Debug("Could try late binding??"); //System.Type oAppType = System.Type.GetTypeFromProgID("Outlook.Application"); //ApplicationClass oAppClass = System.Activator.CreateInstance(oAppType) as ApplicationClass; @@ -1238,7 +1238,7 @@ public static void PoorlyOfficeInstall(System.Exception caughtException) { } private static Boolean comErrorInWiki(System.Exception ex) { - String hResult = OGCSexception.GetErrorCode(ex); + String hResult = Ogcs.Exception.GetErrorCode(ex); String wikiUrl = ""; Regex rgx; @@ -1260,7 +1260,7 @@ private static Boolean comErrorInWiki(System.Exception ex) { hResult = matches[0].Groups[1].Value; } } catch (System.Exception ex2) { - OGCSexception.Analyse("Parsing error message with regex failed.", ex2); + Ogcs.Exception.Analyse("Parsing error message with regex failed.", ex2); } } @@ -1285,7 +1285,7 @@ private static Boolean comErrorInWiki(System.Exception ex) { } } catch (System.Exception htmlEx) { - OGCSexception.Analyse("Could not parse Wiki for existance of COM error.", htmlEx); + Ogcs.Exception.Analyse("Could not parse Wiki for existance of COM error.", htmlEx); } } @@ -1340,7 +1340,7 @@ public static void ExportToCSV(String action, String filename, List", ai, out String anonSummary, appendContext: false), anonSummary, Console.Markup.warning); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); } } } catch (System.Exception ex) { Forms.Main.Instance.Console.Update("Failed to output Outlook events to CSV.", Console.Markup.error); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } finally { if (tw != null) tw.Close(); @@ -1469,13 +1469,13 @@ public static string GetEventSummary(AppointmentItem ai, out String eventSummary eventSummary += '"' + ai.Subject + '"' + (onlyIfNotVerbose ? "
" : ""); } catch (System.Runtime.InteropServices.COMException ex) { - if (OGCSexception.GetErrorCode(ex) == "0x8004010F") + if (Ogcs.Exception.GetErrorCode(ex) == "0x8004010F") throw new System.Exception("Cannot access Outlook OST/PST file. Try restarting Outlook.", ex); else - OGCSexception.Analyse("Failed to get appointment summary: " + eventSummary, ex, true); + Ogcs.Exception.Analyse("Failed to get appointment summary: " + eventSummary, ex, true); } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to get appointment summary: " + eventSummary, ex, true); + Ogcs.Exception.Analyse("Failed to get appointment summary: " + eventSummary, ex, true); } } return eventSummary; @@ -1626,7 +1626,7 @@ public static object ReleaseObject(object obj) { System.Windows.Forms.Application.DoEvents(); } } catch (System.Exception ex) { - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); } GC.Collect(); return null; diff --git a/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs b/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs index 57816f5f..451132b2 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs @@ -75,7 +75,7 @@ public static Color RgbColour(String hexColour) { colour = ColorTranslator.FromHtml(hexColour); log.Fine("Converted '" + hexColour + "' to " + colour.ToString()); } catch (System.Exception ex) { - OGCSexception.Analyse("Could not convert hex '" + hexColour + "' to RGB colour.", ex); + Ogcs.Exception.Analyse("Could not convert hex '" + hexColour + "' to RGB colour.", ex); } return colour; } @@ -87,7 +87,7 @@ public static OutlookCOM.OlCategoryColor GetClosestCategory(Ogcs.Google.EventCol return colourDistance.Find(x => x.Diff == minDistance).Value.Key; } catch (System.Exception ex) { log.Warn("Failed to get closest Outlook category for " + basePalette.ToString()); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); return OutlookCOM.OlCategoryColor.olCategoryColorNone; } } @@ -116,7 +116,7 @@ public Categories() { Delimiter = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator + " "; } catch (System.Exception ex) { log.Error("Failed to get system ListSeparator value."); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); Delimiter = ", "; } } @@ -203,7 +203,7 @@ public void ValidateCategories() { try { if (this._categories != null && this._categories.Count > 0) { } } catch (System.Exception ex) { - OGCSexception.Analyse("Categories are not accessible!", OGCSexception.LogAsFail(ex)); + Ogcs.Exception.Analyse("Categories are not accessible!", Ogcs.Exception.LogAsFail(ex)); this._categories = null; } if (this._categories == null || Calendar.Categories == null) { @@ -216,11 +216,11 @@ public void ValidateCategories() { OutlookCOM.OlCategoryColor catColour = cat.Color; } } catch (System.Exception ex) { - if (OGCSexception.GetErrorCode(ex, 0x0000FFFF) == "0x00004005" && ex.TargetSite.Name == "get_Color") { + if (Ogcs.Exception.GetErrorCode(ex, 0x0000FFFF) == "0x00004005" && ex.TargetSite.Name == "get_Color") { log.Warn("Outlook category '" + catName + "' seems to have changed!"); Calendar.Instance.IOutlook.RefreshCategories(); } else { - OGCSexception.Analyse("Could not access all the Outlook categories.", ex); + Ogcs.Exception.Analyse("Could not access all the Outlook categories.", ex); this.categories = null; return; } @@ -278,7 +278,7 @@ public String FindName(OutlookCOM.OlCategoryColor? olCategory, String categoryNa } } } catch (System.Runtime.InteropServices.COMException ex) { - if (OGCSexception.GetErrorCode(ex, 0x0000FFFF) == "0x00004005") { //The operation failed. + if (Ogcs.Exception.GetErrorCode(ex, 0x0000FFFF) == "0x00004005") { //The operation failed. log.Warn("It seems a category has been manually removed in Outlook."); Calendar.Instance.IOutlook.RefreshCategories(); } else throw; diff --git a/src/OutlookGoogleCalendarSync/Outlook/OutlookErrors.cs b/src/OutlookGoogleCalendarSync/Outlook/OutlookErrors.cs index 6dcf7afe..5dce6bd9 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/OutlookErrors.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/OutlookErrors.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using System; namespace OutlookGoogleCalendarSync.Outlook { @@ -25,7 +26,7 @@ public static ErrorType HandleComError(System.Exception ex) { public static ErrorType HandleComError(System.Exception ex, out String hResult) { ErrorType retVal = ErrorType.Unhandled; try { - hResult = OGCSexception.GetErrorCode(ex); + hResult = Ogcs.Exception.GetErrorCode(ex); log.Warn($"[{hResult}] >> {ex.Message}"); if (hResult == "0x800401E3" && ex.Message.Contains("MK_E_UNAVAILABLE")) { @@ -53,7 +54,7 @@ public static ErrorType HandleComError(System.Exception ex, out String hResult) } } finally { if (retVal != ErrorType.Unhandled) - OGCSexception.Analyse(OGCSexception.LogAsFail(ex)); + Ogcs.Exception.Analyse(Ogcs.Exception.LogAsFail(ex)); } return retVal; diff --git a/src/OutlookGoogleCalendarSync/Program.cs b/src/OutlookGoogleCalendarSync/Program.cs index 433c7dd8..cadd2d8d 100644 --- a/src/OutlookGoogleCalendarSync/Program.cs +++ b/src/OutlookGoogleCalendarSync/Program.cs @@ -93,7 +93,7 @@ private static void Main(string[] args) { throw new ApplicationException(ex.Message.StartsWith("COM error") ? "Suggest startup delay" : ""); } catch (System.Runtime.InteropServices.COMException ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); MessageBox.Show(ex.Message, "Application terminated!", MessageBoxButtons.OK, MessageBoxIcon.Error); throw new ApplicationException("Suggest startup delay"); } @@ -111,7 +111,7 @@ private static void Main(string[] args) { log.Warn("OGCS has crashed out."); } catch (System.Exception ex) { - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); log.Fatal("Application unexpectedly terminated!"); MessageBox.Show(ex.Message, "Application unexpectedly terminated!", MessageBoxButtons.OK, MessageBoxIcon.Error); log.Warn("OGCS has crashed out."); @@ -267,7 +267,7 @@ private static void purgeLogFiles(Int16 retention) { System.IO.File.Delete(file); log.Debug("Deleted " + MaskFilePath(file)); } catch (System.Exception ex) { - OGCSexception.Analyse("Could not delete file " + file, OGCSexception.LogAsFail(ex)); + Ogcs.Exception.Analyse("Could not delete file " + file, Ogcs.Exception.LogAsFail(ex)); } } } @@ -498,8 +498,8 @@ private static void isNewVersion(Boolean isSquirrelInstall) { try { Program.ManageStartupRegKey(); } 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); + if (ex is System.Security.SecurityException) Ogcs.Exception.LogAsFail(ref ex); //User doesn't have rights to access registry + Ogcs.Exception.Analyse("Failed accessing registry for startup key.", ex); } Settings.Instance.Version = Application.ProductVersion; if (isHotFix) { @@ -562,7 +562,7 @@ private static Boolean isCLIstartup() { else return false; } catch (System.Exception ex) { log.Error("Failed to determine if OGCS was started by CLI."); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); return false; } } @@ -622,7 +622,7 @@ public static string MaskFilePath(String path) { } else return path; } catch (System.Exception ex) { - OGCSexception.Analyse("Problems accessing environment variables.", ex); + Ogcs.Exception.Analyse("Problems accessing environment variables.", ex); return path; } } @@ -657,7 +657,7 @@ public static void StackTraceToString() { stackFrames.ForEach(sf => stackString += sf.GetMethod().Name + " < "); log.Warn("StackTrace path: " + stackString); } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } @@ -693,7 +693,7 @@ private static void instancesRunning() { } } catch (System.Exception ex) { - OGCSexception.Analyse("Unable to check for concurrent OGCS processes.", ex); + Ogcs.Exception.Analyse("Unable to check for concurrent OGCS processes.", ex); } } diff --git a/src/OutlookGoogleCalendarSync/Recurrence.cs b/src/OutlookGoogleCalendarSync/Recurrence.cs index 6ccd0a1e..3c0d6ca7 100644 --- a/src/OutlookGoogleCalendarSync/Recurrence.cs +++ b/src/OutlookGoogleCalendarSync/Recurrence.cs @@ -543,7 +543,7 @@ public Event GetGoogleMasterEvent(AppointmentItem ai) { try { Ogcs.Google.Calendar.Instance.UpdateCalendarEntry_save(ref ev); } catch (System.Exception ex) { - OGCSexception.Analyse("Failed saving Outlook IDs to Google Event.", ex, true); + Ogcs.Exception.Analyse("Failed saving Outlook IDs to Google Event.", ex, true); } return ev; } @@ -617,13 +617,13 @@ public static void CreateGoogleExceptions(AppointmentItem ai, String recurringEv break; } } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } finally { ai2 = (Microsoft.Office.Interop.Outlook.AppointmentItem)Outlook.Calendar.ReleaseObject(ai2); } } } catch (System.Exception ex) { - OGCSexception.Analyse("Could not check if there are other exceptions with the same original start date.", ex); + Ogcs.Exception.Analyse("Could not check if there are other exceptions with the same original start date.", ex); } } if (!skipDelete) { @@ -750,12 +750,12 @@ public static void UpdateGoogleExceptions(AppointmentItem ai, Event ev, Boolean log.Debug("Doing a dummy update in order to update the last modified date of Google recurring series exception."); Ogcs.Google.Calendar.Instance.UpdateCalendarEntry_save(ref gExcp); } catch (System.Exception ex) { - OGCSexception.Analyse("Dummy update of unchanged exception for Google recurring series failed.", ex); + Ogcs.Exception.Analyse("Dummy update of unchanged exception for Google recurring series failed.", ex); } continue; } } catch (System.Exception ex) { - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); throw; } } @@ -764,7 +764,7 @@ public static void UpdateGoogleExceptions(AppointmentItem ai, Event ev, Boolean Ogcs.Google.Calendar.Instance.UpdateCalendarEntry_save(ref gExcp); } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("Updated event exception failed to save.", gExcp, out String anonSummary, true), ex, logEntry: anonSummary); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); if (OgcsMessageBox.Show("Updated Google event exception failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else { @@ -811,12 +811,12 @@ private static DeletionState exceptionIsDeleted(Microsoft.Office.Interop.Outlook ai = oExcp.AppointmentItem; return DeletionState.NotDeleted; } catch (System.Exception ex) { - OGCSexception.LogAsFail(ref ex); + Ogcs.Exception.LogAsFail(ref ex); String originalDate = oExcp.OriginalDate.ToString("dd/MM/yyyy"); 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.") { - OGCSexception.Analyse("This Outlook recurrence instance on " + originalDate + " has become inaccessible, probably due to caching", ex); + Ogcs.Exception.Analyse("This Outlook recurrence instance on " + originalDate + " has become inaccessible, probably due to caching", ex); } else { - OGCSexception.Analyse("Error when determining if Outlook recurrence on " + originalDate + " is deleted or not.", ex); + Ogcs.Exception.Analyse("Error when determining if Outlook recurrence on " + originalDate + " is deleted or not.", ex); } return DeletionState.Inaccessible; } finally { @@ -890,7 +890,7 @@ private void processOutlookExceptions(ref AppointmentItem ai, List evExce try { newAiExcp.Save(); } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); if (ex.Message == "Cannot save this item.") { Forms.Main.Instance.Console.Update( Outlook.Calendar.GetEventSummary("Uh oh! Outlook wasn't able to save this recurrence exception! " + diff --git a/src/OutlookGoogleCalendarSync/SettingsStore/Proxy.cs b/src/OutlookGoogleCalendarSync/SettingsStore/Proxy.cs index d14f11f6..0f928bf5 100644 --- a/src/OutlookGoogleCalendarSync/SettingsStore/Proxy.cs +++ b/src/OutlookGoogleCalendarSync/SettingsStore/Proxy.cs @@ -1,7 +1,8 @@ -using System.Runtime.Serialization; -using System.Net; -using System; +using Ogcs = OutlookGoogleCalendarSync; using log4net; +using System; +using System.Net; +using System.Runtime.Serialization; //*** //https://developers.google.com/gdata/articles/proxy_setup @@ -111,17 +112,17 @@ public void Configure() { sr = new System.IO.StreamReader(stream); log.Fail(sr.ReadToEnd()); } catch (System.Exception ex2) { - OGCSexception.Analyse("Could not analyse WebException response.", ex2); + Ogcs.Exception.Analyse("Could not analyse WebException response.", ex2); } finally { if (sr != null) sr.Close(); if (stream != null) stream.Close(); } } else - OGCSexception.Analyse("Testing proxy connection failed.", ex); + Ogcs.Exception.Analyse("Testing proxy connection failed.", ex); } } } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to confirm proxy settings.", ex); + Ogcs.Exception.Analyse("Failed to confirm proxy settings.", ex); } } } diff --git a/src/OutlookGoogleCalendarSync/SettingsStore/Settings.cs b/src/OutlookGoogleCalendarSync/SettingsStore/Settings.cs index e6c3d9b9..8acf03b9 100644 --- a/src/OutlookGoogleCalendarSync/SettingsStore/Settings.cs +++ b/src/OutlookGoogleCalendarSync/SettingsStore/Settings.cs @@ -324,7 +324,7 @@ public static void Load(String XMLfile = null) { log.Debug("User settings loaded successfully this time."); } catch (System.Exception ex2) { log.Error("Still failed to load settings!"); - OGCSexception.Analyse(ex2); + Ogcs.Exception.Analyse(ex2); } } } diff --git a/src/OutlookGoogleCalendarSync/SettingsStore/Upgrade.cs b/src/OutlookGoogleCalendarSync/SettingsStore/Upgrade.cs index 272b2898..51aa34bf 100644 --- a/src/OutlookGoogleCalendarSync/SettingsStore/Upgrade.cs +++ b/src/OutlookGoogleCalendarSync/SettingsStore/Upgrade.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using System; using System.IO; using System.Windows.Forms; @@ -51,11 +52,11 @@ private static void backupSettingsFile() { File.Copy(Settings.ConfigFile, backupFile, false); log.Info(backupFile + " created."); } catch (System.IO.IOException ex) { - if (OGCSexception.GetErrorCode(ex) == "0x80070050") { //File already exists + if (Ogcs.Exception.GetErrorCode(ex) == "0x80070050") { //File already exists log.Warn("The backfile already exists, not overwriting " + backupFile); } } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to create backup settings file", ex); + Ogcs.Exception.Analyse("Failed to create backup settings file", ex); } } @@ -126,7 +127,7 @@ private static void upgradeToMultiCalendar() { XMLManager.MoveElement("LastSyncDate", settingsElement, calendarElement); } catch (System.Exception ex) { - OGCSexception.Analyse("Problem encountered whilst upgrading " + Settings.ConfigFilename, ex); + Ogcs.Exception.Analyse("Problem encountered whilst upgrading " + Settings.ConfigFilename, ex); throw ex; } finally { if (xml != null) { @@ -142,11 +143,11 @@ private static void upgradeToMultiCalendar() { "Settings Cannot Be Saved", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation) == DialogResult.Cancel) { log.Warn("User cancelled attempt to save new settings file."); - OGCSexception.Analyse("Could not save upgraded settings file " + Settings.ConfigFile, ex); + Ogcs.Exception.Analyse("Could not save upgraded settings file " + Settings.ConfigFile, ex); throw; } } catch (System.Exception ex) { - OGCSexception.Analyse("Could not save upgraded settings file " + Settings.ConfigFile, ex); + Ogcs.Exception.Analyse("Could not save upgraded settings file " + Settings.ConfigFile, ex); throw; } } diff --git a/src/OutlookGoogleCalendarSync/Sync/Calendar.cs b/src/OutlookGoogleCalendarSync/Sync/Calendar.cs index 73cf9f6e..91246734 100644 --- a/src/OutlookGoogleCalendarSync/Sync/Calendar.cs +++ b/src/OutlookGoogleCalendarSync/Sync/Calendar.cs @@ -77,7 +77,7 @@ public void StartSync(Boolean manualIgnition, Boolean updateSyncSchedule = true) } } catch (System.Exception ex) { mainFrm.Console.UpdateWithError(null, ex, notifyBubble: true); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); return; } Ogcs.Google.Calendar.APIlimitReached_attendee = false; @@ -136,7 +136,7 @@ public void StartSync(Boolean manualIgnition, Boolean updateSyncSchedule = true) sb = new StringBuilder(); mainFrm.Console.BuildOutput("The following error was encountered during sync:-", ref sb); mainFrm.Console.BuildOutput(ex.Data["OGCS"].ToString(), ref sb); - mainFrm.Console.Update(sb, (OGCSexception.LoggingAsFail(ex) ? Console.Markup.fail : Console.Markup.error), notifyBubble: true); + mainFrm.Console.Update(sb, (Ogcs.Exception.LoggingAsFail(ex) ? Console.Markup.fail : Console.Markup.error), notifyBubble: true); if (ex.Data["OGCS"].ToString().Contains("try again")) { syncResult = Sync.Engine.SyncResult.AutoRetry; } @@ -147,7 +147,7 @@ public void StartSync(Boolean manualIgnition, Boolean updateSyncSchedule = true) error == Outlook.Errors.ErrorType.RpcFailed || error == Outlook.Errors.ErrorType.InvokedObjectDisconnectedFromClients) // { - OGCSexception.Analyse(OGCSexception.LogAsFail(ex)); + Ogcs.Exception.Analyse(Ogcs.Exception.LogAsFail(ex)); String message = "It looks like Outlook was closed during the sync."; if (error == Outlook.Errors.ErrorType.RpcFailed) message = "It looks like Outlook has been restarted and is not yet responsive."; mainFrm.Console.Update(message + "
Will retry syncing in a few seconds...", Console.Markup.fail, newLine: false); @@ -158,7 +158,7 @@ public void StartSync(Boolean manualIgnition, Boolean updateSyncSchedule = true) syncResult = SyncResult.ReconnectThenRetry; } else { - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); mainFrm.Console.UpdateWithError(null, ex, notifyBubble: true); syncResult = SyncResult.Fail; } @@ -313,20 +313,20 @@ private SyncResult synchronize() { Ogcs.Google.Calendar.Instance.GetSettings(); googleEntries = Ogcs.Google.Calendar.Instance.GetCalendarEntriesInRange(); } catch (AggregateException agex) { - OGCSexception.AnalyseAggregate(agex); + Ogcs.Exception.AnalyseAggregate(agex); } catch (global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { - OGCSexception.AnalyseTokenResponse(ex, false); + Ogcs.Exception.AnalyseTokenResponse(ex, false); return SyncResult.Fail; } catch (System.Net.Http.HttpRequestException ex) { - if (ex.InnerException != null && ex.InnerException is System.Net.WebException && OGCSexception.GetErrorCode(ex.InnerException) == "0x80131509") { - ex = OGCSexception.LogAsFail(ex) as System.Net.Http.HttpRequestException; + if (ex.InnerException != null && ex.InnerException is System.Net.WebException && Ogcs.Exception.GetErrorCode(ex.InnerException) == "0x80131509") { + ex = Ogcs.Exception.LogAsFail(ex) as System.Net.Http.HttpRequestException; } - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); ex.Data.Add("OGCS", "ERROR: Unable to connect to the Google calendar. Please try again. " + ((ex.InnerException != null) ? ex.InnerException.Message : ex.Message)); throw; } catch (System.ApplicationException ex) { if (ex.InnerException != null && ex.InnerException is global::Google.GoogleApiException && - (ex.Message.Contains("daily Calendar quota has been exhausted") || OGCSexception.GetErrorCode(ex.InnerException) == "0x80131500")) { + (ex.Message.Contains("daily Calendar quota has been exhausted") || Ogcs.Exception.GetErrorCode(ex.InnerException) == "0x80131500")) { Forms.Main.Instance.Console.Update(ex.Message, Console.Markup.warning); DateTime newQuota = DateTime.UtcNow.Date.AddHours(8); String tryAfter = "08:00 GMT."; @@ -339,13 +339,13 @@ private SyncResult synchronize() { //Already rescheduled to run again once new quota available, so just set to retry. ex.Data.Add("OGCS", "ERROR: Unable to connect to the Google calendar" + (this.Profile.SyncInterval == 0 ? ". Please try again after " + tryAfter : ", but OGCS is all set to automatically try again after " + tryAfter)); - OGCSexception.LogAsFail(ref ex); + Ogcs.Exception.LogAsFail(ref ex); } throw; } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); ex.Data.Add("OGCS", "ERROR: Unable to connect to the Google calendar."); - if (OGCSexception.GetErrorCode(ex) == "0x8013153B") //ex.Message == "A task was canceled." - likely timed out. + if (Ogcs.Exception.GetErrorCode(ex) == "0x8013153B") //ex.Message == "A task was canceled." - likely timed out. ex.Data["OGCS"] += " Please try again."; throw; } @@ -381,7 +381,7 @@ private SyncResult synchronize() { continue; } } catch (System.Exception ex) { - OGCSexception.Analyse("Encountered error casting calendar object to AppointmentItem - cannot sync it. ExchangeMode=" + + Ogcs.Exception.Analyse("Encountered error casting calendar object to AppointmentItem - cannot sync it. ExchangeMode=" + Outlook.Calendar.Instance.IOutlook.ExchangeConnectionMode().ToString(), ex); skipCorruptedItem(ref outlookEntries, outlookEntries[o], ex.Message); ai = (AppointmentItem)Outlook.Calendar.ReleaseObject(ai); @@ -397,16 +397,16 @@ private SyncResult synchronize() { checkStartDate = ai.Start; checkEndDate = ai.End; } catch (System.Runtime.InteropServices.COMException ex) { - if (OGCSexception.GetErrorCode(ex) == "0x80040305" || //Your server administrator has limited the number of items you can open simultaneously. - OGCSexception.GetErrorCode(ex, 0x000FFFFF) == "0x00040115") //Network problems are preventing connection to Microsoft Exchange. + if (Ogcs.Exception.GetErrorCode(ex) == "0x80040305" || //Your server administrator has limited the number of items you can open simultaneously. + Ogcs.Exception.GetErrorCode(ex, 0x000FFFFF) == "0x00040115") //Network problems are preventing connection to Microsoft Exchange. { Forms.Main.Instance.Console.UpdateWithError("Cannot continue synchronising.", ex); return SyncResult.AutoRetry; - } else if (OGCSexception.GetErrorCode(ex, 0x0000FFFF) == "0x00004005") { //You must specify a time/hour + } else if (Ogcs.Exception.GetErrorCode(ex, 0x0000FFFF) == "0x00004005") { //You must specify a time/hour skipCorruptedItem(ref outlookEntries, outlookEntries[o], ex.Message); } else { log.Debug($"EntryID: {entryID}; Start: {checkStartDate}; End: {checkEndDate}"); - OGCSexception.Analyse("Calendar item does not have a proper date range - cannot sync it. ExchangeMode=" + + Ogcs.Exception.Analyse("Calendar item does not have a proper date range - cannot sync it. ExchangeMode=" + Outlook.Calendar.Instance.IOutlook.ExchangeConnectionMode().ToString(), ex); skipCorruptedItem(ref outlookEntries, outlookEntries[o], ex.Message); } @@ -456,7 +456,7 @@ private SyncResult synchronize() { } } } catch (System.Exception ex) { - console.Update("Failed to retrieve master for Google recurring event outside of sync range.", OGCSexception.LoggingAsFail(ex) ? Console.Markup.fail : Console.Markup.error); + console.Update("Failed to retrieve master for Google recurring event outside of sync range.", Ogcs.Exception.LoggingAsFail(ex) ? Console.Markup.fail : Console.Markup.error); throw; } finally { oPattern = (RecurrencePattern)Outlook.Calendar.ReleaseObject(oPattern); @@ -803,7 +803,7 @@ private SyncResult extirpateCustomProperties(List outlookEntrie return returnVal; } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to fully cleanse metadata!", ex); + Ogcs.Exception.Analyse("Failed to fully cleanse metadata!", ex); console.UpdateWithError(null, ex); returnVal = SyncResult.Fail; return returnVal; diff --git a/src/OutlookGoogleCalendarSync/Sync/Engine.cs b/src/OutlookGoogleCalendarSync/Sync/Engine.cs index fb823b4e..e444f517 100644 --- a/src/OutlookGoogleCalendarSync/Sync/Engine.cs +++ b/src/OutlookGoogleCalendarSync/Sync/Engine.cs @@ -62,7 +62,7 @@ private void QueueTimer_Tick(object sender, EventArgs e) { Engine.Instance.ActiveProfile = job.Profile; Engine.Instance.Start(manualIgnition: false, updateSyncSchedule: (job.RequestedBy == "AutoSyncTimer")); } catch (System.Exception ex) { - OGCSexception.Analyse("Scheduled sync encountered a problem.", ex, true); + Ogcs.Exception.Analyse("Scheduled sync encountered a problem.", ex, true); } } } @@ -202,7 +202,7 @@ public void AbortSync() { bwSync.Dispose(); bwSync = null; } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } finally { log.Warn("Sync thread forcefully aborted!"); } diff --git a/src/OutlookGoogleCalendarSync/Sync/Timer.cs b/src/OutlookGoogleCalendarSync/Sync/Timer.cs index 0a21a1f1..ead96778 100644 --- a/src/OutlookGoogleCalendarSync/Sync/Timer.cs +++ b/src/OutlookGoogleCalendarSync/Sync/Timer.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using System; using System.Windows.Forms; @@ -161,7 +162,7 @@ public void ResetLastRun() { log.Fine("Updating calendar item count following Push Sync."); this.lastRunItemCount = Outlook.Calendar.Instance.GetCalendarEntriesInRange(this.owningProfile as SettingsStore.Calendar, true).Count; } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to update item count following a Push Sync.", ex); + Ogcs.Exception.Analyse("Failed to update item count following a Push Sync.", ex); } } @@ -200,10 +201,10 @@ private void ogcsPushTimer_Tick(object sender, EventArgs e) { try { Outlook.Calendar.Instance.Reset(); } catch (System.Exception ex2) { - OGCSexception.Analyse("Failed resetting Outlook connection.", ex2); + Ogcs.Exception.Analyse("Failed resetting Outlook connection.", ex2); } } else - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); if (failures == 10) Forms.Main.Instance.Console.UpdateWithError("Push Sync is failing.", ex, notifyBubble: true); } diff --git a/src/OutlookGoogleCalendarSync/Telemetry.cs b/src/OutlookGoogleCalendarSync/Telemetry.cs index 8af3a20a..ab7d5c94 100644 --- a/src/OutlookGoogleCalendarSync/Telemetry.cs +++ b/src/OutlookGoogleCalendarSync/Telemetry.cs @@ -103,7 +103,7 @@ private async Task getIpGeoData() { } } } catch (System.Exception ex) { - OGCSexception.Analyse("Could not get IP geolocation.", OGCSexception.LogAsFail(ex)); + Ogcs.Exception.Analyse("Could not get IP geolocation.", Ogcs.Exception.LogAsFail(ex)); } } @@ -153,7 +153,7 @@ public static void Send(Analytics.Category category, Analytics.Action action, St wc.UploadStringAsync(new Uri(analyticsUrl), ""); } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } @@ -228,7 +228,7 @@ public void Send() { wc.UploadStringAsync(new Uri(baseAnalyticsUrl), "POST", jsonPayload); } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } diff --git a/src/OutlookGoogleCalendarSync/TimezoneDB.cs b/src/OutlookGoogleCalendarSync/TimezoneDB.cs index dbdac4f3..051ba802 100644 --- a/src/OutlookGoogleCalendarSync/TimezoneDB.cs +++ b/src/OutlookGoogleCalendarSync/TimezoneDB.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using NodaTime.TimeZones; using System; using System.IO; @@ -64,7 +65,7 @@ private void checkForUpdate(String localVersion) { html = wc.DownloadString(nodatimeURL); } catch (System.Exception ex) { log.Error("Failed to get latest NodaTime db version."); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); return; } @@ -87,7 +88,7 @@ private void checkForUpdate(String localVersion) { instance = null; } catch (System.Exception ex) { log.Error("Failed to download new TZDB database from " + html); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } } else { @@ -96,7 +97,7 @@ private void checkForUpdate(String localVersion) { } } } catch (System.Exception ex) { - OGCSexception.Analyse("Could not check for timezone data update.", ex); + Ogcs.Exception.Analyse("Could not check for timezone data update.", ex); } } @@ -121,7 +122,7 @@ public static String FixAlexa(String timezone) { return fixedTimezone; } } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to detect and translate Alexa timezone: " + timezone, ex); + Ogcs.Exception.Analyse("Failed to detect and translate Alexa timezone: " + timezone, ex); } return timezone; } @@ -144,7 +145,7 @@ public static String FixAlexa(String timezone) { return gmtOffset; } } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to detect any timezone offset for: " + outlookTimezone, ex); + Ogcs.Exception.Analyse("Failed to detect any timezone offset for: " + outlookTimezone, ex); } return null; } @@ -167,7 +168,7 @@ public static Int16 GetUtcOffset(String IanaTimezone) { utcOffset = Convert.ToInt16(offset.Seconds / 3600); } } catch (System.Exception ex) { - OGCSexception.Analyse("Not able to convert IANA timezone '" + IanaTimezone + "' to UTC offset.", ex); + Ogcs.Exception.Analyse("Not able to convert IANA timezone '" + IanaTimezone + "' to UTC offset.", ex); } return utcOffset; } diff --git a/src/OutlookGoogleCalendarSync/Updater.cs b/src/OutlookGoogleCalendarSync/Updater.cs index d13e0bed..59c1dac0 100644 --- a/src/OutlookGoogleCalendarSync/Updater.cs +++ b/src/OutlookGoogleCalendarSync/Updater.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using Squirrel; using System; using System.ComponentModel; @@ -44,7 +45,7 @@ public async void CheckForUpdate(Button updateButton = null) { try { System.Diagnostics.Process.Start(restartUpdateExe, "--processStartAndWait OutlookGoogleCalendarSync.exe"); } catch (System.Exception ex) { - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); } try { Forms.Main.Instance.NotificationTray.ExitItem_Click(null, null); @@ -83,11 +84,11 @@ public static Boolean IsSquirrelInstall() { isSquirrelInstall = updateManager.IsInstalledApp; } } catch (System.Exception ex) { - if (OGCSexception.GetErrorCode(ex) == "0x80131500") //Update.exe not found + if (Ogcs.Exception.GetErrorCode(ex) == "0x80131500") //Update.exe not found log.Debug(ex.Message); else { log.Error("Failed to determine if app is a Squirrel install. Assuming not."); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } } @@ -156,7 +157,7 @@ private async Task githubCheck() { } catch (System.Exception ex) { squirrelGaEv.AddParameter(GA4.Squirrel.result, "Failed"); squirrelGaEv.AddParameter(GA4.Squirrel.error, ex.Message); - OGCSexception.Analyse("Failed downloading release file " + update.Filename + " for " + update.Version, ex); + Ogcs.Exception.Analyse("Failed downloading release file " + update.Filename + " for " + update.Version, ex); ex.Data.Add("analyticsLabel", "from=" + Application.ProductVersion + ";download_file=" + update.Filename + ";" + ex.Message); throw new ApplicationException("Failed upgrading OGCS.", ex); } finally { @@ -207,7 +208,7 @@ private async Task githubCheck() { break; } catch (System.AggregateException ex) { ApplyAttempt++; - if (OGCSexception.GetErrorCode(ex.InnerException) == "0x80070057") { //File does not exist + if (Ogcs.Exception.GetErrorCode(ex.InnerException) == "0x80070057") { //File does not exist //File does not exist: C:\Users\Paul\AppData\Local\OutlookGoogleCalendarSync\packages\OutlookGoogleCalendarSync-2.8.4-alpha-full.nupkg //Extract the nupkg filename String regexMatch = ".*" + updates.PackageDirectory.Replace(@"\", @"\\") + @"\\(.*?([\d\.]+-\w+).*)$"; @@ -234,13 +235,13 @@ private async Task githubCheck() { } catch (System.AggregateException ae) { squirrelGaEv.AddParameter(GA4.Squirrel.result, "Failed"); foreach (System.Exception ex in ae.InnerExceptions) { - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); squirrelGaEv.AddParameter(GA4.Squirrel.error, ex.Message); ex.Data.Add("analyticsLabel", squirrelAnalyticsLabel); throw new ApplicationException("Failed upgrading OGCS.", ex); } } catch (System.Exception ex) { - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); squirrelGaEv.AddParameter(GA4.Squirrel.result, "Failed"); squirrelGaEv.AddParameter(GA4.Squirrel.error, ex.Message); ex.Data.Add("analyticsLabel", squirrelAnalyticsLabel); @@ -265,7 +266,7 @@ private async Task githubCheck() { } catch (System.AggregateException ae) { log.Fail("Failed checking for update."); foreach (System.Exception ex in ae.InnerExceptions) { - OGCSexception.Analyse(OGCSexception.LogAsFail(ex), true); + Ogcs.Exception.Analyse(Ogcs.Exception.LogAsFail(ex), true); Telemetry.GA4Event.Event githubGaEv = new(Telemetry.GA4Event.Event.Name.squirrel); githubGaEv.AddParameter(GA4.Squirrel.state, "GitHub check"); githubGaEv.AddParameter(GA4.Squirrel.result, "Failed"); @@ -274,7 +275,7 @@ private async Task githubCheck() { throw; } } catch (System.Exception ex) { - OGCSexception.Analyse("Failed checking for update.", OGCSexception.LogAsFail(ex), true); + Ogcs.Exception.Analyse("Failed checking for update.", Ogcs.Exception.LogAsFail(ex), true); Telemetry.GA4Event.Event githubGaEv = new(Telemetry.GA4Event.Event.Name.squirrel); githubGaEv.AddParameter(GA4.Squirrel.state, "GitHub check"); githubGaEv.AddParameter(GA4.Squirrel.result, "Failed"); @@ -301,7 +302,7 @@ public static void MakeSquirrelAware() { ); } catch (System.Exception ex) { log.Error("SquirrelAwareApp.HandleEvents failed."); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); } } private static void onFirstRun() { @@ -333,7 +334,7 @@ private static void onInitialInstall(Version version) { } } catch (System.Exception ex) { log.Error("Problem encountered on initiall install."); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); } Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.install, version.ToString()); Telemetry.GA4Event.Event squirrelGaEv = new(Telemetry.GA4Event.Event.Name.squirrel); @@ -350,7 +351,7 @@ private static void onAppUpdate(Version version) { } } catch (System.Exception ex) { log.Error("Problem encountered on app update."); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); } } private static void onAppUninstall(Version version) { @@ -388,7 +389,7 @@ private static void onAppUninstall(Version version) { } } catch (System.Exception ex) { log.Error("Problem encountered on app uninstall."); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); } } @@ -415,11 +416,11 @@ private static String[] fixCliArgs() { } private static void clickOnceUninstallError(System.Exception ex) { - if (OGCSexception.GetErrorCode(ex) == "0x80131509") { + if (Ogcs.Exception.GetErrorCode(ex) == "0x80131509") { log.Debug("No ClickOnce install found."); } else { log.Error("Failed removing ClickOnce install."); - OGCSexception.Analyse(ex, true); + Ogcs.Exception.Analyse(ex, true); } } #endregion @@ -446,12 +447,12 @@ private void checkForZip(object sender, DoWorkEventArgs e) { try { html = new Extensions.OgcsWebClient().DownloadString("https://raw.githubusercontent.com/phw198/OutlookGoogleCalendarSync/master/docs/latest_zip_release.md"); } catch (System.Net.WebException ex) { - if (OGCSexception.GetErrorCode(ex) == "0x80131509") + if (Ogcs.Exception.GetErrorCode(ex) == "0x80131509") log.Warn("Failed to retrieve data (no network?): " + ex.Message); else - OGCSexception.Analyse("Failed to retrieve data", ex); + Ogcs.Exception.Analyse("Failed to retrieve data", ex); } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to retrieve data: ", ex); + Ogcs.Exception.Analyse("Failed to retrieve data: ", ex); } if (!string.IsNullOrEmpty(html)) { diff --git a/src/OutlookGoogleCalendarSync/XMLManager.cs b/src/OutlookGoogleCalendarSync/XMLManager.cs index 17d190f8..7bb4c8ca 100644 --- a/src/OutlookGoogleCalendarSync/XMLManager.cs +++ b/src/OutlookGoogleCalendarSync/XMLManager.cs @@ -1,4 +1,5 @@ -using log4net; +using Ogcs = OutlookGoogleCalendarSync; +using log4net; using System; using System.Collections.Generic; using System.IO; @@ -40,7 +41,7 @@ public static T Import(string filename) { try { result = (T)new DataContractSerializer(typeof(T)).ReadObject(fs); } catch (System.Exception ex) { - OGCSexception.Analyse(ex); + Ogcs.Exception.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 { @@ -59,27 +60,27 @@ public static string ImportElement(string nodeName, string filename, Boolean deb return xe.Value; } catch (System.InvalidOperationException ex) { - if (OGCSexception.GetErrorCode(ex) == "0x80131509") { //Sequence contains no elements + if (Ogcs.Exception.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); + Ogcs.Exception.Analyse(ex); } return null; } catch (System.IO.IOException ex) { - if (OGCSexception.GetErrorCode(ex) == "0x80070020") { //Setting file in use by another process + if (Ogcs.Exception.GetErrorCode(ex) == "0x80070020") { //Setting file in use by another process log.Warn("Failed retrieving '" + nodeName + "' from " + filename); log.Warn(ex.Message); } else { log.Error("Failed retrieving '" + nodeName + "' from " + filename); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); } return null; } catch (System.Xml.XmlException ex) { log.Warn("Failed retrieving '" + nodeName + "' from " + filename); - if (OGCSexception.GetErrorCode(ex) == "0x80131940") { //hexadecimal value 0x00, is an invalid character + if (Ogcs.Exception.GetErrorCode(ex) == "0x80131940") { //hexadecimal value 0x00, is an invalid character log.Warn(ex.Message); Settings.ResetFile(filename); try { @@ -90,17 +91,17 @@ public static string ImportElement(string nodeName, string filename, Boolean deb log.Debug("Retrieved setting '" + nodeName + "' with value '" + xe.Value + "'"); return xe.Value; } catch (System.Exception ex2) { - OGCSexception.Analyse("Still failed to retrieve '" + nodeName + "' from " + filename, ex2); + Ogcs.Exception.Analyse("Still failed to retrieve '" + nodeName + "' from " + filename, ex2); return null; } } else { - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); return null; } } catch (System.Exception ex) { log.Error("Failed retrieving '" + nodeName + "' from " + filename); - OGCSexception.Analyse(ex); + Ogcs.Exception.Analyse(ex); return null; } } @@ -110,7 +111,7 @@ public static void ExportElement(Object settingStore, String nodeName, object no try { xml = XDocument.Load(filename); } catch (System.Exception ex) { - OGCSexception.Analyse("Failed to load " + filename, ex, true); + Ogcs.Exception.Analyse("Failed to load " + filename, ex, true); throw; } XElement settingsXE = null; @@ -118,7 +119,7 @@ public static void ExportElement(Object settingStore, String nodeName, object no 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); + Ogcs.Exception.Analyse("Could not access 'Settings' element.", ex, true); return; } XElement xe = null; @@ -147,7 +148,7 @@ public static void ExportElement(Object settingStore, String nodeName, object no xml.Save(filename); log.Debug("Setting '" + nodeName + "' updated to '" + nodeValue + "'"); } catch (System.Exception ex) { - if (OGCSexception.GetErrorCode(ex) == "0x80131509") { //Sequence contains no elements + if (Ogcs.Exception.GetErrorCode(ex) == "0x80131509") { //Sequence contains no elements log.Debug("Adding Setting " + nodeName + " for " + settingStore.ToString() + " to " + filename); if (xeProfile != null) xeProfile.Add(new XElement(ns + nodeName, nodeValue)); @@ -156,7 +157,7 @@ public static void ExportElement(Object settingStore, String nodeName, object no xml.Root.Sort(); xml.Save(filename); } else { - OGCSexception.Analyse("Failed to export setting " + nodeName + "=" + nodeValue + " for " + settingStore.ToString() + " to " + filename + " file.", ex); + Ogcs.Exception.Analyse("Failed to export setting " + nodeName + "=" + nodeValue + " for " + settingStore.ToString() + " to " + filename + " file.", ex); } } } @@ -224,7 +225,7 @@ public static void MoveElement(String nodeName, XElement parent, XElement target target.Add(sourceElement); removeElement(nodeName, parent); } catch (System.Exception ex) { - OGCSexception.Analyse("Could not move '" + nodeName + "'", ex); + Ogcs.Exception.Analyse("Could not move '" + nodeName + "'", ex); } } } From 9cf6312130734d87a13e02aa4ef4df995036a8a1 Mon Sep 17 00:00:00 2001 From: Paul Woolcock <11843015+phw198@users.noreply.github.com> Date: Sun, 28 Apr 2024 12:51:15 +0100 Subject: [PATCH 4/8] Code refactor under OutlookGoogleCalendarSync.Extensions namespace Affects DateTime, fully qualify System.DateTime usage. --- .../Extensions/DateTime.cs | 10 +++--- .../Google/Authenticator.cs | 17 ++++----- .../Google/GoogleCalendar.cs | 29 +++++++-------- .../Outlook.Factory/OutlookNew.cs | 11 +++--- .../Outlook.Factory/OutlookOld.cs | 15 ++++---- .../Outlook/OutlookCalendar.cs | 29 +++++++-------- src/OutlookGoogleCalendarSync/Recurrence.cs | 35 ++++++++++--------- 7 files changed, 76 insertions(+), 70 deletions(-) diff --git a/src/OutlookGoogleCalendarSync/Extensions/DateTime.cs b/src/OutlookGoogleCalendarSync/Extensions/DateTime.cs index 1830c36c..9ffb6778 100644 --- a/src/OutlookGoogleCalendarSync/Extensions/DateTime.cs +++ b/src/OutlookGoogleCalendarSync/Extensions/DateTime.cs @@ -1,15 +1,15 @@ using Google.Apis.Calendar.v3.Data; using System; -namespace OutlookGoogleCalendarSync { - public static class DateTimeExtensions { +namespace OutlookGoogleCalendarSync.Extensions { + public static class DateTime { /// /// Returns the DateTime with time and GMT offset. /// This used to be the string format Google held date-times, eg "2012-08-20T00:00:00+02:00" /// /// Date-time valule /// Formatted string - public static String ToPreciseString(this DateTime dt) { + public static String ToPreciseString(this System.DateTime dt) { return dt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", new System.Globalization.CultureInfo("en-US")); } @@ -17,8 +17,8 @@ public static String ToPreciseString(this DateTime dt) { /// Returns the non-null Date or DateTime properties as a DateTime /// /// DateTime - public static DateTime SafeDateTime(this EventDateTime evDt) { - return evDt.DateTime ?? DateTime.Parse(evDt.Date); + public static System.DateTime SafeDateTime(this EventDateTime evDt) { + return evDt.DateTime ?? System.DateTime.Parse(evDt.Date); } /// diff --git a/src/OutlookGoogleCalendarSync/Google/Authenticator.cs b/src/OutlookGoogleCalendarSync/Google/Authenticator.cs index c12f1824..564e95e0 100644 --- a/src/OutlookGoogleCalendarSync/Google/Authenticator.cs +++ b/src/OutlookGoogleCalendarSync/Google/Authenticator.cs @@ -1,16 +1,17 @@ -using Ogcs = OutlookGoogleCalendarSync; -using Google.Apis.Auth.OAuth2; +using Google.Apis.Auth.OAuth2; using Google.Apis.Calendar.v3; using Google.Apis.Calendar.v3.Data; using Google.Apis.Util.Store; using log4net; using Newtonsoft.Json.Linq; +using OutlookGoogleCalendarSync.Extensions; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; +using Ogcs = OutlookGoogleCalendarSync; namespace OutlookGoogleCalendarSync.Google { public class Authenticator { @@ -142,7 +143,7 @@ private async Task getAuthenticated(ClientSecrets cs) { if (Settings.Instance.Proxy.Type == "Custom") Ogcs.Google.Calendar.Instance.Service.HttpClient.DefaultRequestHeaders.Add("user-agent", Settings.Instance.Proxy.BrowserUserAgent); - if (credential.Token.IssuedUtc.AddSeconds(credential.Token.ExpiresInSeconds.Value) < DateTime.UtcNow.AddMinutes(1)) { + if (credential.Token.IssuedUtc.AddSeconds(credential.Token.ExpiresInSeconds.Value) < System.DateTime.UtcNow.AddMinutes(1)) { log.Debug("Access token needs refreshing."); //This will happen automatically when using the calendar service //But we need a valid token before we call getGaccountEmail() which doesn't use the service @@ -307,8 +308,8 @@ public static String GetMd5(String input, Boolean isEmailAddress = false, Boolea } #region OGCS user status - public static readonly DateTime SubscribedNever = new DateTime(2000, 1, 1); - public static readonly DateTime SubscribedBefore = new DateTime(2001, 1, 1); + public static readonly System.DateTime SubscribedNever = new System.DateTime(2000, 1, 1); + public static readonly System.DateTime SubscribedBefore = new System.DateTime(2001, 1, 1); public void OgcsUserStatus() { if (!checkedOgcsUserStatus) { @@ -383,9 +384,9 @@ public Boolean UserSubscriptionCheck() { } else { Boolean subscribed; Event subscription = subscriptions.Last(); - DateTime subscriptionStart = subscription.Start.SafeDateTime().Date; + System.DateTime subscriptionStart = subscription.Start.SafeDateTime().Date; log.Debug("Last subscription date: " + subscriptionStart.ToString()); - Double subscriptionRemaining = (subscriptionStart.AddYears(1) - DateTime.Now.Date).TotalDays; + Double subscriptionRemaining = (subscriptionStart.AddYears(1) - System.DateTime.Now.Date).TotalDays; if (subscriptionRemaining >= 0) { if (subscriptionRemaining > 360) Forms.Main.Instance.SyncNote(Forms.Main.SyncNotes.RecentSubscription, null); @@ -398,7 +399,7 @@ public Boolean UserSubscriptionCheck() { subscribed = false; } - DateTime prevSubscriptionStart = Settings.Instance.Subscribed; + System.DateTime prevSubscriptionStart = Settings.Instance.Subscribed; if (subscribed) { log.Info("User has an active subscription."); Settings.Instance.Subscribed = subscriptionStart; diff --git a/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs b/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs index b7f630b2..bb8230f8 100644 --- a/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs +++ b/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs @@ -1,8 +1,8 @@ -using Ogcs = OutlookGoogleCalendarSync; -using Google.Apis.Calendar.v3; +using Google.Apis.Calendar.v3; using Google.Apis.Calendar.v3.Data; using log4net; using Microsoft.Office.Interop.Outlook; +using OutlookGoogleCalendarSync.Extensions; using System; using System.Collections.Generic; using System.IO; @@ -10,6 +10,7 @@ using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; +using Ogcs = OutlookGoogleCalendarSync; namespace OutlookGoogleCalendarSync.Google { /// @@ -275,7 +276,7 @@ public List GetCalendarEntriesInRange() { return GetCalendarEntriesInRange(profile.SyncStart, profile.SyncEnd); } - public List GetCalendarEntriesInRange(DateTime from, DateTime to) { + public List GetCalendarEntriesInRange(System.DateTime from, System.DateTime to) { List result = new List(); ExcludedByColour = new Dictionary(); Events request = null; @@ -805,8 +806,8 @@ public Event UpdateCalendarEntry(AppointmentItem ai, Event ev, ref int itemModif sb.AppendLine(aiSummary); //Handle an event's all-day attribute being toggled - DateTime evStart = ev.Start.SafeDateTime(); - DateTime evEnd = ev.End.SafeDateTime(); + System.DateTime evStart = ev.Start.SafeDateTime(); + System.DateTime evEnd = ev.End.SafeDateTime(); if (ai.AllDayEvent && ai.Start.TimeOfDay == new TimeSpan(0, 0, 0)) { ev.Start.DateTime = null; ev.End.DateTime = null; @@ -1345,7 +1346,7 @@ public void CleanDuplicateEntries(ref List google) { log.Warn(duplicateCheck.Count() + " Events found with same creation date and Outlook EntryID."); duplicateCheck.Sort((x, y) => (x.CreatedRaw + ":" + (x.Sequence ?? 0)).CompareTo(y.CreatedRaw + ":" + (y.Sequence ?? 0))); //Skip the first one, the original - DateTime? lastSeenDuplicateSet = null; + System.DateTime? lastSeenDuplicateSet = null; for (int g = 0; g < duplicateCheck.Count(); g++) { Event ev = duplicateCheck[g]; if (lastSeenDuplicateSet == null || lastSeenDuplicateSet != ev.Created) { @@ -2191,10 +2192,10 @@ public static String GetEventSummary(Event ev, out String eventSummaryAnonymised if (!onlyIfNotVerbose || onlyIfNotVerbose && !Settings.Instance.VerboseOutput) { try { if (ev.Start.DateTime != null) { - DateTime gDate = (DateTime)ev.Start.DateTime; + System.DateTime gDate = (System.DateTime)ev.Start.DateTime; eventSummary += gDate.ToShortDateString() + " " + gDate.ToShortTimeString(); } else - eventSummary += DateTime.Parse(ev.Start.Date).ToShortDateString(); + eventSummary += System.DateTime.Parse(ev.Start.Date).ToShortDateString(); if ((ev.Recurrence != null && ev.RecurringEventId == null) || ev.RecurringEventId != null) eventSummary += " (R)"; @@ -2279,7 +2280,7 @@ public static ApiException HandleAPIlimits(ref global::Google.GoogleApiException APIlimitReached_attendee = true; Settings.Instance.APIlimit_inEffect = true; - Settings.Instance.APIlimit_lastHit = DateTime.Now; + Settings.Instance.APIlimit_lastHit = System.DateTime.Now; ev.Attendees = new List(); return ApiException.backoffThenRetry; @@ -2296,8 +2297,8 @@ public static ApiException HandleAPIlimits(ref global::Google.GoogleApiException //Delay next scheduled sync until after the new quota if (profile.SyncInterval != 0) { - DateTime utcNow = DateTime.UtcNow; - DateTime quotaReset = utcNow.Date.AddHours(8).AddMinutes(utcNow.Minute); + System.DateTime utcNow = System.DateTime.UtcNow; + System.DateTime quotaReset = utcNow.Date.AddHours(8).AddMinutes(utcNow.Minute); if ((quotaReset - utcNow).Ticks < 0) quotaReset = quotaReset.AddDays(1); int delayMins = (int)(quotaReset - utcNow).TotalMinutes; profile.OgcsTimer.SetNextSync(delayMins, fromNow: true, calculateInterval: false); @@ -2306,7 +2307,7 @@ public static ApiException HandleAPIlimits(ref global::Google.GoogleApiException return ApiException.freeAPIexhausted; } else if (ex.Message.Contains("Rate Limit Exceeded")) { - if (Settings.Instance.Subscribed > DateTime.Now.AddYears(-1)) + if (Settings.Instance.Subscribed > System.DateTime.Now.AddYears(-1)) return ApiException.backoffThenRetry; log.Warn("Google's free Calendar quota is being exceeded!"); @@ -2314,8 +2315,8 @@ public static ApiException HandleAPIlimits(ref global::Google.GoogleApiException //Delay next scheduled sync for an hour if (profile.SyncInterval != 0) { - DateTime utcNow = DateTime.UtcNow; - DateTime nextSync = utcNow.AddMinutes(60 + new Random().Next(1, 10)); + System.DateTime utcNow = System.DateTime.UtcNow; + System.DateTime nextSync = utcNow.AddMinutes(60 + new Random().Next(1, 10)); int delayMins = (int)(nextSync - utcNow).TotalMinutes; profile.OgcsTimer.SetNextSync(delayMins, fromNow: true, calculateInterval: false); Forms.Main.Instance.Console.Update("The next sync has been delayed by " + delayMins + " minutes to let free quota rebuild.", Console.Markup.warning); diff --git a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookNew.cs b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookNew.cs index 9b50a640..4bb8223b 100644 --- a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookNew.cs +++ b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookNew.cs @@ -1,11 +1,12 @@ -using Ogcs = OutlookGoogleCalendarSync; -using Google.Apis.Calendar.v3.Data; +using Google.Apis.Calendar.v3.Data; using log4net; using Microsoft.Office.Interop.Outlook; +using OutlookGoogleCalendarSync.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; +using Ogcs = OutlookGoogleCalendarSync; namespace OutlookGoogleCalendarSync.Outlook { class OutlookNew : Interface { @@ -214,11 +215,11 @@ public NameSpace GetCurrentUser(NameSpace oNS) { Recipient currentUser = null; try { - DateTime triggerOOMsecurity = DateTime.Now; + System.DateTime triggerOOMsecurity = System.DateTime.Now; SettingsStore.Calendar profile = Settings.Profile.InPlay(); try { currentUser = oNS.CurrentUser; - if (!Forms.Main.Instance.IsHandleCreated && (DateTime.Now - triggerOOMsecurity).TotalSeconds > 1) { + if (!Forms.Main.Instance.IsHandleCreated && (System.DateTime.Now - triggerOOMsecurity).TotalSeconds > 1) { log.Warn(">1s delay possibly due to Outlook security popup."); Outlook.Calendar.OOMsecurityInfo = true; } @@ -977,7 +978,7 @@ private TimeZoneInfo getWindowsTimezoneFromDescription(String tzDescription) { return null; } - public DateTime GetEndInEndTimeZone(AppointmentItem ai) { + public System.DateTime GetEndInEndTimeZone(AppointmentItem ai) { return ai.EndInEndTimeZone; } diff --git a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs index 14a5b353..9e1de0ff 100644 --- a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs +++ b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs @@ -1,12 +1,13 @@ -using Ogcs = OutlookGoogleCalendarSync; -using Google.Apis.Calendar.v3.Data; +using Google.Apis.Calendar.v3.Data; using log4net; using Microsoft.Office.Interop.Outlook; +using OutlookGoogleCalendarSync.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; +using Ogcs = OutlookGoogleCalendarSync; namespace OutlookGoogleCalendarSync.Outlook { class OutlookOld : Interface { @@ -194,10 +195,10 @@ public NameSpace GetCurrentUser(NameSpace oNS) { Recipient currentUser = null; try { - DateTime triggerOOMsecurity = DateTime.Now; + System.DateTime triggerOOMsecurity = System.DateTime.Now; try { currentUser = oNS.CurrentUser; - if (!Forms.Main.Instance.IsHandleCreated && (DateTime.Now - triggerOOMsecurity).TotalSeconds > 1) { + if (!Forms.Main.Instance.IsHandleCreated && (System.DateTime.Now - triggerOOMsecurity).TotalSeconds > 1) { log.Warn(">1s delay possibly due to Outlook security popup."); Outlook.Calendar.OOMsecurityInfo = true; } @@ -804,8 +805,8 @@ public AppointmentItem WindowsTimeZone_set(AppointmentItem ai, Event ev, String return ai; } - private DateTime WindowsTimeZone(EventDateTime time) { - DateTime theDate = time.SafeDateTime(); + private System.DateTime WindowsTimeZone(EventDateTime time) { + System.DateTime theDate = time.SafeDateTime(); /*if (time.TimeZone == null)*/ return theDate; @@ -819,7 +820,7 @@ private DateTime WindowsTimeZone(EventDateTime time) { */ } - public DateTime GetEndInEndTimeZone(AppointmentItem ai) { + public System.DateTime GetEndInEndTimeZone(AppointmentItem ai) { return ai.End; } diff --git a/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs b/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs index fb07f155..3729926a 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs @@ -1,14 +1,15 @@ -using Ogcs = OutlookGoogleCalendarSync; -using Google.Apis.Calendar.v3.Data; +using Google.Apis.Calendar.v3.Data; using log4net; using Microsoft.Office.Interop.Outlook; +using OutlookGoogleCalendarSync.Extensions; using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text.RegularExpressions; using System.Text; +using System.Text.RegularExpressions; using System.Windows.Forms; +using Ogcs = OutlookGoogleCalendarSync; namespace OutlookGoogleCalendarSync.Outlook { /// @@ -162,8 +163,8 @@ public List FilterCalendarEntries(SettingsStore.Calendar profil OutlookItems.Sort("[Start]", Type.Missing); OutlookItems.IncludeRecurrences = false; - DateTime min = DateTime.MinValue; - DateTime max = DateTime.MaxValue; + System.DateTime min = System.DateTime.MinValue; + System.DateTime max = System.DateTime.MaxValue; if (!noDateFilter) { min = profile.SyncStart; max = profile.SyncEnd; @@ -197,7 +198,7 @@ public List FilterCalendarEntries(SettingsStore.Calendar profil } catch (System.NullReferenceException) { log.Debug("NullReferenceException accessing ai.End"); try { - DateTime start = ai.Start; + System.DateTime start = ai.Start; } catch (System.NullReferenceException) { try { log.Debug("Subject: " + ai.Subject); } catch { } log.Fail("Appointment item seems unusable - no Start or End date! Discarding."); @@ -355,8 +356,8 @@ private void createCalendarEntry(Event ev, ref AppointmentItem ai) { SettingsStore.Calendar profile = Sync.Engine.Calendar.Instance.Profile; - ai.Start = new DateTime(); - ai.End = new DateTime(); + ai.Start = new System.DateTime(); + ai.End = new System.DateTime(); ai.AllDayEvent = ev.AllDayEvent(); ai = Outlook.Calendar.Instance.IOutlook.WindowsTimeZone_set(ai, ev); Recurrence.Instance.BuildOutlookPattern(ev, ai); @@ -529,10 +530,10 @@ public Boolean UpdateCalendarEntry(ref AppointmentItem ai, Event ev, ref int ite #endregion #region Start/End & Recurrence - DateTime evStartParsedDate = ev.Start.SafeDateTime(); + System.DateTime evStartParsedDate = ev.Start.SafeDateTime(); Boolean startChange = Sync.Engine.CompareAttribute("Start time", Sync.Direction.GoogleToOutlook, evStartParsedDate, ai.Start, sb, ref itemModified); - DateTime evEndParsedDate = ev.End.SafeDateTime(); + System.DateTime evEndParsedDate = ev.End.SafeDateTime(); Boolean endChange = Sync.Engine.CompareAttribute("End time", Sync.Direction.GoogleToOutlook, evEndParsedDate, ai.End, sb, ref itemModified); RecurrencePattern oPattern = null; @@ -1636,7 +1637,7 @@ public Boolean IsOKtoSyncReminder(AppointmentItem ai) { SettingsStore.Calendar profile = Sync.Engine.Calendar.Instance.Profile; if (profile.ReminderDND) { - DateTime alarm; + System.DateTime alarm; if (ai.ReminderSet) alarm = ai.Start.AddMinutes(-ai.ReminderMinutesBeforeStart); else { @@ -1650,15 +1651,15 @@ public Boolean IsOKtoSyncReminder(AppointmentItem ai) { } return true; } - private Boolean isOKtoSyncReminder(DateTime alarm) { + private Boolean isOKtoSyncReminder(System.DateTime alarm) { SettingsStore.Calendar profile = Sync.Engine.Calendar.Instance.Profile; if (profile.ReminderDNDstart.TimeOfDay > profile.ReminderDNDend.TimeOfDay) { //eg 22:00 to 06:00 //Make sure end time is the day following the start time int shiftDay = 0; - DateTime dndStart; - DateTime dndEnd; + System.DateTime dndStart; + System.DateTime dndEnd; if (alarm.TimeOfDay < profile.ReminderDNDstart.TimeOfDay) shiftDay = -1; dndStart = alarm.Date.AddDays(shiftDay).Add(profile.ReminderDNDstart.TimeOfDay); dndEnd = alarm.Date.AddDays(shiftDay + 1).Add(profile.ReminderDNDend.TimeOfDay); diff --git a/src/OutlookGoogleCalendarSync/Recurrence.cs b/src/OutlookGoogleCalendarSync/Recurrence.cs index 3c0d6ca7..7348a346 100644 --- a/src/OutlookGoogleCalendarSync/Recurrence.cs +++ b/src/OutlookGoogleCalendarSync/Recurrence.cs @@ -1,11 +1,12 @@ -using Ogcs = OutlookGoogleCalendarSync; -using Google.Apis.Calendar.v3.Data; +using Google.Apis.Calendar.v3.Data; using log4net; using Microsoft.Office.Interop.Outlook; +using OutlookGoogleCalendarSync.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; +using Ogcs = OutlookGoogleCalendarSync; namespace OutlookGoogleCalendarSync { class Recurrence { @@ -34,11 +35,11 @@ public List BuildGooglePattern(AppointmentItem ai, Event ev) { RecurrencePattern rp = null; try { rp = ai.GetRecurrencePattern(); - DateTime utcEnd; + System.DateTime utcEnd; if (ai.AllDayEvent) utcEnd = rp.PatternEndDate; else { - DateTime localEnd = rp.PatternEndDate + Outlook.Calendar.Instance.IOutlook.GetEndInEndTimeZone(ai).TimeOfDay; + System.DateTime localEnd = rp.PatternEndDate + Outlook.Calendar.Instance.IOutlook.GetEndInEndTimeZone(ai).TimeOfDay; utcEnd = TimeZoneInfo.ConvertTimeToUtc(localEnd, TimeZoneInfo.FindSystemTimeZoneById(Outlook.Calendar.Instance.IOutlook.GetEndTimeZoneID(ai))); } gPattern.Add("RRULE:" + buildRrule(rp, utcEnd)); @@ -142,11 +143,11 @@ private void buildOutlookPattern(Event ev, AppointmentItem ai, out RecurrencePat log.Warn("Outlook can't handle end dates this far in the future. Converting to no end date."); oPattern.NoEndDate = true; } else { - DateTime endDate; + System.DateTime endDate; if (ruleBook["UNTIL"].Length == 8 && !ruleBook["UNTIL"].EndsWith("Z")) - endDate = DateTime.ParseExact(ruleBook["UNTIL"], "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).Date; + endDate = System.DateTime.ParseExact(ruleBook["UNTIL"], "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).Date; else { - endDate = DateTime.ParseExact(ruleBook["UNTIL"], "yyyyMMddTHHmmssZ", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal); + endDate = System.DateTime.ParseExact(ruleBook["UNTIL"], "yyyyMMddTHHmmssZ", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal); endDate = endDate.AddHours(TimezoneDB.GetUtcOffset(ev.End.TimeZone)).Date; } if (endDate < oPattern.PatternStartDate) { @@ -220,7 +221,7 @@ public void CompareOutlookPattern(Event ev, ref RecurrencePattern aiOpattern, Sy } } - private String buildRrule(RecurrencePattern oPattern, DateTime recurrenceEndUtc) { + private String buildRrule(RecurrencePattern oPattern, System.DateTime recurrenceEndUtc) { log.Fine("Building RRULE"); rrule = new Dictionary(); #region RECURRENCE PATTERN @@ -373,7 +374,7 @@ private static OlDaysOfWeek getDOWmask(String byDay) { return dowMask; } - public static String IANAdate(DateTime dt) { + public static String IANAdate(System.DateTime dt) { return dt.ToString("yyyyMMddTHHmmssZ"); } #endregion @@ -432,7 +433,7 @@ public void SeparateGoogleExceptions(List allEvents) { /// The recurring series to search within /// The date to search for /// - private Event getGoogleInstance(String recurringEventId, DateTime originalInstanceDate) { + private Event getGoogleInstance(String recurringEventId, System.DateTime originalInstanceDate) { return googleExceptions.FirstOrDefault(g => g.RecurringEventId == recurringEventId && g.OriginalStartTime.SafeDateTime().Date == originalInstanceDate); } @@ -581,7 +582,7 @@ public static void CreateGoogleExceptions(AppointmentItem ai, String recurringEv oExcp = excps[e]; for (int g = 0; g < gRecurrences.Count; g++) { Event ev = gRecurrences[g]; - DateTime gDate = ev.OriginalStartTime.SafeDateTime(); + System.DateTime gDate = ev.OriginalStartTime.SafeDateTime(); DeletionState isDeleted = exceptionIsDeleted(oExcp); if (isDeleted == DeletionState.Inaccessible) { log.Warn("Abandoning creation of Google recurrence exception as Outlook exception is inaccessible."); @@ -680,7 +681,7 @@ public static void UpdateGoogleExceptions(AppointmentItem ai, Event ev, Boolean try { oExcp = excps[e]; int excp_itemModified = 0; - DateTime oExcp_currDate; + System.DateTime oExcp_currDate; //Check the exception falls in the date range being synced DeletionState oIsDeleted = exceptionIsDeleted(oExcp); @@ -718,7 +719,7 @@ public static void UpdateGoogleExceptions(AppointmentItem ai, Event ev, Boolean } continue; } else if (oIsDeleted == DeletionState.Deleted && gExcp.Status != "cancelled") { - DateTime movedToStartDate = gExcp.Start.SafeDateTime().Date; + System.DateTime movedToStartDate = gExcp.Start.SafeDateTime().Date; log.Fine("Checking if we have another Google instance that /is/ cancelled on " + movedToStartDate.ToString("dd-MMM-yyyy") + " that this one has been moved to."); Event duplicate = Recurrence.Instance.getGoogleInstance(gExcp.RecurringEventId, movedToStartDate); DialogResult dr = DialogResult.Yes; @@ -744,7 +745,7 @@ public static void UpdateGoogleExceptions(AppointmentItem ai, Event ev, Boolean log.Fine("Modification time difference (in days) between G and O exception: " + modifiedDiff); Boolean forceCompare = modifiedDiff < TimeSpan.FromDays(1); Ogcs.Google.Calendar.Instance.UpdateCalendarEntry(aiExcp, gExcp, ref excp_itemModified, forceCompare); - if (forceCompare && excp_itemModified == 0 && DateTime.Now > aiExcp.LastModificationTime.AddDays(1)) { + if (forceCompare && excp_itemModified == 0 && System.DateTime.Now > aiExcp.LastModificationTime.AddDays(1)) { Ogcs.Google.CustomProperty.SetOGCSlastModified(ref gExcp); try { log.Debug("Doing a dummy update in order to update the last modified date of Google recurring series exception."); @@ -853,8 +854,8 @@ private void processOutlookExceptions(ref AppointmentItem ai, List evExce oPattern = ai.GetRecurrencePattern(); foreach (Event gExcp in evExceptions) { - DateTime gExcpOrigDate = gExcp.OriginalStartTime.SafeDateTime(); - DateTime? gExcpCurrDate = gExcp.Start == null ? null : gExcp.Start.SafeDateTime(); + System.DateTime gExcpOrigDate = gExcp.OriginalStartTime.SafeDateTime(); + System.DateTime? gExcpCurrDate = gExcp.Start == null ? null : gExcp.Start.SafeDateTime(); log.Fine("Found Google exception for original date " + gExcpOrigDate.ToString() + (gExcpCurrDate != null ? " now on " + gExcpCurrDate.ToString() : "")); AppointmentItem newAiExcp = null; @@ -909,7 +910,7 @@ private void processOutlookExceptions(ref AppointmentItem ai, List evExce } } - private static void getOutlookInstance(RecurrencePattern oPattern, DateTime instanceOrigDate, ref AppointmentItem ai, Boolean processingDeletions) { + private static void getOutlookInstance(RecurrencePattern oPattern, System.DateTime instanceOrigDate, ref AppointmentItem ai, Boolean processingDeletions) { //The Outlook API is rubbish: oPattern.GetOccurrence(instanceDate) returns anything currently on that date NOW, regardless of if it was moved there. //Even worse, if 2-Feb was deleted then 1-Feb occurrence is moved to 2-Feb, it will return 2-Feb but there is no OriginalStartDate property to know it was moved. From 7fdffc0a3003a98a4a7db50df039efe917d6ae4c Mon Sep 17 00:00:00 2001 From: Paul Woolcock <11843015+phw198@users.noreply.github.com> Date: Sun, 28 Apr 2024 13:15:10 +0100 Subject: [PATCH 5/8] Code refactor of MessageBox under OutlookGoogleCalendarSync.Extensions namespace --- .../Extensions/ColourPicker.cs | 2 +- .../Extensions/MessageBox.cs | 18 ++++++----- .../Forms/ColourMap.cs | 6 ++-- .../Forms/MainForm.cs | 32 +++++++++---------- src/OutlookGoogleCalendarSync/Forms/Social.cs | 3 +- .../Forms/UpdateInfo.cs | 2 +- .../Google/ApiKeyring.cs | 2 +- .../Google/Authenticator.cs | 8 ++--- .../Google/ErrorReporting.cs | 2 +- .../Google/GoogleCalendar.cs | 24 +++++++------- .../Outlook.Factory/OutlookNew.cs | 10 +++--- .../Outlook.Factory/OutlookOld.cs | 6 ++-- .../Outlook/ExplorerWatcher.cs | 8 ++--- .../Outlook/OutlookCalendar.cs | 18 +++++------ .../Outlook/OutlookCategories.cs | 2 +- src/OutlookGoogleCalendarSync/Program.cs | 10 +++--- src/OutlookGoogleCalendarSync/Recurrence.cs | 4 +-- .../SettingsStore/Settings.cs | 2 +- .../Sync/Calendar.cs | 10 +++--- src/OutlookGoogleCalendarSync/Sync/Engine.cs | 6 ++-- src/OutlookGoogleCalendarSync/Updater.cs | 16 +++++----- 21 files changed, 97 insertions(+), 94 deletions(-) diff --git a/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs b/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs index 4bb7999d..58306015 100644 --- a/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs +++ b/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs @@ -91,7 +91,7 @@ public void ColourPicker_DrawItem(object sender, System.Windows.Forms.DrawItemEv private void ColourPicker_Enter(object sender, EventArgs e) { if (Forms.Main.Instance.ActiveCalendarProfile.UseGoogleCalendar == null || string.IsNullOrEmpty(Forms.Main.Instance.ActiveCalendarProfile.UseGoogleCalendar.Id)) { - OgcsMessageBox.Show("You need to select a Google Calendar first on the 'Settings' tab.", "Configuration Required", MessageBoxButtons.OK, MessageBoxIcon.Information); + Ogcs.Extensions.MessageBox.Show("You need to select a Google Calendar first on the 'Settings' tab.", "Configuration Required", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } diff --git a/src/OutlookGoogleCalendarSync/Extensions/MessageBox.cs b/src/OutlookGoogleCalendarSync/Extensions/MessageBox.cs index edfbd498..58f83c39 100644 --- a/src/OutlookGoogleCalendarSync/Extensions/MessageBox.cs +++ b/src/OutlookGoogleCalendarSync/Extensions/MessageBox.cs @@ -1,11 +1,13 @@ using System.Runtime.InteropServices; +using System.Windows.Forms; +using System; using log4net; -namespace System.Windows.Forms { - public static class OgcsMessageBox { - private static readonly ILog log = LogManager.GetLogger(typeof(OgcsMessageBox)); +namespace OutlookGoogleCalendarSync.Extensions { + public static class MessageBox { + private static readonly ILog log = LogManager.GetLogger(typeof(MessageBox)); private static DialogResult dr; - + #region Window flashing [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] @@ -77,12 +79,12 @@ public static DialogResult Show(string text, string caption, MessageBoxButtons b mainFrm.Invoke(new System.Action(() => { mainFrm.MainFormShow(); flashWindow(mainFrm.Handle, flashMode.FLASHW_ALL | flashMode.FLASHW_TIMERNOFG); - dr = MessageBox.Show(mainFrm, text, caption, buttons, icon); + dr = System.Windows.Forms.MessageBox.Show(mainFrm, text, caption, buttons, icon); })); } else { mainFrm.MainFormShow(); flashWindow(mainFrm.Handle, flashMode.FLASHW_ALL | flashMode.FLASHW_TIMERNOFG); - dr = MessageBox.Show(mainFrm, text, caption, buttons, icon); + dr = System.Windows.Forms.MessageBox.Show(mainFrm, text, caption, buttons, icon); } log.Debug("Response: " + dr.ToString()); return dr; @@ -107,12 +109,12 @@ public static DialogResult Show(string text, string caption, MessageBoxButtons b mainFrm.Invoke(new System.Action(() => { mainFrm.MainFormShow(); flashWindow(mainFrm.Handle, flashMode.FLASHW_ALL | flashMode.FLASHW_TIMERNOFG); - dr = MessageBox.Show(mainFrm, text, caption, buttons, icon, defaultButton); + dr = System.Windows.Forms.MessageBox.Show(mainFrm, text, caption, buttons, icon, defaultButton); })); } else { mainFrm.MainFormShow(); flashWindow(mainFrm.Handle, flashMode.FLASHW_ALL | flashMode.FLASHW_TIMERNOFG); - dr = MessageBox.Show(mainFrm, text, caption, buttons, icon, defaultButton); + dr = System.Windows.Forms.MessageBox.Show(mainFrm, text, caption, buttons, icon, defaultButton); } log.Debug("Response: " + dr.ToString()); return dr; diff --git a/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs b/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs index 4190f09f..ec464b89 100644 --- a/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs +++ b/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs @@ -119,15 +119,15 @@ private void btOK_Click(object sender, EventArgs e) { String gDuplicates = string.Join("\r\n", gColValues.GroupBy(v => v).Where(g => g.Count() > 1).Select(s => "- " + s.Key).ToList()); if (!string.IsNullOrEmpty(oDuplicates) && (profile.SyncDirection.Id == Sync.Direction.OutlookToGoogle.Id || profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id)) { - OgcsMessageBox.Show("The following Outlook categories cannot be mapped more than once:-\r\n\r\n" + oDuplicates, "Duplicate Outlook Mappings", MessageBoxButtons.OK, MessageBoxIcon.Stop); + Ogcs.Extensions.MessageBox.Show("The following Outlook categories cannot be mapped more than once:-\r\n\r\n" + oDuplicates, "Duplicate Outlook Mappings", MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } else if (!string.IsNullOrEmpty(gDuplicates) && (profile.SyncDirection.Id == Sync.Direction.GoogleToOutlook.Id || profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id)) { - OgcsMessageBox.Show("The following Google colours cannot be mapped more than once:-\r\n\r\n" + gDuplicates, "Duplicate Google Mappings", MessageBoxButtons.OK, MessageBoxIcon.Stop); + Ogcs.Extensions.MessageBox.Show("The following Google colours cannot be mapped more than once:-\r\n\r\n" + gDuplicates, "Duplicate Google Mappings", MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } } catch (System.Exception ex) { Ogcs.Exception.Analyse("Failed looking for duplicating mappings before storing in Settings.", ex); - OgcsMessageBox.Show("An error was encountered storing your custom mappings.", "Cannot save mappings", MessageBoxButtons.OK, MessageBoxIcon.Error); + Ogcs.Extensions.MessageBox.Show("An error was encountered storing your custom mappings.", "Cannot save mappings", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } diff --git a/src/OutlookGoogleCalendarSync/Forms/MainForm.cs b/src/OutlookGoogleCalendarSync/Forms/MainForm.cs index cf0090d5..81dd6b94 100644 --- a/src/OutlookGoogleCalendarSync/Forms/MainForm.cs +++ b/src/OutlookGoogleCalendarSync/Forms/MainForm.cs @@ -360,7 +360,7 @@ public void UpdateGUIsettings_Profile() { if (cbOutlookCalendars.SelectedIndex == -1) { if (!string.IsNullOrEmpty(profile.UseOutlookCalendar.Id)) { log.Warn("Outlook calendar '" + profile.UseOutlookCalendar.Name + "' could no longer be found. Selected calendar '" + Outlook.Calendar.Instance.CalendarFolders.First().Key + "' instead."); - OgcsMessageBox.Show("The Outlook calendar '" + profile.UseOutlookCalendar.Name + "' previously configured for syncing is no longer available.\r\n\r\n" + + Ogcs.Extensions.MessageBox.Show("The Outlook calendar '" + profile.UseOutlookCalendar.Name + "' previously configured for syncing is no longer available.\r\n\r\n" + "'" + Outlook.Calendar.Instance.CalendarFolders.First().Key + "' calendar has been selected instead and any automated syncs have been temporarily disabled.", "Outlook Calendar Unavailable", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); profile.SyncInterval = 0; @@ -657,13 +657,13 @@ private void applyProxy() { if (rbProxyCustom.Checked) { if (String.IsNullOrEmpty(txtProxyServer.Text) || String.IsNullOrEmpty(txtProxyPort.Text)) { - OgcsMessageBox.Show("A proxy server name and port must be provided.", "Proxy Authentication Enabled", + Ogcs.Extensions.MessageBox.Show("A proxy server name and port must be provided.", "Proxy Authentication Enabled", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } int nPort; if (!int.TryParse(txtProxyPort.Text, out nPort)) { - OgcsMessageBox.Show("Proxy server port must be a number.", "Invalid Proxy Port", + Ogcs.Extensions.MessageBox.Show("Proxy server port must be a number.", "Invalid Proxy Port", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } @@ -1078,7 +1078,7 @@ private void tbSyncNote_Click(object sender, EventArgs e) { if (!String.IsNullOrEmpty(tbSyncNote.Tag.ToString())) { if (tbSyncNote.Tag.ToString().EndsWith("for ")) { log.Info("User wanted to subscribe, but Google account username is not known :("); - DialogResult authorise = OgcsMessageBox.Show("Thank you for your interest in subscribing. " + + DialogResult authorise = Ogcs.Extensions.MessageBox.Show("Thank you for your interest in subscribing. " + "To kick things off, you'll need to re-authorise OGCS to manage your Google calendar. " + "Would you like to do that now?", "Proceed with authorisation?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (authorise == DialogResult.Yes) { @@ -1088,7 +1088,7 @@ private void tbSyncNote_Click(object sender, EventArgs e) { } } else { if (tbSyncNote.Tag.ToString().Contains("OGCS Premium renewal")) { - OgcsMessageBox.Show("Before renewing, please ensure you don't already have an active recurring annual payment set up in PayPal :-)", + Ogcs.Extensions.MessageBox.Show("Before renewing, please ensure you don't already have an active recurring annual payment set up in PayPal :-)", "Recurring payment already configured?", MessageBoxButtons.OK, MessageBoxIcon.Warning); } Helper.OpenBrowser(tbSyncNote.Tag.ToString()); @@ -1501,10 +1501,10 @@ private void btTestOutlookFilter_Click(object sender, EventArgs e) { msg += " and " + ActiveCalendarProfile.SyncEnd.ToString(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern); log.Info(msg); - OgcsMessageBox.Show(msg, "Date-Time Format Results", MessageBoxButtons.OK, MessageBoxIcon.Information); + Ogcs.Extensions.MessageBox.Show(msg, "Date-Time Format Results", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (System.Exception ex) { Ogcs.Exception.Analyse("Profile '" + Settings.Profile.Name(ActiveCalendarProfile) + "', calendar ID " + ActiveCalendarProfile.UseOutlookCalendar.Id, ex); - OgcsMessageBox.Show(ex.Message, "Unable to perform test", MessageBoxButtons.OK, MessageBoxIcon.Error); + Ogcs.Extensions.MessageBox.Show(ex.Message, "Unable to perform test", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -1547,7 +1547,7 @@ private void GetMyGoogleCalendars_Click(object sender, EventArgs e) { } catch (OperationCanceledException) { } catch (System.Exception ex) { Ogcs.Exception.Analyse(ex); - OgcsMessageBox.Show("Failed to retrieve Google calendars.\r\n" + + Ogcs.Extensions.MessageBox.Show("Failed to retrieve Google calendars.\r\n" + "Please check the output on the Sync tab for more details.", "Google calendar retrieval failed", MessageBoxButtons.OK, MessageBoxIcon.Error); StringBuilder sb = new StringBuilder(); @@ -1559,7 +1559,7 @@ private void GetMyGoogleCalendars_Click(object sender, EventArgs e) { console.BuildOutput(Ogcs.Exception.FriendlyMessage(ex), ref sb, false); console.Update(sb, Console.Markup.error, logit: true); if (Settings.Instance.Proxy.Type == "IE") { - if (OgcsMessageBox.Show("Please ensure you can access the internet with Internet Explorer.\r\n" + + if (Ogcs.Extensions.MessageBox.Show("Please ensure you can access the internet with Internet Explorer.\r\n" + "Test it now? If successful, please retry retrieving your Google calendars.", "Test IE Internet Access", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { @@ -1599,7 +1599,7 @@ private void cbGoogleCalendars_SelectedIndexChanged(object sender, EventArgs e) ActiveCalendarProfile.UseGoogleCalendar = (GoogleCalendarListEntry)cbGoogleCalendars.SelectedItem; if (cbGoogleCalendars.Text.StartsWith("[Read Only]") && ActiveCalendarProfile.SyncDirection.Id != Sync.Direction.GoogleToOutlook.Id) { - OgcsMessageBox.Show("You cannot " + (ActiveCalendarProfile.SyncDirection.Id == Sync.Direction.Bidirectional.Id ? "two-way " : "") + "sync with a read-only Google calendar.\n" + + Ogcs.Extensions.MessageBox.Show("You cannot " + (ActiveCalendarProfile.SyncDirection.Id == Sync.Direction.Bidirectional.Id ? "two-way " : "") + "sync with a read-only Google calendar.\n" + "Please review your calendar selection.", "Read-only Sync", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); this.tabAppSettings.SelectedTab = this.tabAppSettings.TabPages["tabGoogle"]; } @@ -1609,7 +1609,7 @@ private void cbGoogleCalendars_SelectedIndexChanged(object sender, EventArgs e) } private void btResetGCal_Click(object sender, EventArgs e) { - if (OgcsMessageBox.Show("This will disconnect the Google account you are using to synchronise with.\r\n" + + if (Ogcs.Extensions.MessageBox.Show("This will disconnect the Google account you are using to synchronise with.\r\n" + "Useful if you want to start syncing to a different account.", "Disconnect Google account?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) { log.Info("User requested reset of Google authentication details."); @@ -2054,7 +2054,7 @@ private void dgObfuscateRegex_CellValidating(object sender, DataGridViewCellVali if (rgx.IsMatch(strVal)) { e.Cancel = true; - OgcsMessageBox.Show("Cell must only include the characters:-\r S = Subject\r L = Location\r D = Description", + Ogcs.Extensions.MessageBox.Show("Cell must only include the characters:-\r S = Subject\r L = Location\r D = Description", "Invalid target values", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } dgObfuscateRegex.Rows[e.RowIndex].Cells[((int)Obfuscate.Columns.target)].Value = strVal; @@ -2260,7 +2260,7 @@ private void cbAddColours_CheckedChanged(object sender, EventArgs e) { } private void btColourMap_Click(object sender, EventArgs e) { if (ActiveCalendarProfile.UseGoogleCalendar == null || string.IsNullOrEmpty(ActiveCalendarProfile.UseGoogleCalendar.Id)) { - OgcsMessageBox.Show("You need to select a Google Calendar first on the 'Settings' tab.", "Configuration Required", MessageBoxButtons.OK, MessageBoxIcon.Information); + Ogcs.Extensions.MessageBox.Show("You need to select a Google Calendar first on the 'Settings' tab.", "Configuration Required", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { @@ -2314,7 +2314,7 @@ private void cbStartOnStartup_CheckedChanged(object sender, EventArgs e) { if (ex is System.Security.SecurityException) Ogcs.Exception.LogAsFail(ref ex); //User doesn't have rights to access registry Ogcs.Exception.Analyse("Failed accessing registry for startup key(s).", ex); if (this.Visible) { - OgcsMessageBox.Show("You do not have permissions to access the system registry.\nThis setting cannot be used.", + Ogcs.Extensions.MessageBox.Show("You do not have permissions to access the system registry.\nThis setting cannot be used.", "Registry access denied", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } cbStartOnStartup.CheckedChanged -= cbStartOnStartup_CheckedChanged; @@ -2332,7 +2332,7 @@ private void cbStartOnStartupAllUsers_CheckedChanged(object sender, EventArgs e) if (ex is System.Security.SecurityException) Ogcs.Exception.LogAsFail(ref ex); //User doesn't have rights to access registry Ogcs.Exception.Analyse("Failed accessing registry for HKLM startup key.", ex); if (this.Visible) { - OgcsMessageBox.Show("You do not have permissions to access the system registry.\nThis setting cannot be used.", + Ogcs.Extensions.MessageBox.Show("You do not have permissions to access the system registry.\nThis setting cannot be used.", "Registry access denied", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } cbStartOnStartupAllUsers.CheckedChanged -= cbStartOnStartupAllUsers_CheckedChanged; @@ -2390,7 +2390,7 @@ private void cbMinimiseNotCloseCheckedChanged(object sender, System.EventArgs e) private void cbPortable_CheckedChanged(object sender, EventArgs e) { if (Settings.AreApplied) { if (Program.StartedWithFileArgs) - OgcsMessageBox.Show("It is not possible to change portability of OGCS when it is started with command line parameters.", + Ogcs.Extensions.MessageBox.Show("It is not possible to change portability of OGCS when it is started with command line parameters.", "Cannot change portability", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); else { Settings.Instance.Portable = cbPortable.Checked; diff --git a/src/OutlookGoogleCalendarSync/Forms/Social.cs b/src/OutlookGoogleCalendarSync/Forms/Social.cs index e928870d..2d3de1dc 100644 --- a/src/OutlookGoogleCalendarSync/Forms/Social.cs +++ b/src/OutlookGoogleCalendarSync/Forms/Social.cs @@ -1,5 +1,6 @@ using System; using System.Windows.Forms; +using Ogcs = OutlookGoogleCalendarSync; namespace OutlookGoogleCalendarSync.Forms { public partial class Social : Form { @@ -73,7 +74,7 @@ public static void Facebook_share() { Helper.OpenBrowser("http://www.facebook.com/sharer/sharer.php?u=http://bit.ly/OGCalSync"); } public static void Facebook_like() { - if (OgcsMessageBox.Show("Please click the 'Like' button on the project website, which will now open in your browser.", + if (Ogcs.Extensions.MessageBox.Show("Please click the 'Like' button on the project website, which will now open in your browser.", "Like on Facebook", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK) { Helper.OpenBrowser("https://phw198.github.io/OutlookGoogleCalendarSync"); } diff --git a/src/OutlookGoogleCalendarSync/Forms/UpdateInfo.cs b/src/OutlookGoogleCalendarSync/Forms/UpdateInfo.cs index 4438ad5f..3ebeadc5 100644 --- a/src/OutlookGoogleCalendarSync/Forms/UpdateInfo.cs +++ b/src/OutlookGoogleCalendarSync/Forms/UpdateInfo.cs @@ -52,7 +52,7 @@ public UpdateInfo(String releaseVersion, String releaseType, String html, out Di } catch (System.Exception ex) { log.Debug("A problem was encountered showing the release notes."); Ogcs.Exception.Analyse(ex); - dr = OgcsMessageBox.Show("A new " + (releaseType == "alpha" ? "alpha " : "") + "release of OGCS is available.\nWould you like to upgrade to v" + + dr = Ogcs.Extensions.MessageBox.Show("A new " + (releaseType == "alpha" ? "alpha " : "") + "release of OGCS is available.\nWould you like to upgrade to v" + releaseVersion + " now?", "OGCS Update Available", MessageBoxButtons.YesNo, MessageBoxIcon.Information); } } diff --git a/src/OutlookGoogleCalendarSync/Google/ApiKeyring.cs b/src/OutlookGoogleCalendarSync/Google/ApiKeyring.cs index e5257988..a5a2f411 100644 --- a/src/OutlookGoogleCalendarSync/Google/ApiKeyring.cs +++ b/src/OutlookGoogleCalendarSync/Google/ApiKeyring.cs @@ -150,7 +150,7 @@ private static List getKeyRing() { public static void ChangeKeys() { log.Info("Google API keys and refresh token are being updated."); - System.Windows.Forms.OgcsMessageBox.Show("Your Google authorisation token needs updating.\r\n" + + Ogcs.Extensions.MessageBox.Show("Your Google authorisation token needs updating.\r\n" + "The process to reauthorise access to your Google account will now begin...", "Authorisation token invalid", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); Ogcs.Google.Calendar.Instance.Authenticator.Reset(); diff --git a/src/OutlookGoogleCalendarSync/Google/Authenticator.cs b/src/OutlookGoogleCalendarSync/Google/Authenticator.cs index 564e95e0..23c2af85 100644 --- a/src/OutlookGoogleCalendarSync/Google/Authenticator.cs +++ b/src/OutlookGoogleCalendarSync/Google/Authenticator.cs @@ -118,7 +118,7 @@ private async Task getAuthenticated(ClientSecrets cs) { if (ex.Error.Error == "access_denied") { String noAuthGiven = "Sorry, but this application will not work if you don't allow it access to your Google Calendar :("; log.Warn("User did not provide authorisation code. Sync will not be able to work."); - OgcsMessageBox.Show(noAuthGiven, "Authorisation not given", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + Ogcs.Extensions.MessageBox.Show(noAuthGiven, "Authorisation not given", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); throw new ApplicationException(noAuthGiven); } else { Forms.Main.Instance.Console.UpdateWithError("Unable to authenticate with Google. The following error occurred:", ex); @@ -247,7 +247,7 @@ private void getGaccountEmail(String accessToken) { if (rgx.IsMatch(ex.Message)) { if (Settings.Instance.UsingPersonalAPIkeys()) { String msg = "If you are using your own API keys, you must also enable the Google+ API."; - OgcsMessageBox.Show(msg, "Missing API Service", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); + Ogcs.Extensions.MessageBox.Show(msg, "Missing API Service", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); throw new System.ApplicationException(msg); } else { if (getEmailAttempts > 1) { @@ -255,7 +255,7 @@ private void getGaccountEmail(String accessToken) { log.Debug("Using previously retrieved username: " + Settings.Instance.GaccountEmail_masked()); } else { if ((new ApiKey.DefaultKey(ApiKeyring.KeyType.Standard)).ClientId == Settings.Instance.AssignedClientIdentifier) { - System.Windows.Forms.OgcsMessageBox.Show(ex.Message + "\r\n\r\nPlease check your internet connection and any relevant proxy configuration.", + Ogcs.Extensions.MessageBox.Show(ex.Message + "\r\n\r\nPlease check your internet connection and any relevant proxy configuration.", "Unable to communicate with Google", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); throw; } else { @@ -318,7 +318,7 @@ public void OgcsUserStatus() { checkedOgcsUserStatus = true; if (Settings.Instance.UserIsBenefactor() && Settings.Instance.HideSplashScreen == null) { - Boolean hideSplash = OgcsMessageBox.Show("Thank you for your support of OGCS!\r\nWould you like the splash screen to be hidden from now on?", "Hide Splash Screen?", + Boolean hideSplash = Ogcs.Extensions.MessageBox.Show("Thank you for your support of OGCS!\r\nWould you like the splash screen to be hidden from now on?", "Hide Splash Screen?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes; Forms.Main.Instance.SetControlPropertyThreadSafe(Forms.Main.Instance.cbHideSplash, "Checked", hideSplash); Settings.Instance.HideSplashScreen = hideSplash; diff --git a/src/OutlookGoogleCalendarSync/Google/ErrorReporting.cs b/src/OutlookGoogleCalendarSync/Google/ErrorReporting.cs index 32b030a6..17966c87 100644 --- a/src/OutlookGoogleCalendarSync/Google/ErrorReporting.cs +++ b/src/OutlookGoogleCalendarSync/Google/ErrorReporting.cs @@ -78,7 +78,7 @@ public static void Initialise() { //} catch (System.Exception ex) { //Logging isn't initialised yet, so don't catch this error - let it crash out so user is aware and hopefully reports it! - //System.Windows.Forms.OgcsMessageBox.Show(ex.Message); + //Ogcs.Extensions.MessageBox.Show(ex.Message); //log.Debug("Failed to initialise error reporting."); //Ogcs.Exception.Analyse(ex); } diff --git a/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs b/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs index bb8230f8..50190c40 100644 --- a/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs +++ b/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs @@ -510,7 +510,7 @@ public void CreateCalendarEntries(List appointments) { String summary = Outlook.Calendar.GetEventSummary("Event creation failed.", ai, out String anonSummary); Forms.Main.Instance.Console.UpdateWithError(summary, ex, logEntry: anonSummary); Ogcs.Exception.Analyse(ex, true); - if (OgcsMessageBox.Show("Google event creation failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (Ogcs.Extensions.MessageBox.Show("Google event creation failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else throw new UserCancelledSyncException("User chose not to continue sync."); @@ -527,7 +527,7 @@ public void CreateCalendarEntries(List appointments) { } Forms.Main.Instance.Console.UpdateWithError(Outlook.Calendar.GetEventSummary("New event failed to save.", ai, out String anonSummary, true), ex, logEntry: anonSummary); Ogcs.Exception.Analyse(ex, true); - if (OgcsMessageBox.Show("New Google event failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (Ogcs.Extensions.MessageBox.Show("New Google event failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else throw new UserCancelledSyncException("User chose not to continue sync."); @@ -721,7 +721,7 @@ public void UpdateCalendarEntries(Dictionary entriesToBe Forms.Main.Instance.Console.UpdateWithError(summary, ex, logEntry: anonSummary); if (ex is System.Runtime.InteropServices.COMException) throw; Ogcs.Exception.Analyse(ex, true); - if (OgcsMessageBox.Show("Google event update failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (Ogcs.Extensions.MessageBox.Show("Google event update failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else throw new UserCancelledSyncException("User chose not to continue sync."); @@ -736,7 +736,7 @@ public void UpdateCalendarEntries(Dictionary entriesToBe } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(Outlook.Calendar.GetEventSummary("Updated event failed to save.", compare.Key, out String anonSummary, true), ex, logEntry: anonSummary); Ogcs.Exception.Analyse(ex, true); - if (OgcsMessageBox.Show("Updated Google event failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (Ogcs.Extensions.MessageBox.Show("Updated Google event failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else throw new UserCancelledSyncException("User chose not to continue sync."); @@ -763,7 +763,7 @@ public void UpdateCalendarEntries(Dictionary entriesToBe } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(Outlook.Calendar.GetEventSummary("Updated event failed to save.", compare.Key, out String anonSummary, true), ex, logEntry: anonSummary); Ogcs.Exception.Analyse(ex, true); - if (OgcsMessageBox.Show("Updated Google event failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (Ogcs.Extensions.MessageBox.Show("Updated Google event failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else throw new UserCancelledSyncException("User chose not to continue sync."); @@ -1116,7 +1116,7 @@ public void UpdateCalendarEntry_save(ref Event ev) { break; } if (handled != ApiException.justContinue && ex.Error?.Code == 412 && !this.openedIssue1593) { //Precondition failed - OgcsMessageBox.Show("A 'PreCondition Failed [412]' error was encountered.\r\nPlease see issue #1593 on GitHub for further information.", + Ogcs.Extensions.MessageBox.Show("A 'PreCondition Failed [412]' error was encountered.\r\nPlease see issue #1593 on GitHub for further information.", "PreCondition Failed: Issue #1593", MessageBoxButtons.OK, MessageBoxIcon.Hand); Helper.OpenBrowser("https://github.com/phw198/OutlookGoogleCalendarSync/issues/1593"); this.openedIssue1593 = true; @@ -1128,11 +1128,11 @@ public void UpdateCalendarEntry_save(ref Event ev) { //void ShowError(String message, Window windowToBlock) { // if (this.Dispatcher.CheckAccess()) - // OgcsMessageBox.Show(windowToBlock, message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); + // Ogcs.Extensions.MessageBox.Show(windowToBlock, message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); // else { // this.Dispatcher.Invoke( // new Action(() => { - // OgcsMessageBox.Show(windowToBlock, message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); + // Ogcs.Extensions.MessageBox.Show(windowToBlock, message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); // })); // } //} @@ -1149,7 +1149,7 @@ public void DeleteCalendarEntries(List events) { } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("Event deletion failed.", ev, out String anonSummary, true), ex, logEntry: anonSummary); Ogcs.Exception.Analyse(ex, true); - if (OgcsMessageBox.Show("Google event deletion failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (Ogcs.Extensions.MessageBox.Show("Google event deletion failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else { throw new UserCancelledSyncException("User chose not to continue sync."); @@ -1176,7 +1176,7 @@ public void DeleteCalendarEntries(List events) { String summary = GetEventSummary("
Event deletion failed.", ev, out String anonSummary); Forms.Main.Instance.Console.UpdateWithError(summary, ex, logEntry: anonSummary); Ogcs.Exception.Analyse(ex, true); - if (OgcsMessageBox.Show("Google event deletion failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (Ogcs.Extensions.MessageBox.Show("Google event deletion failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else throw new UserCancelledSyncException("User chose not to continue sync."); @@ -1190,7 +1190,7 @@ private Boolean deleteCalendarEntry(Event ev) { Boolean doDelete = true; if (Sync.Engine.Calendar.Instance.Profile.ConfirmOnDelete) { - if (OgcsMessageBox.Show("Delete " + eventSummary + "?", "Confirm Deletion From Google", + if (Ogcs.Extensions.MessageBox.Show("Delete " + eventSummary + "?", "Confirm Deletion From Google", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No) { doDelete = false; if (Sync.Engine.Calendar.Instance.Profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id && CustomProperty.ExistAnyOutlookIDs(ev)) { @@ -1309,7 +1309,7 @@ public void ReclaimOrphanCalendarEntries(ref List gEvents, ref List Email Accounts) to avoid problems syncing meeting attendees.", "No Email Account Found", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); @@ -320,7 +320,7 @@ private MAPIFolder getCalendarStore(NameSpace oNS) { } else { binStore = binFolders.GetFirst().Store; log.Warn("Alternate mailbox '" + profile.MailboxName + "' could no longer be found. Selected mailbox '" + binStore.DisplayName + "' instead."); - OgcsMessageBox.Show("The alternate mailbox '" + profile.MailboxName + "' previously configured for syncing is no longer available.\r\n\r\n" + + Ogcs.Extensions.MessageBox.Show("The alternate mailbox '" + profile.MailboxName + "' previously configured for syncing is no longer available.\r\n\r\n" + "'" + binStore.DisplayName + "' mailbox has been selected instead and any automated syncs have been temporarily disabled.", "Mailbox Unavailable", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); profile.MailboxName = binStore.DisplayName; @@ -363,7 +363,7 @@ private MAPIFolder getCalendarStore(NameSpace oNS) { defaultCalendar = calendarFolders.FirstOrDefault().Value; if (defaultCalendar == null) { log.Info("Could not find Alternative mailbox Calendar folder. Reverting to the default mailbox calendar."); - System.Windows.Forms.OgcsMessageBox.Show("Unable to find a Calendar folder in the alternative mailbox.\r\n" + + Ogcs.Extensions.MessageBox.Show("Unable to find a Calendar folder in the alternative mailbox.\r\n" + "Reverting to the default mailbox calendar", "Calendar not found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); getDefaultCalendar(oNS, ref defaultCalendar); Forms.Main.Instance.ddMailboxName.Text = ""; @@ -431,7 +431,7 @@ private MAPIFolder getSharedCalendar(NameSpace oNS, String sharedURI, Boolean in if (interactive) { String sharerName = "."; if (sharer != null) sharerName = " for '" + sharer.Name + "'."; - OgcsMessageBox.Show("Could not find shared calendar" + sharerName, "No shared calendar found", + Ogcs.Extensions.MessageBox.Show("Could not find shared calendar" + sharerName, "No shared calendar found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return null; } else { @@ -510,7 +510,7 @@ private void findCalendars(Folders folders, Dictionary calen "The Outlook calendar to synchonize with.\nSome may not be listed as you are currently disconnected."); } else { Ogcs.Exception.Analyse("Failed to recurse MAPI folders.", ex); - OgcsMessageBox.Show("A problem was encountered when searching for Outlook calendar folders.\r\n" + ex.Message, + Ogcs.Extensions.MessageBox.Show("A problem was encountered when searching for Outlook calendar folders.\r\n" + ex.Message, "Calendar Folders", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } diff --git a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs index 9e1de0ff..75d197d7 100644 --- a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs +++ b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs @@ -46,7 +46,7 @@ public void Connect() { if (!profile.OutlookGalBlocked && currentUserName == "Unknown") { log.Info("Current username is \"Unknown\""); if (profile.AddAttendees) { - System.Windows.Forms.OgcsMessageBox.Show("It appears you do not have an Email Account configured in Outlook.\r\n" + + Ogcs.Extensions.MessageBox.Show("It appears you do not have an Email Account configured in Outlook.\r\n" + "You should set one up now (Tools > Email Accounts) to avoid problems syncing meeting attendees.", "No Email Account Found", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); @@ -278,7 +278,7 @@ private MAPIFolder getSharedCalendar(NameSpace oNS, String sharedURI) { } catch (System.Exception ex) { log.Error("Failed to get shared calendar from " + sharedURI + ". " + ex.Message); - OgcsMessageBox.Show("Could not find a shared calendar for '" + sharer.Name + "'.", "No shared calendar found", + Ogcs.Extensions.MessageBox.Show("Could not find a shared calendar for '" + sharer.Name + "'.", "No shared calendar found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return null; } finally { @@ -352,7 +352,7 @@ private void findCalendars(Folders folders, Dictionary calen "The Outlook calendar to synchonize with.\nSome may not be listed as you are currently disconnected."); } else { Ogcs.Exception.Analyse("Failed to recurse MAPI folders.", ex); - OgcsMessageBox.Show("A problem was encountered when searching for Outlook calendar folders.\r\n" + ex.Message, + Ogcs.Extensions.MessageBox.Show("A problem was encountered when searching for Outlook calendar folders.\r\n" + ex.Message, "Calendar Folders", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } diff --git a/src/OutlookGoogleCalendarSync/Outlook/ExplorerWatcher.cs b/src/OutlookGoogleCalendarSync/Outlook/ExplorerWatcher.cs index e9c93264..8bc5b301 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/ExplorerWatcher.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/ExplorerWatcher.cs @@ -208,7 +208,7 @@ private void untagAsCopied(String entryID) { if (origStartDate < profile.SyncStart && copiedAi.Start >= profile.SyncStart) { Int16 newDaysInPast = (Int16)(profile.SyncStart.Date - origStartDate.Date).TotalDays; - System.Windows.Forms.OgcsMessageBox.Show("Sync profile affected: " + profile._ProfileName + "\r\n" + + Ogcs.Extensions.MessageBox.Show("Sync profile affected: " + profile._ProfileName + "\r\n" + "An already synced appointment has been moved back into the synced date range.\r\n" + "In order to avoid it being deleted, configuration has automatically been updated to " + (profile.DaysInThePast + newDaysInPast) + " days in the past.\r\n" + "After the next sync you may revert it to " + profile.DaysInThePast + ".", "Appointment moved into synced date range", @@ -217,7 +217,7 @@ private void untagAsCopied(String entryID) { } else if (origStartDate >= profile.SyncStart && copiedAi.Start < profile.SyncStart) { Int16 newDaysInPast = (Int16)(profile.SyncStart.Date - copiedAi.Start.Date).TotalDays; - System.Windows.Forms.OgcsMessageBox.Show("Sync profile affected: " + profile._ProfileName + "\r\n" + + Ogcs.Extensions.MessageBox.Show("Sync profile affected: " + profile._ProfileName + "\r\n" + "An already synced appointment has been moved out of the synced date range.\r\n" + "In order this is synced, configuration has automatically been updated to " + (profile.DaysInThePast + newDaysInPast) + " days in the past.\r\n" + "After the next sync you may revert it to " + profile.DaysInThePast + ".", "Appointment moved out of synced date range", @@ -226,7 +226,7 @@ private void untagAsCopied(String entryID) { } else if (origStartDate > profile.SyncEnd && copiedAi.Start <= profile.SyncEnd) { Int16 newDaysInFuture = (Int16)(origStartDate - profile.SyncEnd.Date).TotalDays; - System.Windows.Forms.OgcsMessageBox.Show("Sync profile affected: " + profile._ProfileName + "\r\n" + + Ogcs.Extensions.MessageBox.Show("Sync profile affected: " + profile._ProfileName + "\r\n" + "An already synced appointment has been moved into the synced date range.\r\n" + "In order this is synced, configuration has automatically been updated to " + (profile.DaysInTheFuture + newDaysInFuture) + " days in the future.\r\n" + "After the next sync you may revert it to " + profile.DaysInTheFuture + ".", "Appointment moved into synced date range", @@ -235,7 +235,7 @@ private void untagAsCopied(String entryID) { } else if (origStartDate <= profile.SyncEnd && copiedAi.Start > profile.SyncEnd) { Int16 newDaysInFuture = (Int16)(copiedAi.Start.Date - profile.SyncEnd.Date).TotalDays; - System.Windows.Forms.OgcsMessageBox.Show("Sync profile affected: " + profile._ProfileName + "\r\n" + + Ogcs.Extensions.MessageBox.Show("Sync profile affected: " + profile._ProfileName + "\r\n" + "An already synced appointment has been moved out of the synced date range.\r\n" + "In order this is synced, configuration has automatically been updated to " + (profile.DaysInTheFuture + newDaysInFuture) + " days in the future.\r\n" + "After the next sync you may revert it to " + profile.DaysInTheFuture + ".", "Appointment moved out of synced date range", diff --git a/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs b/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs index 3729926a..eb0f6b28 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs @@ -120,7 +120,7 @@ public List GetCalendarEntriesInRange(SettingsStore.Calendar pr String wikiURL = "https://github.com/phw198/OutlookGoogleCalendarSync/wiki/Resolving-Outlook-Error-Messages#one-or-more-items-in-the-folder-you-synchronized-do-not-match"; ex.Data.Add("OGCS", ex.Message + "
Please view the wiki for suggestions on " + "how to resolve conflicts within your Outlook account."); - if (!suppressAdvisories && OgcsMessageBox.Show("Your Outlook calendar contains conflicts that need resolving in order to sync successfully.\r\nView the wiki for advice?", + if (!suppressAdvisories && Ogcs.Extensions.MessageBox.Show("Your Outlook calendar contains conflicts that need resolving in order to sync successfully.\r\nView the wiki for advice?", "Outlook conflicts exist", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) Helper.OpenBrowser(wikiURL); } @@ -319,7 +319,7 @@ public void CreateCalendarEntries(List events) { } else { Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("Appointment creation failed.", ev, out String anonSummary, true), ex, logEntry: anonSummary); Ogcs.Exception.Analyse(ex, true); - if (OgcsMessageBox.Show("Outlook appointment creation failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (Ogcs.Extensions.MessageBox.Show("Outlook appointment creation failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else throw new UserCancelledSyncException("User chose not to continue sync."); @@ -332,7 +332,7 @@ public void CreateCalendarEntries(List events) { } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("New appointment failed to save.", ev, out String anonSummary, true), ex, logEntry: anonSummary); Ogcs.Exception.Analyse(ex, true); - if (OgcsMessageBox.Show("New Outlook appointment failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (Ogcs.Extensions.MessageBox.Show("New Outlook appointment failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else throw new UserCancelledSyncException("User chose not to continue sync."); @@ -440,7 +440,7 @@ public void UpdateCalendarEntries(Dictionary entriesToBe } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("
Appointment update failed.", compare.Value, out String anonSummary), ex, logEntry: anonSummary); Ogcs.Exception.Analyse(ex, true); - if (OgcsMessageBox.Show("Outlook appointment update failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (Ogcs.Extensions.MessageBox.Show("Outlook appointment update failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else throw new UserCancelledSyncException("User chose not to continue sync."); @@ -453,7 +453,7 @@ public void UpdateCalendarEntries(Dictionary entriesToBe } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("Updated appointment failed to save.", compare.Value, out String anonSummary, true), ex, logEntry: anonSummary); Ogcs.Exception.Analyse(ex, true); - if (OgcsMessageBox.Show("Updated Outlook appointment failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (Ogcs.Extensions.MessageBox.Show("Updated Outlook appointment failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else throw new UserCancelledSyncException("User chose not to continue sync."); @@ -819,7 +819,7 @@ public void DeleteCalendarEntries(List oAppointments) { } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(GetEventSummary("Appointment deletion failed.", ai, out String anonSummary, true), ex, logEntry: anonSummary); Ogcs.Exception.Analyse(ex, true); - if (OgcsMessageBox.Show("Outlook appointment deletion failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (Ogcs.Extensions.MessageBox.Show("Outlook appointment deletion failed. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else throw new UserCancelledSyncException("User chose not to continue sync."); @@ -831,7 +831,7 @@ public void DeleteCalendarEntries(List oAppointments) { } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(GetEventSummary("Deleted appointment failed to remove.", ai, out String anonSummary, true), ex, logEntry: anonSummary); Ogcs.Exception.Analyse(ex, true); - if (OgcsMessageBox.Show("Deleted Outlook appointment failed to remove. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (Ogcs.Extensions.MessageBox.Show("Deleted Outlook appointment failed to remove. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else throw new UserCancelledSyncException("User chose not to continue sync."); @@ -847,7 +847,7 @@ private Boolean deleteCalendarEntry(AppointmentItem ai) { Boolean doDelete = true; if (Sync.Engine.Calendar.Instance.Profile.ConfirmOnDelete) { - if (OgcsMessageBox.Show("Delete " + eventSummary + "?", "Confirm Deletion From Outlook", + if (Ogcs.Extensions.MessageBox.Show("Delete " + eventSummary + "?", "Confirm Deletion From Outlook", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No) { doDelete = false; if (Sync.Engine.Calendar.Instance.Profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id && CustomProperty.ExistAnyGoogleIDs(ai)) { @@ -939,7 +939,7 @@ public void ReclaimOrphanCalendarEntries(ref List oAppointments } else if (profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id) { log.Debug("These 'orphaned' items must not be deleted - they need syncing up."); } else { - if (OgcsMessageBox.Show(unclaimedAi.Count + " Outlook calendar items can't be matched to Google.\r\n" + + if (Ogcs.Extensions.MessageBox.Show(unclaimedAi.Count + " Outlook calendar items can't be matched to Google.\r\n" + "Remember, it's recommended to have a dedicated Outlook calendar to sync with, " + "or you may wish to merge with unmatched events. Continue with deletions?", "Delete unmatched Outlook items?", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No) { diff --git a/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs b/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs index 451132b2..21181d36 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs @@ -294,7 +294,7 @@ public String FindName(OutlookCOM.OlCategoryColor? olCategory, String categoryNa log.Debug("Did not find Outlook category " + olCategory.ToString() + (categoryName == null ? "" : " \"" + categoryName + "\"")); String newCategoryName = "OGCS " + FriendlyCategoryName(olCategory); if (!createMissingCategory) { - createMissingCategory = OgcsMessageBox.Show("There is no matching Outlook category.\r\nWould you like to create one of the form '" + newCategoryName + "'?", + createMissingCategory = Ogcs.Extensions.MessageBox.Show("There is no matching Outlook category.\r\nWould you like to create one of the form '" + newCategoryName + "'?", "Create new Outlook category?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes; } if (createMissingCategory) { diff --git a/src/OutlookGoogleCalendarSync/Program.cs b/src/OutlookGoogleCalendarSync/Program.cs index cadd2d8d..84653328 100644 --- a/src/OutlookGoogleCalendarSync/Program.cs +++ b/src/OutlookGoogleCalendarSync/Program.cs @@ -135,7 +135,7 @@ private static void parseArgumentsAndInitialise(string[] args) { StartedWithFileArgs = (args.Length != 0 && args.Count(a => a.StartsWith("/") && !a.StartsWith("/d")) != 0); if (args.Contains("/?") || args.Contains("/help", StringComparer.OrdinalIgnoreCase)) { - OgcsMessageBox.Show("Command line parameters:-\r\n" + + Ogcs.Extensions.MessageBox.Show("Command line parameters:-\r\n" + " /?\t\tShow options\r\n" + " /l:OGcalsync.log\tFile to log to\r\n" + " /s:settings.xml\tSettings file to use.\r\n\t\tFile created with defaults if it doesn't exist\r\n" + @@ -347,7 +347,7 @@ private static void addRegKey(Microsoft.Win32.RegistryKey hive, String startupDe } catch (System.UnauthorizedAccessException ex) { log.Warn("Could not create/update " + hive.ToString() + " registry key. " + ex.Message); Settings.Instance.StartOnStartup = false; - if (OgcsMessageBox.Show("You don't have permission to update the registry, so the application can't be set to run on startup.\r\n" + + if (Ogcs.Extensions.MessageBox.Show("You don't have permission to update the registry, so the application can't be set to run on startup.\r\n" + "Try manually adding a shortcut to the 'Startup' folder in Windows instead?", "Permission denied", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) { System.Diagnostics.Process.Start(System.Windows.Forms.Application.StartupPath); @@ -509,7 +509,7 @@ private static void isNewVersion(Boolean isSquirrelInstall) { if (!String.IsNullOrEmpty(disabledSetting)) disabledSetting += " and "; disabledSetting += "telemetry"; } - if (OgcsMessageBox.Show("As you are running a hotfix release, it would be helpful if you could enable " + disabledSetting + ".", + if (Ogcs.Extensions.MessageBox.Show("As you are running a hotfix release, it would be helpful if you could enable " + disabledSetting + ".", "Hotfix release troubleshooting", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { Settings.Instance.TelemetryDisabled = false; Settings.Instance.CloudLogging = true; @@ -543,7 +543,7 @@ private static void isNewVersion(Boolean isSquirrelInstall) { !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" + + Ogcs.Extensions.MessageBox.Show("A suspected improper install location has been detected.\r\n" + "Click 'OK' for further details.", "Improper Install Location", MessageBoxButtons.OK, MessageBoxIcon.Warning); Helper.OpenBrowser("https://github.com/phw198/OutlookGoogleCalendarSync/issues/265"); @@ -682,7 +682,7 @@ private static void instancesRunning() { String cmdLine = getProcessCommandLine(process.Id); if (cmdLine == currentCmdLine) { - OgcsMessageBox.Show("You already have an instance of OGCS running using the same configuration.\r\n" + + Ogcs.Extensions.MessageBox.Show("You already have an instance of OGCS running using the same configuration.\r\n" + "This is not recommended and may cause problems if they sync at the same time.", "Multiple OGCS instances running", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; diff --git a/src/OutlookGoogleCalendarSync/Recurrence.cs b/src/OutlookGoogleCalendarSync/Recurrence.cs index 7348a346..68d14da1 100644 --- a/src/OutlookGoogleCalendarSync/Recurrence.cs +++ b/src/OutlookGoogleCalendarSync/Recurrence.cs @@ -729,7 +729,7 @@ public static void UpdateGoogleExceptions(AppointmentItem ai, Event ev, Boolean String msg = summary + "\r\n\r\nAn occurrence on " + movedToStartDate.ToString("dd-MMM-yyyy") + " was previously deleted, before another occurrence on " + oExcp.OriginalDate.ToString("dd-MMM-yyyy") + " was rescheduled to the same date and then deleted again. " + "Please confirm the Google occurrence, currently on " + movedToStartDate.ToString("dd-MMM-yyyy") + ", should be deleted?"; - dr = OgcsMessageBox.Show(msg, "Confirm deletion of recurring series occurrence", MessageBoxButtons.YesNo, MessageBoxIcon.Question, msg.Replace(summary, anonSummary)); + dr = Ogcs.Extensions.MessageBox.Show(msg, "Confirm deletion of recurring series occurrence", MessageBoxButtons.YesNo, MessageBoxIcon.Question, msg.Replace(summary, anonSummary)); } if (dr == DialogResult.Yes) { Forms.Main.Instance.Console.Update(Ogcs.Google.Calendar.GetEventSummary("
Occurrence deleted.", gExcp, out String anonSummary2), anonSummary2, Console.Markup.calendar, verbose: true); @@ -766,7 +766,7 @@ public static void UpdateGoogleExceptions(AppointmentItem ai, Event ev, Boolean } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError(Ogcs.Google.Calendar.GetEventSummary("Updated event exception failed to save.", gExcp, out String anonSummary, true), ex, logEntry: anonSummary); Ogcs.Exception.Analyse(ex, true); - if (OgcsMessageBox.Show("Updated Google event exception failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (Ogcs.Extensions.MessageBox.Show("Updated Google event exception failed to save. Continue with synchronisation?", "Sync item failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) continue; else { throw new UserCancelledSyncException("User chose not to continue sync."); diff --git a/src/OutlookGoogleCalendarSync/SettingsStore/Settings.cs b/src/OutlookGoogleCalendarSync/SettingsStore/Settings.cs index 8acf03b9..d6808cbf 100644 --- a/src/OutlookGoogleCalendarSync/SettingsStore/Settings.cs +++ b/src/OutlookGoogleCalendarSync/SettingsStore/Settings.cs @@ -330,7 +330,7 @@ public static void Load(String XMLfile = null) { } public static void ResetFile(String XMLfile = null) { - System.Windows.Forms.OgcsMessageBox.Show("Your OGCS settings appear to be corrupt and will have to be reset.", + Ogcs.Extensions.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."); System.IO.File.Delete(XMLfile ?? ConfigFile); diff --git a/src/OutlookGoogleCalendarSync/Sync/Calendar.cs b/src/OutlookGoogleCalendarSync/Sync/Calendar.cs index 91246734..b29860d4 100644 --- a/src/OutlookGoogleCalendarSync/Sync/Calendar.cs +++ b/src/OutlookGoogleCalendarSync/Sync/Calendar.cs @@ -92,7 +92,7 @@ public void StartSync(Boolean manualIgnition, Boolean updateSyncSchedule = true) while ((syncResult == Sync.Engine.SyncResult.Fail || syncResult == Sync.Engine.SyncResult.ReconnectThenRetry) && !Forms.Main.Instance.IsDisposed) { if (failedAttempts > (syncResult == Sync.Engine.SyncResult.ReconnectThenRetry ? 1 : 0)) { - if (OgcsMessageBox.Show("The synchronisation failed - check the Sync tab for further details.\r\nDo you want to try again?", "Sync Failed", + if (Ogcs.Extensions.MessageBox.Show("The synchronisation failed - check the Sync tab for further details.\r\nDo you want to try again?", "Sync Failed", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == System.Windows.Forms.DialogResult.No) { log.Info("User opted to abandon further syncs."); syncResult = Sync.Engine.SyncResult.Abandon; @@ -493,7 +493,7 @@ private SyncResult synchronize() { if (this.Profile.ColourMaps.Count > 0) { this.Profile.ColourMaps.ToList().ForEach(c => { if (Outlook.Calendar.Categories.OutlookColour(c.Key) == null) { - if (OgcsMessageBox.Show("There is a problem with your colour mapping configuration.\r\nColours may not get synced as intended.\r\nReview maps now for missing Outlook colours?", + if (Ogcs.Extensions.MessageBox.Show("There is a problem with your colour mapping configuration.\r\nColours may not get synced as intended.\r\nReview maps now for missing Outlook colours?", "Invalid colour map", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Error) == DialogResult.Yes) new Forms.ColourMap().ShowDialog(); } @@ -572,13 +572,13 @@ private Boolean outlookToGoogle(List outlookEntries, List 1) { - if (OgcsMessageBox.Show("All Google events are going to be deleted. Do you want to allow this?" + + if (Ogcs.Extensions.MessageBox.Show("All Google events are going to be deleted. Do you want to allow this?" + "\r\nNote, " + googleEntriesToBeCreated.Count + " events will then be created.", "Confirm mass deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No) { googleEntriesToBeDeleted = new List(); } else if (this.Profile.SyncDirection.Id == Sync.Direction.OutlookToGoogle.Id && - OgcsMessageBox.Show("If you are syncing an Apple iCalendar from Outlook and get the 'mass deletion' warning for every sync, "+ + Ogcs.Extensions.MessageBox.Show("If you are syncing an Apple iCalendar from Outlook and get the 'mass deletion' warning for every sync, "+ "would you like to read up on a potential solution?", "iCal Syncing?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { Helper.OpenBrowser("https://github.com/phw198/OutlookGoogleCalendarSync/wiki/Syncing-Apple-iCalendar-in-Outlook-causes-'mass-deletion'-warnings"); } @@ -682,7 +682,7 @@ private Boolean googleToOutlook(List googleEntries, List //Protect against very first syncs which may trample pre-existing non-Google events in Outlook if (!this.Profile.DisableDelete && !this.Profile.ConfirmOnDelete && outlookEntriesToBeDeleted.Count == outlookEntries.Count && outlookEntries.Count > 1) { - if (OgcsMessageBox.Show("All Outlook events are going to be deleted. Do you want to allow this?" + + if (Ogcs.Extensions.MessageBox.Show("All Outlook events are going to be deleted. Do you want to allow this?" + "\r\nNote, " + outlookEntriesToBeCreated.Count + " events will then be created.", "Confirm mass deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No) { diff --git a/src/OutlookGoogleCalendarSync/Sync/Engine.cs b/src/OutlookGoogleCalendarSync/Sync/Engine.cs index e444f517..d90ca83c 100644 --- a/src/OutlookGoogleCalendarSync/Sync/Engine.cs +++ b/src/OutlookGoogleCalendarSync/Sync/Engine.cs @@ -159,12 +159,12 @@ public void Sync_Requested(object sender = null, EventArgs e = null) { log.Info("Manual sync requested."); if (SyncingNow) { log.Info("Already busy syncing, cannot accept another sync request."); - OgcsMessageBox.Show("A sync is already running. Please wait for it to complete and then try again.", "Sync already running", MessageBoxButtons.OK, MessageBoxIcon.Hand); + Ogcs.Extensions.MessageBox.Show("A sync is already running. Please wait for it to complete and then try again.", "Sync already running", MessageBoxButtons.OK, MessageBoxIcon.Hand); return; } if (Control.ModifierKeys == Keys.Shift) { if (Forms.Main.Instance.ActiveCalendarProfile.SyncDirection == Direction.Bidirectional) { - OgcsMessageBox.Show("Forcing a full sync is not allowed whilst in 2-way sync mode.\r\nPlease temporarily chose a direction to sync in first.", + Ogcs.Extensions.MessageBox.Show("Forcing a full sync is not allowed whilst in 2-way sync mode.\r\nPlease temporarily chose a direction to sync in first.", "2-way full sync not allowed", MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } @@ -186,7 +186,7 @@ public void Sync_Requested(object sender = null, EventArgs e = null) { AbortSync(); } if (this.JobQueue.Count() > 0) { - if (OgcsMessageBox.Show("There are " + this.JobQueue.Count() + " sync(s) still queued to run. Would you like to cancel these too?", + if (Ogcs.Extensions.MessageBox.Show("There are " + this.JobQueue.Count() + " sync(s) still queued to run. Would you like to cancel these too?", "Clear queued syncs?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { log.Info("User requested clear down of sync queue."); this.JobQueue.Clear(); diff --git a/src/OutlookGoogleCalendarSync/Updater.cs b/src/OutlookGoogleCalendarSync/Updater.cs index 59c1dac0..3fef4d4e 100644 --- a/src/OutlookGoogleCalendarSync/Updater.cs +++ b/src/OutlookGoogleCalendarSync/Updater.cs @@ -64,14 +64,14 @@ public async void CheckForUpdate(Button updateButton = null) { } 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) { + if (Ogcs.Extensions.MessageBox.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) { Helper.OpenBrowser(Program.OgcsWebsite); } } 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); + Ogcs.Extensions.MessageBox.Show("Unable to check for new version.", "Check Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } @@ -227,7 +227,7 @@ private async Task githubCheck() { log.Info("The application has been successfully updated."); squirrelGaEv.AddParameter(GA4.Squirrel.result, "Successful"); - OgcsMessageBox.Show("The application has been updated and will now restart.", + Ogcs.Extensions.MessageBox.Show("The application has been updated and will now restart.", "OGCS successfully updated!", MessageBoxButtons.OK, MessageBoxIcon.Information); restartUpdateExe = updateManager.RootAppDirectory + "\\Update.exe"; return true; @@ -256,7 +256,7 @@ private async Task githubCheck() { if (this.isManualCheck) { //Was a manual check, so give feedback String beta = ""; if (!Settings.Instance.AlphaReleases && Application.ProductVersion.EndsWith(".0.0")) beta = "beta "; - OgcsMessageBox.Show($"You are already running the latest {beta}version of OGCS.", "Latest Version", MessageBoxButtons.OK, MessageBoxIcon.Information); + Ogcs.Extensions.MessageBox.Show($"You are already running the latest {beta}version of OGCS.", "Latest Version", MessageBoxButtons.OK, MessageBoxIcon.Information); } } @@ -368,7 +368,7 @@ private static void onAppUninstall(Version version) { Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.uninstall, version.ToString()); Telemetry.GA4Event.Event squirrelGaEv = new(Telemetry.GA4Event.Event.Name.squirrel); squirrelGaEv.AddParameter(GA4.Squirrel.uninstall, version.ToString()); - if (OgcsMessageBox.Show("Sorry to see you go!\nCould you spare 30 seconds for some feedback?", "Uninstalling OGCS", + if (Ogcs.Extensions.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."); Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.uninstall, Application.ProductVersion + "-feedback"); @@ -479,7 +479,7 @@ private void checkForZip(object sender, DoWorkEventArgs e) { Int32 myReleaseNum = Program.VersionToInt(Application.ProductVersion); if (releaseNum > myReleaseNum) { log.Info("New " + releaseType + " ZIP release found: " + releaseVersion); - DialogResult dr = OgcsMessageBox.Show("A new " + releaseType + " release is available for OGCS. Would you like to upgrade to v" + releaseVersion + "?", "New OGCS Release Available", MessageBoxButtons.YesNo, MessageBoxIcon.Question); + DialogResult dr = Ogcs.Extensions.MessageBox.Show("A new " + releaseType + " release is available for OGCS. Would you like to upgrade to v" + releaseVersion + "?", "New OGCS Release Available", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dr == DialogResult.Yes) { Helper.OpenBrowser(releaseURL); } @@ -488,12 +488,12 @@ private void checkForZip(object sender, DoWorkEventArgs e) { if (isManualCheck) { String beta = ""; if (!Settings.Instance.AlphaReleases && Application.ProductVersion.EndsWith(".0.0")) beta = "beta "; - OgcsMessageBox.Show($"You are already on the latest {beta}release", "No Update Required", MessageBoxButtons.OK, MessageBoxIcon.Information); + Ogcs.Extensions.MessageBox.Show($"You are already on the latest {beta}release", "No Update Required", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } else { log.Info("Did not find ZIP release."); - if (isManualCheck) OgcsMessageBox.Show("Failed to check for ZIP release." + (string.IsNullOrEmpty(errorDetails) ? "" : "\r\n" + errorDetails), + if (isManualCheck) Ogcs.Extensions.MessageBox.Show("Failed to check for ZIP release." + (string.IsNullOrEmpty(errorDetails) ? "" : "\r\n" + errorDetails), "Update Check Failed", MessageBoxButtons.OK, MessageBoxIcon.Information); } } From 413bf98fbb82a5cda47b78a58782ff5575a37c2e Mon Sep 17 00:00:00 2001 From: Paul Woolcock <11843015+phw198@users.noreply.github.com> Date: Sun, 28 Apr 2024 13:59:16 +0100 Subject: [PATCH 6/8] Code refactor of Exception with proper extended methods under OutlookGoogleCalendarSync.Extensions namespace --- .../Console/Console.cs | 2 +- .../Extensions/ColourPicker.cs | 10 +- .../Extensions/Exception.cs | 18 +-- .../Extensions/NumericUpDown.cs | 2 +- .../Forms/ColourMap.cs | 22 ++-- .../Forms/MainForm.cs | 104 +++++++++--------- .../Forms/ProfileManage.cs | 4 +- .../Forms/TimezoneMap.cs | 10 +- .../Google/Authenticator.cs | 6 +- .../Google/CustomProperty.cs | 2 +- .../Google/ErrorReporting.cs | 2 +- .../Google/EventColour.cs | 4 +- src/OutlookGoogleCalendarSync/Google/GMeet.cs | 2 +- .../Google/GoogleCalendar.cs | 32 +++--- src/OutlookGoogleCalendarSync/Helper.cs | 2 +- .../NotificationTray.cs | 2 +- .../Outlook.Factory/OutlookFactory.cs | 6 +- .../Outlook.Factory/OutlookNew.cs | 24 ++-- .../Outlook.Factory/OutlookOld.cs | 12 +- .../Outlook/CustomProperty.cs | 4 +- .../Outlook/ExplorerWatcher.cs | 12 +- .../Outlook/GMeet.cs | 10 +- .../Outlook/OutlookCalendar.cs | 42 +++---- .../Outlook/OutlookCategories.cs | 10 +- .../Outlook/OutlookErrors.cs | 2 +- src/OutlookGoogleCalendarSync/Program.cs | 8 +- src/OutlookGoogleCalendarSync/Recurrence.cs | 10 +- .../SettingsStore/Proxy.cs | 6 +- .../SettingsStore/Upgrade.cs | 10 +- .../Sync/Calendar.cs | 28 ++--- src/OutlookGoogleCalendarSync/Sync/Engine.cs | 2 +- src/OutlookGoogleCalendarSync/Sync/Timer.cs | 4 +- src/OutlookGoogleCalendarSync/Telemetry.cs | 2 +- src/OutlookGoogleCalendarSync/TimezoneDB.cs | 8 +- src/OutlookGoogleCalendarSync/Updater.cs | 16 +-- src/OutlookGoogleCalendarSync/XMLManager.cs | 24 ++-- 36 files changed, 232 insertions(+), 232 deletions(-) diff --git a/src/OutlookGoogleCalendarSync/Console/Console.cs b/src/OutlookGoogleCalendarSync/Console/Console.cs index a3ddacd0..e609b518 100644 --- a/src/OutlookGoogleCalendarSync/Console/Console.cs +++ b/src/OutlookGoogleCalendarSync/Console/Console.cs @@ -328,7 +328,7 @@ public void Update(String moreOutput, Markup? markupPrefix = null, bool newLine public void UpdateWithError(String moreOutput, System.Exception ex, bool notifyBubble = false, String logEntry = null) { Markup emoji = Markup.error; - if (Ogcs.Exception.LoggingAsFail(ex)) + if (ex.LoggingAsFail()) emoji = Markup.fail; Update(moreOutput + (!string.IsNullOrEmpty(moreOutput) ? "
" : "") + Ogcs.Exception.FriendlyMessage(ex), logEntry, emoji, notifyBubble: notifyBubble); } diff --git a/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs b/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs index 58306015..4734f3a4 100644 --- a/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs +++ b/src/OutlookGoogleCalendarSync/Extensions/ColourPicker.cs @@ -123,7 +123,7 @@ private void ColourPicker_Enter(object sender, EventArgs e) { } } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("ColourPicker_Enter()", ex); + ex.Analyse("ColourPicker_Enter()"); } finally { loading.Hide(this); loading.RemoveAll(); @@ -234,7 +234,7 @@ protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.R } } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("OutlookColourComboboxCell.Paint()", ex); + ex.Analyse("OutlookColourComboboxCell.Paint()"); } } } @@ -299,7 +299,7 @@ protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.R } } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("GoogleColourComboboxCell.Paint()", ex); + ex.Analyse("GoogleColourComboboxCell.Paint()"); } } } @@ -480,7 +480,7 @@ void ComboboxColor_DrawItem(object sender, DrawItemEventArgs e) { if (indexItem < 0 || indexItem >= cbColour.Items.Count) return; - KeyValuePair kvp = (KeyValuePair< Outlook.Categories.ColourInfo, String>)cbColour.Items[indexItem]; + KeyValuePair kvp = (KeyValuePair)cbColour.Items[indexItem]; if (kvp.Key != null) { // Get the colour OlCategoryColor olColour = kvp.Key.OutlookCategory; @@ -503,7 +503,7 @@ public GoogleColourCombobox() { } public void PopulateDropdownItems() { - Dictionary cbItems = new Dictionary(); + Dictionary cbItems = new Dictionary(); foreach (Ogcs.Google.EventColour.Palette ci in Forms.ColourMap.GoogleComboBox.Items) { cbItems.Add(ci, ci.Name); } diff --git a/src/OutlookGoogleCalendarSync/Extensions/Exception.cs b/src/OutlookGoogleCalendarSync/Extensions/Exception.cs index ecce03cd..ba4f7355 100644 --- a/src/OutlookGoogleCalendarSync/Extensions/Exception.cs +++ b/src/OutlookGoogleCalendarSync/Extensions/Exception.cs @@ -11,14 +11,14 @@ public UserCancelledSyncException(string message) : base(message) { } public UserCancelledSyncException(string message, System.Exception inner) : base(message, inner) { } } - class Exception { + public static class Exception { private static readonly ILog log = LogManager.GetLogger(typeof(Ogcs.Exception)); - public static void Analyse(String warnDetail, System.Exception ex, Boolean includeStackTrace = false) { + public static void Analyse(this System.Exception ex, String warnDetail, Boolean includeStackTrace = false) { log.Warn(warnDetail); Analyse(ex, includeStackTrace: includeStackTrace); } - public static void Analyse(System.Exception ex, Boolean includeStackTrace = false) { + public static void Analyse(this System.Exception ex, Boolean includeStackTrace = false) { log4net.Core.Level logLevel = log4net.Core.Level.Error; if (LoggingAsFail(ex)) { if (ex is ApplicationException) return; @@ -46,7 +46,7 @@ public static void Analyse(System.Exception ex, Boolean includeStackTrace = fals if (includeStackTrace) log.ErrorOrFail(ex.StackTrace, logLevel); } - public static String GetErrorCode(System.Exception ex, UInt32 mask = 0xFFFFFFFF) { + public static String GetErrorCode(this System.Exception ex, UInt32 mask = 0xFFFFFFFF) { UInt32 maskedCode = (uint)(getErrorCode(ex) & mask); return "0x" + maskedCode.ToString("X8"); } @@ -71,7 +71,7 @@ private static int getErrorCode(System.Exception ex) { return -1; } - public static void AnalyseAggregate(AggregateException agex, Boolean throwError = true) { + public static void AnalyseAggregate(this AggregateException agex, Boolean throwError = true) { foreach (System.Exception ex in agex.InnerExceptions) { if (ex is ApplicationException) { if (!String.IsNullOrEmpty(ex.Message)) Forms.Main.Instance.Console.UpdateWithError(null, ex); @@ -84,7 +84,7 @@ public static void AnalyseAggregate(AggregateException agex, Boolean throwError } } - public static void AnalyseTokenResponse(global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex, Boolean throwError = true) { + public static void AnalyseTokenResponse(this global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex, Boolean throwError = true) { String instructions = "On the Settings > Google tab, please disconnect and re-authenticate your account."; log.Warn("Token response error: " + ex.Message); @@ -107,7 +107,7 @@ public static void AnalyseTokenResponse(global::Google.Apis.Auth.OAuth2.Response if (throwError) throw ex; } - public static String FriendlyMessage(System.Exception ex) { + public static String FriendlyMessage(this System.Exception ex) { if (ex is global::Google.GoogleApiException) { global::Google.GoogleApiException gaex = ex as global::Google.GoogleApiException; if (gaex.Error != null) @@ -140,7 +140,7 @@ public static void LogAsFail(ref System.Exception ex) { /// /// Capture this exception as log4net FAIL (not ERROR) when logged /// - public static System.Exception LogAsFail(System.Exception ex) { + public static System.Exception LogAsFail(this System.Exception ex) { LogAsFail(ref ex); return ex; } @@ -194,7 +194,7 @@ public static void LogAsFail(ref global::Google.GoogleApiException ex) { /// /// Check if this exception has been set to log as log4net FAIL (not ERROR) /// - public static Boolean LoggingAsFail(System.Exception ex) { + public static Boolean LoggingAsFail(this System.Exception ex) { return (ex.Data.Contains(LogAs) && ex.Data[LogAs].ToString() == LogLevel.FAIL.ToString()); } #endregion diff --git a/src/OutlookGoogleCalendarSync/Extensions/NumericUpDown.cs b/src/OutlookGoogleCalendarSync/Extensions/NumericUpDown.cs index 8069f54b..8c0d9403 100644 --- a/src/OutlookGoogleCalendarSync/Extensions/NumericUpDown.cs +++ b/src/OutlookGoogleCalendarSync/Extensions/NumericUpDown.cs @@ -35,7 +35,7 @@ private void checkLimit() { this.tooltip.RemoveAll(); } } catch (System.Exception ex) { - Ogcs.Exception.Analyse(this.Name, ex); + ex.Analyse(this.Name); } } } diff --git a/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs b/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs index ec464b89..86088450 100644 --- a/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs +++ b/src/OutlookGoogleCalendarSync/Forms/ColourMap.cs @@ -10,7 +10,7 @@ public partial class ColourMap : Form { private static readonly ILog log = LogManager.GetLogger(typeof(ColourMap)); public static Extensions.OutlookColourPicker OutlookComboBox = new Extensions.OutlookColourPicker(); public static Extensions.GoogleColourPicker GoogleComboBox = new Extensions.GoogleColourPicker(); - + public ColourMap() { log.Info("Opening colour mapping window."); OutlookComboBox = null; @@ -57,7 +57,7 @@ private void loadConfig() { ddGoogleColour.SelectedIndex = 0; } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Populating gridview cells from Settings.", ex); + ex.Analyse("Populating gridview cells from Settings."); } } @@ -78,7 +78,7 @@ private void addRow(String outlookColour, String googleColour) { colourGridView.NotifyCurrentCellDirty(false); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Adding colour/category map row #" + lastRow, ex); + ex.Analyse("Adding colour/category map row #" + lastRow); } } @@ -96,7 +96,7 @@ private void newRowNeeded() { colourGridView.CurrentCell = lastCell; } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("newRowNeeded(): Adding colour/category map row #" + lastRow, ex); + ex.Analyse("newRowNeeded(): Adding colour/category map row #" + lastRow); } finally { colourGridView.NotifyCurrentCellDirty(true); colourGridView.NotifyCurrentCellDirty(false); @@ -115,7 +115,7 @@ private void btOK_Click(object sender, EventArgs e) { oColValues.Add(row.Cells["OutlookColour"].Value.ToString()); gColValues.Add(row.Cells["GoogleColour"].Value.ToString()); } - String oDuplicates = string.Join("\r\n", oColValues.GroupBy(v => v).Where(g => g.Count() > 1).Select(s => "- "+ s.Key).ToList()); + String oDuplicates = string.Join("\r\n", oColValues.GroupBy(v => v).Where(g => g.Count() > 1).Select(s => "- " + s.Key).ToList()); String gDuplicates = string.Join("\r\n", gColValues.GroupBy(v => v).Where(g => g.Count() > 1).Select(s => "- " + s.Key).ToList()); if (!string.IsNullOrEmpty(oDuplicates) && (profile.SyncDirection.Id == Sync.Direction.OutlookToGoogle.Id || profile.SyncDirection.Id == Sync.Direction.Bidirectional.Id)) { @@ -126,7 +126,7 @@ private void btOK_Click(object sender, EventArgs e) { return; } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed looking for duplicating mappings before storing in Settings.", ex); + ex.Analyse("Failed looking for duplicating mappings before storing in Settings."); Ogcs.Extensions.MessageBox.Show("An error was encountered storing your custom mappings.", "Cannot save mappings", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } @@ -139,13 +139,13 @@ private void btOK_Click(object sender, EventArgs e) { try { profile.ColourMaps.Add(row.Cells["OutlookColour"].Value.ToString(), Ogcs.Google.EventColour.Palette.GetColourId(row.Cells["GoogleColour"].Value.ToString())); } catch (System.ArgumentException ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x80070057") { + if (ex.GetErrorCode() == "0x80070057") { //An item with the same key has already been added } else throw; } } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not save colour/category mappings to Settings.", ex); + ex.Analyse("Could not save colour/category mappings to Settings."); } finally { this.Close(); } @@ -241,7 +241,7 @@ private void ddOutlookColour_SelectedIndexChanged(object sender, EventArgs e) { try { ddGoogleColour.SelectedIndexChanged -= ddGoogleColour_SelectedIndexChanged; - + foreach (DataGridViewRow row in colourGridView.Rows) { if (row.Cells["OutlookColour"].Value.ToString() == ddOutlookColour.SelectedItem.Text && !string.IsNullOrEmpty(row.Cells["GoogleColour"].Value?.ToString())) { String colourId = Ogcs.Google.EventColour.Palette.GetColourId(row.Cells["GoogleColour"].Value.ToString()); @@ -253,7 +253,7 @@ private void ddOutlookColour_SelectedIndexChanged(object sender, EventArgs e) { ddGoogleColour.SelectedIndex = Convert.ToInt16(Ogcs.Google.Calendar.Instance.GetColour(ddOutlookColour.SelectedItem.OutlookCategory).Id); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("ddOutlookColour_SelectedIndexChanged(): Could not update ddGoogleColour.", ex); + ex.Analyse("ddOutlookColour_SelectedIndexChanged(): Could not update ddGoogleColour."); } finally { ddGoogleColour.SelectedIndexChanged += ddGoogleColour_SelectedIndexChanged; } @@ -299,7 +299,7 @@ private void ddGoogleColour_SelectedIndexChanged(object sender, EventArgs e) { ddOutlookColour.SelectedIndex = 0; } catch (System.Exception ex) { - Ogcs.Exception.Analyse("ddGoogleColour_SelectedIndexChanged(): Could not update ddOutlookColour.", ex); + ex.Analyse("ddGoogleColour_SelectedIndexChanged(): Could not update ddOutlookColour."); } finally { ddOutlookColour.SelectedIndexChanged += ddOutlookColour_SelectedIndexChanged; } diff --git a/src/OutlookGoogleCalendarSync/Forms/MainForm.cs b/src/OutlookGoogleCalendarSync/Forms/MainForm.cs index 81dd6b94..3cc38cf5 100644 --- a/src/OutlookGoogleCalendarSync/Forms/MainForm.cs +++ b/src/OutlookGoogleCalendarSync/Forms/MainForm.cs @@ -311,35 +311,35 @@ public void UpdateGUIsettings_Profile() { rbOutlookAltMB.Enabled = false; rbOutlookAltMB.Checked = false; } - Folders theFolders = Outlook.Calendar.Instance.Folders; - Dictionary> folderIDs = new Dictionary>(); - for (int fld = 1; fld <= theFolders.Count; fld++) { - MAPIFolder theFolder = theFolders[fld]; - try { - //Create a dictionary of folder names and a list of their ID(s) - if (!folderIDs.ContainsKey(theFolder.Name)) { - folderIDs.Add(theFolder.Name, new List(new String[] { theFolder.EntryID })); - } else if (!folderIDs[theFolder.Name].Contains(theFolder.EntryID)) { - folderIDs[theFolder.Name].Add(theFolder.EntryID); - } - } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to get EntryID for folder: " + theFolder.Name, Ogcs.Exception.LogAsFail(ex)); - } finally { - theFolder = (MAPIFolder)Outlook.Calendar.ReleaseObject(theFolder); + Folders theFolders = Outlook.Calendar.Instance.Folders; + Dictionary> folderIDs = new Dictionary>(); + for (int fld = 1; fld <= theFolders.Count; fld++) { + MAPIFolder theFolder = theFolders[fld]; + try { + //Create a dictionary of folder names and a list of their ID(s) + if (!folderIDs.ContainsKey(theFolder.Name)) { + folderIDs.Add(theFolder.Name, new List(new String[] { theFolder.EntryID })); + } else if (!folderIDs[theFolder.Name].Contains(theFolder.EntryID)) { + folderIDs[theFolder.Name].Add(theFolder.EntryID); } + } catch (System.Exception ex) { + ex.LogAsFail().Analyse("Failed to get EntryID for folder: " + theFolder.Name); + } finally { + theFolder = (MAPIFolder)Outlook.Calendar.ReleaseObject(theFolder); } - ddMailboxName.Items.Clear(); - ddMailboxName.Items.AddRange(folderIDs.Keys.ToArray()); - ddMailboxName.SelectedItem = profile.MailboxName; + } + ddMailboxName.Items.Clear(); + ddMailboxName.Items.AddRange(folderIDs.Keys.ToArray()); + ddMailboxName.SelectedItem = profile.MailboxName; - if (ddMailboxName.SelectedIndex == -1 && ddMailboxName.Items.Count > 0) { - if (profile.OutlookService == Outlook.Calendar.Service.AlternativeMailbox && string.IsNullOrEmpty(profile.MailboxName)) - log.Warn("Could not find mailbox '" + profile.MailboxName + "' in Alternate Mailbox dropdown. Defaulting to the first in the list."); + if (ddMailboxName.SelectedIndex == -1 && ddMailboxName.Items.Count > 0) { + if (profile.OutlookService == Outlook.Calendar.Service.AlternativeMailbox && string.IsNullOrEmpty(profile.MailboxName)) + log.Warn("Could not find mailbox '" + profile.MailboxName + "' in Alternate Mailbox dropdown. Defaulting to the first in the list."); - ddMailboxName.SelectedIndexChanged -= new System.EventHandler(this.ddMailboxName_SelectedIndexChanged); - ddMailboxName.SelectedIndex = 0; - ddMailboxName.SelectedIndexChanged += new System.EventHandler(this.ddMailboxName_SelectedIndexChanged); - } + ddMailboxName.SelectedIndexChanged -= new System.EventHandler(this.ddMailboxName_SelectedIndexChanged); + ddMailboxName.SelectedIndex = 0; + ddMailboxName.SelectedIndexChanged += new System.EventHandler(this.ddMailboxName_SelectedIndexChanged); + } log.Debug("List Calendar folders"); cbOutlookCalendars.SelectedIndexChanged -= cbOutlookCalendar_SelectedIndexChanged; @@ -595,7 +595,7 @@ public void UpdateGUIsettings_Profile() { #endregion #endregion } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Unable to set GUI profile.", ex); + ex.Analyse("Unable to set GUI profile."); throw; } finally { this.LoadingProfileConfig = false; @@ -610,7 +610,7 @@ public void FeaturesBlockedByCorpPolicy(Boolean isTrue) { ToolTips.SetToolTip(cbAddDescription, isTrue ? tooltip : ""); ToolTips.SetToolTip(rbOutlookSharedCal, isTrue ? tooltip : ""); } catch (System.InvalidOperationException ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x80131509") { //Cross-thread operation + if (ex.GetErrorCode() == "0x80131509") { //Cross-thread operation log.Warn("Can't set form tooltips from sync thread."); //Won't worry too much - will work fine on OGCS startup, and will only arrive here if GAL has been blocked *after* startup. Should be very unlikely. } @@ -706,13 +706,13 @@ private void buildAvailabilityDropdown() { ddAvailabilty.DataSource = new BindingSource(availability, null); ddAvailabilty.Enabled = profile.SetEntriesAvailable; } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed building availability dropdown values.", ex); + ex.Analyse("Failed building availability dropdown values."); return; } try { ddAvailabilty.SelectedValue = Enum.Parse(typeof(OlBusyStatus), profile.AvailabilityStatus); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed selecting availability dropdown value from Settings.", ex); + ex.Analyse("Failed selecting availability dropdown value from Settings."); } finally { if (ddAvailabilty.SelectedIndex == -1 && ddAvailabilty.Items.Count > 0) ddAvailabilty.SelectedIndex = 0; @@ -724,7 +724,7 @@ public void Sync_Click(object sender, EventArgs e) { try { Sync.Engine.Instance.Sync_Requested(sender, e); } catch (System.AggregateException ex) { - Ogcs.Exception.AnalyseAggregate(ex, false); + ex.AnalyseAggregate(false); } catch (System.ApplicationException ex) { if (ex.Message.ToLower().Contains("try again") && sender != null) { Sync_Click(null, null); @@ -1048,7 +1048,7 @@ private void Console_KeyDown(object sender, PreviewKeyDownEventArgs e) { notLogFile(); } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Console_KeyDown detected.", Ogcs.Exception.LogAsFail(ex)); + ex.LogAsFail().Analyse("Console_KeyDown detected."); } } @@ -1267,7 +1267,7 @@ private void miDeleteProfile_Click(object sender, EventArgs e) { Settings.Instance.Save(); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to delete profile '" + profileName + "'.", ex); + ex.Analyse("Failed to delete profile '" + profileName + "'."); throw; } } @@ -1503,7 +1503,7 @@ private void btTestOutlookFilter_Click(object sender, EventArgs e) { log.Info(msg); Ogcs.Extensions.MessageBox.Show(msg, "Date-Time Format Results", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Profile '" + Settings.Profile.Name(ActiveCalendarProfile) + "', calendar ID " + ActiveCalendarProfile.UseOutlookCalendar.Id, ex); + ex.Analyse("Profile '" + Settings.Profile.Name(ActiveCalendarProfile) + "', calendar ID " + ActiveCalendarProfile.UseOutlookCalendar.Id); Ogcs.Extensions.MessageBox.Show(ex.Message, "Unable to perform test", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -1541,9 +1541,9 @@ private void GetMyGoogleCalendars_Click(object sender, EventArgs e) { try { Ogcs.Google.Calendar.Instance.GetCalendars(); } catch (AggregateException agex) { - Ogcs.Exception.AnalyseAggregate(agex, false); + agex.AnalyseAggregate(false); } catch (global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { - Ogcs.Exception.AnalyseTokenResponse(ex, false); + ex.AnalyseTokenResponse(false); } catch (OperationCanceledException) { } catch (System.Exception ex) { Ogcs.Exception.Analyse(ex); @@ -1556,7 +1556,7 @@ private void GetMyGoogleCalendars_Click(object sender, EventArgs e) { console.BuildOutput(ex.Message, ref sb, false); console.Update(sb, Console.Markup.fail, logit: true); } else { - console.BuildOutput(Ogcs.Exception.FriendlyMessage(ex), ref sb, false); + console.BuildOutput(ex.FriendlyMessage(), ref sb, false); console.Update(sb, Console.Markup.error, logit: true); if (Settings.Instance.Proxy.Type == "IE") { if (Ogcs.Extensions.MessageBox.Show("Please ensure you can access the internet with Internet Explorer.\r\n" + @@ -1917,8 +1917,8 @@ private void tbTargetCalendar_SelectedItemChanged(object sender, EventArgs e) { private void cbPrivate_CheckedChanged(object sender, EventArgs e) { ddPrivacy.Enabled = cbPrivate.Checked; - if (this.LoadingProfileConfig) return; - + if (this.LoadingProfileConfig) return; + ActiveCalendarProfile.SetEntriesPrivate = cbPrivate.Checked; } private void ddPrivacy_SelectedIndexChanged(object sender, EventArgs e) { @@ -1929,8 +1929,8 @@ private void ddPrivacy_SelectedIndexChanged(object sender, EventArgs e) { private void cbAvailable_CheckedChanged(object sender, EventArgs e) { ddAvailabilty.Enabled = cbAvailable.Checked; - if (this.LoadingProfileConfig) return; - + if (this.LoadingProfileConfig) return; + ActiveCalendarProfile.SetEntriesAvailable = cbAvailable.Checked; } private void ddAvailabilty_SelectedIndexChanged(object sender, EventArgs e) { @@ -1971,9 +1971,9 @@ private void ddOutlookColour_SelectedIndexChanged(object sender, EventArgs e) { log.Warn("Could not find the Google colour for: " + palette.ToString()); else ddGoogleColour_SelectedIndexChanged(null, null); - + } catch (System.Exception ex) { - Ogcs.Exception.Analyse("ddOutlookColour_SelectedIndexChanged(): Could not update ddGoogleColour.", ex); + ex.Analyse("ddOutlookColour_SelectedIndexChanged(): Could not update ddGoogleColour."); } finally { ddGoogleColour.SelectedIndexChanged += ddGoogleColour_SelectedIndexChanged; } @@ -1993,21 +1993,21 @@ private void ddGoogleColour_SelectedIndexChanged(object sender, EventArgs e) { oCatName = ActiveCalendarProfile.SetEntriesColourName; else oCatName = Outlook.Calendar.Instance.GetCategoryColour(ddGoogleColour.SelectedItem.Id); - + foreach (Outlook.Categories.ColourInfo cInfo in ddOutlookColour.Items) { if (cInfo.Text == oCatName) { ddOutlookColour.SelectedItem = cInfo; break; } } - + if (ddOutlookColour.SelectedIndex == -1) log.Warn("Could not find the Outlook category for '" + oCatName + "'"); else ddOutlookColour_SelectedIndexChanged(null, null); - + } catch (System.Exception ex) { - Ogcs.Exception.Analyse("ddGoogleColour_SelectedIndexChanged(): Could not update ddOutlookColour.", ex); + ex.Analyse("ddGoogleColour_SelectedIndexChanged(): Could not update ddOutlookColour."); } finally { ddOutlookColour.SelectedIndexChanged += ddOutlookColour_SelectedIndexChanged; } @@ -2054,7 +2054,7 @@ private void dgObfuscateRegex_CellValidating(object sender, DataGridViewCellVali if (rgx.IsMatch(strVal)) { e.Cancel = true; - Ogcs.Extensions.MessageBox.Show("Cell must only include the characters:-\r S = Subject\r L = Location\r D = Description", + Ogcs.Extensions.MessageBox.Show("Cell must only include the characters:-\r S = Subject\r L = Location\r D = Description", "Invalid target values", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } dgObfuscateRegex.Rows[e.RowIndex].Cells[((int)Obfuscate.Columns.target)].Value = strVal; @@ -2088,7 +2088,7 @@ private void tbMinuteOffsets_ValueChanged(object sender, EventArgs e) { String tooltip = "Set to zero to disable automated syncs"; if (!Settings.Instance.UsingPersonalAPIkeys()) { String fup = "Fair usage policy: Minimum sync interval of " + MinSyncMinutes + "mins" + (ActiveCalendarProfile.OutlookPush ? " with Push Sync enabled" : "") + "."; - + tbInterval.ValueChanged -= new System.EventHandler(this.tbMinuteOffsets_ValueChanged); cbIntervalUnit.SelectedIndexChanged -= new System.EventHandler(this.cbIntervalUnit_SelectedIndexChanged); try { @@ -2312,7 +2312,7 @@ private void cbStartOnStartup_CheckedChanged(object sender, EventArgs e) { Program.ManageStartupRegKey(); } catch (System.Exception ex) { if (ex is System.Security.SecurityException) Ogcs.Exception.LogAsFail(ref ex); //User doesn't have rights to access registry - Ogcs.Exception.Analyse("Failed accessing registry for startup key(s).", ex); + ex.Analyse("Failed accessing registry for startup key(s)."); if (this.Visible) { Ogcs.Extensions.MessageBox.Show("You do not have permissions to access the system registry.\nThis setting cannot be used.", "Registry access denied", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); @@ -2330,7 +2330,7 @@ private void cbStartOnStartupAllUsers_CheckedChanged(object sender, EventArgs e) Program.ManageStartupRegKey(); } catch (System.Exception ex) { if (ex is System.Security.SecurityException) Ogcs.Exception.LogAsFail(ref ex); //User doesn't have rights to access registry - Ogcs.Exception.Analyse("Failed accessing registry for HKLM startup key.", ex); + ex.Analyse("Failed accessing registry for HKLM startup key."); if (this.Visible) { Ogcs.Extensions.MessageBox.Show("You do not have permissions to access the system registry.\nThis setting cannot be used.", "Registry access denied", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); @@ -2479,7 +2479,7 @@ private void btCheckBrowserAgent_Click(object sender, EventArgs e) { try { Helper.OpenBrowser(Program.OgcsWebsite + "/browseruseragent"); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to check browser's user agent.", ex); + ex.Analyse("Failed to check browser's user agent."); } } @@ -2645,5 +2645,5 @@ private void btSocialGitHub_Click(object sender, EventArgs e) { Social.GitHub(); } #endregion - } + } } \ No newline at end of file diff --git a/src/OutlookGoogleCalendarSync/Forms/ProfileManage.cs b/src/OutlookGoogleCalendarSync/Forms/ProfileManage.cs index 4654b6d8..898c0aed 100644 --- a/src/OutlookGoogleCalendarSync/Forms/ProfileManage.cs +++ b/src/OutlookGoogleCalendarSync/Forms/ProfileManage.cs @@ -50,7 +50,7 @@ private void ProfileManage_FormClosing(object sender, FormClosingEventArgs e) { newCalendar.InitialiseTimer(); newCalendar.RegisterForPushSync(); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to add new profile.", ex); + ex.Analyse("Failed to add new profile."); throw; } @@ -69,7 +69,7 @@ private void ProfileManage_FormClosing(object sender, FormClosingEventArgs e) { log.Info("Renamed calendar settings from '" + currentProfileName + "' to '" + newProfileName + "'."); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to rename profile from '" + currentProfileName + "' to '" + newProfileName + "'.", ex); + ex.Analyse("Failed to rename profile from '" + currentProfileName + "' to '" + newProfileName + "'."); throw; } Forms.Main.Instance.NotificationTray.RenameProfileItem(currentProfileName, newProfileName); diff --git a/src/OutlookGoogleCalendarSync/Forms/TimezoneMap.cs b/src/OutlookGoogleCalendarSync/Forms/TimezoneMap.cs index 54456b37..9cd5aaef 100644 --- a/src/OutlookGoogleCalendarSync/Forms/TimezoneMap.cs +++ b/src/OutlookGoogleCalendarSync/Forms/TimezoneMap.cs @@ -74,7 +74,7 @@ private void loadConfig() { } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Populating gridview cells from Settings.", ex); + ex.Analyse("Populating gridview cells from Settings."); } } @@ -95,7 +95,7 @@ private void addRow(String organiserTz, String systemTz) { tzGridView.NotifyCurrentCellDirty(false); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Adding timezone map row #" + lastRow, ex); + ex.Analyse("Adding timezone map row #" + lastRow); } } @@ -120,13 +120,13 @@ private void btOK_Click(object sender, EventArgs e) { try { Settings.Instance.TimezoneMaps.Add(row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString()); } catch (System.ArgumentException ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x80070057") { + if (ex.GetErrorCode() == "0x80070057") { //An item with the same key has already been added } else throw; } } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not save timezone mappings to Settings.", ex); + ex.Analyse("Could not save timezone mappings to Settings."); } finally { this.Close(); Forms.Main.Instance.SetControlPropertyThreadSafe(Forms.Main.Instance.btCustomTzMap, "Visible", Settings.Instance.TimezoneMaps.Count != 0); @@ -147,7 +147,7 @@ private void tzGridView_DataError(object sender, DataGridViewDataErrorEventArgs log.Debug("Cell[" + cell.RowIndex + "][" + cell.ColumnIndex + "] caused error."); } catch { } finally { - Ogcs.Exception.Analyse("Bad cell value in timezone data grid.", e.Exception); + e.Exception.Analyse("Bad cell value in timezone data grid."); } } } diff --git a/src/OutlookGoogleCalendarSync/Google/Authenticator.cs b/src/OutlookGoogleCalendarSync/Google/Authenticator.cs index 23c2af85..29dce380 100644 --- a/src/OutlookGoogleCalendarSync/Google/Authenticator.cs +++ b/src/OutlookGoogleCalendarSync/Google/Authenticator.cs @@ -67,7 +67,7 @@ private void spawnOauth() { } catch (System.OperationCanceledException) { Forms.Main.Instance.Console.Update("Authorisation to allow OGCS to manage your Google calendar was cancelled.", Console.Markup.warning); } catch (System.Exception ex) { - Ogcs.Exception.Analyse(ex); + ex.Analyse(); } } catch (System.Exception ex) { log.Fail("Problem encountered in getCalendarClientSecrets()"); @@ -239,7 +239,7 @@ private void getGaccountEmail(String accessToken) { System.IO.StreamReader sr = new System.IO.StreamReader(stream); log.Error(sr.ReadToEnd()); } - if (Ogcs.Exception.GetErrorCode(ex) == "0x80131509") { + if (ex.GetErrorCode() == "0x80131509") { log.Warn(ex.Message); System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(@"\b(403|Forbidden|Prohibited|Insufficient Permission)\b", System.Text.RegularExpressions.RegexOptions.IgnoreCase); @@ -356,7 +356,7 @@ public Boolean UserSubscriptionCheck() { return false; } } catch (global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { - Ogcs.Exception.AnalyseTokenResponse(ex); + ex.AnalyseTokenResponse(); } catch (global::Google.GoogleApiException ex) { switch (Ogcs.Google.Calendar.HandleAPIlimits(ref ex, null)) { diff --git a/src/OutlookGoogleCalendarSync/Google/CustomProperty.cs b/src/OutlookGoogleCalendarSync/Google/CustomProperty.cs index 4baeb138..5e199cf0 100644 --- a/src/OutlookGoogleCalendarSync/Google/CustomProperty.cs +++ b/src/OutlookGoogleCalendarSync/Google/CustomProperty.cs @@ -349,7 +349,7 @@ public static void LogProperties(Event ev, log4net.Core.Level thresholdLevel) { } } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to log Event ExtendedProperties", ex); + ex.Analyse("Failed to log Event ExtendedProperties"); } } } diff --git a/src/OutlookGoogleCalendarSync/Google/ErrorReporting.cs b/src/OutlookGoogleCalendarSync/Google/ErrorReporting.cs index 17966c87..965d2e4a 100644 --- a/src/OutlookGoogleCalendarSync/Google/ErrorReporting.cs +++ b/src/OutlookGoogleCalendarSync/Google/ErrorReporting.cs @@ -65,7 +65,7 @@ public static void Initialise() { try { File.WriteAllLines(credFile, newLines.ToArray()); } catch (System.IO.IOException ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x80070020") + if (ex.GetErrorCode() == "0x80070020") log.Warn("ErrorReporting.json is being used by another process (perhaps multiple instances of OGCS are being started on system startup?)"); else throw; diff --git a/src/OutlookGoogleCalendarSync/Google/EventColour.cs b/src/OutlookGoogleCalendarSync/Google/EventColour.cs index 78f794a4..054a7b52 100644 --- a/src/OutlookGoogleCalendarSync/Google/EventColour.cs +++ b/src/OutlookGoogleCalendarSync/Google/EventColour.cs @@ -141,7 +141,7 @@ public static String GetColourId(String name) { try { id = eventColourNames.First(n => (n.Value as Metadata).Name == name).Key.ToString(); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not find colour ID for '" + name + "'.", ex); + ex.Analyse("Could not find colour ID for '" + name + "'."); } return id; } @@ -162,7 +162,7 @@ public static String GetColourName(String id) { else log.Error("GetColourName(): ID '" + id + "' not found."); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not find colour name for '" + id + "'.", ex); + ex.Analyse("Could not find colour name for '" + id + "'."); } return name; } diff --git a/src/OutlookGoogleCalendarSync/Google/GMeet.cs b/src/OutlookGoogleCalendarSync/Google/GMeet.cs index 71de85d8..dd422ffc 100644 --- a/src/OutlookGoogleCalendarSync/Google/GMeet.cs +++ b/src/OutlookGoogleCalendarSync/Google/GMeet.cs @@ -52,7 +52,7 @@ public static void GoogleMeet(this Event ev, String outlookGMeetUrl) { } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not alter Event conference data.", ex); + ex.Analyse("Could not alter Event conference data."); } } } diff --git a/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs b/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs index 50190c40..e2f0b7d5 100644 --- a/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs +++ b/src/OutlookGoogleCalendarSync/Google/GoogleCalendar.cs @@ -216,7 +216,7 @@ public List GetCalendarEntriesInRecurrence(String recurringEventId) { } catch (System.Exception ex) { Forms.Main.Instance.Console.UpdateWithError("Failed to retrieve recurring events.", Ogcs.Exception.LogAsFail(ex)); - Ogcs.Exception.Analyse("recurringEventId: " + recurringEventId, ex); + ex.Analyse("recurringEventId: " + recurringEventId); return null; } } @@ -567,7 +567,7 @@ private Event createCalendarEntry(AppointmentItem ai) { try { ev.Description = Obfuscate.ApplyRegex(Obfuscate.Property.Description, ai.Body, null, Sync.Direction.OutlookToGoogle); } catch (System.Exception ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x80004004") { + if (ex.GetErrorCode() == "0x80004004") { Forms.Main.Instance.Console.Update("You do not have the rights to programmatically access Outlook appointment descriptions.
" + "It may be best to stop syncing the Description attribute.", Console.Markup.warning); } else throw; @@ -933,7 +933,7 @@ public Event UpdateCalendarEntry(AppointmentItem ai, Event ev, ref int itemModif ev = patchEvent(ev) ?? ev; log.Fine("Conference data change successfully saved."); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not update conference data in existing Event.", ex); + ex.Analyse("Could not update conference data in existing Event."); } } } @@ -1798,7 +1798,7 @@ public void GetSettings() { case ApiException.throwException: throw; case ApiException.freeAPIexhausted: Ogcs.Exception.LogAsFail(ref ex); - Ogcs.Exception.Analyse("Not able to " + stage, ex); + ex.Analyse("Not able to " + stage); System.ApplicationException aex = new System.ApplicationException(SubscriptionInvite, ex); Ogcs.Exception.LogAsFail(ref aex); throw aex; @@ -1814,11 +1814,11 @@ public void GetSettings() { } break; } - Ogcs.Exception.Analyse("Not able to " + stage, ex); + ex.Analyse("Not able to " + stage); throw new System.ApplicationException("Unable to " + stage + ".", ex); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Not able to " + stage, ex); + ex.Analyse("Not able to " + stage); throw; } } @@ -1840,7 +1840,7 @@ private void getCalendarSettings() { String responseBody = response.Content.ReadAsStringAsync().Result; cal = Newtonsoft.Json.JsonConvert.DeserializeObject(responseBody); } catch (System.Exception ex2) { - Ogcs.Exception.Analyse("Failed retrieving calendarList via HttpRequestMessage.", ex2); + ex2.Analyse("Failed retrieving calendarList via HttpRequestMessage."); throw; } } else throw; @@ -1905,7 +1905,7 @@ private String getAvailability(OlBusyStatus oBusyStatus, String gTransparency) { if (fbStatus != OlBusyStatus.olFree) overrideTransparency = "opaque"; } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not convert string '" + profile.AvailabilityStatus + "' to OlBusyStatus type. Defaulting override to available.", ex); + ex.Analyse("Could not convert string '" + profile.AvailabilityStatus + "' to OlBusyStatus type. Defaulting override to available."); } if (profile.SyncDirection.Id != Sync.Direction.Bidirectional.Id) { @@ -2053,7 +2053,7 @@ public static void ExportToCSV(String action, String filename, List event log.Debug("Previous export renamed to " + backupFilename); } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to backup previous CSV file.", ex); + ex.Analyse("Failed to backup previous CSV file."); } Stream stream = null; @@ -2064,7 +2064,7 @@ public static void ExportToCSV(String action, String filename, List event tw = new StreamWriter(stream, Encoding.UTF8); } catch (System.Exception ex) { Forms.Main.Instance.Console.Update("Failed to create CSV file '" + filename + "'.", Console.Markup.error); - Ogcs.Exception.Analyse("Error opening file '" + filename + "' for writing.", ex); + ex.Analyse("Error opening file '" + filename + "' for writing."); return; } try { @@ -2198,11 +2198,11 @@ public static String GetEventSummary(Event ev, out String eventSummaryAnonymised eventSummary += System.DateTime.Parse(ev.Start.Date).ToShortDateString(); if ((ev.Recurrence != null && ev.RecurringEventId == null) || ev.RecurringEventId != null) eventSummary += " (R)"; - + if (Settings.Instance.AnonymiseLogs) eventSummaryAnonymised = eventSummary + " => \"" + Authenticator.GetMd5(ev.Summary, silent: true) + "\"" + (onlyIfNotVerbose ? "
" : ""); eventSummary += " => \"" + ev.Summary + "\"" + (onlyIfNotVerbose ? "
" : ""); - + } catch { log.Warn("Failed to create Event summary: " + eventSummary); log.Warn("This Event cannot be synced."); @@ -2284,10 +2284,10 @@ public static ApiException HandleAPIlimits(ref global::Google.GoogleApiException ev.Attendees = new List(); return ApiException.backoffThenRetry; - + } else if (ex.Error.Errors.First().Reason == "rateLimitExceeded") { if (ex.Message.Contains("limit 'Queries per minute'")) { - log.Fail(Ogcs.Exception.FriendlyMessage(ex)); + log.Fail(ex.FriendlyMessage()); Ogcs.Exception.LogAsFail(ref ex); return ApiException.backoffThenRetry; @@ -2344,7 +2344,7 @@ public static ApiException HandleAPIlimits(ref global::Google.GoogleApiException log.Debug("Successfully forced save by ignoring eTag values."); } catch (System.Exception ex2) { try { - Ogcs.Exception.Analyse("Failed forcing save with ETagAction.Ignore", Ogcs.Exception.LogAsFail(ex2)); + ex2.LogAsFail().Analyse("Failed forcing save with ETagAction.Ignore"); log.Fine("Current eTag: " + ev.ETag); log.Fine("Current Updated: " + ev.UpdatedRaw); log.Fine("Current Sequence: " + ev.Sequence); @@ -2367,7 +2367,7 @@ public static ApiException HandleAPIlimits(ref global::Google.GoogleApiException return ApiException.justContinue; } else if (ex.Error?.Code == 500) { - log.Fail(Ogcs.Exception.FriendlyMessage(ex)); + log.Fail(ex.FriendlyMessage()); Ogcs.Exception.LogAsFail(ref ex); return ApiException.backoffThenRetry; } diff --git a/src/OutlookGoogleCalendarSync/Helper.cs b/src/OutlookGoogleCalendarSync/Helper.cs index a83540e3..d1e0fbcc 100644 --- a/src/OutlookGoogleCalendarSync/Helper.cs +++ b/src/OutlookGoogleCalendarSync/Helper.cs @@ -12,7 +12,7 @@ public static void OpenBrowser(String url) { System.Diagnostics.Process.Start(url); return; } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not open default browser.", Ogcs.Exception.LogAsFail(ex)); + ex.LogAsFail().Analyse("Could not open default browser."); } //OK, let's try and determine the default browser from the registry and then directly invoke it. Why is this so much work! diff --git a/src/OutlookGoogleCalendarSync/NotificationTray.cs b/src/OutlookGoogleCalendarSync/NotificationTray.cs index 666d1f0a..b13cb365 100644 --- a/src/OutlookGoogleCalendarSync/NotificationTray.cs +++ b/src/OutlookGoogleCalendarSync/NotificationTray.cs @@ -59,7 +59,7 @@ public NotificationTray(NotifyIcon icon) { } animatedIconFrame = 0; } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not set up animated system tray icon.", ex); + ex.Analyse("Could not set up animated system tray icon."); } } diff --git a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookFactory.cs b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookFactory.cs index 85024b64..df653358 100644 --- a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookFactory.cs +++ b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookFactory.cs @@ -132,7 +132,7 @@ private static void getOutlookVersionName(Int16 version, String versionFull) { outlookVersionName = (OutlookVersionNames)version; outlookVersionNameFull = outlookVersionName.ToString(); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed determining Outlook client version.", ex); + ex.Analyse("Failed determining Outlook client version."); outlookVersionNameFull = "Failed-" + versionFull; outlookVersionName = OutlookVersionNames.Failed; } @@ -182,12 +182,12 @@ private static void getOutlookVersionName(Int16 version, String versionFull) { log.Error("Could not determine exact Outlook version with codebase v16."); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed determining Click-to-Run release.", ex); + ex.Analyse("Failed determining Click-to-Run release."); } } } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed determining Outlook release name from registry for codebase v16.", ex); + ex.Analyse("Failed determining Outlook release name from registry for codebase v16."); } } finally { log.Info("Outlook product name: " + outlookVersionNameFull); diff --git a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookNew.cs b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookNew.cs index 9ae2f3ee..98926c65 100644 --- a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookNew.cs +++ b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookNew.cs @@ -98,7 +98,7 @@ public void Connect() { explorerWatcher = new ExplorerWatcher(oApp); } catch (System.Runtime.InteropServices.COMException ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x84120009") { //Cannot complete the operation. You are not connected. [Issue #514, occurs on GetNamespace("mapi")] + if (ex.GetErrorCode() == "0x84120009") { //Cannot complete the operation. You are not connected. [Issue #514, occurs on GetNamespace("mapi")] log.Warn(ex.Message); throw new ApplicationException("A problem was encountered with your Office install.\r\n" + "Please perform an Office Repair or reinstall Outlook and then try running OGCS again."); @@ -224,7 +224,7 @@ public NameSpace GetCurrentUser(NameSpace oNS) { Outlook.Calendar.OOMsecurityInfo = true; } } catch (System.Exception ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x80004004") { //Access blocked + if (ex.GetErrorCode() == "0x80004004") { //Access blocked if (profile.OutlookGalBlocked) { //Fail fast log.Debug("Corporate policy is still blocking access to GAL."); return oNS; @@ -248,9 +248,9 @@ public NameSpace GetCurrentUser(NameSpace oNS) { delay = maxDelay; } catch (System.Exception ex2) { if (delay == maxDelay) { - if (Ogcs.Exception.GetErrorCode(ex2) == "0x80004004") { //E_ABORT + if (ex2.GetErrorCode() == "0x80004004") { //E_ABORT log.Warn("Corporate policy or possibly anti-virus is blocking access to GAL."); - } else Ogcs.Exception.Analyse(ex2); + } else ex2.Analyse(); log.Warn("OGCS is unable to obtain CurrentUser from Outlook."); profile.OutlookGalBlocked = true; return oNS; @@ -272,7 +272,7 @@ public NameSpace GetCurrentUser(NameSpace oNS) { currentUserName = currentUser.Name; } catch (System.Exception ex) { log.Warn("OGCS is unable to interogate CurrentUser from Outlook."); - if (Ogcs.Exception.GetErrorCode(ex) == "0x80004004") { //E_ABORT + if (ex.GetErrorCode() == "0x80004004") { //E_ABORT log.Warn("Corporate policy or possibly anti-virus is blocking access to GAL."); } else Ogcs.Exception.Analyse(Ogcs.Exception.LogAsFail(ex)); profile.OutlookGalBlocked = true; @@ -335,7 +335,7 @@ private MAPIFolder getCalendarStore(NameSpace oNS) { object bin = pa.GetProperty(PR_IPM_WASTEBASKET_ENTRYID); excludeDeletedFolder = pa.BinaryToString(bin); //EntryID } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not access 'Deleted Items' folder property.", Ogcs.Exception.LogAsFail(ex)); + ex.LogAsFail().Analyse("Could not access 'Deleted Items' folder property."); } Boolean updateGUI = profile.Equals(Forms.Main.Instance.ActiveCalendarProfile); if (updateGUI) { @@ -348,7 +348,7 @@ private MAPIFolder getCalendarStore(NameSpace oNS) { Forms.Main.Instance.lOutlookCalendar.Text = "Select calendar"; } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to find calendar folders in alternate mailbox '" + profile.MailboxName + "'.", ex, true); + ex.Analyse("Failed to find calendar folders in alternate mailbox '" + profile.MailboxName + "'.", true); if (!(Forms.Main.Instance.Visible && Forms.Main.Instance.ActiveControl.Name == "rbOutlookAltMB")) throw new System.Exception("Failed to access alternate mailbox calendar '" + profile.MailboxName + "'", ex); } finally { @@ -502,14 +502,14 @@ private void findCalendars(Folders folders, Dictionary calen } } catch (System.Exception ex) { if (oApp?.Session.ExchangeConnectionMode.ToString().Contains("Disconnected") ?? false || - Ogcs.Exception.GetErrorCode(ex) == "0xC204011D" || ex.Message.StartsWith("Network problems are preventing connection to Microsoft Exchange.") || - Ogcs.Exception.GetErrorCode(ex, 0x000FFFFF) == "0x00040115") { + ex.GetErrorCode() == "0xC204011D" || ex.Message.StartsWith("Network problems are preventing connection to Microsoft Exchange.") || + ex.GetErrorCode(0x000FFFFF) == "0x00040115") { log.Warn(ex.Message); log.Info("Currently disconnected from Exchange - unable to retrieve MAPI folders."); Forms.Main.Instance.ToolTips.SetToolTip(Forms.Main.Instance.cbOutlookCalendars, "The Outlook calendar to synchonize with.\nSome may not be listed as you are currently disconnected."); } else { - Ogcs.Exception.Analyse("Failed to recurse MAPI folders.", ex); + ex.Analyse("Failed to recurse MAPI folders."); Ogcs.Extensions.MessageBox.Show("A problem was encountered when searching for Outlook calendar folders.\r\n" + ex.Message, "Calendar Folders", MessageBoxButtons.OK, MessageBoxIcon.Warning); } @@ -531,7 +531,7 @@ private void calendarFolderAdd(String name, MAPIFolder folder, MAPIFolder parent try { calendarFolders.Add(name, folder); } catch (System.ArgumentException ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x80070057") { + if (ex.GetErrorCode() == "0x80070057") { //An item with the same key has already been added. //Let's recurse up to the parent folder, looking to make it unique object parentObj = (parentFolder != null ? parentFolder.Parent : folder.Parent); @@ -611,7 +611,7 @@ public String GetRecipientEmail(Recipient recipient) { try { retEmail = eu.PrimarySmtpAddress; } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not access Exchange users's primary SMTP.", Ogcs.Exception.LogAsFail(ex)); + ex.LogAsFail().Analyse("Could not access Exchange users's primary SMTP."); } } if (eu == null || string.IsNullOrEmpty(retEmail)) { diff --git a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs index 75d197d7..5d11492e 100644 --- a/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs +++ b/src/OutlookGoogleCalendarSync/Outlook.Factory/OutlookOld.cs @@ -225,7 +225,7 @@ public NameSpace GetCurrentUser(NameSpace oNS) { } catch (System.Exception ex2) { if (delay == maxDelay) { log.Warn("OGCS is unable to obtain CurrentUser from Outlook."); - if (Ogcs.Exception.GetErrorCode(ex2) == "0x80004004") { //E_ABORT + if (ex2.GetErrorCode() == "0x80004004") { //E_ABORT log.Warn("Corporate policy or possibly anti-virus is blocking access to GAL."); } else Ogcs.Exception.Analyse(Ogcs.Exception.LogAsFail(ex2)); profile.OutlookGalBlocked = true; @@ -344,14 +344,14 @@ private void findCalendars(Folders folders, Dictionary calen } } catch (System.Exception ex) { if (oApp.Session.ExchangeConnectionMode.ToString().Contains("Disconnected") || - Ogcs.Exception.GetErrorCode(ex) == "0xC204011D" || ex.Message.StartsWith("Network problems are preventing connection to Microsoft Exchange.") || - Ogcs.Exception.GetErrorCode(ex, 0x000FFFFF) == "0x00040115") { + ex.GetErrorCode() == "0xC204011D" || ex.Message.StartsWith("Network problems are preventing connection to Microsoft Exchange.") || + ex.GetErrorCode(0x000FFFFF) == "0x00040115") { log.Warn(ex.Message); log.Info("Currently disconnected from Exchange - unable to retrieve MAPI folders."); Forms.Main.Instance.ToolTips.SetToolTip(Forms.Main.Instance.cbOutlookCalendars, "The Outlook calendar to synchonize with.\nSome may not be listed as you are currently disconnected."); } else { - Ogcs.Exception.Analyse("Failed to recurse MAPI folders.", ex); + ex.Analyse("Failed to recurse MAPI folders."); Ogcs.Extensions.MessageBox.Show("A problem was encountered when searching for Outlook calendar folders.\r\n" + ex.Message, "Calendar Folders", MessageBoxButtons.OK, MessageBoxIcon.Warning); } @@ -373,7 +373,7 @@ private void calendarFolderAdd(String name, MAPIFolder folder, MAPIFolder parent try { calendarFolders.Add(name, folder); } catch (System.ArgumentException ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x80070057") { + if (ex.GetErrorCode() == "0x80070057") { //An item with the same key has already been added. //Let's recurse up to the parent folder, looking to make it unique object parentObj = (parentFolder != null ? parentFolder.Parent : folder.Parent); @@ -408,7 +408,7 @@ public List FilterItems(Items outlookItems, String filter) { } log.Info(o2003recurring.Count + " recurring items successfully kept for Outlook 2003."); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Unable to iterate Outlook items.", ex); + ex.Analyse("Unable to iterate Outlook items."); } restrictedItems.AddRange(o2003recurring); diff --git a/src/OutlookGoogleCalendarSync/Outlook/CustomProperty.cs b/src/OutlookGoogleCalendarSync/Outlook/CustomProperty.cs index eb6ff534..87992ded 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/CustomProperty.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/CustomProperty.cs @@ -461,7 +461,7 @@ public static void LogProperties(AppointmentItem ai, log4net.Core.Level threshol } } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to log Appointment UserProperties", ex); + ex.Analyse("Failed to log Appointment UserProperties"); } finally { ups = (UserProperties)Calendar.ReleaseObject(ups); } @@ -476,7 +476,7 @@ public static OlBodyFormat BodyFormat(this AppointmentItem ai) { try { format = (OlBodyFormat)ai.GetType().InvokeMember("BodyFormat", System.Reflection.BindingFlags.GetProperty, null, ai, null); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Unable to determine AppointmentItem body format.", ex); + ex.Analyse("Unable to determine AppointmentItem body format."); } return format; } diff --git a/src/OutlookGoogleCalendarSync/Outlook/ExplorerWatcher.cs b/src/OutlookGoogleCalendarSync/Outlook/ExplorerWatcher.cs index 8bc5b301..eab8d0d7 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/ExplorerWatcher.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/ExplorerWatcher.cs @@ -172,13 +172,13 @@ private void repopulateIDs(String entryID, Dictionary propertyVa } catch (System.Exception ex) { if (ex is System.Runtime.InteropServices.COMException && ( - Ogcs.Exception.GetErrorCode(ex) == "0x8004010F" || //The message you specified cannot be found - Ogcs.Exception.GetErrorCode(ex) == "0x8004010A")) //The operation cannot be performed because the object has been deleted + ex.GetErrorCode() == "0x8004010F" || //The message you specified cannot be found + ex.GetErrorCode() == "0x8004010A")) //The operation cannot be performed because the object has been deleted { log.Warn("Could not find Outlook item with entryID " + entryID + " for post-processing."); Ogcs.Exception.LogAsFail(ref ex); } - Ogcs.Exception.Analyse("Failed to repopulate OGCS properties back to copied item.", ex); + ex.Analyse("Failed to repopulate OGCS properties back to copied item."); } finally { copiedAi = (AppointmentItem)Calendar.ReleaseObject(copiedAi); } @@ -248,13 +248,13 @@ private void untagAsCopied(String entryID) { } catch (System.Exception ex) { if (ex is System.Runtime.InteropServices.COMException && ( - Ogcs.Exception.GetErrorCode(ex) == "0x8004010F" || //The message you specified cannot be found - Ogcs.Exception.GetErrorCode(ex) == "0x8004010A")) //The operation cannot be performed because the object has been deleted + ex.GetErrorCode() == "0x8004010F" || //The message you specified cannot be found + ex.GetErrorCode() == "0x8004010A")) //The operation cannot be performed because the object has been deleted { log.Warn("Could not find Outlook item with entryID " + entryID + " for post-processing."); Ogcs.Exception.LogAsFail(ref ex); } - Ogcs.Exception.Analyse("Failed to remove OGCS 'copied' property on copied item.", ex); + ex.Analyse("Failed to remove OGCS 'copied' property on copied item."); } finally { copiedAi = (AppointmentItem)Calendar.ReleaseObject(copiedAi); } diff --git a/src/OutlookGoogleCalendarSync/Outlook/GMeet.cs b/src/OutlookGoogleCalendarSync/Outlook/GMeet.cs index 91a3e5ad..ea3b3b67 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/GMeet.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/GMeet.cs @@ -1,6 +1,6 @@ -using Ogcs = OutlookGoogleCalendarSync; -using log4net; +using log4net; using Microsoft.Office.Interop.Outlook; +using OutlookGoogleCalendarSync.Extensions; using System; using System.Linq; using System.Text.RegularExpressions; @@ -17,8 +17,8 @@ public GMeetLogo() { GMeetLogoBase64 = base64encode(Properties.Resources.gmeet_logo); } - public String GMeetLogoBase64 { - get; internal set; + public String GMeetLogoBase64 { + get; internal set; } private String base64encode(System.Drawing.Image img) { @@ -31,7 +31,7 @@ private String base64encode(System.Drawing.Image img) { return Convert.ToBase64String(imgBytes); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not load GMeet logo.", ex); + ex.Analyse("Could not load GMeet logo."); return ""; } } diff --git a/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs b/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs index eb0f6b28..b4fee95a 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/OutlookCalendar.cs @@ -87,7 +87,7 @@ public static void Disconnect(Boolean onlyWhenNoGUI = false) { InstanceConnect = false; Instance.IOutlook.Disconnect(onlyWhenNoGUI); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not disconnect from Outlook.", Ogcs.Exception.LogAsFail(ex)); + ex.LogAsFail().Analyse("Could not disconnect from Outlook."); } finally { GC.Collect(); GC.WaitForPendingFinalizers(); @@ -111,11 +111,11 @@ public List GetCalendarEntriesInRange(SettingsStore.Calendar pr throw; } } catch (System.Runtime.InteropServices.COMException ex) { - if (Ogcs.Exception.GetErrorCode(ex, 0x0000FFFF) == "0x00004005" && ex.TargetSite.Name == "get_LastModificationTime") { //You must specify a time. + if (ex.GetErrorCode(0x0000FFFF) == "0x00004005" && ex.TargetSite.Name == "get_LastModificationTime") { //You must specify a time. Ogcs.Exception.LogAsFail(ref ex); ex.Data.Add("OGCS", "Corrupted item(s) with no start/end date exist in your Outlook calendar that need fixing or removing before a sync can run.
" + "Switch the calendar folder to List View, sort by date and look for entries with no start and/or end date."); - } else if (Ogcs.Exception.GetErrorCode(ex, 0x000FFFFF) == "0x00020009" && ex.TargetSite.Name == "get_Categories") { //One or more items in the folder you synchronized do not match. + } else if (ex.GetErrorCode(0x000FFFFF) == "0x00020009" && ex.TargetSite.Name == "get_Categories") { //One or more items in the folder you synchronized do not match. Ogcs.Exception.LogAsFail(ref ex); String wikiURL = "https://github.com/phw198/OutlookGoogleCalendarSync/wiki/Resolving-Outlook-Error-Messages#one-or-more-items-in-the-folder-you-synchronized-do-not-match"; ex.Data.Add("OGCS", ex.Message + "
Please view the wiki for suggestions on " + @@ -127,7 +127,7 @@ public List GetCalendarEntriesInRange(SettingsStore.Calendar pr throw; } catch (System.ArgumentNullException ex) { - Ogcs.Exception.Analyse("It seems that Outlook has just been closed.", Ogcs.Exception.LogAsFail(ex)); + ex.LogAsFail().Analyse("It seems that Outlook has just been closed."); Outlook.Calendar.Instance.Reset(); filtered = FilterCalendarEntries(profile, suppressAdvisories: suppressAdvisories); @@ -389,7 +389,7 @@ private void createCalendarEntry(Event ev, ref AppointmentItem ai) { EventReminder reminder = ev.Reminders.Overrides.Where(r => r.Method == "popup").OrderBy(x => x.Minutes).First(); ai.ReminderMinutesBeforeStart = (int)reminder.Minutes; } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed setting Outlook reminder for final popup Google notification.", ex); + ex.Analyse("Failed setting Outlook reminder for final popup Google notification."); } } else if ((ev.Reminders?.UseDefault ?? false) && Ogcs.Google.Calendar.Instance.MinDefaultReminder != int.MinValue) { ai.ReminderSet = true; @@ -770,7 +770,7 @@ public Boolean UpdateCalendarEntry(ref AppointmentItem ai, Event ev, ref int ite itemModified++; } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed setting Outlook reminder for final popup Google notification.", ex); + ex.Analyse("Failed setting Outlook reminder for final popup Google notification."); } } @@ -1023,7 +1023,7 @@ private OlBusyStatus getAvailability(String gTransparency, OlBusyStatus? oBusySt try { Enum.TryParse(profile.AvailabilityStatus, out overrideFbStatus); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not convert string '" + profile.AvailabilityStatus + "' to OlBusyStatus type. Defaulting override to available.", ex); + ex.Analyse("Could not convert string '" + profile.AvailabilityStatus + "' to OlBusyStatus type. Defaulting override to available."); } if (profile.SyncDirection.Id != Sync.Direction.Bidirectional.Id) { @@ -1198,18 +1198,18 @@ public static void PoorlyOfficeInstall(System.Exception caughtException) { log.Warn(ex.Message); throw new ApplicationException("Outlook is busy.", ex); - } else if (Ogcs.Exception.GetErrorCode(ex, 0x000FFFFF) == "0x00040115") { + } else if (ex.GetErrorCode(0x000FFFFF) == "0x00040115") { log.Warn(ex.Message); log.Debug("OGCS is not able to run as Outlook is not properly connected to the Exchange server?"); throw new ApplicationException("Outlook is busy.", ex); - } else if (Ogcs.Exception.GetErrorCode(ex, 0x000FFFFF) == "0x000702E4") { + } else if (ex.GetErrorCode(0x000FFFFF) == "0x000702E4") { log.Warn(ex.Message); throw new ApplicationException("Outlook and OGCS are running in different security elevations.\n" + "Both must be running in Standard or Administrator mode."); } else if (!comErrorInWiki(ex)) { - Ogcs.Exception.Analyse("COM error not in wiki.", ex); + ex.Analyse("COM error not in wiki."); if (!alreadyRedirectedToWikiForComError.Contains(hResult)) { Helper.OpenBrowser("https://github.com/phw198/OutlookGoogleCalendarSync/wiki/FAQs---COM-Errors"); alreadyRedirectedToWikiForComError.Add(hResult); @@ -1222,14 +1222,14 @@ public static void PoorlyOfficeInstall(System.Exception caughtException) { if (!comErrorInWiki(ex)) throw; } catch (System.UnauthorizedAccessException ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x80070005") { // E_ACCESSDENIED + if (ex.GetErrorCode() == "0x80070005") { // E_ACCESSDENIED log.Warn(ex.Message); throw new ApplicationException("OGCS was not permitted to start Outlook.\r\n" + "Please manually start Outlook and then restart OGCS again."); } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Early binding to Outlook appears to have failed.", ex, true); + ex.Analyse("Early binding to Outlook appears to have failed.", true); log.Debug("Could try late binding??"); //System.Type oAppType = System.Type.GetTypeFromProgID("Outlook.Application"); //ApplicationClass oAppClass = System.Activator.CreateInstance(oAppType) as ApplicationClass; @@ -1239,7 +1239,7 @@ public static void PoorlyOfficeInstall(System.Exception caughtException) { } private static Boolean comErrorInWiki(System.Exception ex) { - String hResult = Ogcs.Exception.GetErrorCode(ex); + String hResult = ex.GetErrorCode(); String wikiUrl = ""; Regex rgx; @@ -1261,7 +1261,7 @@ private static Boolean comErrorInWiki(System.Exception ex) { hResult = matches[0].Groups[1].Value; } } catch (System.Exception ex2) { - Ogcs.Exception.Analyse("Parsing error message with regex failed.", ex2); + ex2.Analyse("Parsing error message with regex failed."); } } @@ -1286,7 +1286,7 @@ private static Boolean comErrorInWiki(System.Exception ex) { } } catch (System.Exception htmlEx) { - Ogcs.Exception.Analyse("Could not parse Wiki for existance of COM error.", htmlEx); + htmlEx.Analyse("Could not parse Wiki for existance of COM error."); } } @@ -1341,7 +1341,7 @@ public static void ExportToCSV(String action, String filename, List" : ""); } catch (System.Runtime.InteropServices.COMException ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x8004010F") + if (ex.GetErrorCode() == "0x8004010F") throw new System.Exception("Cannot access Outlook OST/PST file. Try restarting Outlook.", ex); else - Ogcs.Exception.Analyse("Failed to get appointment summary: " + eventSummary, ex, true); + ex.Analyse("Failed to get appointment summary: " + eventSummary, true); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to get appointment summary: " + eventSummary, ex, true); + ex.Analyse("Failed to get appointment summary: " + eventSummary, true); } } return eventSummary; @@ -1681,5 +1681,5 @@ private Boolean isOKtoSyncReminder(System.DateTime alarm) { } } #endregion - } } +} diff --git a/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs b/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs index 21181d36..c15bdc51 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/OutlookCategories.cs @@ -75,7 +75,7 @@ public static Color RgbColour(String hexColour) { colour = ColorTranslator.FromHtml(hexColour); log.Fine("Converted '" + hexColour + "' to " + colour.ToString()); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not convert hex '" + hexColour + "' to RGB colour.", ex); + ex.Analyse("Could not convert hex '" + hexColour + "' to RGB colour."); } return colour; } @@ -203,7 +203,7 @@ public void ValidateCategories() { try { if (this._categories != null && this._categories.Count > 0) { } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Categories are not accessible!", Ogcs.Exception.LogAsFail(ex)); + ex.LogAsFail().Analyse("Categories are not accessible!"); this._categories = null; } if (this._categories == null || Calendar.Categories == null) { @@ -216,11 +216,11 @@ public void ValidateCategories() { OutlookCOM.OlCategoryColor catColour = cat.Color; } } catch (System.Exception ex) { - if (Ogcs.Exception.GetErrorCode(ex, 0x0000FFFF) == "0x00004005" && ex.TargetSite.Name == "get_Color") { + if (ex.GetErrorCode(0x0000FFFF) == "0x00004005" && ex.TargetSite.Name == "get_Color") { log.Warn("Outlook category '" + catName + "' seems to have changed!"); Calendar.Instance.IOutlook.RefreshCategories(); } else { - Ogcs.Exception.Analyse("Could not access all the Outlook categories.", ex); + ex.Analyse("Could not access all the Outlook categories."); this.categories = null; return; } @@ -278,7 +278,7 @@ public String FindName(OutlookCOM.OlCategoryColor? olCategory, String categoryNa } } } catch (System.Runtime.InteropServices.COMException ex) { - if (Ogcs.Exception.GetErrorCode(ex, 0x0000FFFF) == "0x00004005") { //The operation failed. + if (ex.GetErrorCode(0x0000FFFF) == "0x00004005") { //The operation failed. log.Warn("It seems a category has been manually removed in Outlook."); Calendar.Instance.IOutlook.RefreshCategories(); } else throw; diff --git a/src/OutlookGoogleCalendarSync/Outlook/OutlookErrors.cs b/src/OutlookGoogleCalendarSync/Outlook/OutlookErrors.cs index 5dce6bd9..965c1788 100644 --- a/src/OutlookGoogleCalendarSync/Outlook/OutlookErrors.cs +++ b/src/OutlookGoogleCalendarSync/Outlook/OutlookErrors.cs @@ -26,7 +26,7 @@ public static ErrorType HandleComError(System.Exception ex) { public static ErrorType HandleComError(System.Exception ex, out String hResult) { ErrorType retVal = ErrorType.Unhandled; try { - hResult = Ogcs.Exception.GetErrorCode(ex); + hResult = ex.GetErrorCode(); log.Warn($"[{hResult}] >> {ex.Message}"); if (hResult == "0x800401E3" && ex.Message.Contains("MK_E_UNAVAILABLE")) { diff --git a/src/OutlookGoogleCalendarSync/Program.cs b/src/OutlookGoogleCalendarSync/Program.cs index 84653328..f1ee3ba1 100644 --- a/src/OutlookGoogleCalendarSync/Program.cs +++ b/src/OutlookGoogleCalendarSync/Program.cs @@ -267,7 +267,7 @@ private static void purgeLogFiles(Int16 retention) { System.IO.File.Delete(file); log.Debug("Deleted " + MaskFilePath(file)); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not delete file " + file, Ogcs.Exception.LogAsFail(ex)); + ex.LogAsFail().Analyse("Could not delete file " + file); } } } @@ -499,7 +499,7 @@ private static void isNewVersion(Boolean isSquirrelInstall) { Program.ManageStartupRegKey(); } catch (System.Exception ex) { if (ex is System.Security.SecurityException) Ogcs.Exception.LogAsFail(ref ex); //User doesn't have rights to access registry - Ogcs.Exception.Analyse("Failed accessing registry for startup key.", ex); + ex.Analyse("Failed accessing registry for startup key."); } Settings.Instance.Version = Application.ProductVersion; if (isHotFix) { @@ -622,7 +622,7 @@ public static string MaskFilePath(String path) { } else return path; } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Problems accessing environment variables.", ex); + ex.Analyse("Problems accessing environment variables."); return path; } } @@ -693,7 +693,7 @@ private static void instancesRunning() { } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Unable to check for concurrent OGCS processes.", ex); + ex.Analyse("Unable to check for concurrent OGCS processes."); } } diff --git a/src/OutlookGoogleCalendarSync/Recurrence.cs b/src/OutlookGoogleCalendarSync/Recurrence.cs index 68d14da1..387f8b02 100644 --- a/src/OutlookGoogleCalendarSync/Recurrence.cs +++ b/src/OutlookGoogleCalendarSync/Recurrence.cs @@ -544,7 +544,7 @@ public Event GetGoogleMasterEvent(AppointmentItem ai) { try { Ogcs.Google.Calendar.Instance.UpdateCalendarEntry_save(ref ev); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed saving Outlook IDs to Google Event.", ex, true); + ex.Analyse("Failed saving Outlook IDs to Google Event.", true); } return ev; } @@ -624,7 +624,7 @@ public static void CreateGoogleExceptions(AppointmentItem ai, String recurringEv } } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not check if there are other exceptions with the same original start date.", ex); + ex.Analyse("Could not check if there are other exceptions with the same original start date."); } } if (!skipDelete) { @@ -751,7 +751,7 @@ public static void UpdateGoogleExceptions(AppointmentItem ai, Event ev, Boolean log.Debug("Doing a dummy update in order to update the last modified date of Google recurring series exception."); Ogcs.Google.Calendar.Instance.UpdateCalendarEntry_save(ref gExcp); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Dummy update of unchanged exception for Google recurring series failed.", ex); + ex.Analyse("Dummy update of unchanged exception for Google recurring series failed."); } continue; } @@ -815,9 +815,9 @@ private static DeletionState exceptionIsDeleted(Microsoft.Office.Interop.Outlook Ogcs.Exception.LogAsFail(ref ex); String originalDate = oExcp.OriginalDate.ToString("dd/MM/yyyy"); 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.") { - Ogcs.Exception.Analyse("This Outlook recurrence instance on " + originalDate + " has become inaccessible, probably due to caching", ex); + ex.Analyse("This Outlook recurrence instance on " + originalDate + " has become inaccessible, probably due to caching"); } else { - Ogcs.Exception.Analyse("Error when determining if Outlook recurrence on " + originalDate + " is deleted or not.", ex); + ex.Analyse("Error when determining if Outlook recurrence on " + originalDate + " is deleted or not."); } return DeletionState.Inaccessible; } finally { diff --git a/src/OutlookGoogleCalendarSync/SettingsStore/Proxy.cs b/src/OutlookGoogleCalendarSync/SettingsStore/Proxy.cs index 0f928bf5..24d942bf 100644 --- a/src/OutlookGoogleCalendarSync/SettingsStore/Proxy.cs +++ b/src/OutlookGoogleCalendarSync/SettingsStore/Proxy.cs @@ -112,17 +112,17 @@ public void Configure() { sr = new System.IO.StreamReader(stream); log.Fail(sr.ReadToEnd()); } catch (System.Exception ex2) { - Ogcs.Exception.Analyse("Could not analyse WebException response.", ex2); + ex2.Analyse("Could not analyse WebException response."); } finally { if (sr != null) sr.Close(); if (stream != null) stream.Close(); } } else - Ogcs.Exception.Analyse("Testing proxy connection failed.", ex); + ex.Analyse("Testing proxy connection failed."); } } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to confirm proxy settings.", ex); + ex.Analyse("Failed to confirm proxy settings."); } } } diff --git a/src/OutlookGoogleCalendarSync/SettingsStore/Upgrade.cs b/src/OutlookGoogleCalendarSync/SettingsStore/Upgrade.cs index 51aa34bf..d5f43be7 100644 --- a/src/OutlookGoogleCalendarSync/SettingsStore/Upgrade.cs +++ b/src/OutlookGoogleCalendarSync/SettingsStore/Upgrade.cs @@ -52,11 +52,11 @@ private static void backupSettingsFile() { File.Copy(Settings.ConfigFile, backupFile, false); log.Info(backupFile + " created."); } catch (System.IO.IOException ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x80070050") { //File already exists + if (ex.GetErrorCode() == "0x80070050") { //File already exists log.Warn("The backfile already exists, not overwriting " + backupFile); } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to create backup settings file", ex); + ex.Analyse("Failed to create backup settings file"); } } @@ -127,7 +127,7 @@ private static void upgradeToMultiCalendar() { XMLManager.MoveElement("LastSyncDate", settingsElement, calendarElement); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Problem encountered whilst upgrading " + Settings.ConfigFilename, ex); + ex.Analyse("Problem encountered whilst upgrading " + Settings.ConfigFilename); throw ex; } finally { if (xml != null) { @@ -143,11 +143,11 @@ private static void upgradeToMultiCalendar() { "Settings Cannot Be Saved", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation) == DialogResult.Cancel) { log.Warn("User cancelled attempt to save new settings file."); - Ogcs.Exception.Analyse("Could not save upgraded settings file " + Settings.ConfigFile, ex); + ex.Analyse("Could not save upgraded settings file " + Settings.ConfigFile); throw; } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not save upgraded settings file " + Settings.ConfigFile, ex); + ex.Analyse("Could not save upgraded settings file " + Settings.ConfigFile); throw; } } diff --git a/src/OutlookGoogleCalendarSync/Sync/Calendar.cs b/src/OutlookGoogleCalendarSync/Sync/Calendar.cs index b29860d4..862945cd 100644 --- a/src/OutlookGoogleCalendarSync/Sync/Calendar.cs +++ b/src/OutlookGoogleCalendarSync/Sync/Calendar.cs @@ -136,7 +136,7 @@ public void StartSync(Boolean manualIgnition, Boolean updateSyncSchedule = true) sb = new StringBuilder(); mainFrm.Console.BuildOutput("The following error was encountered during sync:-", ref sb); mainFrm.Console.BuildOutput(ex.Data["OGCS"].ToString(), ref sb); - mainFrm.Console.Update(sb, (Ogcs.Exception.LoggingAsFail(ex) ? Console.Markup.fail : Console.Markup.error), notifyBubble: true); + mainFrm.Console.Update(sb, (ex.LoggingAsFail() ? Console.Markup.fail : Console.Markup.error), notifyBubble: true); if (ex.Data["OGCS"].ToString().Contains("try again")) { syncResult = Sync.Engine.SyncResult.AutoRetry; } @@ -313,12 +313,12 @@ private SyncResult synchronize() { Ogcs.Google.Calendar.Instance.GetSettings(); googleEntries = Ogcs.Google.Calendar.Instance.GetCalendarEntriesInRange(); } catch (AggregateException agex) { - Ogcs.Exception.AnalyseAggregate(agex); + agex.AnalyseAggregate(); } catch (global::Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { - Ogcs.Exception.AnalyseTokenResponse(ex, false); + ex.AnalyseTokenResponse(false); return SyncResult.Fail; } catch (System.Net.Http.HttpRequestException ex) { - if (ex.InnerException != null && ex.InnerException is System.Net.WebException && Ogcs.Exception.GetErrorCode(ex.InnerException) == "0x80131509") { + if (ex.InnerException != null && ex.InnerException is System.Net.WebException && ex.InnerException.GetErrorCode() == "0x80131509") { ex = Ogcs.Exception.LogAsFail(ex) as System.Net.Http.HttpRequestException; } Ogcs.Exception.Analyse(ex); @@ -326,7 +326,7 @@ private SyncResult synchronize() { throw; } catch (System.ApplicationException ex) { if (ex.InnerException != null && ex.InnerException is global::Google.GoogleApiException && - (ex.Message.Contains("daily Calendar quota has been exhausted") || Ogcs.Exception.GetErrorCode(ex.InnerException) == "0x80131500")) { + (ex.Message.Contains("daily Calendar quota has been exhausted") || ex.InnerException.GetErrorCode() == "0x80131500")) { Forms.Main.Instance.Console.Update(ex.Message, Console.Markup.warning); DateTime newQuota = DateTime.UtcNow.Date.AddHours(8); String tryAfter = "08:00 GMT."; @@ -345,7 +345,7 @@ private SyncResult synchronize() { } catch (System.Exception ex) { Ogcs.Exception.Analyse(ex); ex.Data.Add("OGCS", "ERROR: Unable to connect to the Google calendar."); - if (Ogcs.Exception.GetErrorCode(ex) == "0x8013153B") //ex.Message == "A task was canceled." - likely timed out. + if (ex.GetErrorCode() == "0x8013153B") //ex.Message == "A task was canceled." - likely timed out. ex.Data["OGCS"] += " Please try again."; throw; } @@ -381,8 +381,8 @@ private SyncResult synchronize() { continue; } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Encountered error casting calendar object to AppointmentItem - cannot sync it. ExchangeMode=" + - Outlook.Calendar.Instance.IOutlook.ExchangeConnectionMode().ToString(), ex); + ex.Analyse("Encountered error casting calendar object to AppointmentItem - cannot sync it. ExchangeMode=" + + Outlook.Calendar.Instance.IOutlook.ExchangeConnectionMode().ToString()); skipCorruptedItem(ref outlookEntries, outlookEntries[o], ex.Message); ai = (AppointmentItem)Outlook.Calendar.ReleaseObject(ai); continue; @@ -397,17 +397,17 @@ private SyncResult synchronize() { checkStartDate = ai.Start; checkEndDate = ai.End; } catch (System.Runtime.InteropServices.COMException ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x80040305" || //Your server administrator has limited the number of items you can open simultaneously. + if (ex.GetErrorCode() == "0x80040305" || //Your server administrator has limited the number of items you can open simultaneously. Ogcs.Exception.GetErrorCode(ex, 0x000FFFFF) == "0x00040115") //Network problems are preventing connection to Microsoft Exchange. { Forms.Main.Instance.Console.UpdateWithError("Cannot continue synchronising.", ex); return SyncResult.AutoRetry; - } else if (Ogcs.Exception.GetErrorCode(ex, 0x0000FFFF) == "0x00004005") { //You must specify a time/hour + } else if (ex.GetErrorCode(0x0000FFFF) == "0x00004005") { //You must specify a time/hour skipCorruptedItem(ref outlookEntries, outlookEntries[o], ex.Message); } else { log.Debug($"EntryID: {entryID}; Start: {checkStartDate}; End: {checkEndDate}"); - Ogcs.Exception.Analyse("Calendar item does not have a proper date range - cannot sync it. ExchangeMode=" + - Outlook.Calendar.Instance.IOutlook.ExchangeConnectionMode().ToString(), ex); + ex.Analyse("Calendar item does not have a proper date range - cannot sync it. ExchangeMode=" + + Outlook.Calendar.Instance.IOutlook.ExchangeConnectionMode().ToString()); skipCorruptedItem(ref outlookEntries, outlookEntries[o], ex.Message); } ai = (AppointmentItem)Outlook.Calendar.ReleaseObject(ai); @@ -456,7 +456,7 @@ private SyncResult synchronize() { } } } catch (System.Exception ex) { - console.Update("Failed to retrieve master for Google recurring event outside of sync range.", Ogcs.Exception.LoggingAsFail(ex) ? Console.Markup.fail : Console.Markup.error); + console.Update("Failed to retrieve master for Google recurring event outside of sync range.", ex.LoggingAsFail() ? Console.Markup.fail : Console.Markup.error); throw; } finally { oPattern = (RecurrencePattern)Outlook.Calendar.ReleaseObject(oPattern); @@ -803,7 +803,7 @@ private SyncResult extirpateCustomProperties(List outlookEntrie return returnVal; } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to fully cleanse metadata!", ex); + ex.Analyse("Failed to fully cleanse metadata!"); console.UpdateWithError(null, ex); returnVal = SyncResult.Fail; return returnVal; diff --git a/src/OutlookGoogleCalendarSync/Sync/Engine.cs b/src/OutlookGoogleCalendarSync/Sync/Engine.cs index d90ca83c..7ad39638 100644 --- a/src/OutlookGoogleCalendarSync/Sync/Engine.cs +++ b/src/OutlookGoogleCalendarSync/Sync/Engine.cs @@ -62,7 +62,7 @@ private void QueueTimer_Tick(object sender, EventArgs e) { Engine.Instance.ActiveProfile = job.Profile; Engine.Instance.Start(manualIgnition: false, updateSyncSchedule: (job.RequestedBy == "AutoSyncTimer")); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Scheduled sync encountered a problem.", ex, true); + ex.Analyse("Scheduled sync encountered a problem.", true); } } } diff --git a/src/OutlookGoogleCalendarSync/Sync/Timer.cs b/src/OutlookGoogleCalendarSync/Sync/Timer.cs index ead96778..8e354115 100644 --- a/src/OutlookGoogleCalendarSync/Sync/Timer.cs +++ b/src/OutlookGoogleCalendarSync/Sync/Timer.cs @@ -162,7 +162,7 @@ public void ResetLastRun() { log.Fine("Updating calendar item count following Push Sync."); this.lastRunItemCount = Outlook.Calendar.Instance.GetCalendarEntriesInRange(this.owningProfile as SettingsStore.Calendar, true).Count; } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to update item count following a Push Sync.", ex); + ex.Analyse("Failed to update item count following a Push Sync."); } } @@ -201,7 +201,7 @@ private void ogcsPushTimer_Tick(object sender, EventArgs e) { try { Outlook.Calendar.Instance.Reset(); } catch (System.Exception ex2) { - Ogcs.Exception.Analyse("Failed resetting Outlook connection.", ex2); + ex2.Analyse("Failed resetting Outlook connection."); } } else Ogcs.Exception.Analyse(ex); diff --git a/src/OutlookGoogleCalendarSync/Telemetry.cs b/src/OutlookGoogleCalendarSync/Telemetry.cs index ab7d5c94..f70b3c62 100644 --- a/src/OutlookGoogleCalendarSync/Telemetry.cs +++ b/src/OutlookGoogleCalendarSync/Telemetry.cs @@ -103,7 +103,7 @@ private async Task getIpGeoData() { } } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not get IP geolocation.", Ogcs.Exception.LogAsFail(ex)); + ex.LogAsFail().Analyse("Could not get IP geolocation."); } } diff --git a/src/OutlookGoogleCalendarSync/TimezoneDB.cs b/src/OutlookGoogleCalendarSync/TimezoneDB.cs index 051ba802..fbfc6277 100644 --- a/src/OutlookGoogleCalendarSync/TimezoneDB.cs +++ b/src/OutlookGoogleCalendarSync/TimezoneDB.cs @@ -97,7 +97,7 @@ private void checkForUpdate(String localVersion) { } } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not check for timezone data update.", ex); + ex.Analyse("Could not check for timezone data update."); } } @@ -122,7 +122,7 @@ public static String FixAlexa(String timezone) { return fixedTimezone; } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to detect and translate Alexa timezone: " + timezone, ex); + ex.Analyse("Failed to detect and translate Alexa timezone: " + timezone); } return timezone; } @@ -145,7 +145,7 @@ public static String FixAlexa(String timezone) { return gmtOffset; } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to detect any timezone offset for: " + outlookTimezone, ex); + ex.Analyse("Failed to detect any timezone offset for: " + outlookTimezone); } return null; } @@ -168,7 +168,7 @@ public static Int16 GetUtcOffset(String IanaTimezone) { utcOffset = Convert.ToInt16(offset.Seconds / 3600); } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Not able to convert IANA timezone '" + IanaTimezone + "' to UTC offset.", ex); + ex.Analyse("Not able to convert IANA timezone '" + IanaTimezone + "' to UTC offset."); } return utcOffset; } diff --git a/src/OutlookGoogleCalendarSync/Updater.cs b/src/OutlookGoogleCalendarSync/Updater.cs index 3fef4d4e..b926b56b 100644 --- a/src/OutlookGoogleCalendarSync/Updater.cs +++ b/src/OutlookGoogleCalendarSync/Updater.cs @@ -84,7 +84,7 @@ public static Boolean IsSquirrelInstall() { isSquirrelInstall = updateManager.IsInstalledApp; } } catch (System.Exception ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x80131500") //Update.exe not found + if (ex.GetErrorCode() == "0x80131500") //Update.exe not found log.Debug(ex.Message); else { log.Error("Failed to determine if app is a Squirrel install. Assuming not."); @@ -157,7 +157,7 @@ private async Task githubCheck() { } catch (System.Exception ex) { squirrelGaEv.AddParameter(GA4.Squirrel.result, "Failed"); squirrelGaEv.AddParameter(GA4.Squirrel.error, ex.Message); - Ogcs.Exception.Analyse("Failed downloading release file " + update.Filename + " for " + update.Version, ex); + ex.Analyse("Failed downloading release file " + update.Filename + " for " + update.Version); ex.Data.Add("analyticsLabel", "from=" + Application.ProductVersion + ";download_file=" + update.Filename + ";" + ex.Message); throw new ApplicationException("Failed upgrading OGCS.", ex); } finally { @@ -208,7 +208,7 @@ private async Task githubCheck() { break; } catch (System.AggregateException ex) { ApplyAttempt++; - if (Ogcs.Exception.GetErrorCode(ex.InnerException) == "0x80070057") { //File does not exist + if (ex.InnerException.GetErrorCode() == "0x80070057") { //File does not exist //File does not exist: C:\Users\Paul\AppData\Local\OutlookGoogleCalendarSync\packages\OutlookGoogleCalendarSync-2.8.4-alpha-full.nupkg //Extract the nupkg filename String regexMatch = ".*" + updates.PackageDirectory.Replace(@"\", @"\\") + @"\\(.*?([\d\.]+-\w+).*)$"; @@ -275,7 +275,7 @@ private async Task githubCheck() { throw; } } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed checking for update.", Ogcs.Exception.LogAsFail(ex), true); + ex.LogAsFail().Analyse("Failed checking for update.", true); Telemetry.GA4Event.Event githubGaEv = new(Telemetry.GA4Event.Event.Name.squirrel); githubGaEv.AddParameter(GA4.Squirrel.state, "GitHub check"); githubGaEv.AddParameter(GA4.Squirrel.result, "Failed"); @@ -416,7 +416,7 @@ private static String[] fixCliArgs() { } private static void clickOnceUninstallError(System.Exception ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x80131509") { + if (ex.GetErrorCode() == "0x80131509") { log.Debug("No ClickOnce install found."); } else { log.Error("Failed removing ClickOnce install."); @@ -447,12 +447,12 @@ private void checkForZip(object sender, DoWorkEventArgs e) { try { html = new Extensions.OgcsWebClient().DownloadString("https://raw.githubusercontent.com/phw198/OutlookGoogleCalendarSync/master/docs/latest_zip_release.md"); } catch (System.Net.WebException ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x80131509") + if (ex.GetErrorCode() == "0x80131509") log.Warn("Failed to retrieve data (no network?): " + ex.Message); else - Ogcs.Exception.Analyse("Failed to retrieve data", ex); + ex.Analyse("Failed to retrieve data"); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to retrieve data: ", ex); + ex.Analyse("Failed to retrieve data: "); } if (!string.IsNullOrEmpty(html)) { diff --git a/src/OutlookGoogleCalendarSync/XMLManager.cs b/src/OutlookGoogleCalendarSync/XMLManager.cs index 7bb4c8ca..25257667 100644 --- a/src/OutlookGoogleCalendarSync/XMLManager.cs +++ b/src/OutlookGoogleCalendarSync/XMLManager.cs @@ -60,7 +60,7 @@ public static string ImportElement(string nodeName, string filename, Boolean deb return xe.Value; } catch (System.InvalidOperationException ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x80131509") { //Sequence contains no elements + if (ex.GetErrorCode() == "0x80131509") { //Sequence contains no elements log.Warn("'" + nodeName + "' could not be found."); } else { log.Error("Failed retrieving '" + nodeName + "' from " + filename); @@ -69,7 +69,7 @@ public static string ImportElement(string nodeName, string filename, Boolean deb return null; } catch (System.IO.IOException ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x80070020") { //Setting file in use by another process + if (ex.GetErrorCode() == "0x80070020") { //Setting file in use by another process log.Warn("Failed retrieving '" + nodeName + "' from " + filename); log.Warn(ex.Message); } else { @@ -79,8 +79,8 @@ public static string ImportElement(string nodeName, string filename, Boolean deb return null; } catch (System.Xml.XmlException ex) { - log.Warn("Failed retrieving '" + nodeName + "' from " + filename); - if (Ogcs.Exception.GetErrorCode(ex) == "0x80131940") { //hexadecimal value 0x00, is an invalid character + log.Warn($"Failed retrieving '{nodeName}' from {filename}"); + if (ex.GetErrorCode() == "0x80131940") { //hexadecimal value 0x00, is an invalid character log.Warn(ex.Message); Settings.ResetFile(filename); try { @@ -88,10 +88,10 @@ public static string ImportElement(string nodeName, string filename, Boolean deb XElement settingsXE = xml.Descendants(ns + "Settings").FirstOrDefault(); XElement xe = settingsXE.Elements(ns + nodeName).First(); if (debugLog) - log.Debug("Retrieved setting '" + nodeName + "' with value '" + xe.Value + "'"); + log.Debug($"Retrieved setting '{nodeName}' with value '{xe.Value}'"); return xe.Value; } catch (System.Exception ex2) { - Ogcs.Exception.Analyse("Still failed to retrieve '" + nodeName + "' from " + filename, ex2); + ex2.Analyse($"Still failed to retrieve '{nodeName}' from {filename}"); return null; } } else { @@ -100,7 +100,7 @@ public static string ImportElement(string nodeName, string filename, Boolean deb } } catch (System.Exception ex) { - log.Error("Failed retrieving '" + nodeName + "' from " + filename); + log.Error($"Failed retrieving '{nodeName}' from {filename}"); Ogcs.Exception.Analyse(ex); return null; } @@ -111,7 +111,7 @@ public static void ExportElement(Object settingStore, String nodeName, object no try { xml = XDocument.Load(filename); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Failed to load " + filename, ex, true); + ex.Analyse("Failed to load " + filename, true); throw; } XElement settingsXE = null; @@ -119,7 +119,7 @@ public static void ExportElement(Object settingStore, String nodeName, object no settingsXE = xml.Descendants(ns + "Settings").FirstOrDefault(); } catch (System.Exception ex) { log.Debug(filename + " head: " + xml.ToString().Substring(0, Math.Min(200, xml.ToString().Length))); - Ogcs.Exception.Analyse("Could not access 'Settings' element.", ex, true); + ex.Analyse("Could not access 'Settings' element.", true); return; } XElement xe = null; @@ -148,7 +148,7 @@ public static void ExportElement(Object settingStore, String nodeName, object no xml.Save(filename); log.Debug("Setting '" + nodeName + "' updated to '" + nodeValue + "'"); } catch (System.Exception ex) { - if (Ogcs.Exception.GetErrorCode(ex) == "0x80131509") { //Sequence contains no elements + if (ex.GetErrorCode() == "0x80131509") { //Sequence contains no elements log.Debug("Adding Setting " + nodeName + " for " + settingStore.ToString() + " to " + filename); if (xeProfile != null) xeProfile.Add(new XElement(ns + nodeName, nodeValue)); @@ -157,7 +157,7 @@ public static void ExportElement(Object settingStore, String nodeName, object no xml.Root.Sort(); xml.Save(filename); } else { - Ogcs.Exception.Analyse("Failed to export setting " + nodeName + "=" + nodeValue + " for " + settingStore.ToString() + " to " + filename + " file.", ex); + ex.Analyse($"Failed to export setting {nodeName}={nodeValue} for {settingStore.ToString()} to {filename} file."); } } } @@ -225,7 +225,7 @@ public static void MoveElement(String nodeName, XElement parent, XElement target target.Add(sourceElement); removeElement(nodeName, parent); } catch (System.Exception ex) { - Ogcs.Exception.Analyse("Could not move '" + nodeName + "'", ex); + ex.Analyse($"Could not move '{nodeName}'"); } } } From 383f601aedab84cab1fd053481c1ed9a9fe9c496 Mon Sep 17 00:00:00 2001 From: Paul Woolcock <11843015+phw198@users.noreply.github.com> Date: Sun, 28 Apr 2024 15:06:55 +0100 Subject: [PATCH 7/8] Code refactor of String methods under OutlookGoogleCalendarSync.Extensions namespace --- src/OutlookGoogleCalendarSync/Extensions/String.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/OutlookGoogleCalendarSync/Extensions/String.cs b/src/OutlookGoogleCalendarSync/Extensions/String.cs index 48524796..907de23f 100644 --- a/src/OutlookGoogleCalendarSync/Extensions/String.cs +++ b/src/OutlookGoogleCalendarSync/Extensions/String.cs @@ -1,7 +1,7 @@ using System; -namespace OutlookGoogleCalendarSync { - public static class StringExtensions { +namespace OutlookGoogleCalendarSync.Extensions { + public static class OgcsString { public static String Append(this String input, String append) { return (String.IsNullOrEmpty(input) ? input : input + append); } From 1bfb06e625d591757df58c1c936c6b5734e02c9d Mon Sep 17 00:00:00 2001 From: Paul Woolcock <11843015+phw198@users.noreply.github.com> Date: Sun, 28 Apr 2024 15:59:44 +0100 Subject: [PATCH 8/8] Refactoring required from upcoming release v2.10.5 --- src/OutlookGoogleCalendarSync/Extensions/MessageBox.cs | 2 +- src/OutlookGoogleCalendarSync/Forms/MainForm.cs | 4 ++-- src/OutlookGoogleCalendarSync/Forms/UpdateInfo.cs | 2 +- src/OutlookGoogleCalendarSync/XMLManager.cs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/OutlookGoogleCalendarSync/Extensions/MessageBox.cs b/src/OutlookGoogleCalendarSync/Extensions/MessageBox.cs index f621c0e2..5b10ee3e 100644 --- a/src/OutlookGoogleCalendarSync/Extensions/MessageBox.cs +++ b/src/OutlookGoogleCalendarSync/Extensions/MessageBox.cs @@ -73,7 +73,7 @@ public static DialogResult Show(string text, string caption, MessageBoxButtons b log.Debug(caption + ": " + (logText ?? text)); if (mainFrm == null || mainFrm.IsDisposed) { - return MessageBox.Show(text, caption, buttons, icon, MessageBoxDefaultButton.Button1, options: MessageBoxOptions.DefaultDesktopOnly); + return System.Windows.Forms.MessageBox.Show(text, caption, buttons, icon, MessageBoxDefaultButton.Button1, options: MessageBoxOptions.DefaultDesktopOnly); } if (mainFrm.InvokeRequired) { diff --git a/src/OutlookGoogleCalendarSync/Forms/MainForm.cs b/src/OutlookGoogleCalendarSync/Forms/MainForm.cs index f5b57efa..0a5a4de1 100644 --- a/src/OutlookGoogleCalendarSync/Forms/MainForm.cs +++ b/src/OutlookGoogleCalendarSync/Forms/MainForm.cs @@ -1028,8 +1028,8 @@ private void mainFormResize(object sender, EventArgs e) { log.Info("Minimising application to task tray."); this.ShowInTaskbar = false; this.Hide(); - if (Settings.Instance.ShowBubbleWhenMinimising) { - NotificationTray.ShowBubbleInfo("OGCS is still running.\r\nClick here to disable this notification.", ToolTipIcon.Info, "ShowBubbleWhenMinimising"); + if (Settings.Instance.ShowSystemNotificationWhenMinimising) { + NotificationTray.ShowBubbleInfo("OGCS is still running.\r\nClick here to disable this notification.", ToolTipIcon.Info, "ShowSystemNotificationWhenMinimising"); } else { trayIcon.Tag = ""; } diff --git a/src/OutlookGoogleCalendarSync/Forms/UpdateInfo.cs b/src/OutlookGoogleCalendarSync/Forms/UpdateInfo.cs index a8877f26..87ff2a41 100644 --- a/src/OutlookGoogleCalendarSync/Forms/UpdateInfo.cs +++ b/src/OutlookGoogleCalendarSync/Forms/UpdateInfo.cs @@ -153,7 +153,7 @@ public void ShowUpgradeProgress(int i) { public void UpgradeCompleted() { if (this.Visible) btUpgrade.Text = "Restart"; else - OgcsMessageBox.Show("The application has been updated and will now restart.", + Ogcs.Extensions.MessageBox.Show("The application has been updated and will now restart.", "OGCS successfully updated!", MessageBoxButtons.OK, MessageBoxIcon.Information); } public Boolean AwaitingRestart { diff --git a/src/OutlookGoogleCalendarSync/XMLManager.cs b/src/OutlookGoogleCalendarSync/XMLManager.cs index fb94a89d..d6367212 100644 --- a/src/OutlookGoogleCalendarSync/XMLManager.cs +++ b/src/OutlookGoogleCalendarSync/XMLManager.cs @@ -237,7 +237,7 @@ public static void RenameElement(String nodeName, XElement parent, String newNod else sourceElement.Name = ns + newNodeName; } catch (System.Exception ex) { - OGCSexception.Analyse("Could not rename '" + nodeName + "'", ex); + ex.Analyse($"Could not rename '{nodeName}'"); } } }