// Af en eller anden årsag fyres dette event to gange. Første gang er Item ok, anden gang kastes der COM exceptions
        void sentItems_ItemAdd(object Item)
        {
            log.Info("sentItems_ItemAdd");

            if (IOfficeConnectGlobals.AutoPopupMails == false)
            {
                log.Info("sentItems_ItemAdd::autopopup slået fra");
                return;
            }

            try
            {
                // Et item blev tilføjet til sent items. Se om det er en mail der ikke er præpareret med arkiveringsinfo.
                var outlookMailItem = Item as Outlook.MailItem;

                if (outlookMailItem != null)
                {
                    // Omgå issue at der fyres to gange
                    var erOk = false;

                    try
                    {
                        var test = outlookMailItem.UserProperties[Constants.MailItemProperty_Archive_CompanyID];

                        erOk = true;
                    }
                    catch
                    {
                        // Åbentbart anden gang den fyrer
                    }

                    if (erOk)
                    {
                        var companyUserProperty = outlookMailItem.UserProperties[Constants.MailItemProperty_Archive_CompanyID];

                        if (companyUserProperty != null)
                        {
                            log.InfoFormat("sentItems_ItemAdd::Item sent: {0}", outlookMailItem.Subject);

                            var contactUserProperty = outlookMailItem.UserProperties[Constants.MailItemProperty_Archive_ContactID];
                            var taskUserProperty = outlookMailItem.UserProperties[Constants.MailItemProperty_Archive_TaskID];
                            var isArchivedProperty = outlookMailItem.UserProperties[Constants.MailItemProperty_IsArchived];

                            var isArchived = isArchivedProperty != null ? bool.Parse(isArchivedProperty.Value) : false;

                            if (isArchived == false)
                            {
                                if (companyUserProperty != null)
                                {
                                    log.InfoFormat("sentItems_ItemAdd::Item {0} skal arkiveres", outlookMailItem.Subject);

                                    var currentBruger = IOfficeConnectGlobals.GetCurrentBruger();
                                    var mailItemInfo = new MailItemInfo(outlookMailItem);

                                    var companyInfo = (KundeInfo)IOfficeConnectGlobals.KunderCache[Guid.Parse(companyUserProperty.Value)];
                                    var contactInfo = contactUserProperty != null ? companyInfo.Kontakter.Single(k => k.Kontakt.ID == Guid.Parse(contactUserProperty.Value)).Kontakt : null;
                                    TaskInfo taskInfo = null;

                                    var sessionNamespace = outlookMailItem.Application.Session;

                                    if (taskUserProperty != null)
                                    {
                                        using (var dc = new iorunEntities())
                                        {
                                            var taskID = (Guid)Guid.Parse(taskUserProperty.Value); // Funky???

                                            taskInfo = new TaskInfo(dc.Tasks.Where(t => t.Task_GUID == taskID).ToList().Single());
                                        }
                                    }

                                    IOfficeConnectGlobals.ArchiveSelectedItem(true, currentBruger, outlookMailItem, mailItemInfo, companyInfo, contactInfo, taskInfo, sessionNamespace);
                                }
                                else
                                {
                                    // Bliver fanget af sent items -> item add event og bruger bliver bedt om at arkivere
                                }
                            }
                            else
                            {
                                // Åbentbart har et arkiveret item fyret
                                log.Warn("Et arkiveret item har fyret i sent items");
                            }
                        }
                        else
                        {
                            // Har sendt mail uden at prækvalificere. Vis mailen.
                            outlookMailItem.Display();
                        }
                    }
                    else
                    {
                        // Var anden gang der blev fyret
                    }
                }
                else
                {
                    // Må være sendt noget andet end en mail (Måske kalender aftale, contact card etc.)
                }
            }
            catch (Exception sentItemsException)
            {
                var m = string.Format("Generel fejl under behandling at sendt post: {0}", sentItemsException.Message);

                log.Error(m, sentItemsException);

                MessageBox.Show(m, "Ukendt fejl sendt post", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        public static bool ArchiveSelectedItem(bool treatAtSentMail, BrugerInfo currentBruger, Outlook.MailItem mailItem, MailItemInfo mailItemInfo, KundeInfo companyInfo, KontaktInfo contactInfo, TaskInfo taskInfo, Outlook.NameSpace sessionNamespace)
        {
            var fromBruger = treatAtSentMail ? currentBruger : null;
            var toBruger = treatAtSentMail ? currentBruger : null;
            var documentType = treatAtSentMail ? DocumentType.SentMail : DocumentType.ReceivedMail;
            var documentGuid = Guid.NewGuid();

            var companyFolder = TryGetCompanyOutlookFolder(companyInfo.ID, currentBruger, sessionNamespace);

            // Vi har muligvis ikke rettigheder til at tilgå eller oprette mappen
            // Brugeren har fået besked så vi kan returnere
            if (companyFolder == null)
            {
                return false;
            }

            SetIOfficeProperties(documentGuid, mailItem);

            dynamic archivedItemDynamic;

            var itemCopy = (Outlook.MailItem)mailItem.Copy();

            archivedItemDynamic = itemCopy.Move(companyFolder);

            var archivedItem = (Outlook.MailItem)archivedItemDynamic;

            // Efter move får item nyt entryID og storeID
            mailItemInfo = new MailItemInfo(archivedItem);

            var mailItemDocument = new IOfficeOutlookAddIn.Document()
            {
                DOC_Body = mailItemInfo.BodyPlainText,
                DOC_CompanyGUID = companyInfo.ID,
                DOC_ContactGUID = contactInfo != null ? contactInfo.ID : new Nullable<Guid>(),
                DOC_CreatedByGUID = currentBruger.ID,
                DOC_CreatedDate = DateTime.Now,
                DOC_DocumentType = (int)documentType,
                DOC_ExchangeEntryID = mailItemInfo.CurrentMailItemEntryID,
                DOC_ExchangeFolderEntryID = null, // BRUGES IKKE
                DOC_ExchangeFolderStoreID = null, // BRUGES IKKE
                DOC_ExchangeStoreID = mailItemInfo.CurrentMailItemFolderStoreID,
                DOC_FromUserGUID = fromBruger != null ? fromBruger.ID : new Nullable<Guid>(),
                DOC_GUID = documentGuid,
                DOC_IsArchived = 1,
                DOC_IsInstantiated = 1,
                DOC_IsPrivate = 0,
                DOC_MailCreatedDatetime = mailItemInfo.Created,
                DOC_MailReceivedDatetime = mailItemInfo.Received,
                DOC_MailSentDatetime = mailItemInfo.Sent,
                DOC_MailUpdatedDatetime = DateTime.Now, // Hvad er det?
                DOC_MasterDate = DateTime.Now, // Hvad er det?
                DOC_OriginalFileName = string.Empty,
                DOC_ProjectGUID = null,
                DOC_SMTP_From = mailItemInfo.FromEmailAddress,
                DOC_SMTP_FromDisplayName = string.IsNullOrEmpty(mailItemInfo.FromDisplayName) == false ? mailItemInfo.FromDisplayName : treatAtSentMail == true ? fromBruger.Navn : "(Unknown)",
                DOC_SMTP_To = mailItemInfo.RecipientsEmailAddress,
                DOC_SMTP_ToDisplayName = mailItemInfo.RecipientsDisplayName,
                DOC_Subject = mailItemInfo.Subject,
                DOC_TaskGUID = taskInfo != null ? taskInfo.ID : new Nullable<Guid>(),
                DOC_TemplateGUID = null,
                DOC_Title = null, // Bruges vist ikke hvis mail
                DOC_ToUserGUID = toBruger != null ? toBruger.ID : new Nullable<Guid>(),
                DOC_TypeGUID = new Nullable<Guid>(), // BRUGES IKKE
                DOC_UpdatedByGUID = currentBruger.ID,
                DOC_UpdatedDate = DateTime.Now,
                DOC_WebVisible = 0,
                IsThrash = 0
            };

            using (var _dc = new iorunEntities())
            {
                _dc.Document.Add(mailItemDocument);

                _dc.SaveChanges();
            }

            return true;
        }
        public void GuessCompanyAndContact(MailItemInfo currentMailItemInfo)
        {
            string contactName;
            string contactEmaiAddress;
            string contactDomainName = string.Empty;

            if (currentMailItemInfo.IsInboxItem == true)
            {
                contactName = currentMailItemInfo.FromDisplayName;
                contactEmaiAddress = currentMailItemInfo.FromEmailAddress;
            }
            else
            {
                if (currentMailItemInfo.Recipients.Count > 0)
                {
                    var recipient = currentMailItemInfo.Recipients.First();

                    contactName = recipient.DisplayName;
                    contactEmaiAddress = recipient.Address;
                }
                else
                {
                    return;
                }
            }

            if (string.IsNullOrEmpty(contactEmaiAddress) && contactEmaiAddress.Contains('@'))
            {
                contactDomainName = contactEmaiAddress.Split(new char[] { '@' })[1];
            }

            var items = new List<KundeKontaktListViewitem>();

            customerContactsListView.SuspendLayout();
            customerContactsListView.Items.Clear();

            foreach (var thisKunde in IOfficeConnectGlobals.KunderCache)
            {
                foreach (var thisContact in thisKunde.Value.Kontakter)
                {
                    if (string.Equals(thisContact.Kontakt.WorkEmail1, contactEmaiAddress, StringComparison.InvariantCultureIgnoreCase) ||
                        string.Equals(thisContact.Kontakt.WorkEmail2, contactEmaiAddress, StringComparison.InvariantCultureIgnoreCase) ||
                        string.Equals(thisContact.Kontakt.WorkEmail3, contactEmaiAddress, StringComparison.InvariantCultureIgnoreCase) ||
                        string.Equals(thisContact.Kontakt.PrivateEmail, contactEmaiAddress, StringComparison.InvariantCultureIgnoreCase))
                    {
                        var lvi = new KundeKontaktListViewitem(thisKunde.Value.Navn);
                        lvi.SubItems.Add(thisContact.Kontakt.Navn);
                        lvi.SubItems.Add(thisContact.Kontakt.WorkEmail1);
                        lvi.Kunde = thisKunde.Value;
                        lvi.Kontakt = thisContact.Kontakt;

                        items.Add(lvi);
                    }
                }
            }

            if (items.Count > 0)
            {
                customerContactsListView.Items.AddRange(items.ToArray());

                customerContactsListView.Enabled = true;

                //customerContactsListView.Items[0].Selected = true;

                var selectIndex = customerContactsListView.Items.IndexOf(items.First());
                customerContactsListView.Items[selectIndex].Selected = true;
            }
            else
            {
                foreach (var thisKunde in IOfficeConnectGlobals.KunderCache)
                {
                    foreach (var thisContact in thisKunde.Value.Kontakter)
                    {
                        if (string.Equals(thisContact.Kontakt.Navn, contactName) ||
                            string.Equals(thisKunde.Value.Navn, contactName, StringComparison.InvariantCultureIgnoreCase) ||
                            string.Equals(thisKunde.Value.DomainName, contactDomainName, StringComparison.InvariantCultureIgnoreCase) ||
                            string.Equals(thisKunde.Value.EmailAddress, contactEmaiAddress, StringComparison.InvariantCultureIgnoreCase))
                        {
                            var lvi = new KundeKontaktListViewitem(thisKunde.Value.Navn);
                            lvi.SubItems.Add(thisContact.Kontakt.Navn);
                            lvi.SubItems.Add(thisContact.Kontakt.WorkEmail1);
                            lvi.Kunde = thisKunde.Value;
                            lvi.Kontakt = thisContact.Kontakt;

                            items.Add(lvi);
                        }
                    }
                }

                if (items.Count > 0)
                {
                    customerContactsListView.Items.AddRange(items.ToArray());

                    customerContactsListView.Enabled = true;

                    var selectIndex = customerContactsListView.Items.IndexOf(items.First());
                    customerContactsListView.Items[selectIndex].Selected = true;
                }
                else
                {
                    customerContactsListView.Items.Add(new ListViewItem("(Unknown contact, use company/contact search facility"));

                    customerContactsListView.Enabled = false;
                }
            }

            customerContactsListView.ResumeLayout();
        }