Using PowerShell and .NET to Construct a DirectorySearcher

NOTE: This post – drafted, composed, written, and published by me – originally appeared on https://blogs.technet.microsoft.com/johnbai and is potentially (c) Microsoft.

PowerShell and .NET are very interoperable and can help to save time, when you’re performing generic, every day tasks. For example, let’s say that I want to create a Date-Time value that’s thirty minutes ago and one for right now, we can do this in one fell swoop in Exchange Management Shell (read: PowerShell):

v2: Get-MessageTrackingLog -Start [System.DateTime]::Now.AddMinutes(-30) -End [System.DateTime]::Now

v3: Get-MessageTrackingLog -Start ([System.DateTime]::Now).AddMinutes(-30) -End ([System.DateTime]::Now)

As you can see, the syntax changes slightly but the methods are the same because they derive from the same .NET class.

Below, I demonstrate constructing a DirectorySearcher object for a specific case. The final script is published on OneScript, here, but I wanted to demonstrate that we can use PowerShell + .NET to solve some complex problems in a rather easy way.

============================================================================================================================================

In rare cases, removal of an Exchange Server from the forest doesn’t go according to plan and, without Exchange Management Shell (EMS), finding servers via Active Directory might be a bit of a pain-point. Enter DirectorySearcher.

Here is an example, finding Exchange 2013 mailbox servers in the forest:

$colMBX = @()
$CurrentDomain = [System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain()
$ForestName = $CurrentDomain.Forest.Name
$ForestDC = $ForestName.Replace(“.”,”,DC=”)
$ForestLDAP = [ADSI]”LDAP://CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=$ForestDC”
$orgName = $ForestLDAP.psbase.children | where {$_.objectClass -eq ‘msExchOrganizationContainer’}
$Path = “LDAP://CN=Servers,CN=Exchange Administrative Group (FYDIBOHF23SPDLT),CN=Administrative Groups,CN=” + $orgName.Name + “,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=” + $ForestDC
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.Filter = ‘(&(&(&(objectCategory=msExchExchangeServer)(msExchCurrentServerRoles:1.2.840.113556.1.4.803:=54)(serialNumber=*15*))))’
$Searcher.PageSize = 10000
$Searcher.SearchScope = “OneLevel”
$Searcher.PropertiesToLoad.Add(“Name”) | Out-Null
$Searcher.SearchRoot = $Path
$ServerResult = $Searcher.FindAll()
foreach ($result in $ServerResult)
{
       $colMBX += $result.Properties.name[0]
}
$colMBX

You’ll notice that in the filter we’re using the numeric value ‘1.2.840.113556.1.4.803’ between the attribute and the value we’re seeking. This OID is an Extensible Matching Rule for the bitwise operator AND, which may also be referred to as ‘LDAP_MATCHING_RULE_BIT_AND‘. It is not required for use in your filter but does follow RFC convention.

In Exchange 2013, for Mailbox servers we can use the value ’54’ to search and for CAS servers we can use the value ‘16385’.

To explain the values, we can demonstrate via table:

Server role Role value
Mailbox role 2
Client Access role (CAS) 4
Unified Messaging role 16
Hub Transport role 32

The Mailbox role now has the previous roles in one server, so 2 + 4 + 16 + 32 = 54.

You can read more on PowerShell + DirectorySearcher here: http://technet.microsoft.com/en-us/library/ff730967.aspx

Exchange2013: Testing MRS Across A DAG

NOTE: This post – drafted, composed, written, and published by me – originally appeared on https://blogs.technet.microsoft.com/johnbai and is potentially (c) Microsoft.

In Exchange 2013, it may become necessary to test the Mailbox Replication Service (MRS) against all members of a Database Availability Group (DAG). To do this, we can perform the following script:

#We obtain the member servers of the DAG
$Servers = ((Get-DatabaseAvailabilityGroup LAB-NAEX15-01).Servers).Name
#We perform a ‘foreach’ against each member
foreach($server in $Servers)
{

Write-Host -ForegroundColor Green $server.Name
Test-MRSHealth -Identity $server -MonitoringContext:$TRUE

}

When we perform the above script, we should receive output like the following:

PERSEPHONE
RunspaceId  : b14e1547-c215-4dbb-8ee1-a3c4978ca7c3
Check       : ServiceCheck
Passed      : True
Message     : The Mailbox Replication Service is running.
Identity    : PERSEPHONE
IsValid     : True
ObjectState : New

RunspaceId  : b14e1547-c215-4dbb-8ee1-a3c4978ca7c3
Check       : RPCPingCheck
Passed      : True
Message     : The Microsoft Exchange Mailbox Replication service is responding to a RPC ping. Server version: 15.0.712.11 caps:3F.
Identity    : PERSEPHONE
IsValid     : True
ObjectState : New

RunspaceId  : b14e1547-c215-4dbb-8ee1-a3c4978ca7c3
Check       : QueueScanCheck
Passed      : True
Message     : The Microsoft Exchange Mailbox Replication service is scanning mailbox database queues for jobs. Last scan age: 00:14:22.0340000.
Identity    : PERSEPHONE
IsValid     : True
ObjectState : New

RunspaceId          : b14e1547-c215-4dbb-8ee1-a3c4978ca7c3
Events              : {Source: MSExchange Monitoring MRSHealth
                      Id: 1000
                      Type: Success
                      Message: MRSHealth check passed.}
PerformanceCounters : {Object: MSExchange Monitoring MRSHealth
                      Counter: Last Scan Age (secs)
                      Instance: PERSEPHONE
                      Value: 862}

MINERVA
RunspaceId  : b14e1547-c215-4dbb-8ee1-a3c4978ca7c3
Check       : ServiceCheck
Passed      : True
Message     : The Mailbox Replication Service is running.
Identity    : MINERVA
IsValid     : True
ObjectState : New

RunspaceId  : b14e1547-c215-4dbb-8ee1-a3c4978ca7c3
Check       : RPCPingCheck
Passed      : True
Message     : The Microsoft Exchange Mailbox Replication service is responding to a RPC ping. Server version: 15.0.712.11 caps:3F.
Identity    : MINERVA
IsValid     : True
ObjectState : New

RunspaceId  : b14e1547-c215-4dbb-8ee1-a3c4978ca7c3
Check       : QueueScanCheck
Passed      : True
Message     : The Microsoft Exchange Mailbox Replication service is scanning mailbox database queues for jobs. Last scan age: 00:03:35.9990000.
Identity    : MINERVA
IsValid     : True
ObjectState : New

RunspaceId          : b14e1547-c215-4dbb-8ee1-a3c4978ca7c3
Events              : {Source: MSExchange Monitoring MRSHealth
                      Id: 1000
                      Type: Success
                      Message: MRSHealth check passed.}
PerformanceCounters : {Object: MSExchange Monitoring MRSHealth
                      Counter: Last Scan Age (secs)
                      Instance: MINERVA
                      Value: 215}

CHARON
RunspaceId  : b14e1547-c215-4dbb-8ee1-a3c4978ca7c3
Check       : ServiceCheck
Passed      : True
Message     : The Mailbox Replication Service is running.
Identity    : CHARON
IsValid     : True
ObjectState : New

RunspaceId  : b14e1547-c215-4dbb-8ee1-a3c4978ca7c3
Check       : RPCPingCheck
Passed      : True
Message     : The Microsoft Exchange Mailbox Replication service is responding to a RPC ping. Server version: 15.0.516.29 caps:3F.
Identity    : CHARON
IsValid     : True
ObjectState : New

RunspaceId  : b14e1547-c215-4dbb-8ee1-a3c4978ca7c3
Check       : QueueScanCheck
Passed      : True
Message     : The Microsoft Exchange Mailbox Replication service is scanning mailbox database queues for jobs. Last scan age: 00:07:23.1520000.
Identity    : CHARON
IsValid     : True
ObjectState : New

RunspaceId          : b14e1547-c215-4dbb-8ee1-a3c4978ca7c3
Events              : {Source: MSExchange Monitoring MRSHealth
                      Id: 1000
                      Type: Success
                      Message: MRSHealth check passed.}
PerformanceCounters : {Object: MSExchange Monitoring MRSHealth
                      Counter: Last Scan Age (secs)
                      Instance: CHARON
                      Value: 443}

AGAMEMNON
RunspaceId  : b14e1547-c215-4dbb-8ee1-a3c4978ca7c3
Check       : ServiceCheck
Passed      : True
Message     : The Mailbox Replication Service is running.
Identity    : AGAMEMNON
IsValid     : True
ObjectState : New

RunspaceId  : b14e1547-c215-4dbb-8ee1-a3c4978ca7c3
Check       : RPCPingCheck
Passed      : True
Message     : The Microsoft Exchange Mailbox Replication service is responding to a RPC ping. Server version: 15.0.712.11 caps:3F.
Identity    : AGAMEMNON
IsValid     : True
ObjectState : New

RunspaceId  : b14e1547-c215-4dbb-8ee1-a3c4978ca7c3
Check       : QueueScanCheck
Passed      : True
Message     : The Microsoft Exchange Mailbox Replication service is scanning mailbox database queues for jobs. Last scan age: 00:07:51.9760000.
Identity    : AGAMEMNON
IsValid     : True
ObjectState : New

RunspaceId          : b14e1547-c215-4dbb-8ee1-a3c4978ca7c3
Events              : {Source: MSExchange Monitoring MRSHealth
                      Id: 1000
                      Type: Success
                      Message: MRSHealth check passed.}
PerformanceCounters : {Object: MSExchange Monitoring MRSHealth
                      Counter: Last Scan Age (secs)
                      Instance: AGAMEMNON
                      Value: 471}

 

Exchange 2013: ‘Get-AgentLog’ Throws Exception When Run From The Front End

NOTE: This post – drafted, composed, written, and published by me – originally appeared on https://blogs.technet.microsoft.com/johnbai and is potentially (c) Microsoft.

During the investigation of a not-so-recent case, it was discovered that Get-AgentLog – when run from a Front-End server – will throw an exception. What occurs is that when you attempt to run the command from EMS, you receive a notice about an exception and that a Watson dump is being generated; however, no Watson dump can be found on the server and there are no events in the Application or Crimson Logs:

Get-AgentLog -TransportService FrontEnd -StartDate ([System.DateTime]::Now).AddDays(-4) -EndDate ([System.DateTime]::Now)
WARNING: An unexpected error has occurred and a Watson dump is being generated: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
Specified cast is not valid.
    + CategoryInfo          : NotSpecified: (:) [Get-AgentLog], InvalidCastException
    + FullyQualifiedErrorId : System.InvalidCastException,Microsoft.Exchange.Management.AgentLog.GetAgentLog
    + PSComputerName        : <Server>

If you attempt to specify the location, you receive an error that the location cannot be found (note the fully qualified error):

VERBOSE: Connecting to <Server>
VERBOSE: Connected to <Server>.
Get-AgentLog -TransportService FrontEnd -StartDate ([System.DateTime]::Now).AddDays(-4) -EndDate ([System.DateTime]::Now) -Location “C:\exchsrvr\TransportRoles\Logs\FrontEnd\AgentLog\”
The location “C:\exchsrvr\TransportRoles\Logs\FrontEnd\AgentLog” does not exist. Please specify a valid file or directory to look for agent logs using the -Location parameter.
Parameter name: Location
    + CategoryInfo          : InvalidArgument: (:) [Get-AgentLog], ArgumentException
    + FullyQualifiedErrorId : [Server=<Server2>,RequestId=5b8d0c5b-6b0b-4b7d-ad94-008aab18485c,TimeStamp=11/27/2013 11:15:48 PM] 97084C54,Microsoft.Exchange.Management.AgentLog.GetAgentLog
    + PSComputerName        : <Server>

In the stack, you would see that the exception is a CLR exception, due to a conversion:

KERNELBASE!RaiseException+0x39
clr!RaiseTheExceptionInternalOnly+0x28b
clr!IL_Throw+0xe3
System_Management_Automation_ni!System.Management.Automation.LanguagePrimitives.ConvertStringToType(System.Object, System.Type, Boolean, System.Management.Automation.PSObject, System.IFormatProvider, System.Management.Automation.Runspaces.TypeTable)+0x126e67e

_message:00000000054d6638 (System.String) Length=89, String=”Cannot convert the “switchAttribute” value of type “System.String” to type “System.Type”.”
_HResult:0x80004002 (System.Int32)
errorId:0000000002d09190 (System.String) Length=27, String=”InvalidCastFromStringToType”

The cause: In Exchange 2013, commands are proxied from the Frontend Server (CAS) to a Backend Server (Mailbox). This is the reason that Server2 shows up in the Fully Qualified Error, when the command is run from Server.

The work-around is to open Windows PowerShell and add the PSSnapin (this bypasses command proxying). Then, you will receive the necessary output, sans any exceptions occurring.

Get-AgentLog -TransportService FrontEnd -StartDate ([System.DateTime]::Now).AddDays(-30) -EndDate ([System.DateTime]::Now) | FT -AutoSize

Timestamp             SessionId        IPAddress   MessageId P1FromAddress     P2FromAddresses    Recipients    Agent                Event              Action

———             ———        ———   ——— ————-     —————    ———-    —–                —–              ——

11/21/2013 8:47:25 PM 08D0B544432ACF98 <Redacted>             <Redacted>        <Redacted>        <Redacted>     Inbound Trust Agent   OnEndOfHeaders    ModifyHeaders

11/21/2013 8:47:25 PM 08D0B544432ACF98 <Redacted>             <Redacted>         <Redacted>         <Redacted>     Inbound Trust Agent   OnEndOfHeaders    ModifyHeaders

11/21/2013 8:48:27 PM 08D0B544432ACF9A <Redacted>             <Redacted>         <Redacted>         <Redacted>     Inbound Trust Agent   OnEndOfHeaders    ModifyHeaders

11/21/2013 8:48:27 PM 08D0B544432ACF9A <Redacted>             <Redacted>         <Redacted>         <Redacted>     Inbound Trust Agent   OnEndOfHeaders    ModifyHeaders

You can read more about this at these sites:

http://blogs.msdn.com/b/dvespa/archive/2013/02/21/install-error-transport-agents-exchange-2013-powershell.aspx

http://technet.microsoft.com/en-us/library/bb125175.aspx

O365: Manual Outlook Profile Creation in Wave 15

NOTE: This post – drafted, composed, written, and published by me – originally appeared on https://blogs.technet.microsoft.com/johnbai and is potentially (c) Microsoft.

After the migration to Wave 15, Tenant Admins may find it necessary to create manual Outlook profiles; primarily, for troubleshooting and reproducing issues. It should be important to note that this is not a fully supported scenario but there are some steps available, if manual profile creation is required.

Server: mailbox.outlook.com
User: <User for the Profile>
Logon Network Security: Anonymous Authentication
Proxy Connection URL: outlook.office365.com
Principal Name for Certificates: msstd:outlook.com

Again, this is only for manual profile creation for Tenant Admins, as your CNAME should point to Autodiscover and it should take over the Outlook Profile Creation via Autoconfigure from the User’s ActiveDirectory attributes.

O365: On-Premises Transport Queuing Lessons Learned from CBL

NOTE: This post – drafted, composed, written, and published by me – originally appeared on https://blogs.technet.microsoft.com/johnbai and is potentially (c) Microsoft.

I recently had a case where on-premises Transport had Queues that were ‘stuck’ going to the cloud. Specifically, they were going to Exchange Online Protection for routing from on-premises to cloud mailboxes. The on-premises transport servers were generating errors, in a unique way. For example, this is what we saw from the Queues in PowerShell:

(Get-TransportServer | Get-Queue | Where{$_.NextHopDomain -ilike ‘<cloud domain>’}  | Select LastError -Unique).LastError

451 4.4.0 Primary target IP address responded with: “451 5.7.3 Must issue a STARTTLS command first.” Attempted failover to alternate host, but that did not succeed. Either there are no alternate hosts, or delivery failed to all alternate hosts.

This error is highly deceptive because it could be inferred that the client is not issuing a STARTTLS to the remote endpoint in the cloud; however, when we looked at the SMTP Send protocol logs, we could clearly see the inverse was true:

<Server>.mail.protection.outlook.com Microsoft ESMTP MAIL Service ready at Fri, 6 Dec 2013 21:54:51 +0000″,
2013-12-06T21:54:51.891Z,Outbound to Office 365,08D0C0DE40C1BF74,3,x.x.x.x:64526,x.x.x.x:25,>,EHLO <on-premises domain>,
2013-12-06T21:54:52.001Z,Outbound to Office 365,08D0C0DE40C1BF74,4,x.x.x.x:64526,x.x.x.x:25,<,250-<Server>.mail.protection.outlook.com Hello [External I.P. Address of Client],
2013-12-06T21:54:52.001Z,Outbound to Office 365,08D0C0DE40C1BF74,5,x.x.x.x:64526,x.x.x.x:25,<,250-SIZE 157286400,
2013-12-06T21:54:52.001Z,Outbound to Office 365,08D0C0DE40C1BF74,6,x.x.x.x:64526,x.x.x.x:25,<,250-PIPELINING,
2013-12-06T21:54:52.001Z,Outbound to Office 365,08D0C0DE40C1BF74,7,x.x.x.x:64526,x.x.x.x:25,<,250-DSN,
2013-12-06T21:54:52.001Z,Outbound to Office 365,08D0C0DE40C1BF74,8,x.x.x.x:64526,x.x.x.x:25,<,250-ENHANCEDSTATUSCODES,
2013-12-06T21:54:52.001Z,Outbound to Office 365,08D0C0DE40C1BF74,9,x.x.x.x:64526,x.x.x.x:25,<,250-AUTH,
2013-12-06T21:54:52.001Z,Outbound to Office 365,08D0C0DE40C1BF74,10,x.x.x.x:64526,x.x.x.x:25,<,250-8BITMIME,
2013-12-06T21:54:52.001Z,Outbound to Office 365,08D0C0DE40C1BF74,11,x.x.x.x:64526,x.x.x.x:25,<,250-BINARYMIME,
2013-12-06T21:54:52.001Z,Outbound to Office 365,08D0C0DE40C1BF74,12,x.x.x.x:64526,x.x.x.x:25,<,250 CHUNKING,
2013-12-06T21:54:52.001Z,Outbound to Office 365,08D0C0DE40C1BF74,13,x.x.x.x:64526,x.x.x.x:25,*,,Connector is configured to send mail only over TLS connections and remote doesn’t support TLS
2013-12-06T21:54:52.001Z,Outbound to Office 365,08D0C0DE40C1BF74,14,x.x.x.x:64526,x.x.x.x:25,>,QUIT,

Ah, so the STARTTLS command is not available from the remote endpoint. Since TLS is required for this send connector, this is why we’re queuing.

Let’s double-check our math and our sanity, really quick. I use nslookup to query for the MX record of the cloud domain and telnet to port 25 on one of the I.P. addresses. So far, so good. I issue ‘EHLO <on-premises domain>’ and get this response:

<I.P. Address> – 220 <Server>.mail.protection.outlook.com Microsoft ESMTP MAIL Service ready at Fri, 6 Dec 2013 22:01:59 +0000
EHLO <on-premises domain> 250-<Server>.mail.protection.outlook.com Hello [External I.P. Address of Client]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-AUTH
250-8BITMIME
250-BINARYMIME
250 CHUNKING

Sure enough, ‘STARTTLS’ isn’t an available ESMTP verb. O.k., but why?

Well, as it turns out, we use public block lists and this company was cited by CBL for RWBL and XBL; specifically, Pushdo was being used to perform a DDoS against port 80 on webservers from an infected machine behind their public I.P. address.

As soon as they were listed, we removed STARTTLS (and other ESMTP verbs).

The customer discovered it was probably a visitor (CBL lists time of last activity) and as it had been over 8 hours, delisted themselves. Immediately, TLS was available for use, again.

O365: PST Export Tool Issue and Possible Resolution[s]

NOTE: This post – drafted, composed, written, and published by me – originally appeared on https://blogs.technet.microsoft.com/johnbai and is potentially (c) Microsoft.

It has been discovered that some customers experience a problem with the PST export tool in the Wave15 version of the cloud. Specifically, the symptom is:

When a Tenant Admin attemptsto download the PST file, he or she receives “Microsoft.Exchange.eDiscovery.ExportTool.exe has stopped working” and their only option is to terminate the process.

This can be resolved in one of two ways:

1. Add outlook.com and office.com to trusted sites in Internet Explorer.

2. Install the .NET 4.5 package.

This should resolve the issue with the PST export tool.

 

Special thanks to mbarta for the tip!

DAGs: When Installing Them Becomes A Chore

NOTE: This post – drafted, composed, written, and published by me – originally appeared on https://blogs.technet.microsoft.com/johnbai and is potentially (c) Microsoft.

I had a lab and I was running into a problem building a Database Availability Group (DAG). I had installed Exchange 2013 Mailbox Role on 3 Windows Server 2008 R2 Standard machines. I was receiving the following error:

A database availability group administrative operation failed. Error: Failed to add or remove the Failover-Clustering feature. Error: ArgumentNotValid: invalid role, role service or feature: ‘Failover-Clustering;. The name was not found.

Well, as it turns out, you cannot install clustering on a Standard Server, it must be Enterprise or Datacenter. Luckily enough, a tool – Deployment Imaging Service Management (DSIM) Utiltiy – can come to our rescue. We can use elevated command prompts to convert our server versions to the desired/needed version and continue installing our DAG members. It’s important to note two things: 1.) The keys for conversion come from Key Management Services (KMS). 2.) You will still need a product key for activation, after the conversion.

To convert from Standard to Enterprise edition:

DISM /online /Set-Edition:ServerEnterprise /ProductKey:489J6-VHDMP-X63PK-3K798-CPX3Y

To convert from the Standard to Datacenter edition:

DISM /online /Set-Edition:ServerDatacenter /ProductKey:74YFP-3QFB3-KQT8W-PMXWJ-7M648

Now, you can install your DAG members and enjoy High Availability.

RBAC: Associating a Command With a Specific Groups

NOTE: This post – drafted, composed, written, and published by me – originally appeared on https://blogs.technet.microsoft.com/johnbai and is potentially (c) Microsoft.

In some scenarios, it becomes prudent to know what Role is able to run which command. We can found out which groups are able to run which commands via the following syntax:

Get-ManagementRoleEntry *\<command>

For example, if you wanted to know who could run ‘Get-CalendarDiagnosticLog’, you would run the following command:

Get-ManagementRoleEntry *\Get-CalendarDiagnosticLog

If you want to check a list of commands, such as when you’re following official documentation, you can create a text file with each command on a separate line and obtain a list of groups:

Get-Content .\CMDs.txt | ForEach-Object{Write-Host -ForegroundColor Green $_;Get-ManagementRoleEntry *\$_ | FT -AutoSize}

O365 & EWS: EmailMessage.SetExtendedProperty() Introduces Undesirable Behavior for Cloud

NOTE: This post – drafted, composed, written, and published by me – originally appeared on https://blogs.technet.microsoft.com/johnbai and is potentially (c) Microsoft.

In Office 365, there is a known issue where Item.SetExtendedProperty() will prevent ResponseMessage.SendAndSaveCopy() from working correctly. Instead of sending the messaging and placing the item in the ‘Sent Items’ folder, the message will be sent and remain in the ‘Drafts’ folder.

This issue can be corrected by changing the source code of the EWS application in either of the following two ways:

1. Specify the ‘Sent Items’ folder via passing ‘SENTFOLDEREWSID‘ in the method (Note: WellKnownFolderName.SentItems will not work for this case):

var messageToSend = responseMessage.Save();

// This is our method that is introducing our repro scenario in O365.
messageToSend.SetExtendedProperty(newExtendedPropertyDefinition(newGuid(“{00000000-0000-0000-0000-000000000000}”), “<String>”, MapiPropertyType.String), 1);

// Send and save a copy of the replied email mesage in the default Sent Items folder.
messageToSend.SendAndSaveCopy(SENTFOLDEREWSID);

 

2. Use Item.Update() before the SendAndSaveCopy() method:

 var messageToSend = responseMessage.Save();

// This is our method that is introducing our repro scenario for the cloud.
messageToSend.SetExtendedProperty(newExtendedPropertyDefinition(newGuid(“{00000000-0000-0000-0000-000000000000}”), “<String>”, MapiPropertyType.String), 1);

// We update the item before sending it.
messageToSend.Update(ConflictResolutionMode.AlwaysOverwrite);

// Send and save a copy of the replied email mesage in the default Sent Items folder.
messageToSend.SendAndSaveCopy();

 

With this, you should be able to work-around this EWS issue until a fix is found. Happy coding!

 

Attached, you will find the repro code with the fix (Program.cs).

Program.cs

EWS: Obtaining Mail Item from List

NOTE: This post – drafted, composed, written, and published by me – originally appeared on https://blogs.technet.microsoft.com/johnbai and is potentially (c) Microsoft.

In troubleshooting an issue for a customer, I ran into a problem: I could obtain the data from the MAPI store (via EWS) but I was unable to figure out how to cast from the list of items obtained to an actual message to action against.

For example, here’s where I was attempting to obtain the items from the MAPI container:

Console.WriteLine(“Connecting to EWS endpoint…”);
ExchangeService ExService = newExchangeService(ExchangeVersion.Exchange2007_SP1);
ExService.Credentials = new WebCredentials(targetMBX, passWord);
ExService.AutodiscoverUrl(targetMBX, RedirectionUrlValidationCallback);

// Obtain the message to reply to.
ItemView iv = new ItemView(3);
FindItemsResults<Item> zeitem = ExService.FindItems(WellKnownFolderName.Inbox, iv);

As you can see, we’re calling FindItems and returning it as a collection of Items. I thought a cast would have to occur, to convert the Item back into an EmailMessage. Instead, as one would be happy to find out  as I was, the Item is an encapsulation of the EmailMessage and we can ‘extract’ it via an array call:

var item = zeitem.Items[0];

From this, we can further action against the mail items via EWS:

if (item is EmailMessage)
{

      Console.WriteLine(“Working with the first item found.”);

   // Reply to the message
ResponseMessage responseMessage = message.CreateReply(replyToAll);
string myReply = “This is a test of the EWS responseMessage method[s].”;
responseMessage.BodyPrefix = myReply;
var messageToSend = responseMessage.Save();

// Send and save a copy of the replied email message in the default Sent Items folder.
messageToSend.SendAndSaveCopy();
}

Using the EWS API, one can do many powerful and important administrative tasks in Exchange. You can read more about it, here.