public static DataFormat ConvertToRestSharpDataFormat(this IRequestBody body)
        {
            if (body == null)
            {
                return(DataFormat.None);
            }

            switch (body.Type)
            {
            case BodyTypes.Javascript:
            case BodyTypes.Json:
            case BodyTypes.MongoQuery:
                return(DataFormat.Json);

            case BodyTypes.Xml:
                return(DataFormat.Xml);

            case BodyTypes.None:
            case BodyTypes.FormData:
            case BodyTypes.UrlEncoded:
            case BodyTypes.Text:
            case BodyTypes.Binary:
            case BodyTypes.Html:
            case BodyTypes.GraphQL:
                return(DataFormat.None);

            default:
                return(DataFormat.None);
            }
        }
Beispiel #2
0
        protected HttpRequest(Resource resource, IRequestBody body)
        {
            Resource = resource;
            Body = body;

            AllowAutoRedirect = true;
        }
Beispiel #3
0
        protected HttpRequest(Resource resource, IRequestBody body)
        {
            Resource = resource;
            Body     = body;

            AllowAutoRedirect = true;
        }
        /// <summary>
        /// Send the request to address book server endpoint.
        /// </summary>
        /// <param name="requestBody">The request body.</param>
        /// <param name="requestType">The type of the request.</param>
        /// <param name="cookieChange">If the session context cookie changed.</param>
        /// <returns>The common response.</returns>
        private CommonResponse SendAddressBookRequest(IRequestBody requestBody, RequestType requestType, bool cookieChange = true)
        {
            byte[]              rawBuffer;
            CommonResponse      commonResponse      = null;
            WebHeaderCollection webHeaderCollection = AdapterHelper.InitializeHTTPHeader(requestType, AdapterHelper.ClientInstance, AdapterHelper.Counter);

            // Send the Execute HTTP request and get the response.
            HttpWebResponse response     = this.SendMAPIHttpRequest(this.userName, this.password, requestBody, ServerEndpoint.AddressBookServerEndpoint, AdapterHelper.SessionContextCookies, webHeaderCollection, out rawBuffer);
            uint            responseCode = AdapterHelper.GetFinalResponseCode(response.Headers["X-ResponseCode"]);

            this.Site.Assert.AreEqual <uint>(0, responseCode, "The request to the address book server should be executed successfully!");

            // Read the HTTP response buffer and parse the response to correct format.
            commonResponse = CommonResponse.ParseCommonResponse(rawBuffer);
            Site.Assert.IsNotNull(commonResponse.ResponseBodyRawData, "The response body should contains data.");
            this.VerifyRequestTypesForAddressBookServerEndpoint(response.Headers, commonResponse);
            this.VerifyAutoDiscover(response.StatusCode, ServerEndpoint.AddressBookServerEndpoint);
            this.VerifyAuthentication(response);

            response.GetResponseStream().Close();
            if (cookieChange)
            {
                AdapterHelper.SessionContextCookies = response.Cookies;
            }

            return(commonResponse);
        }
        /// <summary>
        /// The method to send NotificationWait request to the server.
        /// </summary>
        /// <param name="requestBody">The NotificationWait request body.</param>
        /// <returns>Return the NotificationWait response body.</returns>
        public NotificationWaitSuccessResponseBody NotificationWaitCall(IRequestBody requestBody)
        {
            string          requestType = "NotificationWait";
            HttpWebResponse response    = SendMAPIHttpRequest(this.site, this.mailStoreUrl, this.userName, this.domain, this.userPassword, requestBody, requestType, this.cookies);

            NotificationWaitSuccessResponseBody result = null;

            string responseCode = response.Headers["X-ResponseCode"];

            byte[] rawBuffer = ReadHttpResponse(response);

            response.GetResponseStream().Close();

            if (int.Parse(responseCode) == 0)
            {
                ChunkedResponse chunkedResponse = ChunkedResponse.ParseChunkedResponse(rawBuffer);
                NotificationWaitSuccessResponseBody responseSuccess = NotificationWaitSuccessResponseBody.Parse(chunkedResponse.ResponseBodyRawData);
                result = responseSuccess;
            }
            else
            {
                this.site.Assert.Fail("MAPIHTTP call failed, the error code returned from server is: {0}", responseCode);
            }

            return(result);
        }
Beispiel #6
0
 public async Task <IResponseResult> ExecuteRequestAsync(
     HttpMethod method,
     string url,
     IHeaderCollection headers = null,
     IRequestBody body         = null)
 {
     return(await this.restHandler.ExecuteRequestAsync(method, url, headers, body));
 }
Beispiel #7
0
 protected IResponseResult Post(
     string url,
     IQueryString queryString  = null,
     IHeaderCollection headers = null,
     IRequestBody body         = null)
 {
     return(this.restHandler.ExecuteRequest(HttpMethod.Post, url, queryString, headers, body));
 }
Beispiel #8
0
 protected async ValueTask <IResponseResult <TResult> > PostAsync <TResult>(
     string url,
     IQueryString queryString  = null,
     IHeaderCollection headers = null,
     IRequestBody body         = null)
 {
     return(await this.restHandler.ExecuteRequestAsync <TResult>(HttpMethod.Post, url, queryString, headers, body));
 }
Beispiel #9
0
 public IResponseResult ExecuteRequest(
     HttpMethod method,
     string url,
     IHeaderCollection headers = null,
     IRequestBody body         = null)
 {
     return(this.restHandler.ExecuteRequest(method, url, headers, body));
 }
Beispiel #10
0
 /// <summary>
 /// this class models a request that can be sent to a service
 /// </summary>
 /// <param name="headers">the headers that should be sent as part of the request</param>
 /// <param name="httpMethod">the httpMethod of the request</param>
 /// <param name="pathParameters">any path parameters required</param>
 /// <param name="queryParameters">any query parameters required</param>
 /// <param name="requestBody">a request body if required</param>
 public Request(RESTHeaders headers, RestSharp.Method httpMethod, PathParams pathParameters, IQueryParams queryParameters, IRequestBody requestBody)
 {
     this.headers         = headers;
     this.httpMethod      = httpMethod;
     this.pathParameters  = pathParameters;
     this.queryParameters = queryParameters;
     this.requestBody     = requestBody;
 }
Beispiel #11
0
 public IResponseResult <TResult> ExecuteRequest <TResult>(
     HttpMethod method,
     string url,
     IHeaderCollection headers = null,
     IRequestBody body         = null)
 {
     return(this.ExecuteRequestAsync <TResult>(method, url, headers, body).ConfigureAwait(false).GetAwaiter().GetResult());
 }
        /// <summary>
        /// The method to send MAPIHTTP request to the server.
        /// </summary>
        /// <param name="site">An instance of interface ITestSite which provides logging, assertions,
        /// and adapters for test code onto its execution context.</param>
        /// <param name="mailStoreUrl">Mail store url.</param>
        /// <param name="userName">The user which connects the server.</param>
        /// <param name="domain">The domain of the user.</param>
        /// <param name="password">The password for the user.</param>
        /// <param name="requestBody">The MAPIHTTP request body.</param>
        /// <param name="requestType">The MAPIHTTP request type.</param>
        /// <param name="cookies">Cookie container for client.</param>
        /// <returns>Return the MAPIHTTP response from the server.</returns>
        public static HttpWebResponse SendMAPIHttpRequest(ITestSite site, string mailStoreUrl, string userName, string domain, string password, IRequestBody requestBody, string requestType, CookieCollection cookies)
        {
            HttpWebResponse response = null;

            System.Net.ServicePointManager.ServerCertificateValidationCallback =
            new System.Net.Security.RemoteCertificateValidationCallback(Common.ValidateServerCertificate);
            HttpWebRequest request = WebRequest.Create(mailStoreUrl) as HttpWebRequest;
            request.KeepAlive = true;
            request.CookieContainer = new CookieContainer();
            request.Method = "POST";
            request.ProtocolVersion = HttpVersion.Version11;
            request.Credentials = new System.Net.NetworkCredential(userName, password, domain);
            request.ContentType = "application/mapi-http";
            request.Accept = "application/mapi-http";
            request.Connection = string.Empty;

            byte[] buffer = null;
            if (requestBody != null)
            {
                buffer = requestBody.Serialize();
                request.ContentLength = buffer.Length;
            }
            else
            {
                request.ContentLength = 0;
            }

            request.Headers.Add("X-ClientInfo", "{A7A47AAD-233C-412B-9D10-DDE9108FEBD7}-5");
            request.Headers.Add("X-RequestId", "{16AC2587-EED8-48EB-8A7B-D48558B68BD7}:1");
            request.Headers.Add("X-ClientApplication", "Outlook/15.00.0856.000");
            request.Headers.Add("X-RequestType", requestType);
            if (cookies != null && cookies.Count > 0)
            {
                foreach (Cookie cookie in cookies)
                {
                    request.CookieContainer.Add(cookie);
                }
            }

            if (requestBody != null)
            {
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(buffer, 0, buffer.Length);
                }
            }

            try
            {
                response = request.GetResponse() as HttpWebResponse;
            }
            catch (WebException ex)
            {
                site.Assert.Fail("A WebException happened when connecting the server, The exception is {0}.", ex.Message);
            }

            return response;
        }
        /// <summary>
        ///  Was experiencing timeout issues in theory the query could be one statement
        /// don't have time to debug this any further
        /// </summary>
        public IEnumerable <AirportMonthModel> FilterQuery(IRequestBody Parameters)
        {
            if (Parameters.Query == null)
            {
                return(GetAll().If(Parameters.Skip > 0, td => td.Skip(Parameters.Skip))
                       .If(Parameters.Take > 0, td => td.Take(Parameters.Take)));
            }

            var query  = AirportMonths.Where(td => td.Airport != null);
            var query2 = query.If(!string.IsNullOrEmpty(Parameters.Query.AirportCode),
                                  q => q.Where(td => td.Airport.Code == Parameters.Query?.AirportCode));

            query = query2.Any() ? query2.ToList <AirportMonthModel>().AsEnumerable() : query;


            query2 = query.If(Parameters.Query.FlightCount != null && Parameters.Query.FlightCount.Minimum > 0, q => q.Where(
                                  (td => (td.Statistics.Flights.Total) >= Parameters.Query.FlightCount?.Minimum)))
                     .If(Parameters.Query.FlightCount?.Maximum > 0, q => q.Where(
                             (td => td.Statistics.Flights.Total <= Parameters.Query.FlightCount.Maximum)));

            query = query2.Any() ? query2.ToList <AirportMonthModel>().AsEnumerable() : query;

            query2 = query.If(
                Parameters.Query.DelayCount?.Minimum > 0, q => q.Where(
                    (td => td.Statistics != null)).Where(
                    (td => (td.Statistics?.OfDelays?.Carrier +
                            td.Statistics?.OfDelays?.LateAircraft +
                            td.Statistics?.OfDelays?.NationalAviationSystem +
                            td.Statistics?.OfDelays?.Security +
                            td.Statistics?.OfDelays?.Weather) >= Parameters.Query?.DelayCount.Minimum)));

            query = query2.Any() ? query2.ToList <AirportMonthModel>().AsEnumerable() : query;

            query2 = query.If(
                Parameters.Query.DelayCount?.Maximum > 0 &&
                Parameters.Query.DelayCount?.Maximum >= Parameters.Query.DelayCount?.Minimum, q => q.Where(
                    (td => (td.Statistics.OfDelays.Carrier +
                            td.Statistics.OfDelays.LateAircraft + td.Statistics.OfDelays.NationalAviationSystem +
                            td.Statistics.OfDelays.Security + td.Statistics.OfDelays.Weather) <= Parameters.Query.DelayCount.Maximum)));

            query = query2.Any() ? query2.ToList <AirportMonthModel>().AsEnumerable() : query;


            query2 = query.If(!string.IsNullOrEmpty(Parameters.Query?.Since),
                              q => q.Where(td => td.Time.GetDate() >= td.Time.GetDate(Parameters.Query.Since)));

            query = query2.Any() ? query2.ToList <AirportMonthModel>().AsEnumerable() : query;

            query2 = query.If(!string.IsNullOrEmpty(Parameters.Query?.Until),
                              q => q.Where(td => td.Time.GetDate() <= td.Time.GetDate(Parameters.Query.Until)));

            query = query2.Any() ? query2.ToList <AirportMonthModel>().AsEnumerable() : query;

            query = query.If(Parameters?.Skip > 0, q => q.Skip(Parameters.Skip));
            query = query.If(Parameters?.Take > 0, q => q.Take(Parameters.Take));

            return(query);
        }
Beispiel #14
0
 public async Task <IResponseResult <TResult> > ExecuteRequestAsync <TResult>(
     HttpMethod method,
     string baseUrl,
     IQueryString queryString  = null,
     IHeaderCollection headers = null,
     IRequestBody body         = null)
 {
     return(await this.restHandler.ExecuteRequestAsync <TResult>(method, baseUrl, queryString, headers, body));
 }
Beispiel #15
0
 public Endpoint(string operationId, string path, EndpointType type, HashSet <IParameter> parameters,
                 IRequestBody requestBody, IEnumerable <IHttpResponse> responses)
 {
     _operationId = operationId;
     _path        = path;
     _type        = type;
     _parameters  = parameters;
     _requestBody = requestBody;
     _responses   = responses;
 }
Beispiel #16
0
        public async Task <IResponseResult <TResult> > ExecuteRequestAsync <TResult>(
            HttpMethod method,
            string url,
            IHeaderCollection headers = null,
            IRequestBody body         = null)
        {
            var restSharpMethod = method.ConvertToRestSharpMethod();
            var request         = new RestRequest(url, restSharpMethod)
            {
                RequestFormat = body.ConvertToRestSharpDataFormat()
            };

            if (body != null)
            {
                if (body.Type == BodyTypes.Xml)
                {
                    request.AddXmlBody(body.Payload);
                }
                else
                {
                    request.AddJsonBody(body.Payload);
                }
            }

            if (headers != null)
            {
                foreach (var header in headers.ToDictionary())
                {
                    request.AddHeader(header.Key, header.Value?.ToString() ?? "");
                }
            }

            var response = await this.Client.ExecuteAsync <TResult>(request);

            if (response.IsSuccessful)
            {
                return(new ResponseResult <TResult>(response.StatusCode)
                {
                    Json = response.Content,
                    RawData = response.RawBytes,
                    Data = response.Data
                });
            }
            else
            {
                return(new ResponseResult <TResult>(response.StatusCode)
                {
                    Message = response.Content,
                    Json = response.Content,
                    RawData = response.RawBytes
                });
            }
        }
        public async Task <IResponseResult <TResult> > ExecuteRequestAsync <TResult>(
            HttpMethod method,
            string url,
            IHeaderCollection headers = null,
            IRequestBody body         = null)
        {
            using (var httpClient = new HttpClient())
            {
                var request = new HttpRequestMessage(method, url);
                if (headers != null)
                {
                    foreach (var(key, value) in headers.ToDictionary())
                    {
                        request.Headers.Add(key, value.ToString());
                    }
                }

                var httpContent = body?.GetHttpContent();
                if (httpContent != null)
                {
                    request.Content = httpContent;
                }

                var response = await httpClient.SendAsync(request);

                var rawData = await response.Content.ReadAsByteArrayAsync();

                var json = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    return(new ResponseResult <TResult>(response.StatusCode)
                    {
                        Json = json,
                        RawData = rawData,
                        Data = Newtonsoft.Json.JsonConvert.DeserializeObject <TResult>(json),
                    });
                }
                else
                {
                    return(new ResponseResult <TResult>(response.StatusCode, json)
                    {
                        Json = json,
                        RawData = rawData
                    });
                }
            }
        }
Beispiel #18
0
 public IResponseResult <TResult> ExecuteRequest <TResult>(
     HttpMethod method,
     string baseUrl,
     IQueryString queryString  = null,
     IHeaderCollection headers = null,
     IRequestBody body         = null)
 {
     if (queryString != null && queryString.Any())
     {
         var url = $"{baseUrl}?{queryString}";
         return(this.ExecuteRequest <TResult>(method, url, headers, body));
     }
     else
     {
         return(this.ExecuteRequest <TResult>(method, baseUrl, headers, body));
     }
 }
Beispiel #19
0
        /// <summary>
        /// Send the request to address book server endpoint.
        /// </summary>
        /// <param name="requestBody">The request body.</param>
        /// <param name="requestType">The type of the request.</param>
        /// <param name="cookieChange">Whether the session context cookie is changed.</param>
        /// <returns>The returned chunked response.</returns>
        private ChunkedResponse SendAddressBookRequest(IRequestBody requestBody, RequestType requestType, bool cookieChange = true)
        {
            byte[]          rawBuffer       = null;
            ChunkedResponse chunkedResponse = null;

            // Send the execute HTTP request and get the response
            HttpWebResponse response = MapiHttpAdapter.SendMAPIHttpRequest(this.site, this.addressBookUrl, this.userName, this.domainName, this.password, requestBody, requestType.ToString(), AdapterHelper.SessionContextCookies);

            rawBuffer = MapiHttpAdapter.ReadHttpResponse(response);
            string responseCode = response.Headers["X-ResponseCode"];

            this.site.Assert.AreEqual <uint>(0, uint.Parse(responseCode), "The request to the address book server should be executed successfully!");

            // Read the HTTP response buffer and parse the response to correct format
            chunkedResponse = ChunkedResponse.ParseChunkedResponse(rawBuffer);

            response.GetResponseStream().Close();
            if (cookieChange)
            {
                AdapterHelper.SessionContextCookies = response.Cookies;
            }

            return(chunkedResponse);
        }
        /// <summary>
        /// This method is used to send the http request.
        /// </summary>
        /// <param name="userName">The user name used to connect with server.</param>
        /// <param name="password">The password used to connect with server.</param>
        /// <param name="requestBody">The request body.</param>
        /// <param name="endpoint">The endpoint which the request would be send to.</param>
        /// <param name="cookies">Cookies used to identify the Session Context.</param>
        /// <param name="resquestHeaders">The specified request header used by the request.</param>
        /// <param name="rawBuffer">The raw buffer of the response.</param>
        /// <returns>The response of the request.</returns>
        private HttpWebResponse SendMAPIHttpRequest(string userName, string password, IRequestBody requestBody, ServerEndpoint endpoint, CookieCollection cookies, WebHeaderCollection resquestHeaders, out byte[] rawBuffer)
        {
            rawBuffer = null;
            HttpWebResponse response = null;

            AdapterHelper.Counter++;
            string url = string.Empty;

            if (endpoint == ServerEndpoint.MailboxServerEndpoint)
            {
                if (string.IsNullOrEmpty(this.mailStoreUrl))
                {
                    this.GetEndpointUrl();
                }

                url = this.mailStoreUrl;
            }
            else
            {
                if (string.IsNullOrEmpty(this.addressBookUrl))
                {
                    this.GetEndpointUrl();
                }

                url = this.addressBookUrl;
            }

            System.Net.ServicePointManager.ServerCertificateValidationCallback =
                new System.Net.Security.RemoteCertificateValidationCallback(Common.ValidateServerCertificate);
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            request.CookieContainer = new CookieContainer();
            request.Method          = "POST";
            request.ProtocolVersion = HttpVersion.Version11;
            request.ContentType     = "application/mapi-http";
            request.Credentials     = new NetworkCredential(userName, password, this.domainName);
            request.Headers.Add(resquestHeaders);
            request.CookieContainer.Add(cookies);
            request.Timeout = System.Threading.Timeout.Infinite;

            byte[] buffer = null;
            if (requestBody != null)
            {
                buffer = requestBody.Serialize();
                request.ContentLength = buffer.Length;
            }
            else
            {
                request.ContentLength = 0;
            }

            if (requestBody != null)
            {
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(buffer, 0, buffer.Length);
                }
            }

            try
            {
                response = request.GetResponse() as HttpWebResponse;

                // Read the HTTP response buffer and parse the response to correct format.
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    rawBuffer = this.ReadHttpResponse(response);
                }
            }
            catch (WebException ex)
            {
                this.Site.Log.Add(
                    LogEntryKind.Comment,
                    "A WebException happened when connecting the server, The exception is {0}.",
                    ex.Message);
                return((HttpWebResponse)ex.Response);
            }

            return(response);
        }
Beispiel #21
0
 public static IRequestBuilder WithBody(this IRequestBuilder builder, IRequestBody body)
 {
     return(builder.With(body));
 }
Beispiel #22
0
 public PostRequest(Resource resource, IRequestBody body)
     : base(resource, body)
 {
 }
Beispiel #23
0
 protected PostLikeRequest(Resource resource, IRequestBody body)
     : base(resource, body)
 {
 }
Beispiel #24
0
 protected PostLikeRequest(Resource resource, IRequestBody body)
     : base(resource)
 {
     Body = body;
 }
        private async void ExecuteWebhookRequestAsync(WebhookRequest webhookRequest, string utilizerId, string membershipId, object document, object prior, int tryCount)
        {
            var httpMethod = new HttpMethod(webhookRequest.Method);
            var url        = webhookRequest.Url;
            var headers    = HeaderCollection.Empty;

            if (webhookRequest.Headers != null)
            {
                foreach (var webhookRequestHeader in webhookRequest.Headers)
                {
                    if (!string.IsNullOrEmpty(webhookRequestHeader.Key) && webhookRequestHeader.Value != null && !string.IsNullOrEmpty(webhookRequestHeader.Value.ToString()))
                    {
                        headers = headers.Add(webhookRequestHeader);
                    }
                }
            }

            IRequestBody body = null;

            switch (webhookRequest.BodyTypeEnum)
            {
            case WebhookRequestBodyType.None:
            case WebhookRequestBodyType.Javascript:
            case WebhookRequestBodyType.Json:
                body = new JsonRequestBody(new
                {
                    document,
                    prior,
                    payload = webhookRequest.Body
                });
                break;

            case WebhookRequestBodyType.Html:
            case WebhookRequestBodyType.Xml:
                body = new XmlRequestBody(new
                {
                    document,
                    prior,
                    payload = webhookRequest.Body
                });
                break;
            }

            for (var i = 0; i < tryCount; i++)
            {
                try
                {
                    var response = await this.restHandler.ExecuteRequestAsync(httpMethod, url, QueryString.Empty, headers, body);

                    if (response.IsSuccess)
                    {
                        await this.eventService.FireEventAsync(this, new ErtisAuthEvent(
                                                                   ErtisAuthEventType.WebhookRequestSent,
                                                                   utilizerId,
                                                                   membershipId,
                                                                   response
                                                                   ));

                        break;
                    }
                    else
                    {
                        await this.eventService.FireEventAsync(this, new ErtisAuthEvent(
                                                                   ErtisAuthEventType.WebhookRequestFailed,
                                                                   utilizerId,
                                                                   membershipId,
                                                                   response
                                                                   ));
                    }
                }
                catch (Exception ex)
                {
                    await this.eventService.FireEventAsync(this, new ErtisAuthEvent(
                                                               ErtisAuthEventType.WebhookRequestFailed,
                                                               utilizerId,
                                                               membershipId,
                                                               ex
                                                               ));
                }
            }
        }
        /// <summary>
        /// This method is used to send the http request.
        /// </summary>
        /// <param name="userName">The user name used to connect with server.</param>
        /// <param name="password">The password used to connect with server.</param>
        /// <param name="requestBody">The request body.</param>
        /// <param name="endpoint">The endpoint which the request would be send to.</param>
        /// <param name="cookies">Cookies used to identify the Session Context.</param>
        /// <param name="resquestHeaders">The specified request header used by the request.</param>
        /// <param name="rawBuffer">The raw buffer of the response.</param>
        /// <returns>The response of the request.</returns>
        private HttpWebResponse SendMAPIHttpRequest(string userName, string password, IRequestBody requestBody, ServerEndpoint endpoint, CookieCollection cookies, WebHeaderCollection resquestHeaders, out byte[] rawBuffer)
        {
            rawBuffer = null;
            HttpWebResponse response = null;
            AdapterHelper.Counter++;
            string url = string.Empty;
            if (endpoint == ServerEndpoint.MailboxServerEndpoint)
            {
                if (string.IsNullOrEmpty(this.mailStoreUrl))
                {
                    this.GetEndpointUrl();
                }

                url = this.mailStoreUrl;
            }
            else
            {
                if (string.IsNullOrEmpty(this.addressBookUrl))
                {
                    this.GetEndpointUrl();
                }

                url = this.addressBookUrl;
            }

            System.Net.ServicePointManager.ServerCertificateValidationCallback =
            new System.Net.Security.RemoteCertificateValidationCallback(Common.ValidateServerCertificate);
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = new CookieContainer();
            request.Method = "POST";
            request.ProtocolVersion = HttpVersion.Version11;
            request.ContentType = "application/mapi-http";
            request.Credentials = new NetworkCredential(userName, password, this.domainName);
            request.Headers.Add(resquestHeaders);
            request.CookieContainer.Add(cookies);
            request.Timeout = System.Threading.Timeout.Infinite;

            byte[] buffer = null;
            if (requestBody != null)
            {
                buffer = requestBody.Serialize();
                request.ContentLength = buffer.Length;
            }
            else
            {
                request.ContentLength = 0;
            }   

            if (requestBody != null)
            {
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(buffer, 0, buffer.Length);
                }
            }

            try
            {
                response = request.GetResponse() as HttpWebResponse;

                // Read the HTTP response buffer and parse the response to correct format.
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    rawBuffer = this.ReadHttpResponse(response);
                }
            }
            catch (WebException ex)
            {
                this.Site.Log.Add(
                    LogEntryKind.Comment, 
                    "A WebException happened when connecting the server, The exception is {0}.",
                    ex.Message);
                return (HttpWebResponse)ex.Response;
            }

            return response;
        }
Beispiel #27
0
 public OpenApiModelBuilder AttachRequestBody(string path, IRequestBody request)
 {
     _requestBodies.Add(path, request);
     return(this);
 }
Beispiel #28
0
 public static bool IsMultiparted(this IRequestBody body)
 {
     return(body is IMultipartBody &&
            ((IMultipartBody)body).Parts != null &&
            ((IMultipartBody)body).Parts.Any());
 }
Beispiel #29
0
        private void MapEndpoints(OpenApiModel.OpenApiModelBuilder openApiModelBuilder,
                                  Dictionary <string, PathItem> pathItems)
        {
            foreach (var(url, pathItem) in pathItems)
            {
                var path       = $"#/paths/{url}";
                var parameters = new HashSet <IParameter>();

                if (pathItem.Parameters != null)
                {
                    foreach (var versionedParameter in pathItem.Parameters)
                    {
                        var parameterPath = versionedParameter.GetRef() ??
                                            $"{path}/parameters/{versionedParameter.GetObject().Name}";
                        var parameter = openApiModelBuilder.GetParameterForPath(parameterPath);
                        if (parameter == null)
                        {
                            throw new ArgumentException($"Missing parameter object - {parameterPath}");
                        }

                        parameters.Add(parameter);
                    }
                }

                var operationMap = GetOperationMap(pathItem);
                foreach (var(type, operation) in operationMap)
                {
                    var endpointParameters = new HashSet <IParameter>(parameters);

                    if (operation.Security != null)
                    {
                        foreach (var securityDictionary in operation.Security)
                        {
                            foreach (var key in securityDictionary.Keys)
                            {
                                var securityParameter = openApiModelBuilder.GetSecurityParameterForName(key);
                                endpointParameters.Add(securityParameter);
                            }
                        }
                    }

                    if (operation.Parameters != null)
                    {
                        foreach (var operationParameter in operation.Parameters)
                        {
                            var parameterPath = operationParameter.GetRef() ??
                                                $"{path}/{type.ToString().ToLower()}/parameters/{operationParameter.GetObject().Name}";
                            var parameter = openApiModelBuilder.GetParameterForPath(parameterPath);
                            if (parameter == null)
                            {
                                throw new ArgumentException($"Missing parameter object - {parameterPath}");
                            }

                            endpointParameters.Add(parameter);
                        }
                    }

                    var endpointResponses = new List <IHttpResponse>();
                    foreach (var(status, @ref) in operation.Responses)
                    {
                        var responsePath =
                            @ref.GetRef() ?? $"{path}/{type.ToString().ToLower()}/responses/{status}";
                        var response = openApiModelBuilder.GetResponseForPath(responsePath);
                        endpointResponses.Add(new HttpResponse(int.Parse(status),
                                                               response)); // todo: check if parse was successful
                    }

                    IRequestBody requestBody = null;
                    if (operation.RequestBody != null)
                    {
                        var requestBodyPath = operation.RequestBody?.GetRef() ??
                                              $"{path}/{type.ToString().ToLower()}/requestBody";
                        requestBody = openApiModelBuilder.GetRequestBodyForPath(requestBodyPath);
                    }

                    var operationId = operation.OperationId ??
                                      throw new ArgumentException($"Missing operationId - {path}/{type}");
                    openApiModelBuilder.AttachEndpoint(new Endpoint(operationId, url,
                                                                    type,
                                                                    endpointParameters, requestBody, endpointResponses));
                }
            }
        }
Beispiel #30
0
 public PatchRequest(Resource resource, IRequestBody body)
     : base(resource, body)
 {
 }
Beispiel #31
0
 public static IEnumerable <KeyValuePair <string, IBodyPart> > Parts(this IRequestBody body)
 {
     return(body is IMultipartBody ? ((IMultipartBody)body).Parts : new KeyValuePair <string, IBodyPart> [0]);
 }
 /// <summary>
 /// The method to send NotificationWait request to the server.
 /// </summary>        
 /// <param name="requestBody">The NotificationWait request body.</param>
 /// <returns>Return the NotificationWait response body.</returns>
 public NotificationWaitSuccessResponseBody MAPINotificationWaitCall(IRequestBody requestBody)
 {
     return this.mapiHttpAdapter.NotificationWaitCall(requestBody);
 }
        /// <summary>
        /// Send the request to address book server endpoint. 
        /// </summary>
        /// <param name="requestBody">The request body.</param>
        /// <param name="requestType">The type of the request.</param>
        /// <param name="cookieChange">If the session context cookie changed.</param>
        /// <returns>The common response.</returns>
        private CommonResponse SendAddressBookRequest(IRequestBody requestBody, RequestType requestType, bool cookieChange = true)
        {
            byte[] rawBuffer;
            CommonResponse commonResponse = null;
            WebHeaderCollection webHeaderCollection = AdapterHelper.InitializeHTTPHeader(requestType, AdapterHelper.ClientInstance, AdapterHelper.Counter);
            
            // Send the Execute HTTP request and get the response.
            HttpWebResponse response = this.SendMAPIHttpRequest(this.userName, this.password, requestBody, ServerEndpoint.AddressBookServerEndpoint, AdapterHelper.SessionContextCookies, webHeaderCollection, out rawBuffer);
            uint responseCode = AdapterHelper.GetFinalResponseCode(response.Headers["X-ResponseCode"]);
            this.Site.Assert.AreEqual<uint>(0, responseCode, "The request to the address book server should be executed successfully!");

            // Read the HTTP response buffer and parse the response to correct format.
            commonResponse = CommonResponse.ParseCommonResponse(rawBuffer);
            Site.Assert.IsNotNull(commonResponse.ResponseBodyRawData, "The response body should contains data.");
            this.VerifyRequestTypesForAddressBookServerEndpoint(response.Headers, commonResponse);
            this.VerifyAutoDiscover(response.StatusCode, ServerEndpoint.AddressBookServerEndpoint);
            this.VerifyAuthentication(response);

            response.GetResponseStream().Close();
            if (cookieChange)
            {
                AdapterHelper.SessionContextCookies = response.Cookies;  
            }

            return commonResponse;
        }
Beispiel #34
0
 /// <summary>
 /// The method to send NotificationWait request to the server.
 /// </summary>
 /// <param name="requestBody">The NotificationWait request body.</param>
 /// <returns>Return the NotificationWait response body.</returns>
 public NotificationWaitSuccessResponseBody MAPINotificationWaitCall(IRequestBody requestBody)
 {
     return(this.mapiHttpAdapter.NotificationWaitCall(requestBody));
 }
        /// <summary>
        /// The method to send NotificationWait request to the server.
        /// </summary>        
        /// <param name="requestBody">The NotificationWait request body.</param>
        /// <returns>Return the NotificationWait response body.</returns>
        public NotificationWaitSuccessResponseBody NotificationWaitCall(IRequestBody requestBody)
        {
            string requestType = "NotificationWait";
            HttpWebResponse response = SendMAPIHttpRequest(this.site, this.mailStoreUrl, this.userName, this.domain, this.userPassword, requestBody, requestType, this.cookies);

            NotificationWaitSuccessResponseBody result = null;

            string responseCode = response.Headers["X-ResponseCode"];

            byte[] rawBuffer = ReadHttpResponse(response);

            response.GetResponseStream().Close();

            if (int.Parse(responseCode) == 0)
            {
                ChunkedResponse chunkedResponse = ChunkedResponse.ParseChunkedResponse(rawBuffer);
                NotificationWaitSuccessResponseBody responseSuccess = NotificationWaitSuccessResponseBody.Parse(chunkedResponse.ResponseBodyRawData);
                result = responseSuccess;
            }
            else
            {
                this.site.Assert.Fail("MAPIHTTP call failed, the error code returned from server is: {0}", responseCode);
            }

            return result;
        }
        /// <summary>
        /// The method to send MAPIHTTP request to the server.
        /// </summary>
        /// <param name="site">An instance of interface ITestSite which provides logging, assertions,
        /// and adapters for test code onto its execution context.</param>
        /// <param name="mailStoreUrl">Mail store url.</param>
        /// <param name="userName">The user which connects the server.</param>
        /// <param name="domain">The domain of the user.</param>
        /// <param name="password">The password for the user.</param>
        /// <param name="requestBody">The MAPIHTTP request body.</param>
        /// <param name="requestType">The MAPIHTTP request type.</param>
        /// <param name="cookies">Cookie container for client.</param>
        /// <returns>Return the MAPIHTTP response from the server.</returns>
        public static HttpWebResponse SendMAPIHttpRequest(ITestSite site, string mailStoreUrl, string userName, string domain, string password, IRequestBody requestBody, string requestType, CookieCollection cookies)
        {
            HttpWebResponse response = null;

            System.Net.ServicePointManager.ServerCertificateValidationCallback =
                new System.Net.Security.RemoteCertificateValidationCallback(Common.ValidateServerCertificate);
            System.Net.ServicePointManager.Expect100Continue = false;
            HttpWebRequest request = WebRequest.Create(mailStoreUrl) as HttpWebRequest;

            request.KeepAlive       = true;
            request.CookieContainer = new CookieContainer();
            request.Method          = "POST";
            request.ProtocolVersion = HttpVersion.Version11;
            request.Credentials     = new System.Net.NetworkCredential(userName, password, domain);
            request.ContentType     = "application/mapi-http";
            request.Accept          = "application/mapi-http";
            request.Connection      = string.Empty;

            byte[] buffer = null;
            if (requestBody != null)
            {
                buffer = requestBody.Serialize();
                request.ContentLength = buffer.Length;
            }
            else
            {
                request.ContentLength = 0;
            }

            request.Headers.Add("X-ClientInfo", "{A7A47AAD-233C-412B-9D10-DDE9108FEBD7}-5");
            request.Headers.Add("X-RequestId", "{16AC2587-EED8-48EB-8A7B-D48558B68BD7}:1");
            request.Headers.Add("X-ClientApplication", "Outlook/15.00.0856.000");
            request.Headers.Add("X-RequestType", requestType);
            if (cookies != null && cookies.Count > 0)
            {
                foreach (Cookie cookie in cookies)
                {
                    request.CookieContainer.Add(cookie);
                }
            }

            if (requestBody != null)
            {
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(buffer, 0, buffer.Length);
                }
            }

            try
            {
                response = request.GetResponse() as HttpWebResponse;
            }
            catch (WebException ex)
            {
                site.Assert.Fail("A WebException happened when connecting the server, The exception is {0}.", ex.Message);
            }

            return(response);
        }
Beispiel #37
0
 protected HttpRequest(Resource resource, IRequestBody body)
 {
     Resource = resource;
     Body     = body;
 }
        /// <summary>
        /// Send the request to address book server endpoint. 
        /// </summary>
        /// <param name="requestBody">The request body.</param>
        /// <param name="requestType">The type of the request.</param>
        /// <param name="cookieChange">Whether the session context cookie is changed.</param>
        /// <returns>The returned chunked response.</returns>
        private ChunkedResponse SendAddressBookRequest(IRequestBody requestBody, RequestType requestType, bool cookieChange = true)
        {
            byte[] rawBuffer = null;
            ChunkedResponse chunkedResponse = null;

            // Send the execute HTTP request and get the response
            HttpWebResponse response = MapiHttpAdapter.SendMAPIHttpRequest(this.site, this.addressBookUrl, this.userName, this.domainName, this.password, requestBody, requestType.ToString(), AdapterHelper.SessionContextCookies);
            rawBuffer = MapiHttpAdapter.ReadHttpResponse(response);
            string responseCode = response.Headers["X-ResponseCode"];
            this.site.Assert.AreEqual<uint>(0, uint.Parse(responseCode), "The request to the address book server should be executed successfully!");

            // Read the HTTP response buffer and parse the response to correct format
            chunkedResponse = ChunkedResponse.ParseChunkedResponse(rawBuffer);

            response.GetResponseStream().Close();
            if (cookieChange)
            {
                AdapterHelper.SessionContextCookies = response.Cookies;
            }

            return chunkedResponse;
        }
Beispiel #39
0
 public static bool IsNamed(this IRequestBody body)
 {
     return(!String.IsNullOrEmpty(body.Name));
 }