'Microsoft.Exchange.WebServices.Data.ServiceRequestException at reading the EWS folders

I'm a newbie to C# development

I'm trying to migrate the EWS authentication from basic authentication to OAuth2 authentication.

#Implementation

using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Exchange.WebServices.Data;
using Microsoft.Identity.Client;



namespace DataLoadLibrary.Email
{
    public class OAuthTokenProviders
    {


        public static async Task<OAuthTokenProviders> Create()
        {
            var myClass = new OAuthTokenProviders();
            await myClass.Initialize();
            return myClass;
        }

        private OAuthTokenProviders()
        {
            Console.WriteLine("TESTING INSIDE CONSTRUCT");

        }


        
        private async System.Threading.Tasks.Task Initialize()
        {
            Console.WriteLine("TESTING");
            // Using Microsoft.Identity.Client
            var cca = ConfidentialClientApplicationBuilder
                .Create("")      //client Id
                .WithClientSecret("")
                .WithTenantId("")
                .Build();
            var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
            try
            {
                // Get token
                var authResult = await cca.AcquireTokenForClient(ewsScopes)
                    .ExecuteAsync();
                // Configure the ExchangeService with the access token
                var ewsClient = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
                ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
                ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
                ewsClient.ImpersonatedUserId =
                    new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "");
                //Include x-anchormailbox header
                ewsClient.HttpHeaders.Add("X-AnchorMailbox", "");
                // Make an EWS call to list folders on exhange online

                var folders = ewsClient.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(10));
                foreach (var folder in folders)
                {
                    Console.WriteLine($"Folder: {folder.DisplayName}");
                }
                // Make an EWS call to read 50 emails (last 5 days) from Inbox folder
                TimeSpan ts = new TimeSpan(-60, 0, 0, 0);
                DateTime date = DateTime.Now.Add(ts);
                SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);
                var findResults = ewsClient.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(50));
                foreach (var mailItem in findResults)
                {
                    Console.WriteLine($"Subject: {mailItem.Subject}");
                }
                EmailMessage email = new EmailMessage(ewsClient);
                email.ToRecipients.Add("");
                email.Subject = "HelloWorld";
                email.Body = new MessageBody("This is a test email using MS Exchg we services");
                email.Send();
            }
            catch (MsalException ex)
            {
                Console.WriteLine($"Error acquiring access token: {ex}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex}");
            }
            if (System.Diagnostics.Debugger.IsAttached)
            {
                Console.WriteLine("Hit any key to exit...");
                Console.ReadKey();
            }
        }


    }
}

Using the above implementation am able to get the access token successfully. However when am listing the folder in the mailbox, getting below exceptions

Microsoft.Exchange.WebServices.Data.ServiceRequestException
  HResult=0x80131500
  Message=The request failed. The underlying connection was closed: An unexpected error occurred on a send.
  Source=Microsoft.Exchange.WebServices
  StackTrace:
   at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.GetEwsHttpWebResponse(IEwsHttpWebRequest request)
   at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ValidateAndEmitRequest(IEwsHttpWebRequest& request)
   at Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest`1.Execute()
   at Microsoft.Exchange.WebServices.Data.ExchangeService.InternalFindFolders(IEnumerable`1 parentFolderIds, SearchFilter searchFilter, FolderView view, ServiceErrorHandling errorHandlingMode)
   at Microsoft.Exchange.WebServices.Data.ExchangeService.FindFolders(FolderId parentFolderId, FolderView view)
   at Microsoft.Exchange.WebServices.Data.ExchangeService.FindFolders(WellKnownFolderName parentFolderName, FolderView view)
   at DataLoadLibrary.Email.OAuthTokenProviders.<Initialize>d__2.MoveNext() in C:\Users\path\to\file\DataLoadLibrary\Email\OAuthTokenProviders.cs:line 51

  This exception was originally thrown at this call stack:
    [External Code]

Inner Exception 1:
WebException: The underlying connection was closed: An unexpected error occurred on a send.

Inner Exception 2:
IOException: Authentication failed because the remote party has closed the transport stream.

I would want to know how to solve the exception. Thanks in Advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source