ews-managed-api icon indicating copy to clipboard operation
ews-managed-api copied to clipboard

"System.ArgumentOutOfRangeException: index is out of range." exception is raised while saving an item with ItemAttachment

Open rsrini83 opened this issue 7 years ago • 17 comments

Hi,

I'm trying to save an item in Exchange online into a folder (Inside Inbox), this item has ItemAttachment added. Seems item is being saved to the server properly, however client code throws below exception.

Here is the code to add ItemAttachment,

                        ItemAttachment<EmailMessage> attachment = eMessage.Attachments.AddItemAttachment<EmailMessage>();
                        attachment.ContentType = ewsAttachment.ContentType;
                        attachment.IsInline = ewsAttachment.IsInline;
                        attachment.Name = ewsAttachment.Name;
                        ExtendedPropertyDefinition PR_Flags = new ExtendedPropertyDefinition(3591, MapiPropertyType.Integer);
                        attachment.Item.SetExtendedProperty(PR_Flags, "1");
                        attachment.Item.MimeContent = new MimeContent("UTF-8", Convert.FromBase64String(ewsAttachment.Base64));

ewsAttachment -> is our own model which contains the attachment in Base64.

Parameter name: index at Microsoft.Exchange.WebServices.Data.ComplexPropertyCollection1.get_Item(Int32 index) in C:\lib\ews-managed-api-master\ComplexProperties\ComplexPropertyCollection.cs:line 410 at Microsoft.Exchange.WebServices.Data.ComplexPropertyCollection1.UpdateFromXml(EwsServiceXmlReader reader, XmlNamespace xmlNamespace, String xmlElementName) in C:\lib\ews-managed-api-master\ComplexProperties\ComplexPropertyCollection.cs:line 165 at Microsoft.Exchange.WebServices.Data.ComplexPropertyDefinitionBase.InternalLoadFromXml(EwsServiceXmlReader reader, PropertyBag propertyBag) in C:\lib\ews-managed-api-master\PropertyDefinitions\ComplexPropertyDefinitionBase.cs:line 111 at Microsoft.Exchange.WebServices.Data.ComplexPropertyDefinitionBase.LoadPropertyValueFromXml(EwsServiceXmlReader reader, PropertyBag propertyBag) in C:\lib\ews-managed-api-master\PropertyDefinitions\ComplexPropertyDefinitionBase.cs:line 150 at Microsoft.Exchange.WebServices.Data.PropertyBag.LoadFromXml(EwsServiceXmlReader reader, Boolean clear, PropertySet requestedPropertySet, Boolean onlySummaryPropertiesRequested) in C:\lib\ews-managed-api-master\Core\PropertyBag.cs:line 564 at Microsoft.Exchange.WebServices.Data.ItemAttachment.TryReadElementFromXmlToPatch(EwsServiceXmlReader reader) in C:\lib\ews-managed-api-master\ComplexProperties\ItemAttachment.cs:line 150 at Microsoft.Exchange.WebServices.Data.ComplexProperty.InternalLoadFromXml(EwsServiceXmlReader reader, XmlNamespace xmlNamespace, String xmlElementName, Func2 readAction) in C:\lib\ews-managed-api-master\ComplexProperties\ComplexProperty.cs:line 224 at Microsoft.Exchange.WebServices.Data.ComplexProperty.UpdateFromXml(EwsServiceXmlReader reader, XmlNamespace xmlNamespace, String xmlElementName) in C:\lib\ews-managed-api-master\ComplexProperties\ComplexProperty.cs:line 196 at Microsoft.Exchange.WebServices.Data.ComplexPropertyCollection1.UpdateFromXml(EwsServiceXmlReader reader, XmlNamespace xmlNamespace, String xmlElementName) in C:\lib\ews-managed-api-master\ComplexProperties\ComplexPropertyCollection.cs:line 175 at Microsoft.Exchange.WebServices.Data.ComplexPropertyDefinitionBase.InternalLoadFromXml(EwsServiceXmlReader reader, PropertyBag propertyBag) in C:\lib\ews-managed-api-master\PropertyDefinitions\ComplexPropertyDefinitionBase.cs:line 111 at Microsoft.Exchange.WebServices.Data.ComplexPropertyDefinitionBase.LoadPropertyValueFromXml(EwsServiceXmlReader reader, PropertyBag propertyBag) in C:\lib\ews-managed-api-master\PropertyDefinitions\ComplexPropertyDefinitionBase.cs:line 150 at Microsoft.Exchange.WebServices.Data.PropertyBag.LoadFromXml(EwsServiceXmlReader reader, Boolean clear, PropertySet requestedPropertySet, Boolean onlySummaryPropertiesRequested) in C:\lib\ews-managed-api-master\Core\PropertyBag.cs:line 564 at Microsoft.Exchange.WebServices.Data.EwsServiceXmlReader.ReadServiceObjectsCollectionFromXml[TServiceObject](XmlNamespace collectionXmlNamespace, String collectionXmlElementName, GetObjectInstanceDelegate1 getObjectInstanceDelegate, Boolean clearPropertyBag, PropertySet requestedPropertySet, Boolean summaryPropertiesOnly) in C:\lib\ews-managed-api-master\Core\EwsServiceXmlReader.cs:line 179 at Microsoft.Exchange.WebServices.Data.CreateItemResponseBase.ReadElementsFromXml(EwsServiceXmlReader reader) in C:\lib\ews-managed-api-master\Core\Responses\CreateItemResponseBase.cs:line 65 at Microsoft.Exchange.WebServices.Data.ServiceResponse.LoadFromXml(EwsServiceXmlReader reader, String xmlElementName) in C:\lib\ews-managed-api-master\Core\Responses\ServiceResponse.cs:line 120 at Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest1.ParseResponse(EwsServiceXmlReader reader) in C:\lib\ews-managed-api-master\Core\Requests\MultiResponseServiceRequest.cs:line 65 at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ReadResponse(EwsServiceXmlReader ewsXmlReader, WebHeaderCollection responseHeaders) in C:\lib\ews-managed-api-master\Core\Requests\ServiceRequestBase.cs:line 473 at Microsoft.Exchange.WebServices.Data.SimpleServiceRequestBase.ReadResponse(IEwsHttpWebResponse response) in C:\lib\ews-managed-api-master\Core\Requests\SimpleServiceRequestBase.cs:line 142 at Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest1.Execute() in C:\lib\ews-managed-api-master\Core\Requests\MultiResponseServiceRequest.cs:line 132 at Microsoft.Exchange.WebServices.Data.ExchangeService.InternalCreateItems(IEnumerable1 items, FolderId parentFolderId, Nullable1 messageDisposition, Nullable1 sendInvitationsMode, ServiceErrorHandling errorHandling) in C:\lib\ews-managed-api-master\Core\ExchangeService.cs:line 456 at Microsoft.Exchange.WebServices.Data.ExchangeService.CreateItem(Item item, FolderId parentFolderId, Nullable1 messageDisposition, Nullable1 sendInvitationsMode) in C:\lib\ews-managed-api-master\Core\ExchangeService.cs:line 515 at Microsoft.Exchange.WebServices.Data.Item.InternalCreate(FolderId parentFolderId, Nullable1 messageDisposition, Nullable1 sendInvitationsMode) in C:\lib\ews-managed-api-master\Core\ServiceObjects\Items\Item.cs:line 213 at Microsoft.Exchange.WebServices.Data.Item.Save(FolderId parentFolderId) in C:\lib\ews-managed-api-master\Core\ServiceObjects\Items\Item.cs:line 351 at CloudControlExchangeConnector.Helpers.Implementation.ExchangeHelper.<>c__DisplayClass23_3.<RestoreItemToMailboxFolder>b__2() at CloudControlExchangeConnector.Controller.Helpers.Implementation.RetryHelper.RetryEWSCall(Action method, Job jobDetail, ExchangeService exchangeService, Int32 retryCount, Int32 sleepTime, String callerName)

at Microsoft.Exchange.WebServices.Data.ServiceObject.ThrowIfThisIsNotNew() in C:\lib\ews-managed-api-master\Core\ServiceObjects\ServiceObject.cs:line 70 at Microsoft.Exchange.WebServices.Data.Item.InternalCreate(FolderId parentFolderId, Nullable1 messageDisposition, Nullable1 sendInvitationsMode) in C:\lib\ews-managed-api-master\Core\ServiceObjects\Items\Item.cs:line 211 at Microsoft.Exchange.WebServices.Data.Item.Save(FolderId parentFolderId) in C:\lib\ews-managed-api-master\Core\ServiceObjects\Items\Item.cs:line 351 at CloudControlExchangeConnector.Helpers.Implementation.ExchangeHelper.<>c__DisplayClass23_3.<RestoreItemToMailboxFolder>b__2() at CloudControlExchangeConnector.Controller.Helpers.Implementation.RetryHelper.RetryEWSCall(Action method, Job jobDetail, ExchangeService exchangeService, Int32 retryCount, Int32 sleepTime, String callerName)

rsrini83 avatar Dec 05 '17 13:12 rsrini83

After further debugging, identified the failing scenario.

This issue is happening If there is a FileAttachment in the ItemAttachment.

If attaching an email message(without any attachment) as ItemAttachment then there is no issue.

Anyone faced the issue? I'm stuck here, any help would be greatly appreciated.

rsrini83 avatar Dec 05 '17 18:12 rsrini83

When you say "ewsAttachment -> is our own model which contains the attachment in Base64.", how are you getting this base64? And you say that this is happens when you attach this file attachment on an item attachment which is on an item, right? What happens if you try to attach this file attachment (via the MIME content) directly to an item?

davster avatar Dec 05 '17 19:12 davster

Hi David,

how are you getting this base64 ? Download the ItemAttachment using MIME content and convert it to base64.

Let me give an example,

Assume i'm downloading mailitem1 -> which has an itemattachment mailitem2(EmailMessage). mailitem2 has a file attachment. In this scenario i'm getting the index error. However if mailitem2 does not have any attachment then there is no issue.

What happens if you try to attach this file attachment (via the MIME content) directly to an item? It works, however i need to attach mail item as is.

rsrini83 avatar Dec 05 '17 20:12 rsrini83

Thanks for the info. I'll see if I can repro on my side and if so open a bug to fix it.

davster avatar Dec 05 '17 20:12 davster

Sure. Let me know if you need any sample eml, can create one and send you.

rsrini83 avatar Dec 05 '17 20:12 rsrini83

Hello David,

Are you able to reproduce the issue? Any suggestion to resolve the issue?

rsrini83 avatar Dec 07 '17 16:12 rsrini83

I am having this same problem.

I am using the API to copy and email from one exchange server then send it on a different one (for internal use) If the email I am trying to copy has a file attachment in the mime content then I error out when I try to send it.

Did you ever come up with a solution to your issue?

shooddelta avatar Oct 09 '18 12:10 shooddelta

Did this issue ever got solved? I am facing the exact same problem and I'm stuck!

tallalkazmi avatar Apr 08 '19 09:04 tallalkazmi

I am having this same problem.

I am using the API to copy and email from one exchange server then send it on a different one (for internal use) If the email I am trying to copy has a file attachment in the mime content then I error out when I try to send it.

Did you ever come up with a solution to your issue?

Is there any workaround for this?

tallalkazmi avatar Apr 08 '19 09:04 tallalkazmi

The exception is because of response in 2013 schema like below:

NoError

this.Count will be 0 after read the first attachment element.

Resolved by edit the ComplexPropertyCollection.cs, add "&& this.Count>0" when dealing with complexproperty.

///

/// Loads from XML to update itself. /// /// The reader. /// The XML namespace. /// Name of the XML element. internal override void UpdateFromXml( EwsServiceXmlReader reader, XmlNamespace xmlNamespace, string xmlElementName) { reader.EnsureCurrentNodeIsStartElement(xmlNamespace, xmlElementName);

        if (!reader.IsEmptyElement)
        {
            int index = 0;
            do
            {
              
                reader.Read();

                if (reader.IsStartElement() && this.Count>0)
                {
                    TComplexProperty complexProperty = this.CreateComplexProperty(reader.LocalName);
                    TComplexProperty actualComplexProperty = this[index++];

                    if (complexProperty == null || !complexProperty.GetType().IsInstanceOfType(actualComplexProperty))
                    {
                        throw new ServiceLocalException(Strings.PropertyTypeIncompatibleWhenUpdatingCollection);
                    }

                    actualComplexProperty.UpdateFromXml(reader, xmlNamespace, reader.LocalName);
                }
            }
            while (!reader.IsEndElement(xmlNamespace, xmlElementName) );
        }
    }

GeoffreyYue1 avatar Jul 11 '19 05:07 GeoffreyYue1

@tallalkazmi @shooddelta @rsrini83 for my purpose, i workarounded successfully by adding the item as a FileAttachment:

//assume item = the EmailMessage to attach, message = the EmailMessage to attach to PropertySet psPropSet = new PropertySet(BasePropertySet.FirstClassProperties); psPropSet.Add(ItemSchema.MimeContent); var tmpItem = EmailMessage.Bind(context, item.Id); tmpItem.Load(psPropSet); message.Attachments.AddFileAttachment(item.Subject + ".eml", tmpItem.MimeContent.Content);

beware that this will not copy all outlook properties, e.g. Categories, which was no problem in my scenario.

thegnu avatar Apr 16 '20 12:04 thegnu

I was also having this problem, when I was attaching an Email Item (with file attachments) as an Item Attachment, to a new email, which I was trying to create in an Inbox folder of other mailbox. Solution from @GeoffreyYue1 worked for me too.

laeeq avatar Apr 19 '20 19:04 laeeq

I am having the same issue as well. I'm new to this and how do I implement @GeoffreyYue1 solution? Where do I find ComplexPropertyCollection.cs, im using EWS.

HenryLehloo avatar Apr 22 '20 05:04 HenryLehloo

I am having the same issue as well. I'm new to this and how do I implement @GeoffreyYue1 solution? Where do I find ComplexPropertyCollection.cs, im using EWS.

You actually have to download the entire source code, compile in Visual Studio 2017 or 2019, and then search the file 'ComplexPropertyCollection.cs', which resides in the sub folder '\ews-managed-api-master\ComplexProperties'.

Then, you would have to change line number 162 from if (reader.IsStartElement()) to if (reader.IsStartElement() && this.Count > 0)

I can provide you modified Ews DLL with the fix (which I built) if you want. Thanks

laeeq avatar Apr 22 '20 17:04 laeeq

@laeeq can you please provide the DLL, thank you very much.

HenryLehloo avatar Apr 22 '20 18:04 HenryLehloo

@laeeq can you please provide the DLL, thank you very much.

Here is the link: https://www.dropbox.com/s/zq30p5ozjvir5g5/Microsoft.Exchange.WebServices.zip?dl=0

Thanks

laeeq avatar Apr 22 '20 20:04 laeeq

I am experiencing the same issue as well. I wish this would get addressed in an updated version.

I will roll with @GeoffreyYue1 's fix.

mralecthomas avatar Sep 08 '20 22:09 mralecthomas