Reputation: 526
I am trying to load the Exchange Web Services DLL at runtime and connect to a mailbox. I am following this guide: Using Reflection to load unreferenced assemblies at runtime in C# The code so far:
var DLL = Assembly.LoadFile(@"Microsoft.Exchange.WebServices.dll");
var theType = DLL.GetType("Microsoft.Exchange.WebServices.Data.ExchangeService");
var c = Activator.CreateInstance(theType);
var method = theType.GetMethod("AutodiscoverUrl");
method.Invoke(c, new object[] { @"[email protected]" });
After that code I am lost. How do I use the ExchangeService to bind a Mailbox object using a FolderId? EWS Managed API is not an option for my server and application.
This is the Powershell script equivalent code that I am trying to implement in ASP.NET:
$MailboxName = "account@domain"
$dllpath = "Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
$service.AutodiscoverUrl("[email protected]")
$mbfolderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$MailboxName)
$MsgRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$mbfolderid)
Upvotes: 1
Views: 5145
Reputation: 14956
Using reflection is tedious. You are on the right track though. The following code shows how you can bind to the "Inbox" folder and get the subjects of the first 10 email messages.
Notice how I use the dynamic
keyword so I do not have to call MethodInfo.Invoke
to call instance methods on the reflected types.
string mailboxName = "...";
// Get value for enum WellKnownFolderName.Inbox.
var wellKnownFolderNameType = assem.GetType("Microsoft.Exchange.WebServices.Data.WellKnownFolderName");
var rootFolderName = wellKnownFolderNameType
.GetField("Inbox")
.GetValue(null)
;
// Create requested mailbox and folderid for Inbox-folder for the requested mailbox.
var mailboxType = assem.GetType("Microsoft.Exchange.WebServices.Data.Mailbox");
dynamic mailbox = Activator.CreateInstance(mailboxType, new object[] { mailboxName });
var folderIdType = assem.GetType("Microsoft.Exchange.WebServices.Data.FolderId");
dynamic folderId = Activator.CreateInstance(folderIdType, rootFolderName, mailbox);
// Bind to the Inbox-folder for the requested mailbox.
var folderType = assem.GetType("Microsoft.Exchange.WebServices.Data.Folder");
var bindMethod = folderType.GetMethod("Bind", new Type[] { serviceType, folderIdType });
dynamic folder = bindMethod.Invoke(null, new object[] { service, folderId });
// Get 10 first mailitems
var itemViewType = assem.GetType("Microsoft.Exchange.WebServices.Data.ItemView");
dynamic itemView = Activator.CreateInstance(itemViewType, 10);
dynamic findItemsResults = folder.FindItems(itemView);
foreach (dynamic item in findItemsResults.Items)
{
Console.WriteLine((string) item.Subject);
}
Upvotes: 2