private bool MessageHandler(HttpRequestMessage request, HttpResponseMessage response)
        {
            if (request.RequestUri.OriginalString.Contains("status"))
            {
                try
                {
                    int code =
                        Convert.ToInt32(
                            request.RequestUri.OriginalString.Substring(request.RequestUri.OriginalString.Length - 3, 3));
                    HttpStatusCode status = (HttpStatusCode)code;
                    throw new HttpStatusException(status);
                }
                catch (HttpStatusException)
                {
                    throw;
                }
                catch (Exception)
                {

                    throw new HttpStatusException(HttpStatusCode.BadRequest);
                }
            }
            else
                response.Content = new StringContent(string.Format(Html, DateTime.Now.ToString("s"), request.RequestUri.OriginalString), Encoding.UTF8, "text/html");
            return true;
        }
        public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
        {
            if (actionContext.Request.Headers.Contains("X-AccessToken"))
            {
                var tokenvalue = actionContext.Request.Headers.GetValues("X-AccessToken").FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(tokenvalue) && tokenvalue.Equals(ConfigurationManager.AppSettings["token"]))
                {
                    return continuation();
                }
            }
            else if (actionContext.Request.RequestUri.ParseQueryString() != null)
            {
                var queryValues = actionContext.Request.RequestUri.ParseQueryString();
                var tokenvalue = queryValues["token"];
                if (!string.IsNullOrWhiteSpace(tokenvalue) && tokenvalue.Equals(ConfigurationManager.AppSettings["token"]))
                {
                    return continuation();
                }
            }

            return Task.Factory.StartNew(() =>
            {
                var retur = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent("This resource cannot be used without the correct access token")
                };

                return retur;
            });

        }
        /// <summary>
        /// Get the resource description of the api for swagger documentation
        /// </summary>
        /// <remarks>It is very convenient to have this information available for generating clients. This is the entry point for the swagger UI
        /// </remarks>
        /// <returns>JSON document representing structure of API</returns>
        public HttpResponseMessage Get()
        {
            var docProvider = (XmlCommentDocumentationProvider)GlobalConfiguration.Configuration.Services.GetDocumentationProvider();

            ResourceListing r = SwaggerGen.CreateResourceListing(ControllerContext);
            List<string> uniqueControllers = new List<string>();

            foreach (var api in GlobalConfiguration.Configuration.Services.GetApiExplorer().ApiDescriptions)
            {
                string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
                if (uniqueControllers.Contains(controllerName) ||
                      controllerName.ToUpper().Equals(SwaggerGen.SWAGGER.ToUpper())) continue;

                uniqueControllers.Add(controllerName);

                ResourceApi rApi = SwaggerGen.CreateResourceApi(api);
                r.apis.Add(rApi);
            }

            HttpResponseMessage resp = new HttpResponseMessage();

            resp.Content = new ObjectContent<ResourceListing>(r, ControllerContext.Configuration.Formatters.JsonFormatter);            
            
            return resp;
        }
        public bool CanEnrich(HttpResponseMessage response) {

            var content = response.Content as ObjectContent;

            return content != null
                && (content.ObjectType == typeof(MediaModel));
        }
        public void AddAndDeleteGridWidgetFromFileSystemVerifyPageToolbox()
        {
            RuntimeSettingsModificator.ExecuteWithClientTimeout(800000, () =>  BAT.Macros().NavigateTo().CustomPage("~/sitefinity/pages", false));
            RuntimeSettingsModificator.ExecuteWithClientTimeout(800000, () => BAT.Macros().User().EnsureAdminLoggedIn());
            BAT.Wrappers().Backend().Pages().PagesWrapper().OpenPageZoneEditor(PageName);
            BAT.Wrappers().Backend().Pages().PageZoneEditorWrapper().SwitchEditorLayoutMode(EditorLayoutMode.Layout);
            BATFrontend.Wrappers().Backend().Widgets().GridWidgets().ClickBootstrapGridWidgetButton();
            BATFrontend.Wrappers().Backend().Pages().PageZoneEditorWrapper().DragAndDropLayoutWidgetToPlaceholder(LayoutCaption);
            BAT.Wrappers().Backend().Pages().PageLayoutEditorWrapper().VerifyLayoutWidgetPageEditor(LayoutCaption, GridCount1);
            BAT.Wrappers().Backend().Pages().PageZoneEditorWrapper().PublishPage();

            BAT.Macros().NavigateTo().CustomPage("~/" + PageName.ToLower(), false);
            BATFrontend.Wrappers().Frontend().Widgets().GridWidgets().VerifyNewGridWidgetOnTheFrontend(this.layouts);

            BAT.Arrange(this.TestName).ExecuteArrangement("DeleteGridWidgetFromFileSystem");

            BAT.Macros().NavigateTo().Pages();
            BAT.Wrappers().Backend().Pages().PagesWrapper().OpenPageZoneEditor(PageName);
            BAT.Wrappers().Backend().Pages().PageZoneEditorWrapper().SwitchEditorLayoutMode(EditorLayoutMode.Layout);
            BATFrontend.Wrappers().Backend().Widgets().GridWidgets().ClickBootstrapGridWidgetButton();
            Assert.IsFalse(
                BATFrontend.Wrappers().Backend().Pages().PageZoneEditorWrapper().IsLayoutWidgetPresentInToolbox(LayoutCaption),
                "Layout widget is found in the toolbox");

            BAT.Wrappers().Backend().Pages().PageZoneEditorWrapper().PublishPage();
            BAT.Macros().NavigateTo().CustomPage("~/" + PageName.ToLower(), false);

            // Asserts that the page is not throwing an error 500 on the frontend
            HttpResponseMessage response = new HttpResponseMessage();
            Assert.AreEqual(200, (int)response.StatusCode);
        }
		public Task<HttpResponseMessage> ExecuteAsync( CancellationToken cancellationToken ) {
			//Request.GetOwinContext().Authentication.Challenge( LoginProvider );

			HttpResponseMessage response = new HttpResponseMessage( HttpStatusCode.Unauthorized );
			response.RequestMessage = Request;
			return Task.FromResult( response );
		}
        public static void ThrowIfError(HttpResponseMessage response, dynamic json)
        {
            if (json == null) return;

            if (!JsonHelpers.ContainsProperty(json, Constants.ErrorProperty)) return;

            var error = json[Constants.ErrorProperty];
            if (string.IsNullOrWhiteSpace(error)) return;

            CexApiException exception;

            if (error == Constants.NonceMustBeIncremented)
            {
                exception = new CexNonceException(response, Constants.NonceMustBeIncremented);
            }
            else if (error == Constants.PermissionDenied)
            {
                exception = new CexPermissionDeniedException(response, Constants.PermissionDenied);
            }
            else if (error == Constants.InvalidApiKey)
            {
                exception = new CexInvalidApiKeyException(response, Constants.InvalidApiKey);
            }
            else
            {
                exception = new CexApiException(response, error);
            }

            throw exception;
        }
 public static HttpResponseMessage CreateSuccessTokenResponseMessage()
 {
     HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.OK);
     HttpContent content = new StringContent("{\"token_type\":\"Bearer\",\"expires_in\":\"3599\",\"scope\":\"some-scope1 some-scope2\",\"access_token\":\"some-access-token\",\"refresh_token\":\"OAAsomethingencryptedQwgAA\",\"id_token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSIsImtpZCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSJ9.eyJhdWQiOiJlODU0YTRhNy02YzM0LTQ0OWMtYjIzNy1mYzdhMjgwOTNkODQiLCJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vNmMzZDUxZGQtZjBlNS00OTU5LWI0ZWEtYTgwYzRlMzZmZTVlL3YyLjAvIiwiaWF0IjoxNDU1ODMzODI4LCJuYmYiOjE0NTU4MzM4MjgsImV4cCI6MTQ1NTgzNzcyOCwiaXBhZGRyIjoiMTMxLjEwNy4xNTkuMTE3IiwibmFtZSI6Ik1hcmlvIFJvc3NpIiwib2lkIjoidW5pcXVlX2lkIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiZGlzcGxheWFibGVAaWQuY29tIiwic3ViIjoiSzRfU0dHeEtxVzFTeFVBbWhnNkMxRjZWUGlGemN4LVFkODBlaElFZEZ1cyIsInRpZCI6IjZjM2Q1MWRkLWYwZTUtNDk1OS1iNGVhLWE4MGM0ZTM2ZmU1ZSIsInZlciI6IjIuMCJ9.Z6Xc_PzqTtB-2TjyZwPpFGgkAs47m95F_I-NHxtIJT-H20i_1kbcBdmJaj7lMjHhJwAAMM-tE-iBVF9f7jNmsDZAADt-HgtrrXaXxkIKMwQ_MuB-OI4uY9KYIurEqmkGvOlRUK1ZVNNf7IKE5pqNTOZzyFDEyG8SwSvAmN-J4VnrxFz3d47klHoKVKwLjWJDj7edR2UUkdUQ6ZRj7YBj9UjC8UrmVNLBmvyatPyu9KQxyNyJpmTBT2jDjMZ3J1Z5iL98zWw_Ez0-6W0ti87UaPreJO3hejqQE_pRa4rXMLpw3oAnyEE1H7n0F6tK_3lJndZi9uLTIsdSMEXVnZdoHg\",\"id_token_expires_in\":\"3600\",\"profile_info\":\"eyJ2ZXIiOiIxLjAiLCJuYW1lIjoiTWFyaW8gUm9zc2kiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJtYXJpb0BkZXZlbG9wZXJ0ZW5hbnQub25taWNyb3NvZnQuY29tIiwic3ViIjoiSzRfU0dHeEtxVzFTeFVBbWhnNkMxRjZWUGlGemN4LVFkODBlaElFZEZ1cyIsInRpZCI6IjZjM2Q1MWRkLWYwZTUtNDk1OS1iNGVhLWE4MGM0ZTM2ZmU1ZSJ9\"}");
     responseMessage.Content = content;
     return responseMessage;
 }
        public override Task<HttpResponseMessage> HandleResponseAsync(string linkRelation, HttpResponseMessage responseMessage)
        {
            _action(linkRelation, responseMessage);

            return base.HandleResponseAsync(linkRelation, responseMessage);
            
        }
Example #10
0
 public void RetryAfter_RetryHeader_100()
 {
     var headers = new HttpResponseMessage().Headers;
     headers.Add("Retry-After", "100");
     var response = new FitbitResponse<string>((HttpStatusCode)429, headers, null);
     Assert.AreEqual(100, response.RetryAfter());
 }
        public WebApiResponseMessage(HttpResponseMessage response) : base(response.Content)
        {
            this.response = response;

            this.response.Headers.ToList()
                .ForEach(h => this.messageHeaders.Add(h.Key, h.Value.ToArray()));
        }
 private HttpResponseMessage Execute()
 {
     HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
     response.RequestMessage = request;
     response.ReasonPhrase = errorMessage;
     return response;
 }
        public void ExecuteExceptionFilterAsync_Throws_And_Traces_When_Inner_OnException_Throws()
        {
            // Arrange
            HttpRequestMessage request = new HttpRequestMessage();
            HttpResponseMessage response = new HttpResponseMessage();
            Mock<ExceptionFilterAttribute> mockAttr = new Mock<ExceptionFilterAttribute>() { CallBase = true };
            InvalidOperationException exception = new InvalidOperationException("test");
            mockAttr.Setup(a => a.OnException(It.IsAny<HttpActionExecutedContext>())).Throws(exception);
            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };
            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));
            HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response);
            TestTraceWriter traceWriter = new TestTraceWriter();
            ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttr.Object, traceWriter);
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "OnException" },
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End,  Operation = "OnException" }
            };

            // Act
            Exception thrown =
                Assert.Throws<InvalidOperationException>(
                    () => ((IExceptionFilter) tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None));

            // Assert
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
        public void ExecuteExceptionFilterAsync_Traces()
        {
            // Arrange
            HttpRequestMessage request = new HttpRequestMessage();
            HttpResponseMessage response = new HttpResponseMessage();
            Mock<ExceptionFilterAttribute> mockAttr = new Mock<ExceptionFilterAttribute>() { CallBase = true };
            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };
            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));
            HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response);
            TestTraceWriter traceWriter = new TestTraceWriter();
            ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttr.Object, traceWriter);
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "OnException" },
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.End,  Operation = "OnException" },
            };

            // Act
            Task task = ((IExceptionFilter)tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None);
            task.Wait();

            // Assert
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
Example #15
0
        public void PostTest()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            var result = _contactController.Post(contact);

            Assert.AreEqual(response.StatusCode, result.StatusCode);
        }
        public HttpResponseMessage GetProvidersData([FromUri]Filter filter)
        {
            string factualJsonData;
            try
            {
                factualJsonData = repository.GetHealthCareProviderData(filter);
            }
            catch (FactualApiException ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message) });
            }

            // Get the IContentNegotiator
            IContentNegotiator negotiator = Configuration.Services.GetContentNegotiator();

            // Run content negotiation to select a formatter
            ContentNegotiationResult result = negotiator.Negotiate(
              typeof(string), this.Request, this.Configuration.Formatters);

            var response = new HttpResponseMessage(HttpStatusCode.OK);

            if (result.MediaType.MediaType.Equals("application/xml"))
            {
                string json = string.Format("{0}{1}{2}", "{Root: ", factualJsonData, "}");

                var doc = (XDocument)JsonConvert.DeserializeXNode(json);
                response.Content = new StringContent(doc.ToString(), Encoding.UTF8, result.MediaType.MediaType);
            }
            else
                response.Content = new StringContent(factualJsonData, Encoding.UTF8, "application/json");

            return response;
        }
        public override void OnException(HttpActionExecutedContext context)
        {
            Exception exp;
            try
            {
                var logLevel = GetLogLevel(context.Exception);
                _logException(context.Exception, logLevel);

                var error = ToError(context.Exception);
                var httpResponseMessage = new HttpResponseMessage
                {
                    StatusCode = GetStatusCode(context.Exception),
                    ReasonPhrase = context.Exception.Message,
                    RequestMessage = context.Request,
                    Content = new ObjectContent<Error>(error, new JsonMediaTypeFormatter(), "application/json"),                    
                };
                exp = new HttpResponseException(httpResponseMessage);
            }
            catch (Exception exception)
            {
                var e = new AggregateException(exception, context.Exception);
                _logException(e, LogLevel.SystemError);
                throw;
            }

            throw exp;
        }
Example #18
0
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            bool authorized = false;
            var controller = actionContext.ControllerContext.Controller as ApiAuthorizeController;
            if (controller != null)
            {
                var cookie = actionContext.Request.Headers.GetCookies().Select(
                c => c[controller.Authenticator.CookieTicketConfig.CookieName]).FirstOrDefault();

                CookieHeaderValue cookieValue;
                CookieTicket ticket;
                if (controller.Authenticator.ValidateCookieTicket(cookie, out ticket, out cookieValue))
                {
                    authorized = true;
                    controller.UserId = int.Parse(ticket.Name);
                    if (cookieValue != null)
                    {
                        actionContext.Request.Properties.Add(RenewAuthorizationCookieToken, cookieValue);
                    }
                }
            }
            if (!authorized)
            {
                var message = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
                actionContext.Response = message;
            }
        }
 public static HttpResponseMessage CreateInvalidGrantTokenResponseMessage()
 {
     HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
     HttpContent content = new StringContent("{\"error\":\"invalid_grant\",\"error_description\":\"AADSTS70002: Error validating credentials.AADSTS70008: The provided access grant is expired or revoked.Trace ID: f7ec686c-9196-4220-a754-cd9197de44e9Correlation ID: 04bb0cae-580b-49ac-9a10-b6c3316b1eaaTimestamp: 2015-09-16 07:24:55Z\",\"error_codes\":[70002,70008],\"timestamp\":\"2015-09-16 07:24:55Z\",\"trace_id\":\"f7ec686c-9196-4220-a754-cd9197de44e9\",\"correlation_id\":\"04bb0cae-580b-49ac-9a10-b6c3316b1eaa\"}");
     responseMessage.Content = content;
     return responseMessage;
 }
        public void TestDeleteAzureMediaServiceAccountAsync404()
        {
            FakeHttpMessageHandler fakeHttpHandler;
            MediaServicesManagementClient clientWithHandler = CreateMediaManagementClientWithFakeHttpMessageHandler(out fakeHttpHandler);

            const string responseText = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">{\"Code\":\"NotFound\",\"Message\":\"The specified account was not found.\"}</string>";

            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new FakeHttpContent(responseText)
            };

            fakeHttpHandler.Send = request => response;

            MediaServicesClient target = new MediaServicesClient(null,
                clientWithHandler,
                StorageClient.WithHandler(new FakeHttpMessageHandler()));

            try
            {
                OperationResponse result = target.DeleteAzureMediaServiceAccountAsync(AccountName).Result;
            }
            catch (AggregateException ax)
            {
                CloudException x = (CloudException)ax.InnerExceptions.Single();
                Assert.AreEqual(HttpStatusCode.NotFound, x.Response.StatusCode);
                return;
            }

            Assert.Fail("ServiceManagementClientException expected");
        }
 private HttpResponseMessage Execute()
 {
     HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
     response.RequestMessage = Request;
     response.ReasonPhrase = ReasonPhrase;
     return response;
 }
            protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsyncCore(
                HttpRequestMessage request, CancellationToken cancellationToken)
            {
                TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
                var response = new HttpResponseMessage();

                response.StatusCode = HttpStatusCode.Redirect;
                response.Headers.Location = new Uri(Location + Calls);
                response.RequestMessage = request;

                if (Calls == 1)
                {
                    // First call the message should contain If-* headers
                    Assert.That(request.RequestUri, Is.EqualTo(new Uri(Location)));
                    Assert.That(request.Headers.IfMatch.Count == 1);
                    Assert.That(request.Headers.IfNoneMatch.Count == 1);
                    Assert.That(request.Headers.IfModifiedSince.HasValue);
                    Assert.That(request.Headers.IfUnmodifiedSince.HasValue);
                }
                else
                {
                    // After first call the message should not contain If-* headers
                    Assert.That(request.RequestUri, Is.EqualTo(new Uri(Location + (Calls - 1))));
                    Assert.That(request.Headers.IfMatch.Count == 0);
                    Assert.That(request.Headers.IfNoneMatch.Count == 0);
                    Assert.IsNull(request.Headers.IfModifiedSince);
                    Assert.IsNull(request.Headers.IfUnmodifiedSince);
                }

                tcs.SetResult(response);
                return tcs.Task;
            }
        public void ListWebHostingPlans()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(HttpPayload.ListWebHostingPlans)
            };

            var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };

            var client = GetWebSiteManagementClient(handler);

            var result = client.WebHostingPlans.List("space1");

            // Validate headers 
            Assert.Equal(HttpMethod.Get, handler.Method);

            // Validate response 
            Assert.NotNull(result.WebHostingPlans);
            Assert.Equal(1, result.WebHostingPlans.Count);
            Assert.NotNull(result.WebHostingPlans.ElementAt(0));
            Assert.Equal("Default1", result.WebHostingPlans.ElementAt(0).Name);
            Assert.Equal(SkuOptions.Standard, result.WebHostingPlans.ElementAt(0).SKU);
            Assert.Equal(1, result.WebHostingPlans.ElementAt(0).NumberOfWorkers);
            Assert.Equal("adminsite1", result.WebHostingPlans.ElementAt(0).AdminSiteName);
        }
 public static void LogHttpResponse(this DiagnosticListener @this, HttpResponseMessage response, Guid loggingRequestId)
 {
     if (@this.IsEnabled(HttpHandlerLoggingStrings.ResponseWriteName))
     {
         LogHttpResponseCore(@this, response, loggingRequestId);
     }
 }
        internal static void ReadStatusLine(HttpResponseMessage response, string responseHeader)
        {
            Debug.Assert(responseHeader.StartsWith(HttpPrefix, StringComparison.OrdinalIgnoreCase), "Status Line starts with http prefix");

            int index =  HttpPrefix.Length;
            int majorVersion = ReadInt(responseHeader, ref index);
            CheckResponseMsgFormat(majorVersion != 0);

            CheckResponseMsgFormat(index < responseHeader.Length && responseHeader[index] == '.');
            index++;

            // Need minor version
            CheckResponseMsgFormat(index < responseHeader.Length && responseHeader[index] >= '0' && responseHeader[index] <= '9');
            int minorVersion = ReadInt(responseHeader, ref index);

            CheckResponseMsgFormat(SkipSpace(responseHeader, ref index));

            //  parse status code
            int statusCode = ReadInt(responseHeader, ref index);
            CheckResponseMsgFormat(statusCode >= 100 && statusCode < 600);

            bool foundSpace = SkipSpace(responseHeader, ref index);
            CheckResponseMsgFormat(index <= responseHeader.Length);
            CheckResponseMsgFormat(foundSpace || index == responseHeader.Length);

            // Set the response HttpVersion
            response.Version =
                (majorVersion == 1 && minorVersion == 1) ? HttpVersion.Version11 :
                (majorVersion == 1 && minorVersion == 0) ? HttpVersion.Version10 :
                (majorVersion == 2 && minorVersion == 0) ? HttpVersion.Version20 :
                HttpVersion.Unknown;

            response.StatusCode = (HttpStatusCode)statusCode;
            response.ReasonPhrase = responseHeader.Substring(index);
        }
        // GET /api/messages/5
        public HttpResponseMessage<MessageModels.MessageResponse> Get(string id)
        {
            var message = GetMessage(id);
            //TODO: check to see if message exists with id
            if (message == null)
                return new HttpResponseMessage<MessageModels.MessageResponse>(HttpStatusCode.NotFound);

            //TODO: return message
            var response = new HttpResponseMessage<MessageModels.MessageResponse>(new MessageModels.MessageResponse()
            {
                amount = message.Amount,
                comments = message.Comments,
                createDate = message.CreateDate,
                Id = message.Id.ToString(),
                lastUpdatedDate = message.LastUpdatedDate,
                messageStatus = message.MessageStatus.ToString(),
                messageType = message.MessageType.ToString(),
                recipient = new UserModels.UserResponse()
                {

                },
                recipientUri = message.RecipientUri,
                sender = new UserModels.UserResponse()
                {

                },
                senderUri = message.SenderUri,
                senderAccount = new AccountModels.AccountResponse()
                {

                }
            }, HttpStatusCode.OK);

            return response;
        }
 // GET /api/Contacts/5
 public HttpResponseMessage<Contact> Get(int id)
 {
     var contact = _contactRepository.Get().Where(y => y.Id == id).SingleOrDefault();
     var statusCode = contact != null ? HttpStatusCode.OK : HttpStatusCode.NotFound;
     var response = new HttpResponseMessage<Contact>(contact, statusCode);
     return response;
 }
        public void ResponsePolicyWithBody()
        {
            // Assert
            var responseMessage = new HttpResponseMessage()
            {
                Content = new StringContent("Hello World!")
            };

            var variables = new Dictionary<string, object>()
            {
                { "message-id","xxxyyy"}
            };

            var context = new Context(responseMessage: responseMessage, variables: variables);

            // Act
            string policyResult = SendResponseToEventHub(context);

            //Assert
            Assert.Equal("response:xxxyyy\n"
                                        + "HTTP/1.1 200 OK\r\n"
                                        + "Content-Type: text/plain; charset=utf-8\r\n"
                                        + "Content-Length: 12\r\n"
                                        + "\r\n"
                                        + "Hello World!", policyResult);
        }
 public virtual GetDatabaseResponse Create(HttpResponseMessage httpResponse)
 {
     return Materialize<GetDatabaseResponse>(
         httpResponse,
         SuccessfulResponseMaterializer.Materialize,
         FailedResponseMaterializer.Materialize);
 }
        public void ExecuteAuthorizationFilterAsync_Faults_And_Traces_When_Inner_Faults()
        {
            // Arrange
            Mock<IAuthorizationFilter> mockAttr = new Mock<IAuthorizationFilter>() { CallBase = true };
            HttpResponseMessage response = new HttpResponseMessage();
            InvalidOperationException exception = new InvalidOperationException("test");
            TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(response);
            tcs.TrySetException(exception);
            mockAttr.Setup(a => a.ExecuteAuthorizationFilterAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>(), It.IsAny<Func<Task<HttpResponseMessage>>>())).Returns(tcs.Task);
            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };
            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));
            HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object);
            Func<Task<HttpResponseMessage>> continuation = () => TaskHelpers.FromResult<HttpResponseMessage>(response);
            TestTraceWriter traceWriter = new TestTraceWriter();
            AuthorizationFilterTracer tracer = new AuthorizationFilterTracer(mockAttr.Object, traceWriter);
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteAuthorizationFilterAsync" },
                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End,  Operation = "ExecuteAuthorizationFilterAsync" }
            };

            // Act & Assert
            Task task = ((IAuthorizationFilter)tracer).ExecuteAuthorizationFilterAsync(actionContext, CancellationToken.None, continuation);
            Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait());

            // Assert
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }