I get the following error after deploying my Word Document add-in. The Addin
retrieves Outlook Contacts and add's
them to a Word template. Everything works fine on my development machine.
Unable to cast COM object of type 'System.__ComObject' to interface type
'Microsoft.Office.Interop.Outlook.ContactItem'.
This is the code:
//contacten ophalen uit Outlook en in Datatable zetten
Outlook.Application oApp = new
Microsoft.Office.Interop.Outlook.Application();
Outlook.NameSpace ns = oApp.Session;
ns.Logon(Missing.Value, Missing.Value, false, true);
Outlook.MAPIFolder oContacts;
Outlook.Items oItems;
Outlook.MAPIFolder RootContactsFolder =
ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
string RootFolder = RootContactsFolder.Name;
if ((folder == "") || (folder == RootFolder))
{
// Get the default Contacts folder.
oContacts = RootContactsFolder;
// Get the Items collection from the folder.
oItems = oContacts.Items;
}
else
{
//contactpersonen uit submap halen en foldernaam meegeven
oContacts = RootContactsFolder;
oItems = oContacts.Items;
}
DataTable _dt = new DataTable("OutlookContacts");
_dt.Columns.Add("Title");
_dt.Columns.Add("FirstName");
_dt.Columns.Add("LastName");
_dt.Columns.Add("CompanyName");
_dt.Columns.Add("BusinessAddressStreet");
_dt.Columns.Add("BusinessAddressPostalCode");
_dt.Columns.Add("BusinessAddressCity");
_dt.Columns.Add("BusinessAddressCountry");
_dt.Columns.Add("Email");
//contactpersonen toevoegen aan datatable en teruggeven.
try
{
foreach (Outlook.ContactItem OlContact in oItems)
{
_dt.Rows.Add(OlContact.Title, OlContact.FirstName,
OlContact.LastName, OlContact.CompanyName,
OlContact.BusinessAddressStreet,
OlContact.BusinessAddressPostalCode,
OlContact.BusinessAddressCity,
OlContact.BusinessAddressCountry,
OlContact.Email1Address);
}
return _dt;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
return null;
}
Regards Silvia
As Ken Slovak, MVP - Outlook explained it to me, each object you create
opens an RPC connection to the exchange server and that connection may not be
released until the method/scope ends or you explicitly release the object. I
fixed my problem with code like the following:
Pseudo/real code
…iterator code (i) - over the Outlook.MAPIFolder. myItem is an
Outlook.PostItem (ContactItem' in your case) , from the folder's Items
collection
//Do your stuff...
// Resource Cleanup
System.Runtime.InteropServices.Marshal.ReleaseComObject(myItem);
if (i % 200 == 0) // Force garbage collection after every 200 items
{
GC.Collect();
}
… end iterator
Good luck!!