none
"The request failed. The underlying connection was closed: An unexpected error occurred on a send" during creation of calendar appointment using EWS. RRS feed

  • Question

  • Using:
    - EWS 1.1
    - Exchange server 2010 SP1
    - VB.Net

    I am using EWS to create calendar appointment for more than 2000 users in my company via windows service, I developed a windows service that will create or update appointments for users when they create or update their appointment in our own company enterprise application. 
    1. Initialize ExchangeService with version Exchange2010_SP1
    2. UseDefaultCredentials=True (the logged in user has Impersonation rights)
    3. Use ImpersonatedUserId to impersonate the user that I want to create calendar appointment
    4. Initialize an Appointment object (appointment = new Microsoft.Exchange.WebServices.Data.Appointment)
    5. Populate the Appointment object with values (for example, the properties Start, End, IsAllDayEvent, Body, Sensitivity, Subject, Location)
    6. Create the appointment with Appointment.Save(WellKnownFolderName.Calendar, SendInvitationsMode.SendToNone)
    7. When users update their appointment in our enterprise application, I use Appointment.Update(ConflictResolutionMode.AlwaysOverwrite, SendInvitationsOrCancellationsMode.SendToNone)

    Here is some code snippets:

    Try
        'Initialize the Exchange service
        exchangeService = New ExchangeService(ExchangeVersion.Exchange2010_SP1)
        impersonationContext = CType(System.Web.HttpContext.Current.User.Identity, System.Security.Principal.WindowsIdentity).Impersonate
    
        exchangeService.UseDefaultCredentials = True
        exchangeService.ImpersonatedUserId = New ImpersonatedUserId(ConnectingIdType.SmtpAddress, "user1@domain.com")
    
        System.Net.ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf ValidateCertificate)
    
        exchangeService.Url = New Uri("https://server/ews/Exchange.asmx")
    
        'Create or Update appointment
        If newAppointment Then
            appointment = New Appointment(exchangeService)
        Else
            appointment = Appointment.Bind(exchangeService, New ItemId(appointmentId))
        End If
    
        With appointment
            .Subject = *subject*
            .Start = *start date*
            .End = *end date*
            .Body = *msgbody*
            .Location = *location*
    
            If newAppointment Then
                .Save(WellKnownFolderName.Calendar, SendInvitationsMode.SendToNone)
            Else
                .Update(ConflictResolutionMode.AlwaysOverwrite, SendInvitationsOrCancellationsMode.SendToNone)
            End If
        End With
    Catch ex As Exception
        'Throw exception here
    Finally
        If Not impersonationContext Is Nothing Then
            impersonationContext.Undo()
        End If
    End Try

    The impersonation there is because when this is called from the windows service, the current WindowsIdentity is the IIS AppPool, so I need to impersonate the service acccount before I can initialize the exchange service and create/update appointment.

    There is new exchange service created each time there is a need to create or update appointment.

    Most of the time the process went well, but sometimes I will get a ServiceRequestException that I do not know why and what causes it:

    Microsoft.Exchange.WebServices.Data.ServiceRequestException: The request failed. The underlying connection was closed: An unexpected error occurred on a send. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.ObjectDisposedException: Safe handle has been closed at System.Security.Principal.Win32.ImpersonateLoggedOnUser(SafeTokenHandle hToken) at System.Security.Principal.WindowsIdentity.SafeImpersonate(SafeTokenHandle userToken, WindowsIdentity wi, StackCrawlMark& stackMark) at System.Security.Principal.WindowsIdentity.Impersonate(StackCrawlMark& stackMark) at System.Security.SecurityContext.SetSecurityContext(SecurityContext sc, SecurityContext prevSecurityContext, StackCrawlMark& stackMark) at System.Threading.ExecutionContext.SetExecutionContext(ExecutionContext executionContext) at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Net.ServerCertValidationCallback.Invoke(Object request, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) at System.Net.ServicePoint.HandshakeDoneProcedure.CertValidationCallback(String hostName, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) at System.Net.Security.SecureChannel.VerifyRemoteCertificate(RemoteCertValidationCallback remoteCertValidationCallback) at System.Net.Security.SslState.CompleteHandshake() at System.Net.Security.SslState.CheckCompletionBeforeNextReceive







    • Edited by Ah Lun Thursday, May 24, 2012 2:55 AM
    Thursday, May 24, 2012 1:57 AM

All replies

  • The error says that the underlying connection was closed, are you using the same exchange service connection for the whole thing?

    Maybe it has a timeout or simply disconnects after x requests, try creating a new connection for every appointment.  That's what I do and it works fine

    Thursday, May 24, 2012 3:18 AM
  • Every time when creating or updating appointment, the same codes above will be executed, that means every time there will be new exchangeservice created.
    I didn't set the Timeout for the exchangeservice, which leave it at default which is 100000 milliseconds (about 1.6 minutes).  Not sure whether it is due to the timeout that result in the connection being closed.

    Thursday, May 24, 2012 3:54 AM
  • I am having exatly the same problem while EmailMessage.Save() with attachament greater then 10 MB. I dont know whats the reason and why the connection was forcibely closed by the server as exception suggests. Although email message <10 MB works fine. Im haning exchange online account.

    Exception:

    Microsoft.Exchange.WebServices.Data.ServiceRequestException: The request failed. The underlying connection was closed: An unexpected error occurred on a send. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host

    ............................

    Wednesday, November 28, 2012 5:26 AM