Example #1
0
        /// <summary>
        /// Traces the and emits the request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="needSignature"></param>
        /// <param name="needTrace"></param>
        private void TraceAndEmitRequest(IEwsHttpWebRequest request, bool needSignature, bool needTrace)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this.Service, memoryStream))
                {
                    writer.RequireWSSecurityUtilityNamespace = needSignature;
                    this.WriteToXml(writer);
                }

                if (needSignature)
                {
                    this.service.config.SignStream(memoryStream);
                }

                if (needTrace)
                {
                    this.TraceXmlRequest(memoryStream);
                }

                memoryStream.Position = 0;
                using (var reader = new StreamReader(memoryStream, Encoding.UTF8, false, 4096, true))
                    request.Content = reader.ReadToEnd();
            }
        }
Example #2
0
        /// <summary>
        /// Traces the and emits the request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="needSignature"></param>
        /// <param name="needTrace"></param>
        private void TraceAndEmitRequest(IEwsHttpWebRequest request, bool needSignature, bool needTrace)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this.Service, memoryStream))
                {
                    writer.RequireWSSecurityUtilityNamespace = needSignature;
                    this.WriteToXml(writer);
                }

                if (needSignature)
                {
                    this.service.Credentials.Sign(memoryStream);
                }

                if (needTrace)
                {
                    this.TraceXmlRequest(memoryStream);
                }

                using (Stream serviceRequestStream = this.GetWebRequestStream(request))
                {
                    EwsUtilities.CopyStream(memoryStream, serviceRequestStream);
                }
            }
        }
 /// <summary>
 /// Emits the request.
 /// </summary>
 /// <param name="request">The request.</param>
 private async System.Threading.Tasks.Task EmitRequest(IEwsHttpWebRequest request)
 {
     using (Stream requestStream = await this.GetWebRequestStream(request).ConfigureAwait(false))
     {
         using (EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this.Service, requestStream))
         {
             this.WriteToXml(writer);
         }
     }
 }
Example #4
0
 /// <summary>
 /// Emits the request.
 /// </summary>
 /// <param name="request">The request.</param>
 private void EmitRequest(IEwsHttpWebRequest request)
 {
     using (Stream requestStream = this.GetWebRequestStream(request))
     {
         using (EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this.Service, requestStream))
         {
             this.WriteToXml(writer);
         }
     }
 }
Example #5
0
 /// <summary>
 /// Get the request stream
 /// </summary>
 /// <param name="request">The request</param>
 /// <returns>The Request stream</returns>
 private Stream GetWebRequestStream(IEwsHttpWebRequest request)
 {
     // In the async case, although we can use async callback to make the entire worflow completely async,
     // there is little perf gain with this approach because of EWS's message nature.
     // The overall latency of BeginGetRequestStream() is same as GetRequestStream() in this case.
     // The overhead to implement a two-step async operation includes wait handle synchronization, exception handling and wrapping.
     // Therefore, we only leverage BeginGetResponse() and EndGetResponse() to provide the async functionality.
     // Reference: http://www.wintellect.com/CS/blogs/jeffreyr/archive/2009/02/08/httpwebrequest-its-request-stream-and-sending-data-in-chunks.aspx
     return(request.EndGetRequestStream(request.BeginGetRequestStream(null, null)));
 }
 /// <summary>
 /// Traces the HTTP request headers.
 /// </summary>
 /// <param name="traceType">Kind of trace entry.</param>
 /// <param name="request">The request.</param>
 internal void TraceHttpRequestHeaders(TraceFlags traceType, IEwsHttpWebRequest request)
 {
     if (this.IsTraceEnabledFor(traceType))
     {
         string traceTypeStr    = traceType.ToString();
         string headersAsString = EwsUtilities.FormatHttpRequestHeaders(request);
         string logMessage      = EwsUtilities.FormatLogMessage(traceTypeStr, headersAsString);
         this.TraceListener.Trace(traceTypeStr, logMessage);
     }
 }
Example #7
0
        /// <summary>
        /// This method is called to apply credentials to a service request before the request is made.
        /// </summary>
        /// <param name="request">The request.</param>
        public override void PrepareWebRequest(IEwsHttpWebRequest request)
        {
            if ((this.EwsUrl == null) || (this.EwsUrl != request.RequestUri))
            {
                this.IsAuthenticated = false;
                this.MakeTokenRequestToWindowsLive(request.RequestUri);

                this.IsAuthenticated = true;
                this.EwsUrl          = request.RequestUri;
            }
        }
Example #8
0
        /// <summary>
        /// Builds the IEwsHttpWebRequest object for current service request with exception handling.
        /// </summary>
        /// <returns>An IEwsHttpWebRequest instance</returns>
        protected async Task <IEwsHttpWebRequest> BuildEwsHttpWebRequest()
        {
            IEwsHttpWebRequest request = null;

            try
            {
                request = this.Service.PrepareHttpWebRequest(this.GetXmlElementName());

                this.Service.TraceHttpRequestHeaders(TraceFlags.EwsRequestHttpHeaders, request);

                bool needSignature = this.Service.Credentials != null && this.Service.Credentials.NeedSignature;
                bool needTrace     = this.Service.IsTraceEnabledFor(TraceFlags.EwsRequest);

                // The request might need to add additional headers
                this.AddHeaders(request.Headers);

                // If tracing is enabled, we generate the request in-memory so that we
                // can pass it along to the ITraceListener. Then we copy the stream to
                // the request stream.
                if (needSignature || needTrace)
                {
                    this.TraceAndEmitRequest(request, needSignature, needTrace);
                }
                else
                {
                    this.EmitRequest(request);
                }

                return(request);
            }
            catch (EwsHttpClientException ex)
            {
                if (ex.IsProtocolError && ex.Response != null)
                {
                    await this.ProcessEwsHttpClientException(ex);
                }
                if (request != null)
                {
                    request.Dispose();
                }

                // Wrap exception if the above code block didn't throw
                throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, ex.Message), ex);
            }
            catch (IOException e)
            {
                if (request != null)
                {
                    request.Dispose();
                }
                // Wrap exception.
                throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, e.Message), e);
            }
        }
        /// <summary>
        /// Exectures the request.
        /// </summary>
        internal void InternalExecute()
        {
            lock (this.lockObject)
            {
                var tuple = this.ValidateAndEmitRequest().Result;
                this.request  = tuple.Item1;
                this.response = tuple.Item2;

                this.InternalOnConnect();
            }
        }
Example #10
0
 /// <summary>
 /// Emits the request.
 /// </summary>
 /// <param name="request">The request.</param>
 private void EmitRequest(IEwsHttpWebRequest request)
 {
     using (var memoryStream = new MemoryStream())
     {
         using (EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this.Service, memoryStream))
         {
             this.WriteToXml(writer);
         }
         memoryStream.Position = 0;
         using (StreamReader reader = new StreamReader(memoryStream, Encoding.UTF8, false, 4096, true))
             request.Content = reader.ReadToEnd();
     }
 }
Example #11
0
        /// <summary>
        /// Begins executing this async request.
        /// </summary>
        /// <param name="callback">The AsyncCallback delegate.</param>
        /// <param name="state">An object that contains state information for this request.</param>
        /// <returns>An IAsyncResult that references the asynchronous request.</returns>
        internal IAsyncResult BeginExecute(AsyncCallback callback, object state)
        {
            this.Validate();

            IEwsHttpWebRequest request = this.BuildEwsHttpWebRequest();

            WebAsyncCallStateAnchor wrappedState = new WebAsyncCallStateAnchor(this, request, callback /* user callback */, state /* user state */);

            // BeginGetResponse() does not throw interesting exceptions
            IAsyncResult webAsyncResult = request.BeginGetResponse(SimpleServiceRequestBase.WebRequestAsyncCallback, wrappedState);

            return(new AsyncRequestResult(this, request, webAsyncResult, state /* user state */));
        }
        /// <summary>
        /// Add the Authorization header to a service request.
        /// </summary>
        /// <param name="request">The request</param>
        internal override void PrepareWebRequest(IEwsHttpWebRequest request)
        {
            base.PrepareWebRequest(request);

            if (this.token != null)
            {
                request.Headers.Remove(HttpRequestHeader.Authorization.ToString());
                request.Headers.Authorization = new AuthenticationHeaderValue(this.token);
            }
            else
            {
                request.Credentials = this.credentials;
            }
        }
        /// <summary>
        /// Add the Authorization header to a service request.
        /// </summary>
        /// <param name="request">The request</param>
        internal override void PrepareWebRequest(IEwsHttpWebRequest request)
        {
            base.PrepareWebRequest(request);

            if (this.token != null)
            {
                request.Headers.Remove(HttpRequestHeader.Authorization);
                request.Headers.Add(HttpRequestHeader.Authorization, this.token);
            }
            else
            {
                request.Credentials = this.credentials;
            }
        }
Example #14
0
        private async Task <IEwsHttpWebResponse> ValidateAndEmitRequestInternalAsync(IEwsHttpWebRequest request)
        {
            DateTime startTime = DateTime.UtcNow;

            IEwsHttpWebResponse response = null;

            try
            {
                response = await this.GetEwsHttpWebResponseAsync(request);
            }
            finally
            {
                if (this.service.SendClientLatencies)
                {
                    int    clientSideLatency = (int)(DateTime.UtcNow - startTime).TotalMilliseconds;
                    string requestId         = string.Empty;
                    string soapAction        = this.GetType().Name.Replace("Request", string.Empty);

                    if (response != null && response.Headers != null)
                    {
                        foreach (string requestIdHeader in ServiceRequestBase.RequestIdResponseHeaders)
                        {
                            string requestIdValue = response.Headers.Get(requestIdHeader);
                            if (!string.IsNullOrEmpty(requestIdValue))
                            {
                                requestId = requestIdValue;
                                break;
                            }
                        }
                    }

                    StringBuilder sb = new StringBuilder();
                    sb.Append("MessageId=");
                    sb.Append(requestId);
                    sb.Append(",ResponseTime=");
                    sb.Append(clientSideLatency);
                    sb.Append(",SoapAction=");
                    sb.Append(soapAction);
                    sb.Append(";");

                    lock (clientStatisticsCache)
                    {
                        clientStatisticsCache.Add(sb.ToString());
                    }
                }
            }

            return(response);
        }
        /// <summary>
        /// Contructor
        /// </summary>
        /// <param name="serviceRequest"></param>
        /// <param name="webRequest"></param>
        /// <param name="webAsyncResult"></param>
        /// <param name="asyncState"></param>
        public AsyncRequestResult(
            ServiceRequestBase serviceRequest,
            IEwsHttpWebRequest webRequest,
            IAsyncResult webAsyncResult,
            object asyncState)
        {
            EwsUtilities.ValidateParam(serviceRequest, "serviceRequest");
            EwsUtilities.ValidateParam(webRequest, "webRequest");
            EwsUtilities.ValidateParam(webAsyncResult, "webAsyncResult");

            this.ServiceRequest = serviceRequest;
            this.WebAsyncResult = webAsyncResult;
            this.WebRequest     = webRequest;
            this.AsyncState     = asyncState;
        }
        /// <summary>
        /// Contructor
        /// </summary>
        /// <param name="serviceRequest"></param>
        /// <param name="webRequest"></param>
        /// <param name="asyncCallback"></param>
        /// <param name="asyncState"></param>
        public WebAsyncCallStateAnchor(
            ServiceRequestBase serviceRequest,
            IEwsHttpWebRequest webRequest,
            AsyncCallback asyncCallback,
            object asyncState)
        {
            EwsUtilities.ValidateParam(serviceRequest, "serviceRequest");
            EwsUtilities.ValidateParam(webRequest, "webRequest");

            this.ServiceRequest = serviceRequest;
            this.WebRequest     = webRequest;

            this.AsyncCallback = asyncCallback;
            this.AsyncState    = asyncState;
        }
 /// <summary>
 /// Emits the request.
 /// </summary>
 /// <param name="request">The request.</param>
 private void EmitRequest(IEwsHttpWebRequest request)
 {
     try {
         using (Stream requestStream = this.GetWebRequestStream(request)) {
             using (EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this.Service, requestStream)) {
                 this.WriteToXml(writer);
             }
         }
     } catch (Exception e) {
         //FJC: We found that if the Xml generation generated an exception, then the request would be left in a
         // non-usable state since the requestStream in the request wasn't fully closed?
         // I'm not 100% sure I understand that part... but I found that calling .Abort on the request would force
         // the request/connection to be reinitialized the next time it was used after a Xml exception.
         request.Abort();
         throw e;
     }
 }
        /// <summary>
        /// Traces the and emits the request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="needSignature"></param>
        /// <param name="needTrace"></param>
        private void TraceAndEmitRequest(IEwsHttpWebRequest request, bool needSignature, bool needTrace)
        {
            if (this.service.RenderingMethod == ExchangeService.RenderingMode.Xml)
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this.Service, memoryStream))
                    {
                        writer.RequireWSSecurityUtilityNamespace = needSignature;
                        this.WriteToXml(writer);
                    }

                    if (needSignature)
                    {
                        this.service.Credentials.Sign(memoryStream);
                    }

                    if (needTrace)
                    {
                        this.TraceXmlRequest(memoryStream);
                    }

                    using (Stream serviceRequestStream = this.GetWebRequestStream(request))
                    {
                        EwsUtilities.CopyStream(memoryStream, serviceRequestStream);
                    }
                }
            }
            else if (this.service.RenderingMethod == ExchangeService.RenderingMode.JSON)
            {
                JsonObject requestObject = this.CreateJsonRequest();

                this.TraceJsonRequest(requestObject);

                using (Stream serviceRequestStream = this.GetWebRequestStream(request))
                {
                    requestObject.SerializeToJson(serviceRequestStream);
                }
            }
        }
Example #19
0
        /// <summary>
        ///  Gets the IEwsHttpWebRequest object from the specified IEwsHttpWebRequest object with exception handling
        /// </summary>
        /// <param name="request">The specified IEwsHttpWebRequest</param>
        /// <returns>An IEwsHttpWebResponse instance</returns>
        protected async Task <IEwsHttpWebResponse> GetEwsHttpWebResponse(IEwsHttpWebRequest request, CancellationToken token)
        {
            try
            {
                return(await request.GetResponse(token).ConfigureAwait(false));
            }
            catch (EwsHttpClientException ex)
            {
                if (ex.IsProtocolError && ex.Response != null)
                {
                    await this.ProcessEwsHttpClientException(ex);
                }

                // Wrap exception if the above code block didn't throw
                throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, ex.Message), ex);
            }
            catch (IOException e)
            {
                // Wrap exception.
                throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, e.Message), e);
            }
        }
Example #20
0
        /// <summary>
        ///  Gets the IEwsHttpWebRequest object from the specified IEwsHttpWebRequest object with exception handling
        /// </summary>
        /// <param name="request">The specified IEwsHttpWebRequest</param>
        /// <returns>An IEwsHttpWebResponse instance</returns>
        protected IEwsHttpWebResponse GetEwsHttpWebResponse(IEwsHttpWebRequest request)
        {
            try
            {
                return(request.GetResponse());
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
                {
                    this.ProcessWebException(ex);
                }

                // Wrap exception if the above code block didn't throw
                throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, ex.Message), ex);
            }
            catch (IOException e)
            {
                // Wrap exception.
                throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, e.Message), e);
            }
        }
        /// <summary>
        /// Emits the request.
        /// </summary>
        /// <param name="request">The request.</param>
        private void EmitRequest(IEwsHttpWebRequest request)
        {
            if (this.Service.RenderingMethod == ExchangeService.RenderingMode.Xml)
            {
                using (Stream requestStream = this.GetWebRequestStream(request))
                {
                    using (EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this.Service, requestStream))
                    {
                        this.WriteToXml(writer);
                    }
                }
            }
            else if (this.Service.RenderingMethod == ExchangeService.RenderingMode.JSON)
            {
                JsonObject requestObject = this.CreateJsonRequest();

                using (Stream serviceRequestStream = this.GetWebRequestStream(request))
                {
                    requestObject.SerializeToJson(serviceRequestStream);
                }
            }
        }
Example #22
0
        /// <summary>
        /// Validates request parameters, and emits the request to the server.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>The task which will resplve to response returned by the server.</returns>
        protected Task <IEwsHttpWebResponse> ValidateAndEmitRequestAsync(out IEwsHttpWebRequest request)
        {
            this.Validate();

            request = this.BuildEwsHttpWebRequest();

            if (this.service.SendClientLatencies)
            {
                string clientStatisticsToAdd = null;

                lock (clientStatisticsCache)
                {
                    if (clientStatisticsCache.Count > 0)
                    {
                        clientStatisticsToAdd = clientStatisticsCache[0];
                        clientStatisticsCache.RemoveAt(0);
                    }
                }

                if (!string.IsNullOrEmpty(clientStatisticsToAdd))
                {
                    if (request.Headers[ClientStatisticsRequestHeader] != null)
                    {
                        request.Headers[ClientStatisticsRequestHeader] =
                            request.Headers[ClientStatisticsRequestHeader]
                            + clientStatisticsToAdd;
                    }
                    else
                    {
                        request.Headers.Add(
                            ClientStatisticsRequestHeader,
                            clientStatisticsToAdd);
                    }
                }
            }

            return(ValidateAndEmitRequestInternalAsync(request));
        }
        /// <summary>
        ///  Gets the IEwsHttpWebRequest object from the specified IEwsHttpWebRequest object with exception handling
        /// </summary>
        /// <param name="request">The specified IEwsHttpWebRequest</param>
        /// <returns>An IEwsHttpWebResponse instance</returns>
        protected async Task <IEwsHttpWebResponse> GetEwsHttpWebResponse(IEwsHttpWebRequest request)
        {
            try
            {
                return(await request.GetResponse().ConfigureAwait(false));
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
                {
                    this.ProcessWebException(ex);
                }

                string extraData = null;
                try
                {
                    using (var rs = ex.Response.GetResponseStream())
                    {
                        var buffer = new byte[rs.Length];
                        rs.Position = 0;
                        var data = await rs.ReadAsync(buffer, 0, (int)rs.Length);

                        extraData = Encoding.UTF8.GetString(buffer);
                    }
                }
                catch (Exception) { }

                // Wrap exception if the above code block didn't throw
                throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, string.Format("{0}\n{1}", ex.Message, extraData)), ex);
            }
            catch (IOException e)
            {
                // Wrap exception.
                throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, e.Message), e);
            }
        }
Example #24
0
        /// <summary>
        /// Ends getting the specified async IEwsHttpWebRequest object from the specified IEwsHttpWebRequest object with exception handling.
        /// </summary>
        /// <param name="request">The specified IEwsHttpWebRequest</param>
        /// <param name="asyncResult">An IAsyncResult that references the asynchronous request.</param>
        /// <returns>An IEwsHttpWebResponse instance</returns>
        protected IEwsHttpWebResponse EndGetEwsHttpWebResponse(IEwsHttpWebRequest request, IAsyncResult asyncResult)
        {
            try
            {
                // Note that this call may throw ArgumentException if the HttpWebRequest instance is not the original one,
                // and we just let it out
                return(request.EndGetResponse(asyncResult));
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
                {
                    this.ProcessWebException(ex);
                }

                // Wrap exception if the above code block didn't throw
                throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, ex.Message), ex);
            }
            catch (IOException e)
            {
                // Wrap exception.
                throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, e.Message), e);
            }
        }
        /// <summary>
        /// Ends getting the specified async IEwsHttpWebRequest object from the specified IEwsHttpWebRequest object with exception handling.
        /// </summary>
        /// <param name="request">The specified IEwsHttpWebRequest</param>
        /// <param name="asyncResult">An IAsyncResult that references the asynchronous request.</param>
        /// <returns>An IEwsHttpWebResponse instance</returns>
        protected IEwsHttpWebResponse EndGetEwsHttpWebResponse(IEwsHttpWebRequest request, IAsyncResult asyncResult)
        {
            try
            {
                // Note that this call may throw ArgumentException if the HttpWebRequest instance is not the original one,
                // and we just let it out
                return request.EndGetResponse(asyncResult);
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
                {
                    this.ProcessWebException(ex);
                }

                // Wrap exception if the above code block didn't throw
                throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, ex.Message), ex);
            }
            catch (IOException e)
            {
                // Wrap exception.
                throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, e.Message), e);
            }
        }
 internal virtual void SetContentType(IEwsHttpWebRequest request)
 {
     request.ContentType = "text/xml; charset=utf-8";
     request.Accept      = "text/xml";
 }
Example #27
0
        /// <summary>
        /// Validates request parameters, and emits the request to the server.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>The response returned by the server.</returns>
        protected IEwsHttpWebResponse ValidateAndEmitRequest(out IEwsHttpWebRequest request)
        {
            this.Validate();

            request = this.BuildEwsHttpWebRequest();

            if (this.service.SendClientLatencies)
            {
                string clientStatisticsToAdd = null;

                lock (clientStatisticsCache)
                {
                    if (clientStatisticsCache.Count > 0)
                    {
                        clientStatisticsToAdd = clientStatisticsCache[0];
                        clientStatisticsCache.RemoveAt(0);
                    }
                }

                if (!string.IsNullOrEmpty(clientStatisticsToAdd))
                {
                    if (request.Headers[ClientStatisticsRequestHeader] != null)
                    {
                        request.Headers[ClientStatisticsRequestHeader] =
                            request.Headers[ClientStatisticsRequestHeader]
                            + clientStatisticsToAdd;
                    }
                    else
                    {
                        request.Headers.Add(
                            ClientStatisticsRequestHeader,
                            clientStatisticsToAdd);
                    }
                }
            }

            DateTime            startTime = DateTime.UtcNow;
            IEwsHttpWebResponse response  = null;

            try
            {
                response = this.GetEwsHttpWebResponse(request);
            }
            finally
            {
                if (this.service.SendClientLatencies)
                {
                    int    clientSideLatency = (int)(DateTime.UtcNow - startTime).TotalMilliseconds;
                    string requestId         = string.Empty;
                    string soapAction        = this.GetType().Name.Replace("Request", string.Empty);

                    if (response != null && response.Headers != null)
                    {
                        foreach (string requestIdHeader in ServiceRequestBase.RequestIdResponseHeaders)
                        {
                            string requestIdValue = response.Headers.Get(requestIdHeader);
                            if (!string.IsNullOrEmpty(requestIdValue))
                            {
                                requestId = requestIdValue;
                                break;
                            }
                        }
                    }

                    StringBuilder sb = new StringBuilder();
                    sb.Append("MessageId=");
                    sb.Append(requestId);
                    sb.Append(",ResponseTime=");
                    sb.Append(clientSideLatency);
                    sb.Append(",SoapAction=");
                    sb.Append(soapAction);
                    sb.Append(";");

                    lock (clientStatisticsCache)
                    {
                        clientStatisticsCache.Add(sb.ToString());
                    }
                }
            }

            return(response);
        }
 /// <summary>
 /// Emits the request.
 /// </summary>
 /// <param name="request">The request.</param>
 private void EmitRequest(IEwsHttpWebRequest request)
 {
     using (Stream requestStream = this.GetWebRequestStream(request))
     {
         using (EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this.Service, requestStream))
         {
             this.WriteToXml(writer);
         }
     }
 }
        /// <summary>
        /// Traces the and emits the request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="needSignature"></param>
        /// <param name="needTrace"></param>
        private void TraceAndEmitRequest(IEwsHttpWebRequest request, bool needSignature, bool needTrace)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this.Service, memoryStream))
                {
                    writer.RequireWSSecurityUtilityNamespace = needSignature;
                    this.WriteToXml(writer);
                }

                if (needSignature)
                {
                    this.service.Credentials.Sign(memoryStream);
                }

                if (needTrace)
                {
                    this.TraceXmlRequest(memoryStream);
                }

                using (Stream serviceRequestStream = this.GetWebRequestStream(request))
                {
                    EwsUtilities.CopyStream(memoryStream, serviceRequestStream);
                }
            }
        }
 /// <summary>
 /// Get the request stream
 /// </summary>
 /// <param name="request">The request</param>
 /// <returns>The Request stream</returns>
 private Stream GetWebRequestStream(IEwsHttpWebRequest request)
 {
     // In the async case, although we can use async callback to make the entire worflow completely async, 
     // there is little perf gain with this approach because of EWS's message nature.
     // The overall latency of BeginGetRequestStream() is same as GetRequestStream() in this case.
     // The overhead to implement a two-step async operation includes wait handle synchronization, exception handling and wrapping.
     // Therefore, we only leverage BeginGetResponse() and EndGetReponse() to provide the async functionality.
     // Reference: http://www.wintellect.com/CS/blogs/jeffreyr/archive/2009/02/08/httpwebrequest-its-request-stream-and-sending-data-in-chunks.aspx
     return request.EndGetRequestStream(request.BeginGetRequestStream(null, null));
 }
        /// <summary>
        /// This method is called to apply credentials to a service request before the request is made.
        /// </summary>
        /// <param name="request">The request.</param>
        internal override void PrepareWebRequest(IEwsHttpWebRequest request)
        {
            if ((this.EwsUrl == null) || (this.EwsUrl != request.RequestUri))
            {
                this.IsAuthenticated = false;
                this.MakeTokenRequestToWindowsLive(request.RequestUri);

                this.IsAuthenticated = true;
                this.EwsUrl = request.RequestUri;
            }
        }
 /// <summary>
 /// This method is called to apply credentials to a service request before the request is made.  
 /// </summary>
 /// <param name="request">The request.</param>
 internal virtual void PrepareWebRequest(IEwsHttpWebRequest request)
 {
     // do nothing by default.
 }
        /// <summary>
        /// Validates request parameters, and emits the request to the server.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>The response returned by the server.</returns>
        protected IEwsHttpWebResponse ValidateAndEmitRequest(out IEwsHttpWebRequest request)
        {
            this.Validate();

            request = this.BuildEwsHttpWebRequest();

            if (this.service.SendClientLatencies)
            {
                string clientStatisticsToAdd = null;

                lock (clientStatisticsCache)
                {
                    if (clientStatisticsCache.Count > 0)
                    {
                        clientStatisticsToAdd = clientStatisticsCache[0];
                        clientStatisticsCache.RemoveAt(0);
                    }
                }

                if (!string.IsNullOrEmpty(clientStatisticsToAdd))
                {
                    if (request.Headers[ClientStatisticsRequestHeader] != null)
                    {
                        request.Headers[ClientStatisticsRequestHeader] =
                            request.Headers[ClientStatisticsRequestHeader]
                            + clientStatisticsToAdd;
                    }
                    else
                    {
                        request.Headers.Add(
                            ClientStatisticsRequestHeader,
                            clientStatisticsToAdd);
                    }
                }
            }

            DateTime startTime = DateTime.UtcNow;
            IEwsHttpWebResponse response = null;

            try
            {
                response = this.GetEwsHttpWebResponse(request);
            }
            finally
            {
                if (this.service.SendClientLatencies)
                {
                    int clientSideLatency = (int)(DateTime.UtcNow - startTime).TotalMilliseconds;
                    string requestId = string.Empty;
                    string soapAction = this.GetType().Name.Replace("Request", string.Empty);

                    if (response != null && response.Headers != null)
                    {
                        foreach (string requestIdHeader in ServiceRequestBase.RequestIdResponseHeaders)
                        {
                            string requestIdValue = response.Headers.Get(requestIdHeader);
                            if (!string.IsNullOrEmpty(requestIdValue))
                            {
                                requestId = requestIdValue;
                                break;
                            }
                        }
                    }

                    StringBuilder sb = new StringBuilder();
                    sb.Append("MessageId=");
                    sb.Append(requestId);
                    sb.Append(",ResponseTime=");
                    sb.Append(clientSideLatency);
                    sb.Append(",SoapAction=");
                    sb.Append(soapAction);
                    sb.Append(";");

                    lock (clientStatisticsCache)
                    {
                        clientStatisticsCache.Add(sb.ToString());
                    }
                }
            }

            return response;
        }
 /// <summary>
 /// Traces the HTTP request headers.
 /// </summary>
 /// <param name="traceType">Kind of trace entry.</param>
 /// <param name="request">The request.</param>
 internal void TraceHttpRequestHeaders(TraceFlags traceType, IEwsHttpWebRequest request)
 {
     if (this.IsTraceEnabledFor(traceType))
     {
         string traceTypeStr = traceType.ToString();
         string headersAsString = EwsUtilities.FormatHttpRequestHeaders(request);
         string logMessage = EwsUtilities.FormatLogMessage(traceTypeStr, headersAsString);
         this.TraceListener.Trace(traceTypeStr, logMessage);
     }
 }
 internal virtual void SetContentType(IEwsHttpWebRequest request)
 {
     request.ContentType = "text/xml; charset=utf-8";
     request.Accept = "text/xml";
 }
 /// <summary>
 /// Applies NetworkCredential associated with this instance to a service request.
 /// </summary>
 /// <param name="request">The request.</param>
 internal override void PrepareWebRequest(IEwsHttpWebRequest request)
 {
     request.Credentials = this.credentials;
 }
 /// <summary>
 /// This method is called to apply credentials to a service request before the request is made.
 /// </summary>
 /// <param name="request">The request.</param>
 internal override void PrepareWebRequest(IEwsHttpWebRequest request)
 {
     this.EwsUrl = request.RequestUri;
 }
 /// <summary>
 /// This method is called to apply credentials to a service request before the request is made.
 /// </summary>
 /// <param name="request">The request.</param>
 public virtual void PrepareWebRequest(IEwsHttpWebRequest request)
 {
     // do nothing by default.
 }
        /// <summary>
        /// Creates an HttpWebRequest instance and initializes it with the appropriate parameters,
        /// based on the configuration of this service object.
        /// </summary>
        /// <param name="url">The URL that the HttpWebRequest should target.</param>
        /// <param name="acceptGzipEncoding">If true, ask server for GZip compressed content.</param>
        /// <param name="allowAutoRedirect">If true, redirection responses will be automatically followed.</param>
        /// <returns>A initialized instance of HttpWebRequest.</returns>
        internal IEwsHttpWebRequest PrepareHttpWebRequestForUrl(
            Uri url,
            bool acceptGzipEncoding,
            bool allowAutoRedirect)
        {
            // Verify that the protocol is something that we can handle
            if ((url.Scheme != Uri.UriSchemeHttp) && (url.Scheme != Uri.UriSchemeHttps))
            {
                throw new ServiceLocalException(string.Format(Strings.UnsupportedWebProtocol, url.Scheme));
            }

            IEwsHttpWebRequest request = this.HttpWebRequestFactory.CreateRequest(url);

            request.PreAuthenticate = this.PreAuthenticate;
            request.Timeout         = this.Timeout;
            this.SetContentType(request);
            request.Method              = "POST";
            request.UserAgent           = this.UserAgent;
            request.AllowAutoRedirect   = allowAutoRedirect;
            request.CookieContainer     = this.CookieContainer;
            request.KeepAlive           = this.keepAlive;
            request.ConnectionGroupName = this.connectionGroupName;

            if (acceptGzipEncoding)
            {
                request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
            }

            if (!string.IsNullOrEmpty(this.clientRequestId))
            {
                request.Headers.Add("client-request-id", this.clientRequestId);
                if (this.returnClientRequestId)
                {
                    request.Headers.Add("return-client-request-id", "true");
                }
            }

            if (this.webProxy != null)
            {
                request.Proxy = this.webProxy;
            }

            if (this.HttpHeaders.Count > 0)
            {
                this.HttpHeaders.ForEach((kv) => request.Headers.Add(kv.Key, kv.Value));
            }

            request.UseDefaultCredentials = this.UseDefaultCredentials;
            if (!request.UseDefaultCredentials)
            {
                ExchangeCredentials serviceCredentials = this.Credentials;
                if (serviceCredentials == null)
                {
                    throw new ServiceLocalException(Strings.CredentialsRequired);
                }

                // Make sure that credentials have been authenticated if required
                serviceCredentials.PreAuthenticate();

                // Apply credentials to the request
                serviceCredentials.PrepareWebRequest(request);
            }

            this.httpResponseHeaders.Clear();

            return(request);
        }
        /// <summary>
        ///  Gets the IEwsHttpWebRequest object from the specified IEwsHttpWebRequest object with exception handling
        /// </summary>
        /// <param name="request">The specified IEwsHttpWebRequest</param>
        /// <returns>An IEwsHttpWebResponse instance</returns>
        protected IEwsHttpWebResponse GetEwsHttpWebResponse(IEwsHttpWebRequest request)
        {
            try
            {
                return request.GetResponse();
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
                {
                    this.ProcessWebException(ex);
                }

                // Wrap exception if the above code block didn't throw
                throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, ex.Message), ex);
            }
            catch (IOException e)
            {
                // Wrap exception.
                throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, e.Message), e);
            }
        }
        /// <summary>
        /// Add the Authorization header to a service request.
        /// </summary>
        /// <param name="request">The request</param>
        internal override void PrepareWebRequest(IEwsHttpWebRequest request)
        {
            base.PrepareWebRequest(request);

            if (this.token != null)
            {
                request.Headers.Remove(HttpRequestHeader.Authorization);
                request.Headers.Add(HttpRequestHeader.Authorization, this.token);
            }
            else
            {
                request.Credentials = this.credentials;
            }
        }
Example #42
0
 /// <summary>
 /// This method is called to apply credentials to a service request before the request is made.
 /// </summary>
 /// <param name="request">The request.</param>
 protected internal override void PrepareWebRequest(IEwsHttpWebRequest request)
 {
     request.ClientCertificates = this.ClientCertificates;
 }
Example #43
0
 /// <summary>
 /// This method is called to apply credentials to a service request before the request is made.
 /// </summary>
 /// <param name="request">The request.</param>
 internal override void PrepareWebRequest(IEwsHttpWebRequest request)
 {
     this.EwsUrl = request.RequestUri;
 }
 /// <summary>
 /// This method is called to apply credentials to a service request before the request is made.
 /// </summary>
 /// <param name="request">The request.</param>
 internal override void PrepareWebRequest(IEwsHttpWebRequest request)
 {
     request.ClientCertificates = this.ClientCertificates;
 }