WcfCoreMtomEncoder icon indicating copy to clipboard operation
WcfCoreMtomEncoder copied to clipboard

Sequence contains no elements Error

Open bwhittington opened this issue 5 years ago • 0 comments

First off! THANK YOU for creating such a great package. It has definitely saved my bacon on this project.

I did find an issue that affected me when connecting to a WCF service using your Mtom encoder. I am making a service call that expects a document back and I received the "Sequence contains no elements Error" when making a call to 3rd party WCF service. I incorrectly thought that the service was bad but I was provided with a .NET 3.5 project that actually works.

To find the issue, I pulled down your repo and consumed it directly and found that the error is occurring in the following method:

`private static string ResolveRefs(string mainContent, IList<MtomPart> parts) { bool ReferenceMatch(XAttribute hrefAttr, MtomPart part) { var partId = Regex.Match(part.ContentId, "<(?.)>"); var href = Regex.Match(hrefAttr.Value, "cid:(?.)");

            return href.Groups["uri"].Value == partId.Groups["uri"].Value;
        }

        var doc = XDocument.Parse(mainContent);
        var references = doc.Descendants(XName.Get("Include", "http://www.w3.org/2004/08/xop/include")).ToList();

        foreach (var reference in references)
        {
            var referencedPart = (
                from part in parts
                where ReferenceMatch(reference.Attribute("href"), part)
                select part).Single();

            reference.ReplaceWith(Convert.ToBase64String(referencedPart.GetRawContent()));
        }
        return doc.ToString(SaveOptions.DisableFormatting);
    }`

Basically, this method was not finding any matches in the returned result from the WCF Service. When I debugged the code, I found that I should have been finding a match but there was a key difference. The RefenceMatch logic was not finding a match:

var partId = Regex.Match(part.ContentId, "<(?<uri>.*)>"); var href = Regex.Match(hrefAttr.Value, "cid:(?<uri>.*)");

In my case the second line of the above code was not URL decoded so the two URI didn't match. The web service was returning this uri encoded By adding WebUtility.UrlDecode to the hrefAttr.Value, it was able to find the match and give me my returned result.

Working code: var href = Regex.Match(WebUtility.UrlDecode(hrefAttr.Value), "cid:(?<uri>.*)");

I'm not sure that this change should be added to the package but I wanted to post this here to help others if they run into this in the future.

bwhittington avatar Apr 10 '20 15:04 bwhittington