EWS Managed API - 1. BindToItems returns ErrorAccessDenied error, 2. appointments created in one mailbox show up in others

Hi,
I know there are other questions about ErrorAccessDenied but they are not exactly describing my situation and all are pretty much old and mostly not answered so forgive me for creating my own.
Also, wall of text coming so please bear with me.
We have an application that synchronizes Exchange items into our internal systems. Items created on Exchange are stored in that system and vice versa of course with a lot of business logic and rules, etc. Application uses EWS Managed API and impersonation
to access users mailboxes. Everything works fine but now we have this one customer that has a lot of strange things going on with main 2 problems mentioned in subject.
1. To ensure both sides (Exchange and our system) are in sync we have a functionality that allows users to decide that items no longer existing on Exchange should be removed also from system database. Since in our record we store id of original Exchange
item internal system simply sends us list of those ids to confirm items still exist. What application does is a BindToItems method call with BasePropertySet.IdOnly as requested property and depending on server response we notify internal system about state
of items. There is some semi complex logic behind what exactly is done on system side but in general NoError and item returned means item exists, ErrorItemNotFound means item doesn't exist.
For this one customer suddenly we started to receive ErrorAccessDenied and ErrorBatchProcessingStopped error codes which is very strange because seconds earlier there were events read from PullSubscribtion, items read from server, items created on server
and bunch of other stuff going on which basically makes me sure that impersonation is working. For some reason during execution of this particular code ErrorAccesDenied is returned and it messes up whole BindToItems call.
But what is really strange is that for first id in list of ids we get NoError and correct item returned, for second id we get ErrorAccessDenied, and rest of responses is ErrorBatchProcessingStopped. So is it really about credentials or there is some
completely different reason AccessDenied is retuned? According to customer those items exist in user mailbox for whom those errors are showing up. It doesn't happen for all users, only for some - who have exactly the same configuration of mailboxes as rest
(according to customer).
2. For same customer another problem started to occur since 1st of January, at least that is a date when they noticed it for the first time. Again, it happens for some users and there is no scenario that would guarantee to reproduce it.
When new record is created in our system or its data change it has to be created/updated on Exchange. With same impersonation as for problem described above I simply create new item or find existing item using id provided by our system, set item properties
according to whatever was sent and save/update item on Exchange. Simple and it works in multiple installations without problems.
But this customer reports that appointments created for one user show up in other users mailboxes which I find really strange because as far as I know when I impersonate [email protected] everything I do is executed in context of this one user only. So if
I create appointment in his calendar I cannot create same appointment in userB's calendar without explicitly switching impersonation to userB. What is worth mentioning during our sync process we store on Exchange items bunch of custom properties that help
us verify whole process and do various filters, etc. All of those custom properties are visible in outlook in that design form view or whatever it is called. And I have screenshot from user that claims to have one of those "not his" appointments
and basically half of our properties is not there and some have no values while they definitely should have otherwise whole sync would fail and everything is logged as successful.
Sorry for this wall of text but I really have no idea what can causing those strange problems so I tried to describe as much as possible without breaching NDA and such stuff. We added a lot of logging around areas where impersonation is changed, Exchange
items are created/updated, etc. Logs show nothing, of course.
So, for first issue: is it possible that items were moved on Exchange in such way that user still can see them but for EWS API call we get ErrorAccessDenied? I'm not sure where exactly could be such location because if id of an item would change we should
rather get ErrorItemNotFound or even something about id being not properly formatted, right?
For second issue: is it possible that there is something running on Exchange server and does some kind of simplistic mirroring of items between mailboxes? Customer claims there are no such things on server nor user side but can it be something that non-IT
people wouldn't know? Like some kind of script that admins like to run to keep server healthy or something innocent but lethal for our scenarios? Anybody has any hints what we should even ask customer about to get closer to solution of those mysterious problems?

Were you able to figure what was going on with your first problem? we're seeing the exact same issue with one of our customers.

Similar Messages

  • Trying to retrieve list of rooms using EWS Managed API but it returned empty collection

    Hi,
    I'm trying to retrieve list of rooms using EWS Managed API. Before I have tried the following code I make sure our Administrator put all the rooms in a list following  link https://technet.microsoft.com/en-us/library/ee633471%28v=exchg.141%29.aspx.
    Here is the simple code I have used :
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.Exchange.WebServices.Data;
    using System.Net;
    using System.Security;
    namespace ExchangeConsole1
    class Program
    static void Main(string[] args)
    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
    service.Credentials = new NetworkCredential("username", "Password1", "domain");
    service.Url = new Uri("https://email.xxxx.com/ews/exchange.asmx");
    EmailMessage email = new EmailMessage(service);
    EmailAddressCollection listOfRoomList = service.GetRoomLists();
    // Display the individual rooms.
    foreach (EmailAddress address in listOfRoomList)
    Console.WriteLine("Email Address: {0}", address.Address);
    service.GetRoomLists() results "Enumeration yielded no results". Could anybody help me please ?
    Thanks
    Sandipan

    Enable tracing and see what the response from the server looks like. Also depending on your setup and how long ago your administrator created the list, it may take some
    time to replicate.
    Administrator has done it one week ago. Here is the trace response I am getting
    <Trace Tag="EwsResponse" Tid="9" Time="2015-04-10 15:36:37Z" Version="15.00.0847.030">
    <?xml version="1.0" encoding="utf-8"?>
    <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header>
    <h:ServerVersionInfo MajorVersion="15" MinorVersion="0" MajorBuildNumber="995" MinorBuildNumber="31" Version="V2_15" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
    </s:Header>
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <m:GetRoomListsResponse ResponseClass="Success" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
    <m:ResponseCode>NoError</m:ResponseCode>
    <m:RoomLists />
    </m:GetRoomListsResponse>
    </s:Body>
    </s:Envelope>
    </Trace>
    It's say no error.  Any help ?
    Thanks
    Sandipan

  • EWS Manage Api Exchange Online TokenCredentials always returning 401

    Hi,
    Im trying to get acces to Exchange Online with the EWS manage api 2.2 and Im trying using this
    ExchangeService service = new ExchangeService();
    service.TraceEnabled = true;
    service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
    //service.HttpHeaders.Add("Authorization", "Bearer " + token);
    service.Credentials = new TokenCredentials(token);
    //service.PreAuthenticate = true;
    //service.SendClientLatencies = true;
    //service.EnableScpLookup = false;
    Always I get 401 unauthorized the token I get Azure Ad Authentication library , with this code
    var authenticationContext = new AuthenticationContext(_config.AuthString, false);
    // Config for OAuth client credentials
    var clientCred = new ClientCredential(_config.ClientId, _config.ClientSecret);
    AuthenticationResult authenticationResult = authenticationContext.AcquireToken(_config.ResourceUrl,clientCred);
    string token = authenticationResult.AccessToken;
    The app is registered on Azure Ad and have all the permision ,
    Im missing something? There is somewhere  a working example?
    I thinks is the same problem that is explained  here
    Live like you'll die tomorrow, learn like you'll live forever.
    Blog

    Got this "nuclear bomb", as i call this type of unexpected issues, in response too.
     {[x-ms-diagnostics, 2000010;reason="The access token is acquired using an authentication method
    that is too weak to allow access for this application. Presented auth strength was 1, required is 2.";error_category="insufficient_auth_strength"]}
    As i see, have to use a trusted certificate via ADAL (not self-signed), i guess, to get prtectio
    level 2.
    But all i initially was need - edit subject of an item at read-view outlook web (content) app...

  • Getting the message "The sharing message is not supported." while sharing the calendar using ews managed api.

      public void ShareCalendar(Calendar calendar)
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
                  service.Credentials = new NetworkCredential("user1", "password", "domain");
                service.Url = new Uri("https://sampleUrl/ews/exchange.asmx");
                try
                    // Bind to the folder
                    //Folder folderStoreInfo;
                    //folderStoreInfo = Folder.Bind(service, calendar.ExchangeId);
                    //string EwsID = folderStoreInfo.Id.UniqueId;
                    string EwsID = calendar.FolderExchangeId;
                    // The value of folderidHex will be what we need to use for the FolderId in the xml file
                    AutodiscoverService autoDiscover = new AutodiscoverService(ExchangeVersion.Exchange2013);
                    autoDiscover.Credentials =  new NetworkCredential("user1", "password", "domain");
                    autoDiscover.RedirectionUrlValidationCallback = RedirectionUrlValidationCallback;
                    Dictionary<string, string> userSettings = GetUserSettings(autoDiscover);
                    string folderidHex = GetConvertedEWSIDinHex(service, EwsID, "[email protected]");
                    string domainName = string.Empty;
                    string mailBoxServer = string.Empty;
                    string userName = string.Empty;
                    foreach (var item in userSettings)
                        switch (item.Key)
                            case "UserDN":
                                domainName = item.Value.ToString();
                                break;
                            case "InternalMailboxServer":
                                mailBoxServer = item.Value.ToString();
                                break;
                            case "UserDisplayName":
                                userName = item.Value.ToString();
                                break;
                    string entryId = GetIntiatorEntryID(domainName);
                    string mailboxId = GetInvitationMailboxId(mailBoxServer, domainName);
                    string sharedFilePath = CreateSharingMessageAttachment(folderidHex, userName, entryId, mailboxId, "[email protected]", "calendar", calendar.FolderName);
                    // Create a new message
                    EmailMessage invitationRequest = new EmailMessage(service);
                    invitationRequest.Subject = "I'd like to share my calendar with you";
                    invitationRequest.Body = "Sent by Exchange Administrator on behalf of user";                
                    //invitationRequest.Culture = "en-US";
                    invitationRequest.Sensitivity = Sensitivity.Normal;
                    // Set a sharing specific property on the message
                    invitationRequest.ItemClass = "IPM.Sharing"; /* Constant Required Value [MS-ProtocolSpec] */
                    byte[] byteEntryId = HexStringToByteArray(entryId);
                    // This is the Guid of the Sharing Provider in Exchange, and it's value does not change
                    Guid binSharingProviderGuid = new Guid("{AEF00600-0000-0000-C000-000000000046}");
                    // Even though I don't think setting this property is mandatory, 
                    // it just seemed like the right thing to do and it works so I \
                    // ain't messin with it!                                        
                    byte[] byteSharingProviderGuid = binSharingProviderGuid.ToByteArray();
                    string strPRBODYHTML = "<html dir=\"ltr\">\r\n<head>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\r\n<meta name=\"GENERATOR\"
    content=\"MSHTML 8.00.7601.17514\">\r\n<style id=\"owaParaStyle\">P {\r\n   MARGIN-TOP: 0px; MARGIN-BOTTOM: 0px \r\n}\r\n</style>\r\n</head>\r\n<body fPStyle=\"1\" ocsi=\"0\">\r\n<tt>\r\n<pre>SharedByUserDisplayName
    (SharedByUserSmtpAddress) has invited you to view his or her Microsoft Exchange Calendar.\r\n\r\nFor instructions on how to view shared folders on Exchange, see the following article:\r\n\r\nhttp://go.microsoft.com/fwlink/?LinkId=57561\r\n\r\n*~*~*~*~*~*~*~*~*~*\r\n\r\n</pre>\r\n</tt>\r\n<div>\r\n<div
    style=\"direction: ltr;font-family: Tahoma;color: #000000;font-size: 10pt;\">this is a test message</div>\r\n</div>\r\n</body>\r\n</html>\r\n";
                    string strBODY = @"
    SharedByUserDisplayName (SharedByUserSmtpAddress) has invited you to view his or
    her Microsoft Exchange Calendar.
    For instructions on how to view shared folders on Exchange, see the
    following article:
    http://go.microsoft.com/fwlink/?LinkId=57561
    *~*~*~*~*~*~*~*~*~*
    test body
                    // Convert these to hex and binary equivelants to assign to their relevant
                    // extended properties
                    string hexPRBODYHTML = ConvertStringToHex(strPRBODYHTML);
                    byte[] binPRBODYHTML = HexStringToByteArray(hexPRBODYHTML);
                    Guid PropertySetSharing = Guid.Parse("00062040-0000-0000-C000-000000000046");//constant 
                    Guid PropertySetInternetHeaders = Guid.Parse("00020386-0000-0000-C000-000000000046");//constant
                    ExtendedPropertyDefinition PidLidSharingProviderGuidProperty = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A01, MapiPropertyType.CLSID);
                    ExtendedPropertyDefinition ConversationIdProperty = new ExtendedPropertyDefinition(0x3013, MapiPropertyType.Binary);
                    // Sharing Properties (in order of reference according to protocol examples in: [MS-OXSHARE])
                    // Additional Property Constraints
                    // [MS-OXSHARE] 2.2.5.2
                    ExtendedPropertyDefinition PidTagMessageClass = new ExtendedPropertyDefinition(0x001A, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.5.1
                    //ExtendedPropertyDefinition PidNameContentClass = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.InternetHeaders, "Content-Class", MapiPropertyType.String);
                    ExtendedPropertyDefinition PidNameContentClass = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "Content-class", MapiPropertyType.String);
                    // Common Message Object Properties               
                    // [MS-OXSHARE] 2.2.1
                    ExtendedPropertyDefinition PidTagNormalizedSubject = new ExtendedPropertyDefinition(0x0E1D, MapiPropertyType.String);
                    // The PidTagSubjectPrefix is a zero-length string, so I do not set it
                    // ExtendedPropertyDefinition PidTagSubjectPrefix = new ExtendedPropertyDefinition(0x003D, MapiPropertyType.String);
                    // Sharing Object Message Properties
                    // [MS-OXSHARE] 2.2.2.12
                    ExtendedPropertyDefinition PidLidSharingProviderGuid = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A01, MapiPropertyType.Binary);
                    // [MS-OXSHARE] 2.2.2.13
                    ExtendedPropertyDefinition PidNameXSharingProviderGuid = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Provider-GUID", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.14
                    ExtendedPropertyDefinition PidLidSharingProviderName = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A02, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.15           
                    ExtendedPropertyDefinition PidNameXSharingProviderName = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Provider-Name", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.16
                    ExtendedPropertyDefinition PidLidSharingProviderUrl = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A03, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.17
                    ExtendedPropertyDefinition PidNameXSharingProviderUrl = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Provider-URL", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.5
                    ExtendedPropertyDefinition PidLidSharingFlavor = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A18, MapiPropertyType.Integer);
                    // [MS-OXSHARE] 2.2.2.6
                    ExtendedPropertyDefinition PidNameXSharingFlavor = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Flavor", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.1
                    ExtendedPropertyDefinition PidLidSharingCapabilities = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A17, MapiPropertyType.Integer);
                    // [MS-OXSHARE] 2.2.2.2
                    ExtendedPropertyDefinition PidNameXSharingCapabilities = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Capabilities", MapiPropertyType.String);
                    // Sections 2.3 and 2.4 are also zero-length strings, so I won't set those either
                    // [MS-OXSHARE] 2.2.2.3
                    // ExtendedPropertyDefinition PidLidSharingConfigurationUrl = new   //ExtendedPropertyDefinition(PropertySetSharing, 0x8A24, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.4
                    //ExtendedPropertyDefinition PidNameXSharingConfigUrl = new //ExtendedPropertyDefinition(DefaultExtendedPropertySet.InternetHeaders, "X-Sharing-Config-Url", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.10
                    ExtendedPropertyDefinition PidLidSharingLocalType = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A14, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.11
                    ExtendedPropertyDefinition PidNameXSharingLocalType = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Local-Type", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.7
                    ExtendedPropertyDefinition PidLidSharingInitiatorEntryId = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A09, MapiPropertyType.Binary);
                    // [MS-OXSHARE] 2.2.2.8
                    ExtendedPropertyDefinition PidLidSharingInitiatorName = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A07, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.9
                    ExtendedPropertyDefinition PidLidSharingInitiatorSMTP = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A08, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.3.1
                    ExtendedPropertyDefinition PidLidSharingRemoteName = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A05, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.3.2 
                    ExtendedPropertyDefinition PidNameXSharingRemoteName = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Remote-Name", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.3.5 
                    ExtendedPropertyDefinition PidLidSharingRemoteType = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A1D, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.3.6 
                    ExtendedPropertyDefinition PidNameXSharingRemoteType = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Remote-Type", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.3.7 
                    ExtendedPropertyDefinition PidLidSharingRemoteUid = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A06, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.3.8 
                    ExtendedPropertyDefinition PidNameXSharingRemoteUid = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Remote-Uid", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.3.3
                    ExtendedPropertyDefinition PidLidSharingRemoteStoreUid = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A48, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.3.4
                    ExtendedPropertyDefinition PidNameXSharingRemoteStoreUid = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Remote-Store-Uid", MapiPropertyType.String);
                    //From troubleshooting I noticed I was missing
                    ExtendedPropertyDefinition PidTagPriority = new ExtendedPropertyDefinition(0x0026, MapiPropertyType.Integer);
                    ExtendedPropertyDefinition PidTagSensitivity = new ExtendedPropertyDefinition(0x0036, MapiPropertyType.Integer);
                    ExtendedPropertyDefinition PR_BODY_HTML = new ExtendedPropertyDefinition(0x1013, MapiPropertyType.Binary); //PR_BOD
                    ExtendedPropertyDefinition PR_BODY = new ExtendedPropertyDefinition(0x1000, MapiPropertyType.String);
                    ExtendedPropertyDefinition RecipientReassignmentProhibited = new ExtendedPropertyDefinition(0x002b, MapiPropertyType.Boolean);
                    // Section 2.2.1
                    invitationRequest.SetExtendedProperty(PidTagNormalizedSubject, "I'd like to share my calendar with you"); /* Constant Required Value [MS-OXSHARE] 2.2.1 */
                    //invitationRequest.SetExtendedProperty(PidTagSubjectPrefix, String.Empty); /* Constant Required Value [MS-OXSHARE] 2.2.1 */
                    // Section 2.2.2
                    invitationRequest.SetExtendedProperty(PidLidSharingCapabilities, 0x40220); /* value for Special Folders */
                    invitationRequest.SetExtendedProperty(PidNameXSharingCapabilities, "40220"); /* Test representation of SharingCapabilities value */
                    //invitationRequest.SetExtendedProperty(PidLidSharingConfigurationUrl, String.Empty); /* Zero-Length String [MS-OXSHARE] 2.2.2.3 */
                    //invitationRequest.SetExtendedProperty(PidNameXSharingConfigUrl, String.Empty); /* Zero-Length String [MS-OXSHARE] 2.2.2.4 */
                    invitationRequest.SetExtendedProperty(PidLidSharingFlavor, 0x20310); /* Indicates Invitation for a special folder [MS-OXSHARE] 2.2.2.5 */
                    invitationRequest.SetExtendedProperty(PidNameXSharingFlavor, "20310"); /* Text representation of SharingFlavor value [MS-OXSHARE] 2.2.2.6 */
                    invitationRequest.SetExtendedProperty(PidLidSharingInitiatorEntryId, byteEntryId); /* Value from the Initiator/EntryId value in the Sharing Message attachment .xml document */
                    invitationRequest.SetExtendedProperty(PidLidSharingInitiatorSMTP, "[email protected]"); /* Value from Initiator/Smtp Address in the Sharing message attachment .xml document */
                    invitationRequest.SetExtendedProperty(PidLidSharingInitiatorName, "User1"); /* Value from Initiator/Name Address in the Sharing message attachment .xml document */
                    invitationRequest.SetExtendedProperty(PidLidSharingLocalType, "IPF.Appointment"); /* MUST be set to PidTagContainerClass of folder to be shared */
                    invitationRequest.SetExtendedProperty(PidNameXSharingLocalType, "IPF.Appointment"); /* MUST be set to same value as PidLidSharingLocalType */
                    invitationRequest.SetExtendedProperty(PidLidSharingProviderGuid, byteSharingProviderGuid); /* Constant Required Value [MS-OXSHARE] 2.2.2.12 */
                    invitationRequest.SetExtendedProperty(PidNameXSharingProviderGuid, "AEF0060000000000C000000000000046"); /* Constant Required Value [MS-OXSHARE] 2.2.2.13 */
                    invitationRequest.SetExtendedProperty(PidLidSharingProviderName, "Microsoft Exchange"); /* Constant Required Value [MS-OXSHARE] 2.2.2.14 */
                    invitationRequest.SetExtendedProperty(PidNameXSharingProviderName, "Microsoft Exchange"); /* Constant Required Value [MS-OXSHARE] 2.2.2.15] */
                    invitationRequest.SetExtendedProperty(PidLidSharingProviderUrl, "http://www.microsoft.com/exchange"); /* Constant Required Value [MS-OXSHARE] 2.2.2.16 */
                    invitationRequest.SetExtendedProperty(PidNameXSharingProviderUrl, "http://www.microsoft.com/exchange"); /* Constant Required Value [MS-OXSHARE] 2.2.2.17 */
                    // Section 2.2.3
                    invitationRequest.SetExtendedProperty(PidLidSharingRemoteName, calendar.FolderName); /* MUST be set to PidTagDisplayName of the folder being shared */
                    invitationRequest.SetExtendedProperty(PidNameXSharingRemoteName, calendar.FolderName); /* MUST be set to same value as PidLidSharingRemoteName */
                    invitationRequest.SetExtendedProperty(PidLidSharingRemoteStoreUid, mailboxId); /* Must be set to PidTagStoreEntryId of the folder being shared */
                    invitationRequest.SetExtendedProperty(PidNameXSharingRemoteStoreUid, mailboxId); /* MUST be set to same value as PidLidSharingRemoteStoreUid */
                    invitationRequest.SetExtendedProperty(PidLidSharingRemoteType, "IPF.Appointment"); /* Constant Required Value [MS-OXSHARE] 2.2.3.5 */
                    invitationRequest.SetExtendedProperty(PidNameXSharingRemoteType, "IPF.Appointment"); /* Constant Required Value [MS-OXSHARE] 2.2.3.6 */
                    invitationRequest.SetExtendedProperty(PidLidSharingRemoteUid, folderidHex); /* MUST be set to PidTagEntryId of folder being shared */
                    invitationRequest.SetExtendedProperty(PidNameXSharingRemoteUid, folderidHex); /* Must be set to same value as PidLidSharingRemoteUid */
                    // Section 2.2.5
                    invitationRequest.SetExtendedProperty(PidNameContentClass, "Sharing"); /* Constant Required Value [MS-ProtocolSpec] */
                    invitationRequest.SetExtendedProperty(PidTagMessageClass, "IPM.Sharing"); /* Constant Required Value [MS-ProtocolSpec] */
                    // ********* ADDITIONAL MAPPED PROPERTIES IM FINDING AS I TROUBLESHOOT ********************** //
                    invitationRequest.SetExtendedProperty(PidTagPriority, 0); /* From troubleshooting I'm just trying to match up values that were missing */
                    invitationRequest.SetExtendedProperty(PidTagSensitivity, 0); /* From troubleshooting as well */
                    invitationRequest.SetExtendedProperty(PR_BODY_HTML, binPRBODYHTML); /* From troubleshooting OWA error pointing to serializing HTML failing */
                    invitationRequest.SetExtendedProperty(PR_BODY, strBODY);
                    invitationRequest.SetExtendedProperty(RecipientReassignmentProhibited, true); /* Because it seemed like a good idea */
                    // Add a file attachment by using a stream
                    // We need to do the following in order to prevent 3 extra bytes from being prepended to the attachment
                    string sharMetadata = File.ReadAllText(sharedFilePath, Encoding.ASCII);
                    byte[] fileContents;
                    UTF8Encoding encoding = new System.Text.UTF8Encoding();
                    fileContents = encoding.GetBytes(sharMetadata);
                    //fileContents = File.ReadAllBytes(sharedFilePath);
                    //// fileContents is a Stream object that represents the content of the file to attach.
                    invitationRequest.Attachments.AddFileAttachment("sharing_metadata.xml", fileContents);
                    ////invitationRequest.Attachments.AddFileAttachment(sharedFilePath);
                    //// This is where we set those "special" headers and other pertinent
                    //// information I noted in Part 1 of this series...
                    //Attachment thisAttachment = invitationRequest.Attachments[0];
                    //thisAttachment.ContentType = "application/x-sharing-metadata-xml";
                    //thisAttachment.Name = "sharing_metadata.xml";
                    //thisAttachment.IsInline = false;
                    // Add recipient info and send message
                    invitationRequest.ToRecipients.Add(new EmailAddress() { Address = "[email protected]" });
                    invitationRequest.SendAndSaveCopy();
                    // I always end my methods by returning the EWS 
                    // impersonated user to null to clean up
                    service.ImpersonatedUserId = null;
                catch (Exception ex)
            public String GetConvertedEWSIDinHex(ExchangeService esb, String sID, String strSMTPAdd)
                // Create a request to convert identifiers.
                AlternateId objAltID = new AlternateId();
                objAltID.Format = IdFormat.EwsId;
                objAltID.Mailbox = strSMTPAdd;
                objAltID.UniqueId = sID;
                //Convert  PR_ENTRYID identifier format to an EWS identifier.
                AlternateIdBase objAltIDBase = esb.ConvertId(objAltID, IdFormat.HexEntryId);
                AlternateId objAltIDResp = (AlternateId)objAltIDBase;
                return objAltIDResp.UniqueId.ToString();
            public String GetInvitationMailboxId(string mailBoxServer, string domainName)
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
                service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "[email protected]");
                // Generate The Store Entry Id for the impersonated user
                StringBuilder MailboxIDPointer = new StringBuilder();          
                string fqdn = mailBoxServer;
                string legacyDN = domainName;
                MailboxIDPointer.Append("00000000"); /* Flags */
                MailboxIDPointer.Append("38A1BB1005E5101AA1BB08002B2A56C2"); /* ProviderUID */
                MailboxIDPointer.Append("00"); /* Version */
                MailboxIDPointer.Append("00"); /* Flag */
                MailboxIDPointer.Append("454D534D44422E444C4C00000000"); /* DLLFileName */
                MailboxIDPointer.Append("00000000"); /* Wrapped Flags */
                MailboxIDPointer.Append("1B55FA20AA6611CD9BC800AA002FC45A"); /* WrappedProvider UID (Mailbox Store Object) */
                MailboxIDPointer.Append("0C000000"); /* Wrapped Type (Mailbox Store) */
                MailboxIDPointer.Append(ConvertStringToHex(fqdn)); /* ServerShortname (FQDN) */
                MailboxIDPointer.Append("00"); /* termination bit */
                MailboxIDPointer.Append(ConvertStringToHex(legacyDN)); /* Returns the userDN of the impersonated user */
                MailboxIDPointer.Append("00"); /* terminator bit */
                service.ImpersonatedUserId = null;
                return MailboxIDPointer.ToString();
            static bool RedirectionUrlValidationCallback(String redirectionUrl)
                bool redirectionValidated = false;
                if (redirectionUrl.Equals("https://SampleUrl/autodiscover/autodiscover.xml"))          
                    redirectionValidated = true;
                return redirectionValidated;
            public String GetIntiatorEntryID(string domainName)
                String result = String.Empty;
                //// Bind to EWS
                //ExchangeService service = ExchangeConnection.ExchangeService();
                //service.ImpersonatedUserId =
                //new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "[email protected]");
                //// Get LegacyDN Using the function above this one 
                string sharedByLegacyDN = domainName;
                // A conversion function from earlier
                string legacyDNinHex = ConvertStringToHex(sharedByLegacyDN);
                StringBuilder addBookEntryId = new StringBuilder();
                addBookEntryId.Append("00000000"); /* Flags */
                addBookEntryId.Append("DCA740C8C042101AB4B908002B2FE182"); /* ProviderUID */
                addBookEntryId.Append("01000000"); /* Version */
                addBookEntryId.Append("00000000"); /* Type - 00 00 00 00  = Local Mail User */
                addBookEntryId.Append(legacyDNinHex); /* Returns the userDN of the impersonated user */
                addBookEntryId.Append("00"); /* terminator bit */
                result = addBookEntryId.ToString();
                //service.ImpersonatedUserId = null;
                return result;
            public string ConvertStringToHex(string input)
                // Take our input and break it into an array
                char[] arrInput = input.ToCharArray();
                String result = String.Empty;
                // For each set of characters
                foreach (char element in arrInput)
                    if (String.IsNullOrEmpty(result))
                        result = String.Format("{0:X2}", Convert.ToUInt16(element)).ToString();
                    else
                        result += String.Format("{0:X2}", Convert.ToUInt16(element)).ToString();
                return result.ToString();
     public string CreateSharingMessageAttachment(string folderid, string userSharing, string userSharingEntryID, string invitationMailboxID, string userSharedTo, string dataType, string calendarName)
                XmlDocument sharedMetadataXML = new XmlDocument();
                string sharedMetaDataFilePath = string.Empty;
                try
                    // Create a String that contains our new sharing_metadata.xml file
                    StringBuilder metadataString = new StringBuilder("<?xml version=\"1.0\"?>");              
                    metadataString.Append("<SharingMessage xmlns=\"http://schemas.microsoft.com/sharing/2008\">");
                    metadataString.Append("<DataType>" + dataType + "</DataType>");
                    metadataString.Append("<Initiator>");
                    metadataString.Append("<Name>" + userSharing + "</Name>");
                    metadataString.Append("<SmtpAddress>" + "[email protected]" + "</SmtpAddress><EntryId>" + userSharingEntryID.Trim());
                    metadataString.Append("</EntryId>");
                    metadataString.Append("</Initiator>");
                    metadataString.Append("<Invitation>");
                    metadataString.Append("<Title>" + calendarName + "</Title>");
                    metadataString.Append("<Providers>");
                    metadataString.Append("<Provider Type=\"ms-exchange-internal\" TargetRecipients=\"" + userSharedTo + "\">");
                    metadataString.Append("<FolderId xmlns=\"http://schemas.microsoft.com/exchange/sharing/2008\">");
                    metadataString.Append(folderid);
                    metadataString.Append("</FolderId>");
                    metadataString.Append("<MailboxId xmlns=\"http://schemas.microsoft.com/exchange/sharing/2008\">");
                    metadataString.Append(invitationMailboxID);
                    metadataString.Append("</MailboxId>");
                    metadataString.Append("</Provider>");
                    metadataString.Append("</Providers>");
                    metadataString.Append("</Invitation>");
                    metadataString.Append("</SharingMessage>");
                    sharedMetadataXML.LoadXml(metadataString.ToString());
                    string tempPath = System.IO.Path.GetTempPath();
                    sharedMetaDataFilePath = tempPath + "sharing_metadata.xml";
                    sharedMetadataXML.Save(sharedMetaDataFilePath);
                catch (Exception eg)
                    throw eg;               
                return sharedMetaDataFilePath;
            public Dictionary<string, string> GetUserSettings(AutodiscoverService autodiscoverService)
                GetUserSettingsResponse userresponse = autodiscoverService.GetUserSettings(
                    "[email protected]",
                    UserSettingName.UserDisplayName,
                    UserSettingName.InternalMailboxServerDN,
                    UserSettingName.UserDN
                Dictionary<string, string> myUserSettings = new Dictionary<string, string>();
                foreach (KeyValuePair<UserSettingName, Object> usersetting in userresponse.Settings)
                    if (usersetting.Key.ToString() == "InternalMailboxServerDN")
                        int lastIndexOfEqual = usersetting.Value.ToString().LastIndexOf("=");
                        string subString = usersetting.Value.ToString().Substring(lastIndexOfEqual + 1);
                        string value = subString;
                        myUserSettings.Add("InternalMailboxServer", value.ToString());
                    if (usersetting.Key.ToString() == "UserDisplayName")
                        string[] arrResult = usersetting.Value.ToString().Split('.');
                        myUserSettings.Add("UserDisplayName", arrResult[0].ToString());
                    if (usersetting.Key.ToString() == "UserDN")
                        string[] arrResult = usersetting.Value.ToString().Split('.');
                        myUserSettings.Add("UserDN", arrResult[0].ToString());
                return myUserSettings;
            private static byte[] HexStringToByteArray(string input)
                byte[] Bytes;
                int ByteLength;
                string HexValue = "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9|||||||\xA\xB\xC\xD\xE\xF";
                ByteLength = input.Length / 2;
                Bytes = new byte[ByteLength];
                for (int x = 0, i = 0; i < input.Length; i += 2, x += 1)
                    Bytes[x] = (byte)(HexValue[Char.ToUpper(input[i + 0]) - '0'] << 4);
                    Bytes[x] |= (byte)(HexValue[Char.ToUpper(input[i + 1]) - '0']);
                return Bytes;

    Hi,
    I'm trying to share a calendar through ews managed api v.2 and using exchange 2013 version.
    i'm preparing a shared calendar and providing values to extended properties .
    Here comes the problem when i'm trying to send the sharing request(email message) 
    The following is code snippet.
      public void ShareCalendar(Calendar calendar)
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
                  service.Credentials = new NetworkCredential("user1", "password", "domain");
                service.Url = new Uri("https://sampleUrl/ews/exchange.asmx");
                try
                    // Bind to the folder
                    //Folder folderStoreInfo;
                    //folderStoreInfo = Folder.Bind(service, calendar.ExchangeId);
                    //string EwsID = folderStoreInfo.Id.UniqueId;
                    string EwsID = calendar.FolderExchangeId;
                    // The value of folderidHex will be what we need to use for the FolderId in the xml file
                    AutodiscoverService autoDiscover = new AutodiscoverService(ExchangeVersion.Exchange2013);
                    autoDiscover.Credentials =  new NetworkCredential("user1", "password", "domain");
                    autoDiscover.RedirectionUrlValidationCallback = RedirectionUrlValidationCallback;
                    Dictionary<string, string> userSettings = GetUserSettings(autoDiscover);
                    string folderidHex = GetConvertedEWSIDinHex(service, EwsID, "[email protected]");
                    string domainName = string.Empty;
                    string mailBoxServer = string.Empty;
                    string userName = string.Empty;
                    foreach (var item in userSettings)
                        switch (item.Key)
                            case "UserDN":
                                domainName = item.Value.ToString();
                                break;
                            case "InternalMailboxServer":
                                mailBoxServer = item.Value.ToString();
                                break;
                            case "UserDisplayName":
                                userName = item.Value.ToString();
                                break;
                    string entryId = GetIntiatorEntryID(domainName);
                    string mailboxId = GetInvitationMailboxId(mailBoxServer, domainName);
                    string sharedFilePath = CreateSharingMessageAttachment(folderidHex, userName, entryId, mailboxId, "[email protected]", "calendar", calendar.FolderName);
                    // Create a new message
                    EmailMessage invitationRequest = new EmailMessage(service);
                    invitationRequest.Subject = "I'd like to share my calendar with you";
                    invitationRequest.Body = "Sent by Exchange Administrator on behalf of user";                
                    //invitationRequest.Culture = "en-US";
                    invitationRequest.Sensitivity = Sensitivity.Normal;
                    // Set a sharing specific property on the message
                    invitationRequest.ItemClass = "IPM.Sharing"; /* Constant Required Value [MS-ProtocolSpec] */
                    byte[] byteEntryId = HexStringToByteArray(entryId);
                    // This is the Guid of the Sharing Provider in Exchange, and it's value does not change
                    Guid binSharingProviderGuid = new Guid("{AEF00600-0000-0000-C000-000000000046}");
                    // Even though I don't think setting this property is mandatory, 
                    // it just seemed like the right thing to do and it works so I \
                    // ain't messin with it!                                        
                    byte[] byteSharingProviderGuid = binSharingProviderGuid.ToByteArray();
                    string strPRBODYHTML = "<html dir=\"ltr\">\r\n<head>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\r\n<meta name=\"GENERATOR\"
    content=\"MSHTML 8.00.7601.17514\">\r\n<style id=\"owaParaStyle\">P {\r\n   MARGIN-TOP: 0px; MARGIN-BOTTOM: 0px \r\n}\r\n</style>\r\n</head>\r\n<body fPStyle=\"1\" ocsi=\"0\">\r\n<tt>\r\n<pre>SharedByUserDisplayName
    (SharedByUserSmtpAddress) has invited you to view his or her Microsoft Exchange Calendar.\r\n\r\nFor instructions on how to view shared folders on Exchange, see the following article:\r\n\r\nhttp://go.microsoft.com/fwlink/?LinkId=57561\r\n\r\n*~*~*~*~*~*~*~*~*~*\r\n\r\n</pre>\r\n</tt>\r\n<div>\r\n<div
    style=\"direction: ltr;font-family: Tahoma;color: #000000;font-size: 10pt;\">this is a test message</div>\r\n</div>\r\n</body>\r\n</html>\r\n";
                    string strBODY = @"
    SharedByUserDisplayName (SharedByUserSmtpAddress) has invited you to view his or
    her Microsoft Exchange Calendar.
    For instructions on how to view shared folders on Exchange, see the
    following article:
    http://go.microsoft.com/fwlink/?LinkId=57561
    *~*~*~*~*~*~*~*~*~*
    test body
                    // Convert these to hex and binary equivelants to assign to their relevant
                    // extended properties
                    string hexPRBODYHTML = ConvertStringToHex(strPRBODYHTML);
                    byte[] binPRBODYHTML = HexStringToByteArray(hexPRBODYHTML);
                    Guid PropertySetSharing = Guid.Parse("00062040-0000-0000-C000-000000000046");//constant 
                    Guid PropertySetInternetHeaders = Guid.Parse("00020386-0000-0000-C000-000000000046");//constant
                    ExtendedPropertyDefinition PidLidSharingProviderGuidProperty = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A01, MapiPropertyType.CLSID);
                    ExtendedPropertyDefinition ConversationIdProperty = new ExtendedPropertyDefinition(0x3013, MapiPropertyType.Binary);
                    // Sharing Properties (in order of reference according to protocol examples in: [MS-OXSHARE])
                    // Additional Property Constraints
                    // [MS-OXSHARE] 2.2.5.2
                    ExtendedPropertyDefinition PidTagMessageClass = new ExtendedPropertyDefinition(0x001A, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.5.1
                    //ExtendedPropertyDefinition PidNameContentClass = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.InternetHeaders, "Content-Class", MapiPropertyType.String);
                    ExtendedPropertyDefinition PidNameContentClass = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "Content-class", MapiPropertyType.String);
                    // Common Message Object Properties               
                    // [MS-OXSHARE] 2.2.1
                    ExtendedPropertyDefinition PidTagNormalizedSubject = new ExtendedPropertyDefinition(0x0E1D, MapiPropertyType.String);
                    // The PidTagSubjectPrefix is a zero-length string, so I do not set it
                    // ExtendedPropertyDefinition PidTagSubjectPrefix = new ExtendedPropertyDefinition(0x003D, MapiPropertyType.String);
                    // Sharing Object Message Properties
                    // [MS-OXSHARE] 2.2.2.12
                    ExtendedPropertyDefinition PidLidSharingProviderGuid = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A01, MapiPropertyType.Binary);
                    // [MS-OXSHARE] 2.2.2.13
                    ExtendedPropertyDefinition PidNameXSharingProviderGuid = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Provider-GUID", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.14
                    ExtendedPropertyDefinition PidLidSharingProviderName = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A02, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.15           
                    ExtendedPropertyDefinition PidNameXSharingProviderName = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Provider-Name", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.16
                    ExtendedPropertyDefinition PidLidSharingProviderUrl = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A03, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.17
                    ExtendedPropertyDefinition PidNameXSharingProviderUrl = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Provider-URL", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.5
                    ExtendedPropertyDefinition PidLidSharingFlavor = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A18, MapiPropertyType.Integer);
                    // [MS-OXSHARE] 2.2.2.6
                    ExtendedPropertyDefinition PidNameXSharingFlavor = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Flavor", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.1
                    ExtendedPropertyDefinition PidLidSharingCapabilities = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A17, MapiPropertyType.Integer);
                    // [MS-OXSHARE] 2.2.2.2
                    ExtendedPropertyDefinition PidNameXSharingCapabilities = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Capabilities", MapiPropertyType.String);
                    // Sections 2.3 and 2.4 are also zero-length strings, so I won't set those either
                    // [MS-OXSHARE] 2.2.2.3
                    // ExtendedPropertyDefinition PidLidSharingConfigurationUrl = new   //ExtendedPropertyDefinition(PropertySetSharing, 0x8A24, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.4
                    //ExtendedPropertyDefinition PidNameXSharingConfigUrl = new //ExtendedPropertyDefinition(DefaultExtendedPropertySet.InternetHeaders, "X-Sharing-Config-Url", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.10
                    ExtendedPropertyDefinition PidLidSharingLocalType = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A14, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.11
                    ExtendedPropertyDefinition PidNameXSharingLocalType = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Local-Type", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.7
                    ExtendedPropertyDefinition PidLidSharingInitiatorEntryId = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A09, MapiPropertyType.Binary);
                    // [MS-OXSHARE] 2.2.2.8
                    ExtendedPropertyDefinition PidLidSharingInitiatorName = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A07, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.2.9
                    ExtendedPropertyDefinition PidLidSharingInitiatorSMTP = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A08, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.3.1
                    ExtendedPropertyDefinition PidLidSharingRemoteName = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A05, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.3.2 
                    ExtendedPropertyDefinition PidNameXSharingRemoteName = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Remote-Name", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.3.5 
                    ExtendedPropertyDefinition PidLidSharingRemoteType = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A1D, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.3.6 
                    ExtendedPropertyDefinition PidNameXSharingRemoteType = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Remote-Type", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.3.7 
                    ExtendedPropertyDefinition PidLidSharingRemoteUid = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A06, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.3.8 
                    ExtendedPropertyDefinition PidNameXSharingRemoteUid = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Remote-Uid", MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.3.3
                    ExtendedPropertyDefinition PidLidSharingRemoteStoreUid = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A48, MapiPropertyType.String);
                    // [MS-OXSHARE] 2.2.3.4
                    ExtendedPropertyDefinition PidNameXSharingRemoteStoreUid = new ExtendedPropertyDefinition(PropertySetInternetHeaders, "X-Sharing-Remote-Store-Uid", MapiPropertyType.String);
                    //From troubleshooting I noticed I was missing
                    ExtendedPropertyDefinition PidTagPriority = new ExtendedPropertyDefinition(0x0026, MapiPropertyType.Integer);
                    ExtendedPropertyDefinition PidTagSensitivity = new ExtendedPropertyDefinition(0x0036, MapiPropertyType.Integer);
                    ExtendedPropertyDefinition PR_BODY_HTML = new ExtendedPropertyDefinition(0x1013, MapiPropertyType.Binary); //PR_BOD
                    ExtendedPropertyDefinition PR_BODY = new ExtendedPropertyDefinition(0x1000, MapiPropertyType.String);
                    ExtendedPropertyDefinition RecipientReassignmentProhibited = new ExtendedPropertyDefinition(0x002b, MapiPropertyType.Boolean);
                    // Section 2.2.1
                    invitationRequest.SetExtendedProperty(PidTagNormalizedSubject, "I'd like to share my calendar with you"); /* Constant Required Value [MS-OXSHARE] 2.2.1 */
                    //invitationRequest.SetExtendedProperty(PidTagSubjectPrefix, String.Empty); /* Constant Required Value [MS-OXSHARE] 2.2.1 */
                    // Section 2.2.2
                    invitationRequest.SetExtendedProperty(PidLidSharingCapabilities, 0x40220); /* value for Special Folders */
                    invitationRequest.SetExtendedProperty(PidNameXSharingCapabilities, "40220"); /* Test representation of SharingCapabilities value */
                    //invitationRequest.SetExtendedProperty(PidLidSharingConfigurationUrl, String.Empty); /* Zero-Length String [MS-OXSHARE] 2.2.2.3 */
                    //invitationRequest.SetExtendedProperty(PidNameXSharingConfigUrl, String.Empty); /* Zero-Length String [MS-OXSHARE] 2.2.2.4 */
                    invitationRequest.SetExtendedProperty(PidLidSharingFlavor, 0x20310); /* Indicates Invitation for a special folder [MS-OXSHARE] 2.2.2.5 */
                    invitationRequest.SetExtendedProperty(PidNameXSharingFlavor, "20310"); /* Text representation of SharingFlavor value [MS-OXSHARE] 2.2.2.6 */
                    invitationRequest.SetExtendedProperty(PidLidSharingInitiatorEntryId, byteEntryId); /* Value from the Initiator/EntryId value in the Sharing Message attachment .xml document */
                    invitationRequest.SetExtendedProperty(PidLidSharingInitiatorSMTP, "[email protected]"); /* Value from Initiator/Smtp Address in the Sharing message attachment .xml document */
                    invitationRequest.SetExtendedProperty(PidLidSharingInitiatorName, "User1"); /* Value from Initiator/Name Address in the Sharing message attachment .xml document */
                    invitationRequest.SetExtendedProperty(PidLidSharingLocalType, "IPF.Appointment"); /* MUST be set to PidTagContainerClass of folder to be shared */
                    invitationRequest.SetExtendedProperty(PidNameXSharingLocalType, "IPF.Appointment"); /* MUST be set to same value as PidLidSharingLocalType */
                    invitationRequest.SetExtendedProperty(PidLidSharingProviderGuid, byteSharingProviderGuid); /* Constant Required Value [MS-OXSHARE] 2.2.2.12 */
                    invitationRequest.SetExtendedProperty(PidNameXSharingProviderGuid, "AEF0060000000000C000000000000046"); /* Constant Required Value [MS-OXSHARE] 2.2.2.13 */
                    invitationRequest.SetExtendedProperty(PidLidSharingProviderName, "Microsoft Exchange"); /* Constant Required Value [MS-OXSHARE] 2.2.2.14 */
                    invitationRequest.SetExtendedProperty(PidNameXSharingProviderName, "Microsoft Exchange"); /* Constant Required Value [MS-OXSHARE] 2.2.2.15] */
                    invitationRequest.SetExtendedProperty(PidLidSharingProviderUrl, "http://www.microsoft.com/exchange"); /* Constant Required Value [MS-OXSHARE] 2.2.2.16 */
                    invitationRequest.SetExtendedProperty(PidNameXSharingProviderUrl, "http://www.microsoft.com/exchange"); /* Constant Required Value [MS-OXSHARE] 2.2.2.17 */
                    // Section 2.2.3
                    invitationRequest.SetExtendedProperty(PidLidSharingRemoteName, calendar.FolderName); /* MUST be set to PidTagDisplayName of the folder being shared */
                    invitationRequest.SetExtendedProperty(PidNameXSharingRemoteName, calendar.FolderName); /* MUST be set to same value as PidLidSharingRemoteName */
                    invitationRequest.SetExtendedProperty(PidLidSharingRemoteStoreUid, mailboxId); /* Must be set to PidTagStoreEntryId of the folder being shared */
                    invitationRequest.SetExtendedProperty(PidNameXSharingRemoteStoreUid, mailboxId); /* MUST be set to same value as PidLidSharingRemoteStoreUid */
                    invitationRequest.SetExtendedProperty(PidLidSharingRemoteType, "IPF.Appointment"); /* Constant Required Value [MS-OXSHARE] 2.2.3.5 */
                    invitationRequest.SetExtendedProperty(PidNameXSharingRemoteType, "IPF.Appointment"); /* Constant Required Value [MS-OXSHARE] 2.2.3.6 */
                    invitationRequest.SetExtendedProperty(PidLidSharingRemoteUid, folderidHex); /* MUST be set to PidTagEntryId of folder being shared */
                    invitationRequest.SetExtendedProperty(PidNameXSharingRemoteUid, folderidHex); /* Must be set to same value as PidLidSharingRemoteUid */
                    // Section 2.2.5
                    invitationRequest.SetExtendedProperty(PidNameContentClass, "Sharing"); /* Constant Required Value [MS-ProtocolSpec] */
                    invitationRequest.SetExtendedProperty(PidTagMessageClass, "IPM.Sharing"); /* Constant Required Value [MS-ProtocolSpec] */
                    // ********* ADDITIONAL MAPPED PROPERTIES IM FINDING AS I TROUBLESHOOT ********************** //
                    invitationRequest.SetExtendedProperty(PidTagPriority, 0); /* From troubleshooting I'm just trying to match up values that were missing */
                    invitationRequest.SetExtendedProperty(PidTagSensitivity, 0); /* From troubleshooting as well */
                    invitationRequest.SetExtendedProperty(PR_BODY_HTML, binPRBODYHTML); /* From troubleshooting OWA error pointing to serializing HTML failing */
                    invitationRequest.SetExtendedProperty(PR_BODY, strBODY);
                    invitationRequest.SetExtendedProperty(RecipientReassignmentProhibited, true); /* Because it seemed like a good idea */
                    // Add a file attachment by using a stream
                    // We need to do the following in order to prevent 3 extra bytes from being prepended to the attachment
                    string sharMetadata = File.ReadAllText(sharedFilePath, Encoding.ASCII);
                    byte[] fileContents;
                    UTF8Encoding encoding = new System.Text.UTF8Encoding();
                    fileContents = encoding.GetBytes(sharMetadata);
                    //fileContents = File.ReadAllBytes(sharedFilePath);
                    //// fileContents is a Stream object that represents the content of the file to attach.
                    invitationRequest.Attachments.AddFileAttachment("sharing_metadata.xml", fileContents);
                    ////invitationRequest.Attachments.AddFileAttachment(sharedFilePath);
                    //// This is where we set those "special" headers and other pertinent
                    //// information I noted in Part 1 of this series...
                    //Attachment thisAttachment = invitationRequest.Attachments[0];
                    //thisAttachment.ContentType = "application/x-sharing-metadata-xml";
                    //thisAttachment.Name = "sharing_metadata.xml";
                    //thisAttachment.IsInline = false;
                    // Add recipient info and send message
                    invitationRequest.ToRecipients.Add(new EmailAddress() { Address = "[email protected]" });
                    invitationRequest.SendAndSaveCopy();
                    // I always end my methods by returning the EWS 
                    // impersonated user to null to clean up
                    service.ImpersonatedUserId = null;
                catch (Exception ex)
            public String GetConvertedEWSIDinHex(ExchangeService esb, String sID, String strSMTPAdd)
                // Create a request to convert identifiers.
                AlternateId objAltID = new AlternateId();
                objAltID.Format = IdFormat.EwsId;
                objAltID.Mailbox = strSMTPAdd;
                objAltID.UniqueId = sID;
                //Convert  PR_ENTRYID identifier format to an EWS identifier.
                AlternateIdBase objAltIDBase = esb.ConvertId(objAltID, IdFormat.HexEntryId);
                AlternateId objAltIDResp = (AlternateId)objAltIDBase;
                return objAltIDResp.UniqueId.ToString();
            public String GetInvitationMailboxId(string mailBoxServer, string domainName)
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
                service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "[email protected]");
                // Generate The Store Entry Id for the impersonated user
                StringBuilder MailboxIDPointer = new StringBuilder();          
                string fqdn = mailBoxServer;
                string legacyDN = domainName;
                MailboxIDPointer.Append("00000000"); /* Flags */
                MailboxIDPointer.Append("38A1BB1005E5101AA1BB08002B2A56C2"); /* ProviderUID */
                MailboxIDPointer.Append("00"); /* Version */
                MailboxIDPointer.Append("00"); /* Flag */
                MailboxIDPointer.Append("454D534D44422E444C4C00000000"); /* DLLFileName */
                MailboxIDPointer.Append("00000000"); /* Wrapped Flags */
                MailboxIDPointer.Append("1B55FA20AA6611CD9BC800AA002FC45A"); /* WrappedProvider UID (Mailbox Store Object) */
                MailboxIDPointer.Append("0C000000"); /* Wrapped Type (Mailbox Store) */
                MailboxIDPointer.Append(ConvertStringToHex(fqdn)); /* ServerShortname (FQDN) */
                MailboxIDPointer.Append("00"); /* termination bit */
                MailboxIDPointer.Append(ConvertStringToHex(legacyDN)); /* Returns the userDN of the impersonated user */
                MailboxIDPointer.Append("00"); /* terminator bit */
                service.ImpersonatedUserId = null;
                return MailboxIDPointer.ToString();
            static bool RedirectionUrlValidationCallback(String redirectionUrl)
                bool redirectionValidated = false;
                if (redirectionUrl.Equals("https://SampleUrl/autodiscover/autodiscover.xml"))          
                    redirectionValidated = true;
                return redirectionValidated;
            public String GetIntiatorEntryID(string domainName)
                String result = String.Empty;
                //// Bind to EWS
                //ExchangeService service = ExchangeConnection.ExchangeService();
                //service.ImpersonatedUserId =
                //new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "[email protected]");
                //// Get LegacyDN Using the function above this one 
                string sharedByLegacyDN = domainName;
                // A conversion function from earlier
                string legacyDNinHex = ConvertStringToHex(sharedByLegacyDN);
                StringBuilder addBookEntryId = new StringBuilder();
                addBookEntryId.Append("00000000"); /* Flags */
                addBookEntryId.Append("DCA740C8C042101AB4B908002B2FE182"); /* ProviderUID */
                addBookEntryId.Append("01000000"); /* Version */
                addBookEntryId.Append("00000000"); /* Type - 00 00 00 00  = Local Mail User */
                addBookEntryId.Append(legacyDNinHex); /* Returns the userDN of the impersonated user */
                addBookEntryId.Append("00"); /* terminator bit */
                result = addBookEntryId.ToString();
                //service.ImpersonatedUserId = null;
                return result;
            public string ConvertStringToHex(string input)
                // Take our input and break it into an array
                char[] arrInput = input.ToCharArray();
                String result = String.Empty;
                // For each set of characters
                foreach (char element in arrInput)
                    if (String.IsNullOrEmpty(result))
                        result = String.Format("{0:X2}", Convert.ToUInt16(element)).ToString();
                    else
                        result += String.Format("{0:X2}", Convert.ToUInt16(element)).ToString();
                return result.ToString();
     public string CreateSharingMessageAttachment(string folderid, string userSharing, string userSharingEntryID, string invitationMailboxID, string userSharedTo, string dataType, string calendarName)
                XmlDocument sharedMetadataXML = new XmlDocument();
                string sharedMetaDataFilePath = string.Empty;
                try
                    // Create a String that contains our new sharing_metadata.xml file
                    StringBuilder metadataString = new StringBuilder("<?xml version=\"1.0\"?>");              
                    metadataString.Append("<SharingMessage xmlns=\"http://schemas.microsoft.com/sharing/2008\">");
                    metadataString.Append("<DataType>" + dataType + "</DataType>");
                    metadataString.Append("<Initiator>");
                    metadataString.Append("<Name>" + userSharing + "</Name>");
                    metadataString.Append("<SmtpAddress>" + "[email protected]" + "</SmtpAddress><EntryId>" + userSharingEntryID.Trim());
                    metadataString.Append("</EntryId>");
                    metadataString.Append("</Initiator>");
                    metadataString.Append("<Invitation>");
                    metadataString.Append("<Title>" + calendarName + "</Title>");
                    metadataString.Append("<Providers>");
                    metadataString.Append("<Provider Type=\"ms-exchange-internal\" TargetRecipients=\"" + userSharedTo + "\">");
                    metadataString.Append("<FolderId xmlns=\"http://schemas.microsoft.com/exchange/sharing/2008\">");
                    metadataString.Append(folderid);
                    metadataString.Append("</FolderId>");
                    metadataString.Append("<MailboxId xmlns=\"http://schemas.microsoft.com/exchange/sharing/2008\">");
                    metadataString.Append(invitationMailboxID);
                    metadataString.Append("</MailboxId>");
                    metadataString.Append("</Provider>");
                    metadataString.Append("</Providers>");
                    metadataString.Append("</Invitation>");
                    metadataString.Append("</SharingMessage>");
                    sharedMetadataXML.LoadXml(metadataString.ToString());
                    string tempPath = System.IO.Path.GetTempPath();
                    sharedMetaDataFilePath = tempPath + "sharing_metadata.xml";
                    sharedMetadataXML.Save(sharedMetaDataFilePath);
                catch (Exception eg)
                    throw eg;               
                return sharedMetaDataFilePath;
            public Dictionary<string, string> GetUserSettings(AutodiscoverService autodiscoverService)
                GetUserSettingsResponse userresponse = autodiscoverService.GetUserSettings(
                    "[email protected]",
                    UserSettingName.UserDisplayName,
                    UserSettingName.InternalMailboxServerDN,
                    UserSettingName.UserDN
                Dictionary<string, string> myUserSettings = new Dictionary<string, string>();
                foreach (KeyValuePair<UserSettingName, Object> usersetting in userresponse.Settings)
                    if (usersetting.Key.ToString() == "InternalMailboxServerDN")
                        int lastIndexOfEqual = usersetting.Value.ToString().LastIndexOf("=");
                        string subString = usersetting.Value.ToString().Substring(lastIndexOfEqual + 1);
                        string value = subString;
                        myUserSettings.Add("InternalMailboxServer", value.ToString());
                    if (usersetting.Key.ToString() == "UserDisplayName")
                        string[] arrResult = usersetting.Value.ToString().Split('.');
                        myUserSettings.Add("UserDisplayName", arrResult[0].ToString());
                    if (usersetting.Key.ToString() == "UserDN")
                        string[] arrResult = usersetting.Value.ToString().Split('.');
                        myUserSettings.Add("UserDN", arrResult[0].ToString());
                return myUserSettings;
            private static byte[] HexStringToByteArray(string input)
                byte[] Bytes;
                int ByteLength;
                string HexValue = "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9|||||||\xA\xB\xC\xD\xE\xF";
                ByteLength = input.Length / 2;
                Bytes = new byte[ByteLength];
                for (int x = 0, i = 0; i < input.Length; i += 2, x += 1)
                    Bytes[x] = (byte)(HexValue[Char.ToUpper(input[i + 0]) - '0'] << 4);
                    Bytes[x] |= (byte)(HexValue[Char.ToUpper(input[i + 1]) - '0']);
                return Bytes;
    am i missing anything 
    any help is appreciated 
    Thanks in advance

  • HttpStatusCode from an EWS Managed API call

    Hi there,
    I am in the process of converting a service from using WebDAV to the EWS Managed API for data access to an Exchange server (client is moving from Exchange 2007 to 2013). This service polls a mailbox folder, does some processing on emails that arrive there,
    and deletes or moves the emails once it is completed. The code I am working with has been using the status code from the HttpWebResponse returned from WebDAV requests for logging as well as handling WebExceptions (which have a response property for access
    to the request status).
    What I am wondering is whether the same status information is available for an EWS Managed API call - will calling Send() on a new EmailMessage always throw an exception if it is not successful? What are the common exception types to handle? So far I have
    simply been assuming success or exception and handling the WebException to get a status code if one of those is thrown. I will be starting to test against the new code shortly but it would be great if I had a better idea of whether I need to do more to handle
    call failures. I am quite new to developing against Exchange.
    Cheers,
    Richard

    Thanks for the quick reply Glen.
    Unfortunately none of the Managed API calls I'm making return ServiceResponseCollections which means there are no response messages for me to refer to so I'll just have to rely on the exception handling to log what has gone wrong.
    The only ExchangeService method I'm calling is FindFolders() and I'm calling FindItems() on the Folder class and Send(), Move(), and Delete() on the EmailMessage class. The linked page does state that any methods that don't return a response collection will
    throw an exception if the method does not complete successfully so I guess that is good enough for me.
    But also in the page you've linked to it appears I should be handling ServiceResponseExceptions if I want to access the response (and its error code) to get more information about the cause of an exception.
    It's a shame that the last ServiceResponseCollection from an EWS call is not available on the ExchangeService like the HttpResponseHeaders are.
    Thanks again!

  • Get list of User Mailboxes in Exchange server 2013 by using EWS managed API

    Hi all,
    I need list of Users exists in my Exchange server 2013 , i.e Mail Box Users log in name.
    i know the command in Powershell  to get list, but i need this using code[ ews managed API].
    How can i achieve this ?
    Please share your ideas

    Hi Glen,
    i follow your suggested links i wrote below code ,
    here i am getting error  
    The term 'Get-Users' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    SecureString password = new SecureString();
    string str_password = "EIS2014!@#";
    string username = "[email protected]";
    foreach (char x in str_password) { password.AppendChar(x); }
    PSCredential credential = new PSCredential(username, password);
    WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("http://ExchangeServer.admin.com/powershell"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
    //connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
    Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
    PowerShell powershell = PowerShell.Create();
    PSCommand command = new PSCommand();
    command.AddCommand("Get-Users");
    command.AddParameter("ResultSize", 50);
    powershell.Commands = command;
    runspace.Open();
    powershell.Runspace = runspace;
    var aa = powershell.Invoke();
    Please help me.

  • [office365 Exchange online][MVC5][EWS Managed Api] Need a hack to get access token ?

    Hi there, I am using following code example to get access token from Azure AD online. I need to bridge EWS managed api with office 365 Api via Azure AD. The below code is working just fine in my MVC application but I am looking for a way to get the access
    token in simple string returning  function so that I can use it to make call against EWS mananged api.
    private static string tempToken = "";
    public static string GetAccessToken()
    return tempToken;
    internal static async Task<OutlookServicesClient> EnsureOutlookServicesClientCreatedAsync(string capabilityName)
    var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
    var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
    AuthenticationContext authContext = new AuthenticationContext(Settings.Authority, new NaiveSessionCache(signInUserId));
    try
    DiscoveryClient discClient = new DiscoveryClient(Settings.DiscoveryServiceEndpointUri,
    async () =>
    var authResult = await authContext.AcquireTokenSilentAsync(Settings.DiscoveryServiceResourceId,
    new ClientCredential(Settings.ClientId,
    Settings.AppKey),
    new UserIdentifier(userObjectId,
    UserIdentifierType.UniqueId));
    return authResult.AccessToken;
    var dcr = await discClient.DiscoverCapabilityAsync(capabilityName);
    return new OutlookServicesClient(dcr.ServiceEndpointUri,
    async () =>
    var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId,
    new ClientCredential(Settings.ClientId,
    Settings.AppKey),
    new UserIdentifier(userObjectId,
    UserIdentifierType.UniqueId));
    return authResult.AccessToken;
    catch (AdalException exception)
    //Handle token acquisition failure
    if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
    authContext.TokenCache.Clear();
    return null;
    This is an excerpt from Microsoft single tenant application in MVC5.  In the code, I have created a function called GetAccessToken() which does nothing.. I am hoping you experts can help me figure out how to transfer the accessToken from EnsureOutlookServcesClientCreated
    function which is actually returning token, to  my GetAccessToken() so that I can make call against EWS managed Api. Sorry, If I sound pretty stupid but I really need your help in this regard. 
    best regards,

    Yes sir, Let me try to explain me about my scenario. I need to use EWS managed Api with office 365 Rest Api to get benefits from both the Apis. Here is here code I am using to connect to EWS managed Api but it is failing with 401:Unauthorized.  I already
    have "Full Access" turned on in Azure AD.  I have the access token from AZure AD and want to use it to make call against EWS managed Api.
    var outlookClient = await AuthHelper.EnsureOutlookServicesClientCreatedAsync("Mail");
    //IPagedCollection<IMessage> messagesResults = await outlookClient.Me.Messages.ExecuteAsync();
    // Get the ID of the first message.
    // string messageId = messagesResults.CurrentPage[0].Id;
    string tokenx = AuthHelper.GetAccessToken();
    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
    service.HttpHeaders.Add("Authorization", "Bearer " + tokenx);
    service.PreAuthenticate = true;
    service.SendClientLatencies = true;
    service.EnableScpLookup = false;
    service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
    // Get all the folders in the message's root folder.
    ExFolder rootfolder = ExFolder.Bind(service, WellKnownFolderName.MsgFolderRoot);S
    Scenario of my migration application:
    1. I have a Gmail mailbox email in Raw(complete email in base64-urlsafe with attachments) format with RFC2822. I need to migrate this mailbox to Exchange online. I believe EWS managed Api has better support on this one.
    2.  Likewise I need to migrate Gmail Calendars, Tasks and Contacts to Exchange online.
    I would be highly grateful to you , if you tell me how to bridge EWS managed Api with office 365 Api.
    best regards,

  • EWS Managed API Should I use GUID or DefaultExtendedPropertySet.PublicStrings while constructing DefaultExtendedPropertySet

    I am developing C# .NET Framework 4.5 Windows Form application using EWS Managed API 1.2 with Exchange Server 2007 which performs some sort of syncing of mails.
    Now that I am dealing with Extended Properties, I want to be clear some things:
    Q1. What is the purpose of DefaultExtendedPropertySet class?
    MSDN says "Defines
    the default sets of extended properties."
    Is it just to group the extended properties?
    If yes, why is the grouping there at first place?
    Do we have any Ews API method which can fetch values of all extended properties belonging to the same group on an item?
    Q2. I am unable to decide whether should I use custom GUID or DefaultExtendedPropertySet.PublicStrings while
    constructing ExtendedPropertyDefinition:
    ExtendedPropertyDefinition MyXProp = new ExtendedPropertyDefinition(
    DefaultExtendedPropertySet.PublicStrings,
    "MyXProp", MapiPropertyType.String);
    OR
    Guid MyPropertySetId = new Guid("{C11FF724-AA03-4555-9952-FA248A11C3E}");
    ExtendedPropertyDefinition extendedPropertyDefinition = new ExtendedPropertyDefinition(
    MyPropertySetId, "MyXProp", MapiPropertyType.String);
    What are the factors that should dictate the above decision?
    Also what difference it makes by above two approaches?

    1.  Have a read of
    http://blogs.technet.com/b/exchange/archive/2009/04/06/3407221.aspx which explains the history and why's and what's of named properties.
    >>Do we have any Ews API method which can fetch values of all extended properties belonging to the same group on an item?
    No EWS will only return the properties you ask it to return there is no way to enumerate all the extended properties on an Item.
    2. There is no right or wrong answer to this using PS_PUBLIC_STRINGS with a generic propertyname is generally a bad idea because another product could decide to use the same propertyname and you have a clash. So using your own guid can have
    it's advantages. Personally I find working with PS_PUBLIC_STRINGS make things more discoverable and easier to use if you need to integrate further with MAPI or Transport Agents.
    Cheers
    Glen

  • Internal ArgumentOutOfRangeException in EWS Managed API

    Dear Microsoft,
    We’ve been happily using the EWS Managed API for one of our products, but recently ran into an obscure problem with it.
    While forwarding e-mails always used to work flawlessly, we recently started getting the following, strange error at a client site: an ArgumentOutOfRangeException in some get_Item() method over 20 layers deep in the call stack.
     Microsoft.Exchange.WebServices.dll version number: 15.0.516.14
    The stacktrace:
    System.ArgumentOutOfRangeException: index is out of range.
    Parameter name: index
       at Microsoft.Exchange.WebServices.Data.ComplexPropertyCollection`1.get_Item(Int32 index)
       at Microsoft.Exchange.WebServices.Data.ComplexPropertyCollection`1.UpdateFromXml(EwsServiceXmlReader reader, XmlNamespace xmlNamespace, String xmlElementName)
       at Microsoft.Exchange.WebServices.Data.ComplexProperty.UpdateFromXml(EwsServiceXmlReader reader, String xmlElementName)
       at Microsoft.Exchange.WebServices.Data.ComplexPropertyDefinitionBase.InternalLoadFromXml(EwsServiceXmlReader reader, PropertyBag propertyBag)
       at Microsoft.Exchange.WebServices.Data.ComplexPropertyDefinitionBase.LoadPropertyValueFromXml(EwsServiceXmlReader reader, PropertyBag propertyBag)
       at Microsoft.Exchange.WebServices.Data.PropertyBag.LoadFromXml(EwsServiceXmlReader reader, Boolean clear, PropertySet requestedPropertySet, Boolean onlySummaryPropertiesRequested)
       at Microsoft.Exchange.WebServices.Data.ItemAttachment.TryReadElementFromXmlToPatch(EwsServiceXmlReader reader)
       at Microsoft.Exchange.WebServices.Data.ComplexProperty.InternalLoadFromXml(EwsServiceXmlReader reader, XmlNamespace xmlNamespace, String xmlElementName, Func`2 readAction)
       at Microsoft.Exchange.WebServices.Data.ComplexProperty.UpdateFromXml(EwsServiceXmlReader reader, XmlNamespace xmlNamespace, String xmlElementName)
       at Microsoft.Exchange.WebServices.Data.ComplexPropertyCollection`1.UpdateFromXml(EwsServiceXmlReader reader, XmlNamespace xmlNamespace, String xmlElementName)
       at Microsoft.Exchange.WebServices.Data.ComplexProperty.UpdateFromXml(EwsServiceXmlReader reader, String xmlElementName)
       at Microsoft.Exchange.WebServices.Data.ComplexPropertyDefinitionBase.InternalLoadFromXml(EwsServiceXmlReader reader, PropertyBag propertyBag)
       at Microsoft.Exchange.WebServices.Data.ComplexPropertyDefinitionBase.LoadPropertyValueFromXml(EwsServiceXmlReader reader, PropertyBag propertyBag)
       at Microsoft.Exchange.WebServices.Data.PropertyBag.LoadFromXml(EwsServiceXmlReader reader, Boolean clear, PropertySet requestedPropertySet, Boolean onlySummaryPropertiesRequested)
       at Microsoft.Exchange.WebServices.Data.EwsServiceXmlReader.ReadServiceObjectsCollectionFromXml[TServiceObject](XmlNamespace collectionXmlNamespace, String collectionXmlElementName, GetObjectInstanceDelegate`1 getObjectInstanceDelegate, Boolean
    clearPropertyBag, PropertySet requestedPropertySet, Boolean summaryPropertiesOnly)
       at Microsoft.Exchange.WebServices.Data.CreateItemResponseBase.ReadElementsFromXml(EwsServiceXmlReader reader)
       at Microsoft.Exchange.WebServices.Data.ServiceResponse.LoadFromXml(EwsServiceXmlReader reader, String xmlElementName)
       at Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest`1.ParseResponse(EwsServiceXmlReader reader)
       at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ReadResponse(EwsServiceXmlReader ewsXmlReader)
       at Microsoft.Exchange.WebServices.Data.SimpleServiceRequestBase.ReadResponseXml(Stream responseStream)
       at Microsoft.Exchange.WebServices.Data.SimpleServiceRequestBase.ReadResponse(IEwsHttpWebResponse response)
       at Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest`1.Execute()
       at Microsoft.Exchange.WebServices.Data.ExchangeService.InternalCreateItems(IEnumerable`1 items, FolderId parentFolderId, Nullable`1 messageDisposition, Nullable`1 sendInvitationsMode, ServiceErrorHandling errorHandling)
       at Microsoft.Exchange.WebServices.Data.Item.InternalCreate(FolderId parentFolderId, Nullable`1 messageDisposition, Nullable`1 sendInvitationsMode)
       at Microsoft.Exchange.WebServices.Data.EmailMessage.InternalSend(FolderId parentFolderId, MessageDisposition messageDisposition)
       at Microsoft.Exchange.WebServices.Data.EmailMessage.SendAndSaveCopy()
    The code that triggers it:
    ExtendedPropertyDefinition pr_flags =
    new
    ExtendedPropertyDefinition(3591,
    MapiPropertyType.Integer);
    itemAttachment.Item.SetExtendedProperty(pr_flags,
    "1");
    itemAttachment.Name = originalEwsMailObject.Subject;
    bodyBuilder.AppendLine("[product name etc. snipped]   forwarded because: \r\n\r\n"
    + reason);
    myMail.Body = bodyBuilder.ToString();
    myMail.ToRecipients.Add(adminAddress);
    myMail.SendAndSaveCopy();
    Does anyone know how to solve this, or is it perhaps a bug in the API and should I report it somewhere?
    Kind regards, 
    Tom Kersbergen
    Docspo B.V.

    The Managed API is now open source so if you go to
    https://github.com/OfficeDev/ews-managed-api clone the repository and compile a version to use in debugging then reproduce your problem you should be able to work out what's going wrong.
    Its looks like its having problems reading the response so you may want enable tracing
    https://msdn.microsoft.com/en-us/library/office/dn495632(v=exchg.150).aspx or watch the request/response with something like fiddler.
    Cheers
    Glen

  • Deleted Item not actually getting deleted or **delay** deleted thus getting refetched (EWS Managed API)

    I am polling Exchange Server to fetch all the mails left in the Inbox and then fetching them, processing them and finally moving them to the deleted folder. My procedure takes following form of EWS Managed API calls:
    1 itemResults = service.FindItems(WellKnownFolderName.Inbox, itemView);
    2 //some code...
    3 service.LoadPropertiesForItems(itemResults.Items, itItemPropSet);
    4 //some code...
    5 foreach(Item item in itemResults)
    6 {
    7 //process item
    8 item.Delete(DeleteMode.MoveToDeletedItems);
    9 }
    To test this code I flooded the inbox with 5000 mails, 5 threads flooding 1000 mails each at the interval of 4ms.
    After test run, I realized some mails are getting processed multiple times.
    When I read the soap traces logged using TraceListener, I realized that when there are more than 100 mails in the inbox, there are more SOAP packets were dispatched in burst of 100s.
    Logically below set of SOAP Packets (let us call it "Set 1") should occur only once:
    <m:FindItem>...</m:FindItem> //generated by line 1
    <m:FindItemResponse>...</m:FindItemResponse> //generated by line 1
    <m:GetItem>...</m:GetItem> //generated by line 3
    <m:GetItemResponse>...</m:GetItemResponse> //generated by line 3
    followed x number of Delete SOAP packets for x number of mails in the Inbox
    <m:DeleteItem>...</m:DeleteItem> //generated by line 8
    <m:DeleteItemRepsonse>...</m:DeleteItemRepsonse> //generated by line 8
    However if there are say 325 mails in the inbox, then there first occurs 4 occurences of Set 1 followed by Delete SOAP packest as follows:
    //1st occurence
    <m:FindItem>100 items</m:FindItem>
    <m:FindItemResponse>100 items</m:FindItemResponse>
    <m:GetItem>100 items</m:GetItem>
    <m:GetItemResponse>35 items</m:GetItemResponse>
    //2nd occurence
    <m:FindItem>100 items</m:FindItem>
    <m:FindItemResponse>100 items</m:FindItemResponse>
    <m:GetItem>100 items</m:GetItem>
    <m:GetItemResponse>35 items</m:GetItemResponse>
    //3rd occurence
    <m:FindItem>100 items</m:FindItem>
    <m:FindItemResponse>100 items</m:FindItemResponse>
    <m:GetItem>100 items</m:GetItem>
    <m:GetItemResponse>100 items</m:GetItemResponse>
    //4th occurence
    <m:FindItem>35 items</m:FindItem>
    <m:FindItemResponse>35 items</m:FindItemResponse>
    <m:GetItem>35 items</m:GetItem>
    <m:GetItemResponse>35 items</m:GetItemResponse> //****followed by 335 occurences of the Delete SOAP packets****<m:DeleteItem>...</m:DeleteItem>  
    <m:DeleteItemRepsonse>...</m:DeleteItemRepsonse> 
    //334 more of above
    So there are 100 + 100 + 100 + 35 = 335 items actually getting handled, which is 10 more than what are actually present in the inbox. 
    Also notice that Delete SOAP packets are queued till end. They are not dispatched in burst.
    First thing I realize dispatching SOAP packets in burst of 100s is EWS Managed API behavior. I guess there must be traffic reason behind it and there must be some configuration setting to tweak it.
    Q1. How can we change this count of 100?
    I inferred that there are some overlaps in fetching of mails.
    So I copy pasted SOAP Traces for first two of
    <m:GetItem>100 items</m:GetItem>
    in two different files, and compared them in text comparer. I realised that some mails that are at the end of the first 100s were reappearing at the beginning of 2nd 100: 
    This is the pattern in many test runs.
    Due to this these overlapping mails, these mails are getting processed twice. Also the attempt to second time delete them was throwing exception : The specified object was not found in the store.
    So I guess there is time delay in delete mail API call and mails actually getting deleted, between which they are getting refetched.
    Q2. How can I handle this to avoid redundant processing of mails and unnecessary exceptions.

    I am polling Exchange Server to fetch all the mails left in the Inbox and then fetching them, processing them and finally moving them to the deleted folder. My procedure takes following form of EWS Managed API calls:
    1 itemResults = service.FindItems(WellKnownFolderName.Inbox, itemView);
    2 //some code...
    3 service.LoadPropertiesForItems(itemResults.Items, itItemPropSet);
    4 //some code...
    5 foreach(Item item in itemResults)
    6 {
    7 //process item
    8 item.Delete(DeleteMode.MoveToDeletedItems);
    9 }
    To test this code I flooded the inbox with 5000 mails, 5 threads flooding 1000 mails each at the interval of 4ms.
    After test run, I realized some mails are getting processed multiple times.
    When I read the soap traces logged using TraceListener, I realized that when there are more than 100 mails in the inbox, there are more SOAP packets were dispatched in burst of 100s.
    Logically below set of SOAP Packets (let us call it "Set 1") should occur only once:
    <m:FindItem>...</m:FindItem> //generated by line 1
    <m:FindItemResponse>...</m:FindItemResponse> //generated by line 1
    <m:GetItem>...</m:GetItem> //generated by line 3
    <m:GetItemResponse>...</m:GetItemResponse> //generated by line 3
    followed x number of Delete SOAP packets for x number of mails in the Inbox
    <m:DeleteItem>...</m:DeleteItem> //generated by line 8
    <m:DeleteItemRepsonse>...</m:DeleteItemRepsonse> //generated by line 8
    However if there are say 325 mails in the inbox, then there first occurs 4 occurences of Set 1 followed by Delete SOAP packest as follows:
    //1st occurence
    <m:FindItem>100 items</m:FindItem>
    <m:FindItemResponse>100 items</m:FindItemResponse>
    <m:GetItem>100 items</m:GetItem>
    <m:GetItemResponse>35 items</m:GetItemResponse>
    //2nd occurence
    <m:FindItem>100 items</m:FindItem>
    <m:FindItemResponse>100 items</m:FindItemResponse>
    <m:GetItem>100 items</m:GetItem>
    <m:GetItemResponse>35 items</m:GetItemResponse>
    //3rd occurence
    <m:FindItem>100 items</m:FindItem>
    <m:FindItemResponse>100 items</m:FindItemResponse>
    <m:GetItem>100 items</m:GetItem>
    <m:GetItemResponse>100 items</m:GetItemResponse>
    //4th occurence
    <m:FindItem>35 items</m:FindItem>
    <m:FindItemResponse>35 items</m:FindItemResponse>
    <m:GetItem>35 items</m:GetItem>
    <m:GetItemResponse>35 items</m:GetItemResponse> //****followed by 335 occurences of the Delete SOAP packets****<m:DeleteItem>...</m:DeleteItem>  
    <m:DeleteItemRepsonse>...</m:DeleteItemRepsonse> 
    //334 more of above
    So there are 100 + 100 + 100 + 35 = 335 items actually getting handled, which is 10 more than what are actually present in the inbox. 
    Also notice that Delete SOAP packets are queued till end. They are not dispatched in burst.
    First thing I realize dispatching SOAP packets in burst of 100s is EWS Managed API behavior. I guess there must be traffic reason behind it and there must be some configuration setting to tweak it.
    Q1. How can we change this count of 100?
    I inferred that there are some overlaps in fetching of mails.
    So I copy pasted SOAP Traces for first two of
    <m:GetItem>100 items</m:GetItem>
    in two different files, and compared them in text comparer. I realised that some mails that are at the end of the first 100s were reappearing at the beginning of 2nd 100: 
    This is the pattern in many test runs.
    Due to this these overlapping mails, these mails are getting processed twice. Also the attempt to second time delete them was throwing exception : The specified object was not found in the store.
    So I guess there is time delay in delete mail API call and mails actually getting deleted, between which they are getting refetched.
    Q2. How can I handle this to avoid redundant processing of mails and unnecessary exceptions.

  • EWS Managed API 2.0 - Attachment.Inline property value incorrect

    I have an application where I am reading the emails from a mailbox using EWS managed api. One of the things that I check for in the email message is whether it has any inline attachments. 
    I am having this issue where I have an email with an image in the body and an excel file attached. When I check the Attachment.Inline property for the image, it says "false". This is not right. It should say "true".
    I tried to reproduce this behavior by creating an email of my own with the same image and another excel file as attachment but cannot reproduce it.
    I tried stripping the excel attachment and forwarding the problem email with just the picture in it's body but I still see the inline property as false.
    The text format on all these emails is HTML.
    I am not sure why inline is false and why I am unable to reproduce this behavior.
    Thanks.

    Yes FolderId's (like MessageId's) are globally unique.
    >> In other words: Can 2 folders have the same id when accessing them?
    No see
    http://msdn.microsoft.com/en-us/library/ee178877(v=exchg.80).aspx
    Cheers
    Glen

  • How to get list of Users[MailBoxes] in Exchange Server 2013 by using EWS Managed API

    Hi all,
    I need list of Users exists in my Exchange server 2013 , i.e Mail Box Users login name.
    I was  created Full Access permissions of all users to Admin user account,  to access each user Mailbox programatically 
    i need the list of Mailboxes in exchange server .
    MailBox  mailbox = new MailBox("user");
    Please share your ideas

    Hi,
    We can run the following command in Exchange Management Shell to get all user mailboxes name and export it to a .csv file:
    Get-Mailbox -ResultSize Unlimited | Select Name,Alias,RecipientTypeDetails | Export-Csv c:\Users.csv
    If you want to retrieve the list of users by using EWS Managed API, I suggest you can ask a question in Exchange Development forum for more suggestion:
    http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/threads
    Regards,
    Winnie Liang
    TechNet Community Support

  • Create and send an email as a delegate using EWS Managed API

    Hi All,
    I would like to create and send an email as a delegate using EWS Managed API for that i have crated one user as a delegate to that mailbox owner.
    after adding user as delegate, when i try to create an email The EmailMessage class taking only FolderId as parameter but not taking Mailbox object as parameter. But in web reference they said that EmailMessage taking FolderId and Mailbox object as parameter.
    EmailMessage message = new EmailMessage(service);
    message.Subject = "Company Soccer Team";
    message.Body = "Are you interested in joining?";
    message.ToRecipients.Add("[email protected]");
    message.Save(new FolderId(WellKnownFolderName.Drafts, new Mailbox("[email protected]")));https://msdn.microsoft.com/EN-US/library/office/dn641963(v=exchg.150).aspx#bk_createewsmacould you people please help me on this?ThanksNaresh

    Thanks for reply glen.
    I have added delegate using Add-MailboxPermissions. Now i am able to save an email in mailbox owner drafts
    folder.
    Glen,
     I have a one more question.(I am using EWS Managed API).
    I(owner) have shared my calendar(eg. samplecalenderfolder) with another user(delegate) (i.e.,he is the
    delegate of my mailbox) and i have given only permission to the this folder(samplecalenderfolder)
    only and the permission level is Reviewer.
    if i login with user(i.e.delegate) i am not able to get the shared calendar folders(i.e.,samplecalenderfolder)
    that what i a have shared.
    below is the code snippet i am using to get the calendar folders.
    Folder folder = Folder.Bind(service,WellKnownFolderName.Calendar);
    FindFoldersResults addtionalFolders = service.FindFolders(folder.Id, new FolderView(10));
    could you please tell us how to get the shared calendar folders.
    Thanks
    Naresh

  • Difference between attachment display name in Outlook and FileAttachment.Name in EWS Managed API

    Hello.
    Does anybody know why a plain-text attachment would appear to have one name when viewed in Outlook and saved from there to my computer, but have a different name when I load the attachment from the message using the EWS Managed Api - specifically using the
    EmailMessage and FileAttachment classes from Microsoft.Exchange.WebServices.Data?
    I am connecting to on-premises MS Exchange 2010 with SP3 and using v2 of the EWS libraries.
    Many thanks in advanced for any help you can offer.

    Outlook stopped using DisplayName (PR_DISPLAY_NAME) for attachments back in the Outlook 2002 days to prevent malicious code from displaying MyEvil.exe as ReadMe.txt.
    Dmitry Streblechenko (MVP)
    http://www.dimastr.com/redemption
    Redemption - what the Outlook
    Object Model should have been
    Version 5.5 is now available!

  • EWS Managed API 2.1 Download: 32 or 64 bit is not clear

    Hello,
    When I download EWS Managed API 2.1 from the following link, I don't get both 32bit and 64 bit options.
    http://www.microsoft.com/en-ca/download/details.aspx?id=42022
    When I install it, it installs it in the 32 bit program file folder, which concerns me:
    C:\Program Files (x86)\Microsoft\Exchange\Web Services\2.1\
    How do I make sure that I am using the 64 bit of the EWS Managed API 2.1
    Thank you,

    Alan, we have consolidated the Managed API to just one msi. The dll's in the IL are not architecture specific, so they should work the same way for both x86 or 64 bit.

Maybe you are looking for

  • Lion Recovery says I haven't purchased

    I will explain exactly how I came to where I am today as I think it may be important so sorry if its a bit long! I have been using Windows since it began and wanted to see what using a mac was like.  What I did is head over to ebay and got myself a m

  • DNS Advice Needed

    Is it possible or advisable to let a standalone webserver hosting a handful of websites to be it's own dns server - in terms of holding the authoritative records for the domains hosted? Thank you

  • Selection Screen getting refreshed after execution..

    Hello All, I have a strange problem.. My selection-screen values are getting refreshed after execution and come back to selection screen. I am using normal ALV Fm to display the values. Can some suggest a possible reason? Many thanks, V Nair

  • Threadgroup - nullpointer expcetion (help!)

    Please can anybody explain why the following code throws a nullpointer exception in the //PROBLEM HERE line? My JBuilder debugger shows that when i is 1, my threads array has 101 threads in it, but when I try to do a Thread t = threads[i] t ends up a

  • Help please copying, importing files into Dreamweaver

    Hello, I am having trouble imporitng files into dreamweaver from Godady. What is my best route. I downloaded Filezilla and connect my ISP, Hosting and passwords and successfuly my files loaded to filezilla. I am perplexed at the next step as to how t