예제 #1
0
        public UpdateInfo(String releaseVersion, String releaseType, String html, out DialogResult dr)
        {
            InitializeComponent();

            log.Info("Showing new release information.");
            version = releaseVersion;
            dr      = DialogResult.Cancel;
            try {
                lTitle.Text   = "A new " + (releaseType == "alpha" ? "alpha " : "") + "release of OGCS is available";
                lSummary.Text = "Would you like to upgrade to v" + releaseVersion + " now?";

                if (html == null)
                {
                    String githubReleaseNotes = "https://github.com/phw198/OutlookGoogleCalendarSync/blob/master/docs/Release%20Notes.md";
                    anchorRequested = "v" + releaseVersion.Replace(".", "") + "---" + releaseType;
                    log.Debug("Browser anchor: " + anchorRequested);
                    webBrowser.DocumentCompleted += WebBrowser_DocumentCompleted;
                    webBrowser.Navigate(githubReleaseNotes);
                }
                else
                {
                    html = html.TrimStart("< ![CDATA[".ToCharArray());
                    html = html.TrimEnd("]]>".ToCharArray());
                    html = htmlHead + html + "</body></html>";
                    webBrowser.DocumentText = html;
                }
                dr = ShowDialog();
            } catch (System.Exception ex) {
                log.Debug("A problem was encountered showing the release notes.");
                OGCSexception.Analyse(ex);
                dr = 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);
            }
        }
        private static void add(ref AppointmentItem ai, MetadataId key, OlUserPropertyType keyType, object keyValue)
        {
            String addkeyName = metadataIdKeyName(key);

            UserProperties ups = null;

            try {
                if (!Exists(ai, key))
                {
                    int newSet;
                    int?keySet = getKeySet(ai, out newSet);
                    keySet = keySet ?? newSet + 1;
                    if (keySet.HasValue && keySet.Value != 0)
                    {
                        addkeyName += "-" + keySet.Value.ToString("D2");
                    }

                    try {
                        ups = ai.UserProperties;
                        ups.Add(addkeyName, keyType);
                    } catch (System.Exception ex) {
                        OGCSexception.Analyse(ex);
                        ups.Add(addkeyName, keyType, false);
                    } finally {
                        ups = (UserProperties)Calendar.ReleaseObject(ups);
                    }
                }
                ups = ai.UserProperties;
                ups[addkeyName].Value = keyValue;
                log.Fine("Set userproperty " + addkeyName + "=" + keyValue.ToString());
            } finally {
                ups = (UserProperties)Calendar.ReleaseObject(ups);
            }
        }
        /// <summary>
        /// Retrieve calendar's Event colours from Google
        /// </summary>
        public void Get()
        {
            log.Debug("Retrieving calendar Event colours.");
            Colors colours = null;

            calendarPalette = new List <Palette>();
            eventPalette    = new List <Palette>();
            try {
                colours = GoogleOgcs.Calendar.Instance.Service.Colors.Get().Execute();
            } catch (System.Exception ex) {
                log.Error("Failed retrieving calendar Event colours.");
                OGCSexception.Analyse(ex);
                return;
            }

            if (colours == null)
            {
                log.Warn("No colours found!");
            }
            else
            {
                log.Debug(colours.Event__.Count() + " event colours and " + colours.Calendar.Count() + " calendars (with a colour) found.");
            }

            foreach (KeyValuePair <String, ColorDefinition> colour in colours.Event__)
            {
                eventPalette.Add(new Palette(Palette.Type.Event, colour.Key, colour.Value.Background, OutlookOgcs.Categories.Map.RgbColour(colour.Value.Background)));
            }
            foreach (KeyValuePair <String, ColorDefinition> colour in colours.Calendar)
            {
                calendarPalette.Add(new Palette(Palette.Type.Calendar, colour.Key, colour.Value.Background, OutlookOgcs.Categories.Map.RgbColour(colour.Value.Background)));
            }
        }
 private void colourGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
 {
     try {
         if (e.Control is ComboBox)
         {
             ComboBox cb = e.Control as ComboBox;
             cb.DrawMode              = DrawMode.OwnerDrawFixed;
             cb.SelectedIndexChanged -= colourGridView_SelectedIndexChanged;
             cb.SelectedIndexChanged += colourGridView_SelectedIndexChanged;
             if (cb is Extensions.OutlookColourCombobox)
             {
                 cb.DrawItem -= OutlookComboBox.ColourPicker_DrawItem;
                 cb.DrawItem += OutlookComboBox.ColourPicker_DrawItem;
                 OutlookComboBox.ColourPicker_DrawItem(sender, null);
             }
             else if (cb is Extensions.GoogleColourCombobox)
             {
                 cb.DrawItem -= GoogleComboBox.ColourPicker_DrawItem;
                 cb.DrawItem += GoogleComboBox.ColourPicker_DrawItem;
                 GoogleComboBox.ColourPicker_DrawItem(sender, null);
             }
         }
     } catch (System.Exception ex) {
         OGCSexception.Analyse(ex);
     }
 }
        private void CloudLogging_Shown(object sender, EventArgs e)
        {
            try {
                //Highlight the ERROR text and scroll so it's in view
                int lastError = tbLog.Text.LastIndexOf(" ERROR ") + 1;
                if (lastError == 0)
                {
                    lastError = tbLog.Text.LastIndexOf(" FATAL ") + 1;
                }
                int highlightLength = tbLog.Text.Substring(lastError).IndexOf("\n");
                tbLog.Select(lastError, highlightLength);

                if (tbLog.SelectionStart != 0)
                {
                    tbLog.SelectionBackColor = System.Drawing.Color.Yellow;

                    int previousLineBreak = tbLog.Text.Substring(0, lastError).LastIndexOf("\n");
                    tbLog.SelectionStart = previousLineBreak;
                    tbLog.ScrollToCaret();
                }
                btYes.Focus();
            } catch (System.Exception ex) {
                OGCSexception.Analyse(ex);
            }
        }
예제 #6
0
        /// <summary>
        /// Retrieve calendar's Event colours from Google
        /// </summary>
        public void Get()
        {
            log.Debug("Retrieving calendar Event colours.");
            Colors            colours        = null;
            CalendarListEntry calendarColour = null;

            colourPalette = new List <Palette>();
            try {
                colours        = GoogleOgcs.Calendar.Instance.Service.Colors.Get().Execute();
                calendarColour = GoogleOgcs.Calendar.Instance.Service.CalendarList.Get(Settings.Instance.UseGoogleCalendar.Id).Execute();
            } catch (System.Exception ex) {
                log.Error("Failed retrieving calendar Event colours.");
                OGCSexception.Analyse(ex);
                return;
            }

            if (colours == null)
            {
                log.Warn("No colours found!");
            }
            else
            {
                log.Debug(colours.Event__.Count() + " colours found.");
            }

            foreach (KeyValuePair <String, ColorDefinition> colour in colours.Event__)
            {
                colourPalette.Add(new Palette(colour.Key, colour.Value.Background, OutlookOgcs.CategoryMap.RgbColour(colour.Value.Background)));
            }
            if (calendarColour != null && calendarColour.BackgroundColor != null)
            {
                colourPalette.Add(new Palette("Custom", calendarColour.BackgroundColor, OutlookOgcs.CategoryMap.RgbColour(calendarColour.BackgroundColor)));
            }
        }
        private void getDefaultCalendar(NameSpace oNS, ref MAPIFolder defaultCalendar)
        {
            log.Debug("Finding default Mailbox calendar folders");
            try {
                MainForm.Instance.rbOutlookDefaultMB.CheckedChanged -= MainForm.Instance.rbOutlookDefaultMB_CheckedChanged;
                MainForm.Instance.rbOutlookDefaultMB.Checked         = true;
                Settings.Instance.OutlookService = OutlookOgcs.Calendar.Service.DefaultMailbox;
                MainForm.Instance.rbOutlookDefaultMB.CheckedChanged += MainForm.Instance.rbOutlookDefaultMB_CheckedChanged;

                defaultCalendar = oNS.GetDefaultFolder(OlDefaultFolders.olFolderCalendar);
                calendarFolders.Add("Default " + defaultCalendar.Name, defaultCalendar);
                string excludeDeletedFolder = folders.Application.Session.GetDefaultFolder(OlDefaultFolders.olFolderDeletedItems).EntryID;

                MainForm.Instance.lOutlookCalendar.BackColor = System.Drawing.Color.Yellow;
                MainForm.Instance.lOutlookCalendar.Text      = "Getting calendars";

                findCalendars(oNS.DefaultStore.GetRootFolder().Folders, calendarFolders, excludeDeletedFolder, defaultCalendar);

                MainForm.Instance.lOutlookCalendar.BackColor = System.Drawing.Color.White;
                MainForm.Instance.lOutlookCalendar.Text      = "Select calendar";
            } catch (System.Exception ex) {
                OGCSexception.Analyse(ex, true);
                throw ex;
            }
        }
예제 #8
0
        public static void DrawComboboxItemColour(ComboBox cbColour, Brush boxColour, String itemDescription, DrawItemEventArgs e)
        {
            try {
                e.Graphics.FillRectangle(new SolidBrush(cbColour.BackColor), e.Bounds);
                e.DrawBackground();
                Boolean comboEnabled = cbColour.Enabled;

                // Write colour name
                Boolean highlighted = (e.State & DrawItemState.Selected) != DrawItemState.None;
                Brush   brush       = comboEnabled ? SystemBrushes.WindowText : SystemBrushes.InactiveCaptionText;
                if (highlighted)
                {
                    brush = comboEnabled ? SystemBrushes.HighlightText : SystemBrushes.InactiveCaptionText;
                }

                DrawComboboxItemColour(comboEnabled, boxColour, brush, itemDescription, e.Graphics, e.Bounds);

                // Draw the focus rectangle if appropriate
                if ((e.State & DrawItemState.NoFocusRect) == DrawItemState.None)
                {
                    e.DrawFocusRectangle();
                }
            } catch (System.Exception ex) {
                OGCSexception.Analyse(ex);
            }
        }
예제 #9
0
        private void ddOutlookColour_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!this.Visible)
            {
                return;
            }

            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 = GoogleOgcs.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);
            } catch (System.Exception ex) {
                OGCSexception.Analyse("ddOutlookColour_SelectedIndexChanged(): Could not update ddGoogleColour.", ex);
            } finally {
                ddGoogleColour.SelectedIndexChanged += ddGoogleColour_SelectedIndexChanged;
            }
        }
예제 #10
0
        protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, System.Windows.Forms.DataGridViewElementStates elementState, object value, object formattedValue, string errorText, System.Windows.Forms.DataGridViewCellStyle cellStyle, System.Windows.Forms.DataGridViewAdvancedBorderStyle advancedBorderStyle, System.Windows.Forms.DataGridViewPaintParts paintParts)
        {
            //Paint inactive cells
            base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, "", "", errorText, cellStyle, advancedBorderStyle, paintParts);

            try {
                if (rowIndex < 0)
                {
                    return;
                }

                foreach (GoogleOgcs.EventColour.Palette ci in Forms.ColourMap.GoogleComboBox.Items)
                {
                    if (ci.Name == this.Value.ToString())
                    {
                        Brush boxBrush  = new SolidBrush(ci.RgbValue);
                        Brush textBrush = SystemBrushes.WindowText;
                        Extensions.ColourCombobox.DrawComboboxItemColour(true, boxBrush, textBrush, this.Value.ToString(), graphics, cellBounds);
                        break;
                    }
                }
            } catch (System.Exception ex) {
                OGCSexception.Analyse("GoogleColourComboboxCell.Paint()", ex);
            }
        }
예제 #11
0
        public List <Object> FilterItems(Items outlookItems, String filter)
        {
            List <Object> restrictedItems = new List <Object>();

            foreach (Object obj in outlookItems.Restrict(filter))
            {
                restrictedItems.Add(obj);
            }

            // Recurring items with start dates before the synced date range are excluded incorrectly - this retains them
            List <Object> o2003recurring = new List <Object>();

            try {
                for (int i = 1; i <= outlookItems.Count; i++)
                {
                    AppointmentItem ai = null;
                    if (outlookItems[i] is AppointmentItem)
                    {
                        ai = outlookItems[i] as AppointmentItem;
                        if (ai.IsRecurring && ai.Start.Date < Settings.Instance.SyncStart && ai.End.Date < Settings.Instance.SyncStart)
                        {
                            o2003recurring.Add(outlookItems[i]);
                        }
                    }
                }
                log.Info(o2003recurring.Count + " recurring items successfully kept for Outlook 2003.");
            } catch (System.Exception ex) {
                OGCSexception.Analyse("Unable to iterate Outlook items.", ex);
            }
            restrictedItems.AddRange(o2003recurring);

            return(restrictedItems);
        }
예제 #12
0
        private Dictionary <OutlookOgcs.CustomProperty.MetadataId, object> cleanIDs(ref AppointmentItem copiedAi)
        {
            log.Info("Temporarily removing OGCS properties from copied Outlook appointment item.");

            Dictionary <OutlookOgcs.CustomProperty.MetadataId, object> propertyBackup = new Dictionary <OutlookOgcs.CustomProperty.MetadataId, object>();

            try {
                object backupValue = null;
                foreach (OutlookOgcs.CustomProperty.MetadataId metaDataId in Enum.GetValues(typeof(OutlookOgcs.CustomProperty.MetadataId)))
                {
                    log.Fine("Backing up " + metaDataId.ToString());
                    if (metaDataId == OutlookOgcs.CustomProperty.MetadataId.ogcsModified)
                    {
                        backupValue = OutlookOgcs.CustomProperty.GetOGCSlastModified(copiedAi);
                    }
                    else
                    {
                        backupValue = OutlookOgcs.CustomProperty.Get(copiedAi, metaDataId);
                    }
                    propertyBackup.Add(metaDataId, backupValue);
                }
                OutlookOgcs.CustomProperty.RemoveAll(ref copiedAi);
                OutlookOgcs.CustomProperty.Add(ref copiedAi, OutlookOgcs.CustomProperty.MetadataId.locallyCopied, true.ToString());
                copiedAi.Save();
            } catch (System.Exception ex) {
                log.Warn("Failed to clean OGCS properties from copied item.");
                OGCSexception.Analyse(ex);
            }
            return(propertyBackup);
        }
예제 #13
0
        private void initialiseDataGridView()
        {
            try {
                log.Info("Opening timezone mapping window.");

                log.Fine("Building default system timezone dropdowns.");
                System.Collections.ObjectModel.ReadOnlyCollection <TimeZoneInfo> sysTZ = TimeZoneInfo.GetSystemTimeZones();
                Dictionary <String, String> cbTz = new Dictionary <String, String>();
                sysTZ.ToList().ForEach(tzi => cbTz.Add(tzi.Id, tzi.DisplayName));

                //Replace existing TZ column with custom dropdown
                DataGridViewComboBoxColumn col = tzGridView.Columns[1] as DataGridViewComboBoxColumn;
                col.DataSource    = new BindingSource(cbTz, null);
                col.DisplayMember = "Value";
                col.ValueMember   = "Key";
                col.DisplayStyle  = DataGridViewComboBoxDisplayStyle.ComboBox;

                tzGridView.Columns.RemoveAt(1);
                tzGridView.Columns.Add(col);

                loadConfig();
            } catch (System.Exception ex) {
                OGCSexception.Analyse(ex);
            }
        }
예제 #14
0
        public void PickKey(KeyType keyType)
        {
            log.Debug("Picking a " + keyType.ToString() + " key.");
            try {
                List <ApiKey> keyRing = (keyType == KeyType.Standard) ? standardKeys : subscriberKeys;
                if (keyRing == null || keyRing.Count == 0)
                {
                    log.Warn(keyType.ToString() + " keyring is empty!");
                    if (!string.IsNullOrEmpty(Settings.Instance.AssignedClientIdentifier) &&
                        !string.IsNullOrEmpty(Settings.Instance.AssignedClientSecret))
                    {
                        log.Debug("Using key from settings file.");
                        key = new ApiKey(Settings.Instance.AssignedClientIdentifier, Settings.Instance.AssignedClientSecret);
                    }
                    else
                    {
                        log.Debug("Reverting to default key.");
                        Key = new ApiKey.DefaultKey(keyType);
                    }
                    return;
                }

                if (!string.IsNullOrEmpty(Settings.Instance.AssignedClientIdentifier))
                {
                    log.Fine("Checking " + (Settings.Instance.AssignedClientIdentifier == new ApiKey.DefaultKey(keyType).ClientId ? "" : "non-") + "default assigned API key is still on the keyring.");
                    ApiKey retrievedKey = keyRing.Find(k => k.ClientId == Settings.Instance.AssignedClientIdentifier);
                    if (retrievedKey == null)
                    {
                        log.Warn("Could not find assigned key on keyring!");
                        if (standardKeys.Concat(subscriberKeys).Any(k => k.ClientId == Settings.Instance.AssignedClientIdentifier))
                        {
                            log.Warn("The key was been taken from the other keyring!");
                        }
                        log.Debug("Picking a new key from the ring.");
                    }
                    else
                    {
                        if (retrievedKey.Status == KeyStatus.DEAD.ToString())
                        {
                            log.Warn("The assigned key can no longer be used. A new key must be assigned.");
                        }
                        else
                        {
                            Key = retrievedKey;
                            return;
                        }
                    }
                }
                keyRing = keyRing.Where(k => k.Status == KeyStatus.ACTIVE.ToString()).ToList();
                Random rnd       = new Random();
                int    chosenKey = rnd.Next(0, keyRing.Count - 1);
                log.Fine("Picked random active key #" + chosenKey + 1);
                Key = keyRing[chosenKey];
            } catch (System.Exception ex) {
                log.Fail("Failed picking " + keyType.ToString() + " API key. clientID=" + Settings.Instance.AssignedClientIdentifier);
                OGCSexception.Analyse(ex);
                log.Debug("Reverting to default key.");
                Key = new ApiKey.DefaultKey(keyType);
            }
        }
        /// <summary>
        /// Log the various User Properties.
        /// </summary>
        /// <param name="ai">The Appointment item.</param>
        /// <param name="thresholdLevel">Only log if logging configured at this level or higher.</param>
        public static void LogProperties(AppointmentItem ai, log4net.Core.Level thresholdLevel)
        {
            if (((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level.Value > thresholdLevel.Value)
            {
                return;
            }

            UserProperties ups = null;
            UserProperty   up  = null;

            try {
                log.Debug(OutlookOgcs.Calendar.GetEventSummary(ai));
                ups = ai.UserProperties;
                for (int p = 1; p <= ups.Count; p++)
                {
                    try {
                        up = ups[p];
                        log.Debug(up.Name + "=" + up.Value.ToString());
                    } finally {
                        up = (UserProperty)OutlookOgcs.Calendar.ReleaseObject(up);
                    }
                }
            } catch (System.Exception ex) {
                OGCSexception.Analyse("Failed to log Appointment UserProperties", ex);
            } finally {
                ups = (UserProperties)OutlookOgcs.Calendar.ReleaseObject(ups);
            }
        }
예제 #16
0
 private void btOK_Click(object sender, EventArgs e)
 {
     try {
         Settings.Instance.TimezoneMaps.Clear();
         foreach (DataGridViewRow row in tzGridView.Rows)
         {
             if (row.Cells[0].Value == null || row.Cells[0].Value.ToString().Trim() == "")
             {
                 continue;
             }
             try {
                 Settings.Instance.TimezoneMaps.Add(row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString());
             } catch (System.ArgumentException ex) {
                 if (OGCSexception.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);
     } finally {
         this.Close();
         Forms.Main.Instance.SetControlPropertyThreadSafe(Forms.Main.Instance.btCustomTzMap, "Visible", Settings.Instance.TimezoneMaps.Count != 0);
         Settings.Instance.Save();
     }
 }
        private void checkLimit()
        {
            try {
                if (base.ParentForm.Name != Forms.Main.Instance.Name)
                {
                    return;
                }

                if (Settings.Instance.UsingPersonalAPIkeys())
                {
                    if (!string.IsNullOrEmpty(this.tooltip.GetToolTip(this)))
                    {
                        this.tooltip.RemoveAll();
                    }
                }
                else
                {
                    if (this.Value == this.Maximum)
                    {
                        this.tooltip.Show("Limited to 1 year unless personal API keys are used. See 'Developer Options' on Google tab.", this);
                    }
                    else
                    {
                        this.tooltip.RemoveAll();
                    }
                }
            } catch (System.Exception ex) {
                OGCSexception.Analyse(this.Name, ex);
            }
        }
예제 #18
0
        private void loadConfig()
        {
            try {
                if (Forms.Main.Instance.ActiveCalendarProfile.ColourMaps.Count > 0)
                {
                    colourGridView.Rows.Clear();
                }
                foreach (KeyValuePair <String, String> colourMap in Forms.Main.Instance.ActiveCalendarProfile.ColourMaps)
                {
                    addRow(colourMap.Key, GoogleOgcs.EventColour.Palette.GetColourName(colourMap.Value));
                }
                ddOutlookColour.AddCategoryColours();
                if (ddOutlookColour.Items.Count > 0)
                {
                    ddOutlookColour.SelectedIndex = 0;
                }

                ddGoogleColour.AddPaletteColours();
                if (ddGoogleColour.Items.Count > 0)
                {
                    ddGoogleColour.SelectedIndex = 0;
                }
            } catch (System.Exception ex) {
                OGCSexception.Analyse("Populating gridview cells from Settings.", ex);
            }
        }
예제 #19
0
        private void ddGoogleColour_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!this.Visible)
            {
                return;
            }

            try {
                ddOutlookColour.SelectedIndexChanged -= ddOutlookColour_SelectedIndexChanged;

                String oCatName = null;
                log.Fine("Checking grid for map...");
                foreach (DataGridViewRow row in colourGridView.Rows)
                {
                    if (row.Cells["GoogleColour"].Value != null && row.Cells["GoogleColour"].Value.ToString() == ddGoogleColour.SelectedItem.Name)
                    {
                        oCatName = row.Cells["OutlookColour"].Value.ToString();
                        break;
                    }
                }

                if (string.IsNullOrEmpty(oCatName))
                {
                    oCatName = OutlookOgcs.Calendar.Instance.GetCategoryColour(ddGoogleColour.SelectedItem.Id, false);
                }

                if (!string.IsNullOrEmpty(oCatName))
                {
                    foreach (OutlookOgcs.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();
                    while (ddOutlookColour.Items.Count > 0)
                    {
                        ddOutlookColour.Items.RemoveAt(0);
                    }
                    ddOutlookColour.AddCategoryColours();

                    foreach (OutlookOgcs.Categories.ColourInfo cInfo in ddOutlookColour.Items)
                    {
                        if (cInfo.Text == oCatName)
                        {
                            ddOutlookColour.SelectedItem = cInfo;
                            return;
                        }
                    }
                }
                ddOutlookColour.SelectedIndex = 0;
            } catch (System.Exception ex) {
                OGCSexception.Analyse("ddGoogleColour_SelectedIndexChanged(): Could not update ddOutlookColour.", ex);
            } finally {
                ddOutlookColour.SelectedIndexChanged += ddOutlookColour_SelectedIndexChanged;
            }
        }
        /// <summary>
        /// Get the Outlook category colour from the name given to the category
        /// </summary>
        /// <param name="categoryName">The user named Outlook category</param>
        /// <returns>The Outlook category type</returns>
        public Outlook.OlCategoryColor?OutlookColour(String categoryName)
        {
            if (string.IsNullOrEmpty(categoryName))
            {
                log.Warn("Category name is empty.");
            }

            try {
                if (this.categories != null && this.categories.Count > 0)
                {
                }
            } catch (System.Exception ex) {
                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();
                this.categories = Calendar.Categories.categories;
            }

            foreach (Outlook.Category category in this.categories)
            {
                if (category.Name == categoryName.Trim())
                {
                    return(category.Color);
                }
            }

            log.Warn("Could not convert category name '" + categoryName + "' into Outlook category type.");
            return(null);
        }
예제 #21
0
        private void ogcsPushTimer_Tick(object sender, EventArgs e)
        {
            log.Fine("Push sync triggered.");

            try {
                System.Collections.Generic.List <Microsoft.Office.Interop.Outlook.AppointmentItem> items = OutlookOgcs.Calendar.Instance.GetCalendarEntriesInRange(true);

                if (items.Count < this.lastRunItemCount || items.FindAll(x => x.LastModificationTime > this.lastRunTime).Count > 0)
                {
                    log.Debug("Changes found for Push sync.");
                    Forms.Main.Instance.NotificationTray.ShowBubbleInfo("Autosyncing calendars: " + Settings.Instance.SyncDirection.Name + "...");
                    if (!Sync.Engine.Instance.SyncingNow)
                    {
                        Forms.Main.Instance.Sync_Click(sender, null);
                    }
                    else
                    {
                        log.Debug("Busy syncing already. No need to push.");
                    }
                }
                else
                {
                    log.Fine("No changes found.");
                }
                failures = 0;
            } catch (System.Exception ex) {
                failures++;
                log.Warn("Push Sync failed " + failures + " times to check for changed items.");
                OGCSexception.Analyse(ex);
                if (failures == 10)
                {
                    Forms.Main.Instance.Console.UpdateWithError("Push Sync is failing.", ex, notifyBubble: true);
                }
            }
        }
예제 #22
0
        private void btOK_Click(object sender, EventArgs e)
        {
            log.Fine("Checking no duplicate mappings exist.");
            SettingsStore.Calendar profile = Forms.Main.Instance.ActiveCalendarProfile;
            try {
                List <String> oColValues = new List <String>();
                List <String> gColValues = new List <String>();
                foreach (DataGridViewRow row in colourGridView.Rows)
                {
                    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 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);
                    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);
                    return;
                }
            } catch (System.Exception ex) {
                OGCSexception.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;
            }

            try {
                log.Fine("Storing colour mappings in Settings.");
                profile.ColourMaps.Clear();
                foreach (DataGridViewRow row in colourGridView.Rows)
                {
                    if (row.Cells["OutlookColour"].Value == null || row.Cells["OutlookColour"].Value.ToString().Trim() == "")
                    {
                        continue;
                    }
                    try {
                        profile.ColourMaps.Add(row.Cells["OutlookColour"].Value.ToString(), GoogleOgcs.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
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            } catch (System.Exception ex) {
                OGCSexception.Analyse("Could not save colour/category mappings to Settings.", ex);
            } finally {
                this.Close();
            }
        }
예제 #23
0
        private void ogcsPushTimer_Tick(object sender, EventArgs e)
        {
            if (Forms.ErrorReporting.Instance.Visible)
            {
                return;
            }
            log.Fine("Push sync triggered.");

            try {
                System.Collections.Generic.List <Microsoft.Office.Interop.Outlook.AppointmentItem> items = OutlookOgcs.Calendar.Instance.GetCalendarEntriesInRange(true);

                if (items.Count < this.lastRunItemCount || items.FindAll(x => x.LastModificationTime > this.lastRunTime).Count > 0)
                {
                    log.Debug("Changes found for Push sync.");
                    Forms.Main.Instance.NotificationTray.ShowBubbleInfo("Autosyncing calendars: " + Settings.Instance.SyncDirection.Name + "...");
                    if (!Sync.Engine.Instance.SyncingNow)
                    {
                        Forms.Main.Instance.Sync_Click(sender, null);
                    }
                    else
                    {
                        log.Debug("Busy syncing already. No need to push.");
                    }
                }
                else
                {
                    log.Fine("No changes found.");
                }
                failures = 0;
            } catch (System.Exception ex) {
                failures++;
                log.Warn("Push Sync failed " + failures + " times to check for changed items.");

                String hResult = OGCSexception.GetErrorCode(ex);
                if ((ex is System.InvalidCastException && hResult == "0x80004002" && ex.Message.Contains("0x800706BA")) || //The RPC server is unavailable
                    (ex is System.Runtime.InteropServices.COMException && (
                         ex.Message.Contains("0x80010108(RPC_E_DISCONNECTED)") ||                                          //The object invoked has disconnected from its clients
                         hResult == "0x800706BE" ||                                                                        //The remote procedure call failed
                         hResult == "0x800706BA"))                                                                         //The RPC server is unavailable
                    )
                {
                    OGCSexception.Analyse(OGCSexception.LogAsFail(ex));
                    try {
                        OutlookOgcs.Calendar.Instance.Reset();
                    } catch (System.Exception ex2) {
                        OGCSexception.Analyse("Failed resetting Outlook connection.", ex2);
                    }
                }
                else
                {
                    OGCSexception.Analyse(ex);
                }
                if (failures == 10)
                {
                    Forms.Main.Instance.Console.UpdateWithError("Push Sync is failing.", ex, notifyBubble: true);
                }
            }
        }
예제 #24
0
        /// <summary>
        /// Detects paste events in order to remove OGCS properties from pasted item.
        ///
        /// However, the clipboard is a reference to the copied item
        /// and the pasted object is not available yet until AFTER this function!
        /// We can't short-circuit the paste event by setting "Cancel = true" and performing the Copy()
        /// because it pastes to the same DateTime as the copied item.
        /// In Outlook2010 the (Explorer.View as CalendarView).SelectedStartTime exists, but not in 2007,
        /// so there's no way of knowing the time to paste the item in to.
        ///
        /// So the workaround is to temporarily doctor the original copied item (ie remove OGCS properties),
        /// which the pasted item inherits. A delayed background thread then post-processes the original item
        /// to revert any changes and repopulate values.
        /// </summary>
        private void beforeItemPaste(ref object ClipboardContent, MAPIFolder Target, ref bool Cancel)
        {
            log.Info("Item paste event caught.");
            try {
                Selection selection = ClipboardContent as Selection;
                if (selection == null)
                {
                    log.Warn("Clipboard selection returned nothing.");
                    return;
                }
                log.Debug("We've got " + selection.Count + " items selected for copy.");

                foreach (Object item in selection)
                {
                    AppointmentItem copiedAi = null;
                    try {
                        if (item is AppointmentItem)
                        {
                            copiedAi = item as AppointmentItem;
                        }
                        else
                        {
                            throw new ApplicationException("The item is not an appointment item.");
                        }
                        log.Debug(OutlookOgcs.Calendar.GetEventSummary(copiedAi));
                        String entryID = copiedAi.EntryID;
                        if (OutlookOgcs.CustomProperty.Exists(copiedAi, OutlookOgcs.CustomProperty.MetadataId.gEventID))
                        {
                            Dictionary <String, object> propertyBackup = cleanIDs(ref copiedAi);
                            OutlookOgcs.CustomProperty.Add(ref copiedAi, CustomProperty.MetadataId.originalStartDate, copiedAi.Start);
                            copiedAi.Save();
                            System.Threading.Thread repopIDsThrd = new System.Threading.Thread(() => repopulateIDs(entryID, propertyBackup));
                            repopIDsThrd.Start();
                        }
                        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());
                            copiedAi.Save();
                            //Untag the original copied item
                            System.Threading.Thread untagAsCopiedThrd = new System.Threading.Thread(() => untagAsCopied(entryID));
                            untagAsCopiedThrd.Start();
                        }
                    } catch (System.ApplicationException ex) {
                        log.Debug(ex.Message);
                    } catch (System.Exception ex) {
                        log.Warn("Not able to process copy and pasted event.");
                        OGCSexception.Analyse(ex);
                    } finally {
                        copiedAi = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(copiedAi);
                    }
                }
            } catch (System.Exception ex) {
                OGCSexception.Analyse(ex);
            }
        }
        private void ProfileManage_FormClosing(object sender, FormClosingEventArgs e)
        {
            if ((sender as Form).DialogResult == DialogResult.Cancel)
            {
                return;
            }

            if (this.btOK.Text == "Add")
            {
                SettingsStore.Calendar newCalendar = null;
                try {
                    String profileName = this.txtProfileName.Text;
                    if (string.IsNullOrEmpty(profileName))
                    {
                        return;
                    }

                    newCalendar = new SettingsStore.Calendar();
                    newCalendar._ProfileName = profileName;
                    Settings.Instance.Calendars.Add(newCalendar);
                    log.Info("Added new calendar settings '" + profileName + "'.");
                    int addedIdx = ddProfile.Items.Add(profileName);
                    ddProfile.SelectedIndex = addedIdx;
                    Forms.Main.Instance.NotificationTray.AddProfileItem(profileName);

                    newCalendar.InitialiseTimer();
                    newCalendar.RegisterForPushSync();
                } catch (System.Exception ex) {
                    OGCSexception.Analyse("Failed to add new profile.", ex);
                    throw;
                }
            }
            else if (this.btOK.Text == "Rename")
            {
                String currentProfileName = ddProfile.Text;
                String newProfileName     = "";
                try {
                    newProfileName = this.txtProfileName.Text;
                    if (newProfileName == "")
                    {
                        return;
                    }

                    Forms.Main.Instance.ActiveCalendarProfile._ProfileName = newProfileName;
                    int idx = ddProfile.SelectedIndex;
                    ddProfile.Items.RemoveAt(idx);
                    ddProfile.Items.Insert(idx, newProfileName);
                    ddProfile.SelectedIndex = idx;
                    log.Info("Renamed calendar settings from '" + currentProfileName + "' to '" + newProfileName + "'.");
                } catch (System.Exception ex) {
                    OGCSexception.Analyse("Failed to rename profile from '" + currentProfileName + "' to '" + newProfileName + "'.", ex);
                    throw;
                }
                Forms.Main.Instance.NotificationTray.RenameProfileItem(currentProfileName, newProfileName);
            }
        }
 public Categories()
 {
     try {
         Delimiter = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator + " ";
     } catch (System.Exception ex) {
         log.Error("Failed to get system ListSeparator value.");
         OGCSexception.Analyse(ex);
         Delimiter = ", ";
     }
 }
예제 #27
0
 public void ResetLastRun()
 {
     this.lastRunTime = DateTime.Now;
     try {
         log.Fine("Updating calendar item count following Push Sync.");
         this.lastRunItemCount = OutlookOgcs.Calendar.Instance.GetCalendarEntriesInRange(true).Count;
     } catch (System.Exception ex) {
         OGCSexception.Analyse("Failed to update item count following a Push Sync.", ex);
     }
 }
예제 #28
0
        private void findCalendars(Folders folders, Dictionary <string, MAPIFolder> calendarFolders, String excludeDeletedFolder, MAPIFolder defaultCalendar = null)
        {
            //Initiate progress bar (red line underneath "Getting calendars" text)
            System.Drawing.Graphics g          = Forms.Main.Instance.tabOutlook.CreateGraphics();
            System.Drawing.Pen      p          = new System.Drawing.Pen(System.Drawing.Color.Red, 3);
            System.Drawing.Point    startPoint = new System.Drawing.Point(Forms.Main.Instance.lOutlookCalendar.Location.X,
                                                                          Forms.Main.Instance.lOutlookCalendar.Location.Y + Forms.Main.Instance.lOutlookCalendar.Size.Height + 3);
            double stepSize = Forms.Main.Instance.lOutlookCalendar.Size.Width / folders.Count;

            int fldCnt = 0;

            foreach (MAPIFolder folder in folders)
            {
                fldCnt++;
                System.Drawing.Point endPoint = new System.Drawing.Point(Forms.Main.Instance.lOutlookCalendar.Location.X + Convert.ToInt16(fldCnt * stepSize),
                                                                         Forms.Main.Instance.lOutlookCalendar.Location.Y + Forms.Main.Instance.lOutlookCalendar.Size.Height + 3);
                try { g.DrawLine(p, startPoint, endPoint); } catch { /*May get GDI+ error if g has been repainted*/ }
                System.Windows.Forms.Application.DoEvents();
                try {
                    OlItemType defaultItemType = folder.DefaultItemType;
                    if (defaultItemType == OlItemType.olAppointmentItem)
                    {
                        if (defaultCalendar == null || (folder.EntryID != defaultCalendar.EntryID))
                        {
                            calendarFolderAdd(folder.Name, folder);
                        }
                    }
                    if (folder.EntryID != excludeDeletedFolder && folder.Folders.Count > 0)
                    {
                        findCalendars(folder.Folders, calendarFolders, excludeDeletedFolder, defaultCalendar);
                    }
                } catch (System.Exception ex) {
                    OGCSexception.Analyse(ex);
                    if (oApp.Session.ExchangeConnectionMode.ToString().Contains("Disconnected") ||
                        ex.Message.StartsWith("Network problems are preventing connection to Microsoft Exchange.") ||
                        OGCSexception.GetErrorCode(ex, 0x000FFFFF) == "0x00040115")
                    {
                        log.Info("Currently disconnected from Exchange - unable to retrieve MAPI folders.");
                        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
                    {
                        log.Error("Failed to recurse MAPI folders.");
                        log.Error(ex.Message);
                        MessageBox.Show("A problem was encountered when searching for Outlook calendar folders.",
                                        "Calendar Folders", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            p.Dispose();
            try { g.Clear(System.Drawing.Color.White); } catch { }
            g.Dispose();
            System.Windows.Forms.Application.DoEvents();
        }
        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);
                return;
            }

            ToolTip loading = new ToolTip();

            try {
                GoogleOgcs.EventColour.Palette currentSelection = null;

                if (GoogleOgcs.Calendar.IsInstanceNull || !GoogleOgcs.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;

                    loading.Hide(this);
                }
                if (Items.Count != GoogleOgcs.Calendar.Instance.ColourPalette.ActivePalette.Count)
                {
                    while (Items.Count > 0)
                    {
                        Items.RemoveAt(0);
                    }
                    AddPaletteColours(true);
                }

                foreach (GoogleOgcs.EventColour.Palette pInfo in Items)
                {
                    if (pInfo.Id == currentSelection?.Id)
                    {
                        SelectedItem = pInfo;
                        break;
                    }
                }
            } catch (System.Exception ex) {
                OGCSexception.Analyse("ColourPicker_Enter()", ex);
            } finally {
                loading.Hide(this);
                loading.RemoveAll();
            }

            if (Items.Count > 1 && SelectedIndex == -1)
            {
                SelectedIndex = 0;
            }
        }
            /// <summary>
            /// Get colour ID from the name
            /// </summary>
            /// <param name="name">The name of the colour</param>
            /// <returns>The ID number</returns>
            public static String GetColourId(String name)
            {
                String id = null;

                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);
                }
                return(id);
            }