private MAPIFolder getCalendarStore(NameSpace oNS)
        {
            MAPIFolder defaultCalendar = null;

            SettingsStore.Calendar profile = Settings.Profile.InPlay();
            if (profile.OutlookService == OutlookOgcs.Calendar.Service.DefaultMailbox)
            {
                getDefaultCalendar(oNS, ref defaultCalendar);
            }
            log.Debug("Default Calendar folder: " + defaultCalendar.Name);
            return(defaultCalendar);
        }
        private void getDefaultCalendar(NameSpace oNS, ref MAPIFolder defaultCalendar)
        {
            log.Debug("Finding default Mailbox calendar folders");
            try {
                SettingsStore.Calendar profile = Settings.Profile.InPlay();
                Boolean updateGUI = profile.Equals(Forms.Main.Instance.ActiveCalendarProfile);
                if (updateGUI)
                {
                    Forms.Main.Instance.rbOutlookDefaultMB.CheckedChanged -= Forms.Main.Instance.rbOutlookDefaultMB_CheckedChanged;
                    Forms.Main.Instance.rbOutlookDefaultMB.Checked         = true;
                }
                profile.OutlookService = OutlookOgcs.Calendar.Service.DefaultMailbox;
                if (updateGUI)
                {
                    Forms.Main.Instance.rbOutlookDefaultMB.CheckedChanged += Forms.Main.Instance.rbOutlookDefaultMB_CheckedChanged;
                }

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

                if (updateGUI)
                {
                    Forms.Main.Instance.lOutlookCalendar.BackColor = System.Drawing.Color.Yellow;
                    Forms.Main.Instance.SetControlPropertyThreadSafe(Forms.Main.Instance.lOutlookCalendar, "Text", "Getting calendars");
                }
                findCalendars(((MAPIFolder)defaultCalendar.Parent).Folders, calendarFolders, excludeDeletedFolder, defaultCalendar);
                if (updateGUI)
                {
                    Forms.Main.Instance.lOutlookCalendar.BackColor = System.Drawing.Color.White;
                    Forms.Main.Instance.SetControlPropertyThreadSafe(Forms.Main.Instance.lOutlookCalendar, "Text", "Select calendar");
                }
            } catch (System.Exception ex) {
                OGCSexception.Analyse(ex, true);
                throw;
            }
        }
        public NameSpace GetCurrentUser(NameSpace oNS)
        {
            SettingsStore.Calendar profile = Settings.Profile.InPlay();

            //We only need the current user details when syncing meeting attendees.
            //If GAL had previously been detected as blocked, let's always try one attempt to see if it's been opened up
            if (!profile.OutlookGalBlocked && !profile.AddAttendees)
            {
                return(oNS);
            }

            Boolean releaseNamespace = (oNS == null);

            if (releaseNamespace)
            {
                oNS = oApp.GetNamespace("mapi");
            }

            Recipient currentUser = null;

            try {
                DateTime triggerOOMsecurity = DateTime.Now;
                try {
                    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;
                    }
                } catch (System.Exception ex) {
                    OGCSexception.Analyse(ex);
                    if (profile.OutlookGalBlocked)   //Fail fast
                    {
                        log.Debug("Corporate policy is still blocking access to GAL.");
                        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);
                    Disconnect();
                    OutlookOgcs.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: true, withSystemCall: true);
                    oNS = oApp.GetNamespace("mapi");

                    int maxDelay = 5;
                    int delay    = 1;
                    while (delay <= maxDelay)
                    {
                        log.Debug("Sleeping..." + delay + "/" + maxDelay);
                        System.Threading.Thread.Sleep(10000);
                        try {
                            currentUser = oNS.CurrentUser;
                            delay       = maxDelay;
                        } catch (System.Exception ex2) {
                            if (delay == maxDelay)
                            {
                                if (OGCSexception.GetErrorCode(ex2) == "0x80004004")   //E_ABORT
                                {
                                    log.Warn("Corporate policy or possibly anti-virus is blocking access to GAL.");
                                }
                                else
                                {
                                    OGCSexception.Analyse(ex2);
                                }
                                log.Warn("OGCS is unable to obtain CurrentUser from Outlook.");
                                profile.OutlookGalBlocked = true;
                                return(oNS);
                            }
                            OGCSexception.Analyse(ex2);
                        }
                        delay++;
                    }
                }
                if (profile.OutlookGalBlocked)
                {
                    log.Debug("GAL is no longer blocked!");
                }
                profile.OutlookGalBlocked = false;
                currentUserSMTP           = GetRecipientEmail(currentUser);
                currentUserName           = currentUser.Name;
            } finally {
                currentUser = (Recipient)OutlookOgcs.Calendar.ReleaseObject(currentUser);
                if (releaseNamespace)
                {
                    oNS = (NameSpace)OutlookOgcs.Calendar.ReleaseObject(oNS);
                }
            }
            return(oNS);
        }
        public void Connect()
        {
            if (!OutlookOgcs.Calendar.InstanceConnect)
            {
                return;
            }

            OutlookOgcs.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: true, withSystemCall: false);
            log.Debug("Setting up Outlook connection.");

            // Get the NameSpace and Logon information.
            NameSpace oNS = null;

            try {
                oNS = oApp.GetNamespace("mapi");

                //Implicit logon to default profile, with no dialog box
                //If 1< profile, a dialogue is forced unless implicit login used
                exchangeConnectionMode = oNS.ExchangeConnectionMode;
                if (exchangeConnectionMode != OlExchangeConnectionMode.olNoExchange)
                {
                    log.Info("Exchange server version: Unknown");
                }
                log.Info("Exchange connection mode: " + exchangeConnectionMode.ToString());

                oNS = GetCurrentUser(oNS);
                SettingsStore.Calendar profile = Settings.Profile.InPlay();

                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" +
                                                                 "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);
                    }
                }

                log.Debug("Get the folders configured in Outlook");
                folders = oNS.Folders;

                // Get the Calendar folders
                useOutlookCalendar = getCalendarStore(oNS);
                if (Forms.Main.Instance.IsHandleCreated && profile.Equals(Forms.Main.Instance.ActiveCalendarProfile))
                {
                    log.Fine("Resetting connection, so re-selecting calendar from GUI dropdown");

                    Forms.Main.Instance.cbOutlookCalendars.SelectedIndexChanged -= Forms.Main.Instance.cbOutlookCalendar_SelectedIndexChanged;
                    Forms.Main.Instance.cbOutlookCalendars.DataSource            = new BindingSource(calendarFolders, null);

                    //Select the right calendar
                    int c = 0;
                    foreach (KeyValuePair <String, MAPIFolder> calendarFolder in calendarFolders)
                    {
                        if (calendarFolder.Value.EntryID == profile.UseOutlookCalendar.Id)
                        {
                            Forms.Main.Instance.SetControlPropertyThreadSafe(Forms.Main.Instance.cbOutlookCalendars, "SelectedIndex", c);
                        }
                        c++;
                    }
                    if ((int)Forms.Main.Instance.GetControlPropertyThreadSafe(Forms.Main.Instance.cbOutlookCalendars, "SelectedIndex") == -1)
                    {
                        Forms.Main.Instance.SetControlPropertyThreadSafe(Forms.Main.Instance.cbOutlookCalendars, "SelectedIndex", 0);
                    }

                    KeyValuePair <String, MAPIFolder> calendar = (KeyValuePair <String, MAPIFolder>)Forms.Main.Instance.GetControlPropertyThreadSafe(Forms.Main.Instance.cbOutlookCalendars, "SelectedItem");
                    useOutlookCalendar = calendar.Value;

                    Forms.Main.Instance.cbOutlookCalendars.SelectedIndexChanged += Forms.Main.Instance.cbOutlookCalendar_SelectedIndexChanged;
                }

                OutlookOgcs.Calendar.Categories = null;
            } finally {
                // Done. Log off.
                if (oNS != null)
                {
                    oNS.Logoff();
                }
                oNS = (NameSpace)OutlookOgcs.Calendar.ReleaseObject(oNS);
            }
        }