Add creation of contacts if needed OUT-401
authorThomas
Wed, 14 Feb 2018 16:42:43 +0100
branchOUT-401
changeset 2004 fef678d01f1f
parent 2003 c0dfc0f23c17
child 2005 d5fa428e94ea
Add creation of contacts if needed
PEPIdentity.cs
PEPMessage.cs
PEPSettings.cs
ThisAddIn.cs
--- a/PEPIdentity.cs	Tue Feb 13 15:18:56 2018 +0100
+++ b/PEPIdentity.cs	Wed Feb 14 16:42:43 2018 +0100
@@ -1452,11 +1452,11 @@
                     {
                         exchangeUser = true;
                     }
-                    /* SenderEmailType showed to be null in some occasions. Therefore, we need to 
-                     * doublecheck if this is an Exchange user.
-                     */
                     else if (omi.SenderEmailType == null)
                     {
+                        /* SenderEmailType showed to be null in some occasions. Therefore, we need to 
+                         * doublecheck if this is an Exchange user.
+                         */
                         try
                         {
                             // Exchange address types, see: https://msdn.microsoft.com/en-us/library/office/ff868214.aspx
@@ -1493,24 +1493,25 @@
                                     from.Address = exchSender.PrimarySmtpAddress;
                                     from.UserName = exchSender.Name;
 
-                                    // Add the contact force unencrypted property
+                                    // Add the contact if necessary
                                     try
                                     {
-                                        contact = exchSender.GetContact();
+                                        contact = exchSender.GetContact() ?? PEPIdentity.CreateContact(from.Address, from.UserName, "EX");
+                                        from.UserId = Globals.ThisAddIn.GetUserId(from.Address, contact);
+
+                                        // Read the contact's ForceUnencrypted property
+                                        from.IsForceUnencrypted = contact?.GetForceUnencrypted();
 
-                                        if (contact != null)
-                                        {
-                                            from.IsForceUnencrypted = contact.GetForceUnencrypted();
-                                            // Marshal.ReleaseComObject(contact);
-                                            contact = null;
-                                        }
+                                        status = Globals.ReturnStatus.Success;
                                     }
-                                    catch { }
-
-                                    // Add the user ID
-                                    from.UserId = Globals.ThisAddIn.GetUserId(from.Address, contact, sender);
-
-                                    status = Globals.ReturnStatus.Success;
+                                    catch (Exception ex)
+                                    {
+                                        Log.Error("GetFromIdentity: Error getting contact. " + ex.ToString());
+                                    }
+                                    finally
+                                    {
+                                        contact = null;
+                                    }
                                 }
                                 else
                                 {
@@ -1524,24 +1525,25 @@
                                 from.Address = (string)MapiHelper.GetProperty(sender, MapiProperty.PidTagSmtpAddress);
                                 from.UserName = sender.Name;
 
-                                // Add the contact force unencrypted property
+                                // Add the contact if necessary
                                 try
                                 {
-                                    contact = sender.GetContact();
+                                    contact = sender.GetContact() ?? PEPIdentity.CreateContact(from.Address, from.UserName, "EX");
+                                    from.UserId = Globals.ThisAddIn.GetUserId(from.Address, contact);
+
+                                    // Read the contact's ForceUnencrypted property
+                                    from.IsForceUnencrypted = contact?.GetForceUnencrypted();
 
-                                    if (contact != null)
-                                    {
-                                        from.IsForceUnencrypted = contact.GetForceUnencrypted();
-                                        // Marshal.ReleaseComObject(contact);
-                                        contact = null;
-                                    }
+                                    status = Globals.ReturnStatus.Success;
                                 }
-                                catch { }
-
-                                // Add the user ID
-                                from.UserId = Globals.ThisAddIn.GetUserId(from.Address, contact, sender);
-
-                                status = Globals.ReturnStatus.Success;
+                                catch (Exception ex)
+                                {
+                                    Log.Error("GetFromIdentity: Error getting contact. " + ex.ToString());
+                                }
+                                finally
+                                {
+                                    contact = null;
+                                }
                             }
                         }
                         catch
@@ -1561,24 +1563,25 @@
                         from.Address = omi.SenderEmailAddress;
                         from.UserName = omi.SenderName;
 
-                        // Add the contact force unencrypted property
+                        // Add the contact if necessary
                         try
                         {
-                            contact = sender.GetContact();
+                            contact = sender.GetContact() ?? PEPIdentity.CreateContact(from.Address, from.UserName);
+                            from.UserId = Globals.ThisAddIn.GetUserId(from.Address, contact);
+
+                            // Read the contact's ForceUnencrypted property
+                            from.IsForceUnencrypted = contact?.GetForceUnencrypted();
 
-                            if (contact != null)
-                            {
-                                from.IsForceUnencrypted = contact.GetForceUnencrypted();
-                                // Marshal.ReleaseComObject(contact);
-                                contact = null;
-                            }
+                            status = Globals.ReturnStatus.Success;
                         }
-                        catch { }
-
-                        // Add the user ID
-                        from.UserId = Globals.ThisAddIn.GetUserId(from.Address, contact, sender);
-
-                        status = Globals.ReturnStatus.Success;
+                        catch (Exception ex)
+                        {
+                            Log.Error("GetFromIdentity: Error getting contact. " + ex.ToString());
+                        }
+                        finally
+                        {
+                            contact = null;
+                        }
                     }
                 }
                 else if (omi.GetIsIncoming() == false) // Probably outgoing if sender is null
@@ -1601,30 +1604,10 @@
             }
             finally
             {
-                // Release objects
-                if (contact != null)
-                {
-                    // Marshal.ReleaseComObject(contact);
-                    contact = null;
-                }
-
-                if (sender != null)
-                {
-                    // Marshal.ReleaseComObject(sender);
-                    sender = null;
-                }
-
-                if (exchSender != null)
-                {
-                    // Marshal.ReleaseComObject(exchSender);
-                    exchSender = null;
-                }
-
-                if (sendingAccount != null)
-                {
-                    // Marshal.ReleaseComObject(sendingAccount);
-                    sendingAccount = null;
-                }
+                contact = null;
+                sender = null;
+                exchSender = null;
+                sendingAccount = null;
             }
 
             fromIdentity = from;
@@ -1632,6 +1615,34 @@
         }
 
         /// <summary>
+        /// Creates a ContactItem in the Outlook Address Book. Can return null.
+        /// </summary>
+        /// <param name="address">The address of the contact to create.</param>
+        /// <param name="userName">The user name of the contact to create.</param>
+        /// <param name="addressType">The address type of the contact to create. Optional.</param>
+        /// <returns>The created contact or null if an error occured.</returns>
+        private static Outlook.ContactItem CreateContact(string address, string userName, string addressType = null)
+        {
+            Outlook.ContactItem contact = null;
+
+            try
+            {
+                contact = Globals.ThisAddIn.Application.CreateItem(Outlook.OlItemType.olContactItem);
+                contact.Email1Address = address;
+                contact.FullName = userName;
+                contact.Email1AddressType = addressType;
+                contact.Save();
+            }
+            catch (Exception ex)
+            {
+                contact = null;
+                Log.Error("CreateContact: Error creating contact. " + ex.ToString());
+            }
+
+            return contact;
+        }
+
+        /// <summary>
         /// Gets the default from/sender identity using the default Outlook user.
         /// Warning: The result can be null.
         /// </summary>
@@ -1688,9 +1699,10 @@
         /// <param name="identity">The output pEp identity of the recipient (will never be null).</param>
         /// <returns>The status of the method.</returns>
         public static Globals.ReturnStatus Create(Outlook.Recipient recipient,
-                                                  out PEPIdentity identity)
+                                                  out PEPIdentity identity,
+                                                  bool addContact = false)
         {
-            string smtpAddress= null;
+            string smtpAddress = null;
             Outlook.AddressEntry addressEntry = null;
             PEPIdentity newIdent = null;
             Globals.ReturnStatus status = Globals.ReturnStatus.Success;
@@ -1712,7 +1724,7 @@
             // run through the full Create() method. If no address entry is available, create a new pEp identity from the recipient.
             if (addressEntry != null)
             {
-                status = Create(addressEntry, out newIdent);
+                status = Create(addressEntry, out newIdent, addContact);
             }
             else
             {
@@ -1757,7 +1769,8 @@
         /// <param name="identity">The output pEp identity of the address entry (will never be null).</param>
         /// <returns>The status of the method.</returns>
         public static Globals.ReturnStatus Create(Outlook.AddressEntry addressEntry,
-                                                  out PEPIdentity identity)
+                                                  out PEPIdentity identity,
+                                                  bool addContact = false)
         {
             bool identityCreated = false;
             bool? forceUnencryptedProperty = null;
@@ -1808,15 +1821,10 @@
             {
                 // Save contact for later user ID calculation
                 contact = addressEntry.GetContact();
-                if (contact != null)
-                {
-                    forceUnencryptedProperty = contact.GetForceUnencrypted();
-                }
             }
-            catch
-            {
-                forceUnencryptedProperty = null;
-            }
+            catch { }
+
+            forceUnencryptedProperty = contact?.GetForceUnencrypted();
 
             ///////////////////////////////////////////////////////////
             // Handle Outlook distribution lists
@@ -1856,7 +1864,7 @@
 
                             if (currentMember != null)
                             {
-                                sts = PEPIdentity.Create(currentMember, out member);
+                                sts = PEPIdentity.Create(currentMember, out member, addContact);
                                 newIdent.Members.Add(member);
 
                                 // Marshal.ReleaseComObject(currentMember);
@@ -1948,40 +1956,28 @@
                                     {
                                         currContact = exchUser.GetContact();
 
-                                        if (currContact != null)
+                                        if (contact == null && addContact)
                                         {
-                                            newIdent2.IsForceUnencrypted = currContact.GetForceUnencrypted();
+                                            currContact = PEPIdentity.CreateContact(newIdent2.Address, newIdent2.UserName);
                                         }
+
+                                        newIdent2.IsForceUnencrypted = currContact?.GetForceUnencrypted();
                                     }
                                     catch
                                     {
                                         currContact = null;
                                     }
 
-                                    newIdent2.UserId = Globals.ThisAddIn.GetUserId(newIdent2.Address, currContact, currAddressEntry);
+                                    newIdent2.UserId = Globals.ThisAddIn.GetUserId(newIdent2.Address, currContact);
                                     newIdent.Members.Add(newIdent2);
                                 }
                             }
                             catch { }
                             finally
                             {
-                                if (currAddressEntry != null)
-                                {
-                                    // Marshal.ReleaseComObject(currAddressEntry);
-                                    currAddressEntry = null;
-                                }
-
-                                if (exchUser != null)
-                                {
-                                    // Marshal.ReleaseComObject(exchUser);
-                                    exchUser = null;
-                                }
-
-                                if (currContact != null)
-                                {
-                                    // Marshal.ReleaseComObject(currContact);
-                                    currContact = null;
-                                }
+                                currAddressEntry = null;
+                                exchUser = null;
+                                currContact = null;
                             }
                         }
                     }
@@ -1991,35 +1987,11 @@
                 catch { }
                 finally
                 {
-                    if (exchDL != null)
-                    {
-                        // Marshal.ReleaseComObject(exchDL);
-                        exchDL = null;
-                    }
-
-                    if (exchDLMembers != null)
-                    {
-                        // Marshal.ReleaseComObject(exchDLMembers);
-                        exchDLMembers = null;
-                    }
-
-                    if (currAddressEntry != null)
-                    {
-                        // Marshal.ReleaseComObject(currAddressEntry);
-                        currAddressEntry = null;
-                    }
-
-                    if (exchUser != null)
-                    {
-                        // Marshal.ReleaseComObject(exchUser);
-                        exchUser = null;
-                    }
-
-                    if (currContact != null)
-                    {
-                        // Marshal.ReleaseComObject(currContact);
-                        currContact = null;
-                    }
+                    currContact = null;
+                    exchDL = null;
+                    exchDLMembers = null;
+                    currAddressEntry = null;
+                    exchUser = null;
                 }
             }
 
@@ -2079,18 +2051,8 @@
                 // As a fallback, get information from the associated contact
                 if (string.IsNullOrWhiteSpace(tempAddress))
                 {
-                    try
-                    {
-                        tempAddress = contact.Email1Address;
-                        tempUserName = contact.Email1DisplayName;
-                    }
-                    catch { }
-                }
-
-                // Add address if possible
-                if (string.IsNullOrWhiteSpace(tempAddress) == false)
-                {
-                    newIdent.Address = tempAddress.Trim();
+                    tempAddress = contact?.Email1Address;
+                    tempUserName = contact?.Email1DisplayName;
                 }
 
                 // Add user name if possible
@@ -2099,27 +2061,25 @@
                     newIdent.UserName = tempUserName.Trim();
                 }
 
-                // Get the unique user ID if possible
-                if (string.IsNullOrEmpty(newIdent.Address) == false)
+                // Add address if possible
+                if (string.IsNullOrWhiteSpace(tempAddress) == false)
                 {
-                    newIdent.UserId = Globals.ThisAddIn.GetUserId(newIdent.Address, contact, addressEntry);
+                    newIdent.Address = tempAddress.Trim();
+
+                    // Add contact if required
+                    if ((contact == null) &&
+                        addContact)
+                    {
+                        contact = PEPIdentity.CreateContact(newIdent.Address, newIdent.UserName);
+                    }
                 }
 
+                newIdent.UserId = Globals.ThisAddIn.GetUserId(newIdent.Address, contact);
+
                 identityCreated = true;
             }
 
-            // Free resources
-            if (addressEntry != null)
-            {
-                // Marshal.ReleaseComObject(addressEntry);
-                addressEntry = null;
-            }
-
-            if (contact != null)
-            {
-                // Marshal.ReleaseComObject(contact);
-                contact = null;
-            }
+            contact = null;
 
             identity = newIdent;
             return (status);
--- a/PEPMessage.cs	Tue Feb 13 15:18:56 2018 +0100
+++ b/PEPMessage.cs	Wed Feb 14 16:42:43 2018 +0100
@@ -2329,7 +2329,10 @@
 
             try
             {
-                Log.Verbose("PEPMessage.Create: Creating new PEPMessage from OMI started, calculating recipients.");
+                Log.Verbose("PEPMessage.Create: Creating new PEPMessage from OMI started.");
+
+                newMessage.Direction = omi.GetIsIncoming() ? pEpMsgDirection.pEpDirIncoming : pEpMsgDirection.pEpDirOutgoing;
+                Log.Verbose("PEPMessage.Create: direction calculated.");
 
                 // Calculate recipients
                 newMessage.Bcc.Clear();
@@ -2364,7 +2367,7 @@
                             }
                         case Outlook.OlMailRecipientType.olCC:
                             {
-                                sts = PEPIdentity.Create(currRecipient, out ident);
+                                sts = PEPIdentity.Create(currRecipient, out ident, (newMessage.Direction == pEpMsgDirection.pEpDirOutgoing));
                                 if (sts == Globals.ReturnStatus.Success)
                                 {
                                     newMessage.Cc.Add(ident);
@@ -2384,7 +2387,7 @@
                             }
                         case Outlook.OlMailRecipientType.olTo:
                             {
-                                sts = PEPIdentity.Create(currRecipient, out ident);
+                                sts = PEPIdentity.Create(currRecipient, out ident, (newMessage.Direction == pEpMsgDirection.pEpDirOutgoing));
                                 if (sts == Globals.ReturnStatus.Success)
                                 {
                                     newMessage.To.Add(ident);
@@ -2410,9 +2413,6 @@
 
                 Log.Verbose("PEPMessage.Create: Recipients calculated, calculating main properties.");
 
-                newMessage.Direction = omi.GetIsIncoming() ? pEpMsgDirection.pEpDirIncoming : pEpMsgDirection.pEpDirOutgoing;
-                Log.Verbose("PEPMessage.Create: direction calculated.");
-
                 if (onlyRecipientsAndDirection == false)
                 {
                     // From
@@ -2433,7 +2433,7 @@
                     }
                     Log.Verbose("PEPMessage.Create: From identity calculated.");
 
-                    newMessage.Id = (string)MapiHelper.GetProperty(omi, MapiProperty.PidTagInternetMessageId, "");
+                    newMessage.Id = MapiHelper.GetProperty(omi, MapiProperty.PidTagInternetMessageId, "") as string;
                     newMessage.ShortMsg = omi.Subject;
 
                     /* Date & Times
--- a/PEPSettings.cs	Tue Feb 13 15:18:56 2018 +0100
+++ b/PEPSettings.cs	Wed Feb 14 16:42:43 2018 +0100
@@ -30,7 +30,7 @@
             AllMessages
         }
 
-        public const string PEP_OWN_USER_ID                                     = "pEpForOutlook_pEp_own_userId";
+        public const string PEP_OWN_USER_ID                                     = "pEp_own_userId";
 
         public const string REG_KEY_SOFTWARE                                    = "Software";
         public const string REG_KEY_PEP                                         = "pEp";
--- a/ThisAddIn.cs	Tue Feb 13 15:18:56 2018 +0100
+++ b/ThisAddIn.cs	Wed Feb 14 16:42:43 2018 +0100
@@ -593,12 +593,9 @@
         /// <param name="address">The address to get the user ID for.</param>
         /// <param name="contact">The contact associated with the address (if any).
         /// This value can be null and is not required for 'myself' user IDs.</param>
-        /// <param name="addressEntry">The addressEntry associated with the address (if any).
-        /// This value can be null and is not required for 'myself' user IDs.</param>
         /// <returns>The user ID (Outlook EntryID) for the given address</returns>
         internal string GetUserId(string address,
-                                  Outlook.ContactItem contact = null,
-                                  Outlook.AddressEntry addressEntry = null)
+                                  Outlook.ContactItem contact = null)
         {
             string id = null;
             Outlook.Folder contactFolder = null;
@@ -637,8 +634,7 @@
                     {
                         try
                         {
-                            contactFolder = (Outlook.Folder)contact.Parent;
-                            id = contactFolder.StoreID.ToUpperInvariant() + "_" + contact.EntryID.ToUpperInvariant();
+                            id = contact.EntryID;
                             this.userIdCache[address] = id;
                         }
                         catch
@@ -646,14 +642,6 @@
                             Log.Error("GetUserId: Attempted to use contact but failed.");
                         }
                     }
-
-                    // Use the addressEntry ID if available
-                    if ((id == null) &&
-                        (addressEntry != null))
-                    {
-                        id = addressEntry.ID;
-                        this.userIdCache[address] = id;
-                    }
                 }
             }
             catch (Exception ex)