示例#1
0
 private INavigationResult BuildNavigationResult(IRequest request, IResponse response)
 {
     return new NavigationResult(request, response)
     {
         TimeSpent = watch.ElapsedMilliseconds
     };
 }
        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            if (AuthenticateService.AuthProviders == null)
                throw new InvalidOperationException(
                    "The AuthService must be initialized by calling AuthService.Init to use an authenticate attribute");

            var matchingOAuthConfigs = AuthenticateService.AuthProviders.Where(x =>
                this.Provider.IsNullOrEmpty()
                || x.Provider == this.Provider).ToList();

            if (matchingOAuthConfigs.Count == 0)
            {
                res.WriteError(req, requestDto, "No OAuth Configs found matching {0} provider"
                    .Fmt(this.Provider ?? "any"));
                res.EndRequest();
                return;
            }

            if (matchingOAuthConfigs.Any(x => x.Provider == DigestAuthProvider.Name))
                AuthenticateIfDigestAuth(req, res);

            if (matchingOAuthConfigs.Any(x => x.Provider == BasicAuthProvider.Name))
                AuthenticateIfBasicAuth(req, res);

            var session = req.GetSession();
            if (session == null || !matchingOAuthConfigs.Any(x => session.IsAuthorized(x.Provider)))
            {
                if (this.DoHtmlRedirectIfConfigured(req, res, true)) return;

                AuthProvider.HandleFailedAuth(matchingOAuthConfigs[0], session, req, res);
            }
        }
        public override Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName)
        {
            try
            {
                var appHost = HostContext.AppHost;
                if (appHost.ApplyPreRequestFilters(httpReq, httpRes)) 
                    return EmptyTask;
                
                var restPath = GetRestPath(httpReq.Verb, httpReq.PathInfo);
                if (restPath == null)
                {
                    return new NotSupportedException("No RestPath found for: " + httpReq.Verb + " " + httpReq.PathInfo)
                        .AsTaskException();
                }
                httpReq.SetRoute(restPath as RestPath);

                operationName = restPath.RequestType.GetOperationName();

                var callback = httpReq.GetJsonpCallback();
                var doJsonp = HostContext.Config.AllowJsonpRequests
                              && !string.IsNullOrEmpty(callback);

                if (ResponseContentType != null)
                    httpReq.ResponseContentType = ResponseContentType;

                var responseContentType = httpReq.ResponseContentType;
                appHost.AssertContentType(responseContentType);

                var request = httpReq.Dto = CreateRequest(httpReq, restPath);

                if (appHost.ApplyRequestFilters(httpReq, httpRes, request)) 
                    return EmptyTask;

                var rawResponse = GetResponse(httpReq, request);
                return HandleResponse(rawResponse, response => 
                {
                    response = appHost.ApplyResponseConverters(httpReq, response);

                    if (appHost.ApplyResponseFilters(httpReq, httpRes, response)) 
                        return EmptyTask;

                    if (responseContentType.Contains("jsv") && !string.IsNullOrEmpty(httpReq.QueryString[Keywords.Debug]))
                        return WriteDebugResponse(httpRes, response);

                    if (doJsonp && !(response is CompressedResult))
                        return httpRes.WriteToResponse(httpReq, response, (callback + "(").ToUtf8Bytes(), ")".ToUtf8Bytes());
                    
                    return httpRes.WriteToResponse(httpReq, response);
                },  
                ex => !HostContext.Config.WriteErrorsToResponse 
                    ? ex.ApplyResponseConverters(httpReq).AsTaskException()
                    : HandleException(httpReq, httpRes, operationName, ex.ApplyResponseConverters(httpReq)));
            }
            catch (Exception ex)
            {
                return !HostContext.Config.WriteErrorsToResponse
                    ? ex.ApplyResponseConverters(httpReq).AsTaskException()
                    : HandleException(httpReq, httpRes, operationName, ex.ApplyResponseConverters(httpReq));
            }
        }
示例#4
0
 public void SetUp()
 {
     request = MockRepository.GenerateStub<IRequest>();
     response = MockRepository.GenerateStub<IResponse>();
     engine = MockRepository.GenerateStub<ILessEngine>();
     lessSource = MockRepository.GenerateStub<ILessSource>();
 }
示例#5
0
        public override void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
        {
            HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes);
            if (httpRes.IsClosed) return;

            httpRes.ContentType = MimeTypes.Html;
            if (RazorFormat == null)
                RazorFormat = RazorFormat.Instance;

            var contentPage = RazorPage ?? RazorFormat.FindByPathInfo(PathInfo);
            if (contentPage == null)
            {
                httpRes.StatusCode = (int)HttpStatusCode.NotFound;
                httpRes.EndHttpHandlerRequest();
                return;
            }

            var model = Model;
            if (model == null)
                httpReq.Items.TryGetValue("Model", out model);
            if (model == null)
            {
                var modelType = RazorPage != null ? RazorPage.ModelType : null;
                model = modelType == null || modelType == typeof(DynamicRequestObject)
                    ? null
                    : DeserializeHttpRequest(modelType, httpReq, httpReq.ContentType);
            }

            RazorFormat.ProcessRazorPage(httpReq, contentPage, model, httpRes);
        }
        /// <summary>
        /// Non ASP.NET requests
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="operationName"></param>
        public override void ProcessRequest(IRequest request, IResponse response, string operationName)
        {
            if (string.IsNullOrEmpty(RelativeUrl) && string.IsNullOrEmpty(AbsoluteUrl))
                throw new ArgumentException("RelativeUrl and AbsoluteUrl is Required");

            if (!string.IsNullOrEmpty(AbsoluteUrl))
            {
                response.StatusCode = (int)StatusCode;
                response.AddHeader(HttpHeaders.Location, this.AbsoluteUrl);
            }
            else
            {
                var absoluteUrl = request.GetApplicationUrl();
                if (!string.IsNullOrEmpty(RelativeUrl))
                {
                    if (this.RelativeUrl.StartsWith("/"))
                        absoluteUrl = absoluteUrl.CombineWith(this.RelativeUrl);
                    else if (this.RelativeUrl.StartsWith("~/"))
                        absoluteUrl = absoluteUrl.CombineWith(this.RelativeUrl.Replace("~/", ""));
                    else
                        absoluteUrl = request.AbsoluteUri.CombineWith(this.RelativeUrl);
                }
                response.StatusCode = (int)StatusCode;
                response.AddHeader(HttpHeaders.Location, absoluteUrl);
            }

            response.EndHttpHandlerRequest(skipClose: true);
        }
 /// <summary>
 /// Evaluates the response.
 /// </summary>
 /// <param name="response">The response to parse.</param>
 /// <param name="options">The options to consider.</param>
 public void Evaluate(IResponse response, ScriptOptions options)
 {
     var reader = new StreamReader(response.Content, options.Encoding ?? Encoding.UTF8, true);
     var content = reader.ReadToEnd();
     reader.Close();
     Evaluate(content, options);
 }
        public override void ProcessRequest(IRequest request, IResponse response, string operationName)
        {
            response.ContentType = "text/plain";
            response.StatusCode = 403;

		    response.EndHttpHandlerRequest(skipClose: true, afterBody: r => {
                r.Write("Forbidden\n\n");

                r.Write("\nRequest.HttpMethod: " + request.Verb);
                r.Write("\nRequest.PathInfo: " + request.PathInfo);
                r.Write("\nRequest.QueryString: " + request.QueryString);

                if (HostContext.Config.DebugMode)
                {
                    r.Write("\nRequest.RawUrl: " + request.RawUrl);

                    if (IsIntegratedPipeline.HasValue)
                        r.Write("\nApp.IsIntegratedPipeline: " + IsIntegratedPipeline);
                    if (!WebHostPhysicalPath.IsNullOrEmpty())
                        r.Write("\nApp.WebHostPhysicalPath: " + WebHostPhysicalPath);
                    if (!WebHostRootFileNames.IsEmpty())
                        r.Write("\nApp.WebHostRootFileNames: " + TypeSerializer.SerializeToString(WebHostRootFileNames));
                    if (!WebHostUrl.IsNullOrEmpty())
                        r.Write("\nApp.WebHostUrl: " + WebHostUrl);
                    if (!DefaultRootFileName.IsNullOrEmpty())
                        r.Write("\nApp.DefaultRootFileName: " + DefaultRootFileName);
                    if (!DefaultHandler.IsNullOrEmpty())
                        r.Write("\nApp.DefaultHandler: " + DefaultHandler);
                    if (!HttpHandlerFactory.DebugLastHandlerArgs.IsNullOrEmpty())
                        r.Write("\nApp.DebugLastHandlerArgs: " + HttpHandlerFactory.DebugLastHandlerArgs);
                }
            });
		}
示例#9
0
		public override void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
    	{
            if (!AssertAccess(httpReq, httpRes, httpReq.QueryString["op"])) return;

			var operationTypes = HostContext.Metadata.GetAllTypes();

    		if (httpReq.QueryString["xsd"] != null)
    		{
				var xsdNo = Convert.ToInt32(httpReq.QueryString["xsd"]);
                var schemaSet = XsdUtils.GetXmlSchemaSet(operationTypes);
    			var schemas = schemaSet.Schemas();
    			var i = 0; 
    			if (xsdNo >= schemas.Count)
    			{
    				throw new ArgumentOutOfRangeException("xsd");
    			}
    			httpRes.ContentType = "text/xml";
    			foreach (XmlSchema schema in schemaSet.Schemas())
    			{
    				if (xsdNo != i++) continue;
    				schema.Write(httpRes.OutputStream);
    				break;
    			}
    			return;
    		}

			using (var sw = new StreamWriter(httpRes.OutputStream))
			{
				var writer = new HtmlTextWriter(sw);
				httpRes.ContentType = "text/html";
				ProcessOperations(writer, httpReq, httpRes);
			}
    	}
示例#10
0
        public static void RequestFilter(IRequest req, IResponse res, object requestDto)
        {
            var validator = ValidatorCache.GetValidator(req, requestDto.GetType());
            if (validator == null) return;

            var validatorWithHttpRequest = validator as IRequiresRequest;
            if (validatorWithHttpRequest != null)
                validatorWithHttpRequest.Request = req;

            var ruleSet = req.Verb;
            var validationResult = validator.Validate(
                new ValidationContext(requestDto, null, new MultiRuleSetValidatorSelector(ruleSet)));

            if (validationResult.IsValid) return;

            var errorResponse = DtoUtils.CreateErrorResponse(
                requestDto, validationResult.ToErrorResult());

            var validationFeature = HostContext.GetPlugin<ValidationFeature>();
            if (validationFeature != null && validationFeature.ErrorResponseFilter != null)
            {
                errorResponse = validationFeature.ErrorResponseFilter(validationResult, errorResponse);
            }

            res.WriteToResponse(req, errorResponse);
        }
        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            var authErrorMessage = "";
            try
            {
                // Perform security check
                if (CanExecute(req))
                    return;
            }
            catch (System.Exception ex)
            {
                authErrorMessage = ex.Message;
                var message = string.Format("Blocked unauthorized request: {0} {1} by ip = {2} due to {3}",
                    req.Verb,
                    req.AbsoluteUri,
                    req.UserHostAddress ?? "unknown",
                    authErrorMessage);
                Log.Error(message);
            }

            // Security failed!
            var responseMessage = "You are not authorized. " + authErrorMessage;

            res.StatusCode = (int)HttpStatusCode.Unauthorized;
            res.StatusDescription = responseMessage;
            res.AddHeader(HttpHeaders.WwwAuthenticate, string.Format("{0} realm=\"{1}\"", "", "custom api"));
            res.ContentType = "text/plain";
            res.Write(responseMessage);
            res.Close();
        }
		public void Setup()
		{
			cruiseRequestWrapperMock = new DynamicMock(typeof(ICruiseRequest));
			buildNameRetrieverMock = new DynamicMock(typeof(IBuildNameRetriever));
			recentBuildsViewBuilderMock = new DynamicMock(typeof(IRecentBuildsViewBuilder));
			pluginLinkCalculatorMock = new DynamicMock(typeof(IPluginLinkCalculator));
			velocityViewGeneratorMock = new DynamicMock(typeof(IVelocityViewGenerator));
			linkFactoryMock = new DynamicMock(typeof(ILinkFactory));
			linkListFactoryMock = new DynamicMock(typeof(ILinkListFactory));
			farmServiceMock = new DynamicMock(typeof(IFarmService));


			sideBarViewBuilder = new SideBarViewBuilder(
				(ICruiseRequest) cruiseRequestWrapperMock.MockInstance,
				(IBuildNameRetriever) buildNameRetrieverMock.MockInstance,
				(IRecentBuildsViewBuilder) recentBuildsViewBuilderMock.MockInstance,
				(IPluginLinkCalculator) pluginLinkCalculatorMock.MockInstance,
				(IVelocityViewGenerator) velocityViewGeneratorMock.MockInstance,
				(ILinkFactory) linkFactoryMock.MockInstance,
				(ILinkListFactory)linkListFactoryMock.MockInstance,
				(IFarmService) farmServiceMock.MockInstance,
                null);

			velocityResponse = new HtmlFragmentResponse("velocity view");
			velocityContext = new Hashtable();
			links = new IAbsoluteLink[] { new GeneralAbsoluteLink("link")};
			serverLinks = new IAbsoluteLink[] { new GeneralAbsoluteLink("link")};
			serverSpecifiers = new IServerSpecifier[] {new DefaultServerSpecifier("test")};
		}
示例#13
0
        public void Assert(IResponse response)
        {
            // when there are no assertions it is a success
            bool success = (this.assertions.Count == 0);

            // when the response was timedout, there is no data to test/assert
            if (!response.IsTimedOut())
            {
                foreach (AbstractAssertion assertion in this.assertions)
                {
                    success = assertion.Assert(response);
                    LOG.DebugFormat("Assert: {0} result: {1}", assertion.GetType().Name, success);

                    if (!success)
                    {
                        break;
                    }
                }

            }

            // record results
            this.result.Executed = true;
            this.result.ExecutionTime = response.GetExecutionTime();
            this.result.Success = success;
            this.result.TimedOut = response.IsTimedOut();
            this.result.StatusCode = response.GetStatusCode();
            this.result.StatusDescription = response.GetStatusDescription();
            this.result.ResponseText = response.GetResponseText();
        }
示例#14
0
        public override async Task Execute(string[] parameters, IResponse response)
        {
            var username = parameters[1];
            var repoName = parameters[3];

            var activeRepositories = Brain.Get<AvailableRepositories>();

            var repo = activeRepositories.SingleOrDefault(r => r.Name == repoName);

            if (repo == null)
            {
                await response.Send("Repository not found, please add it using: mmbot add repo " + repoName).IgnoreWaitContext();
                return;
            }

            if (username.ToLower() == "my self")
            {
                repo.Caretaker = CurrentUser.Name;
            }
            else
            {
                repo.Caretaker = username;
            }

            Brain.Set(activeRepositories);

            await response.Send(username + " is now caretaker for " + repo.Name);
        }
示例#15
0
        public override async Task Execute(string[] parameters, IResponse response)
        {
            string sourceRepo;
            string issueNumberString;
            if (!RepoParser.ParseRepoAndIssueNumber(parameters[1], out sourceRepo, out issueNumberString))
            {
                await response.Send($"I could not parse the source repository and issue number from '{parameters[1]}'. Are you using the correct syntax?");
                return;
            }

            string targetRepo;
            if (!RepoParser.ParseRepo(parameters[2], out targetRepo))
            {
                await response.Send($"I could not parse the target repository from '{parameters[2]}'. Are you using the correct syntax?");
                return;
            }

            int issueNumber;
            if (!int.TryParse(issueNumberString, out issueNumber))
            {
                await response.Send("Issue number should be a valid number dude!");
                return;
            }

            var owner = "Particular";

            await response.Send($"Copying issue https://github.com/{owner}/{sourceRepo}/issues/{issueNumber}").IgnoreWaitContext();

            var newIssue = await IssueUtility.Transfer(owner, sourceRepo, issueNumber, owner, targetRepo, false).IgnoreWaitContext();

            await response.Send($"Issue copied to https://github.com/{owner}/{targetRepo}/issues/{newIssue.Number}").IgnoreWaitContext();
        }
示例#16
0
        public override async Task Execute(string[] parameters, IResponse response)
        {
            var username = response.User.Name;

            var repoNames = Brain.Get<AvailableRepositories>()
                .Where(r => r.Caretaker == username)
                .Select(r => r.Name)
                .ToList();

            if (!repoNames.Any())
            {
                await response.Send($"Hey {username} I couldn't find any repos where you're the caretaker? Please type `pbot list caretakers` for instructions on how to join the fun!").IgnoreWaitContext();
                return;
            }

            var client = GitHubClientBuilder.Build();

            var validationErrors = repoNames.SelectMany(repoName =>
            {
                var repo = client.Repository.Get("Particular", repoName).Result;

                return new CheckIssuesForRepository(repo, client)
                    .Execute();
            })
                .ToList();

            if (!validationErrors.Any())
            {
                await response.Send($"Nice job citizen, your repos are squeaky clean!! (Checked {string.Join(", ", repoNames)})").IgnoreWaitContext();
                return;
            }

            await response.Send(FormatErrors(validationErrors)).IgnoreWaitContext();
        }
 protected override async Task ProcessResponseAsync(IResponse response)
 {
     var context = new BrowsingContext(_parentDocument.Context, Sandboxes.None);
     var options = new CreateDocumentOptions(response, _configuration, _parentDocument);
     var factory = _configuration.GetFactory<IDocumentFactory>();
     ChildDocument = await factory.CreateAsync(context, options, CancellationToken.None).ConfigureAwait(false);
 }
示例#18
0
 public LessHandlerImpl(IHttp http, IResponse response, ILessEngine engine, IFileReader fileReader)
 {
     Http = http;
     Response = response;
     Engine = engine;
     FileReader = fileReader;
 }
        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            string apiKey;

            if (req.Headers.AllKeys.Contains("X-API-Key"))
            {
                apiKey = req.Headers["X-API-Key"];
            }
            else
            {
                // try to get it through the dto
                var apiKeyDto = requestDto as IHasApiKey;

                if (apiKeyDto != null)
                {
                    apiKey = apiKeyDto.ApiKey;
                }
                else
                {
                    throw HttpError.Unauthorized("No API-Key provided.");
                }
            }

            if (!ApiKeyValidator.Validate(apiKey))
            {
                throw HttpError.Unauthorized("API-Key invalid.");
            }
        }
示例#20
0
        public virtual int Serialize(IResponse response, byte[] buffer)
        {
            var stream = new MemoryStream(buffer);
            var writer = new StreamWriter(stream, Encoding.ASCII);
            writer.Write(response.SipVersion);
            writer.Write(" ");
            writer.Write((int) response.StatusCode);
            writer.Write(" ");
            writer.WriteLine(response.ReasonPhrase);

            WriteHeader(writer, "To", response.To);
            WriteHeader(writer, "From", response.From);
            WriteHeader(writer, "Contact", response.Contact);
            WriteHeader(writer, "Via", response.Via);
            WriteHeader(writer, "CSeq", response.CSeq);
            //WriteHeader(writer, "Call-Id", response.CallId);
            foreach (var header in response.Headers)
                WriteHeader(writer, header.Key, header.Value.ToString());
            if (response.Body != null && response.Body.Length > 0)
                WriteHeader(writer, "Content-Length", response.Body.Length);
            else
                WriteHeader(writer, "Content-Length", "0");
            writer.WriteLine();

            if (response.Body != null)
            {
                var ms = (MemoryStream) response.Body;
                ms.WriteTo(stream);
            }

            writer.Flush();

            string temp = Encoding.ASCII.GetString(buffer, 0, (int) stream.Length);
            return (int) stream.Position;
        }
        /// <summary>
        /// Send all headers to the client
        /// </summary>
        /// <param name="response">Response containing call headers.</param>
        /// <param name="writer">Writer to write everything to</param>
        public void SerializeResponse(IResponse response, IBufferWriter writer)
        {
            WriteString(writer, "{0} {1} {2}\r\n", response.ProtocolVersion, response.StatusCode,
                        response.StatusDescription);

            var contentType = response.ContentType ?? "text/html";
            if (response.ContentEncoding != null)
                contentType += ";charset=" + response.ContentEncoding.WebName;

            var length = response.ContentLength == 0 || response.Body != null
                             ? response.ContentLength
                             : response.Body.Length;

            // go through all property headers.
            WriteString(writer, "Content-Type: {0}\r\n", contentType);
            WriteString(writer, "Content-Length: {0}\r\n", length);
            //writer.WriteLine(response.KeepAlive ? "Connection: Keep-Alive" : "Connection: Close");

            if (response.Cookies != null && response.Cookies.Count > 0)
            {
                SerializeCookies(response, writer);
            }

            foreach (var header in response.Headers)
                WriteString(writer, "{0}: {1}\r\n", header.Name, header.Value);

            // header/body delimiter
            WriteString(writer, "\r\n");
        }
示例#22
0
 public HostContext(IRequest request, IResponse response, IPrincipal user)
 {
     Request = request;
     Response = response;
     User = user;
     Items = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
 }
示例#23
0
        /// <summary>
        /// This is called by the hosting environment via CatchAll usually for content pages.
        /// </summary>
        public override void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
        {
            httpRes.ContentType = MimeTypes.Html;

            ResolveAndExecuteRazorPage(httpReq, httpRes, null);
            httpRes.EndRequest(skipHeaders: true);
        }
        /// <summary>
        /// Handles rendering a previous MiniProfiler session, identified by its "?id=GUID" on the query.
        /// </summary>
        private static string Results(IRequest httpReq, IResponse httpRes)
        {
            // this guid is the MiniProfiler.Id property
            var id = new Guid();
            if (!Guid.TryParse(httpReq.QueryString["id"], out id))
            {
                return NotFound(httpRes, "text/plain", "No Guid id specified on the query string");
            }

            // load profiler
            var profiler = Profiler.Settings.Storage.Load(id);
            if (profiler == null)
            {
                return NotFound(httpRes, "text/plain", "No MiniProfiler results found with Id=" + id.ToString());
            }

            // ensure that callers have access to these results
            var authorize = Profiler.Settings.Results_Authorize;
            if (authorize != null && !authorize(httpReq, profiler))
            {
                httpRes.StatusCode = 401;
                httpRes.ContentType = "text/plain";
                return "Unauthorized";
            }

            // Only manage full page
            return ResultsFullPage(httpRes, profiler);
        }
示例#25
0
        /// <summary>
        /// The request filter is executed before the service.
        /// </summary>
        /// <param name="request">The http request wrapper</param>
        /// <param name="response">The http response wrapper</param>
        /// <param name="requestDto">The request DTO</param>
        public void RequestFilter(IRequest request, IResponse response, object requestDto)
        {
            var serviceRequest = new ServiceStackServiceRequest(request);
            
            //This code is executed before the service
            var auth = AuthorizationContext.GetAuthorizationInfo(serviceRequest);

            if (auth != null)
            {
                User user = null;

                if (!string.IsNullOrWhiteSpace(auth.UserId))
                {
                    var userId = auth.UserId;

                    user = UserManager.GetUserById(userId);
                }

                string deviceId = auth.DeviceId;
                string device = auth.Device;
                string client = auth.Client;
                string version = auth.Version;

                if (!string.IsNullOrEmpty(client) && !string.IsNullOrEmpty(deviceId) && !string.IsNullOrEmpty(device) && !string.IsNullOrEmpty(version))
                {
                    var remoteEndPoint = request.RemoteIp;

                    SessionManager.LogSessionActivity(client, version, deviceId, device, remoteEndPoint, user);
                }
            }
        }
示例#26
0
文件: Cgi.cs 项目: remitaylor/knack
        public static string GetResponseText(IResponse response)
        {
            StringBuilder builder = new StringBuilder();

            // Status
            builder.AppendFormat("Status: {0}\n", response.Status);

            // Headers
            foreach (KeyValuePair<string,IEnumerable<string>> header in response.Headers)
                foreach (string value in header.Value)
                builder.AppendFormat("{0}: {1}\n", header.Key, value);

            builder.Append("\n");

            // Body ... just supports a string body for now ... next up: FileInfo support?
            foreach (object bodyPart in response.GetBody())
                if (bodyPart is string)
                    builder.Append(bodyPart as string);
                else if (bodyPart is byte[])
                    throw new NotImplementedException("TODO test CGI byte[] body output"); //builder.Append(Encoding.UTF8.GetString(bodyPart)); // assume UTF8 encoding for now ...
                else if (bodyPart is ArraySegment<byte>)
                    throw new NotImplementedException("TODO test CGI ArraySegment<byte> body output");
                else if (bodyPart is FileInfo)
                    throw new NotImplementedException("TODO test CGI FileInfo body output");
                else
                    throw new FormatException("Unknown object returned by IResponse.GetBody(): " + bodyPart.GetType().Name);

            return builder.ToString();
        }
示例#27
0
        public HostContext(IRequest request, IResponse response)
        {
            Request = request;
            Response = response;

            Environment = new Dictionary<string, object>();
        }
 public void Respond(IRequest request, IResponse response)
 {
     response.StatusCode = HttpStatusCode.NotFound;
     response.StatusMessage = "Resource not found";
     response.Output.WriteLine("<h1>404: The resource <i>{0}</i> could not be found.</h1>",
                               request.VirtualPath);
 }
        public override void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
                return;

            Action(httpReq, httpRes);
        }
示例#30
0
        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            if (HostContext.HasValidAuthSecret(req))
                return;

            base.Execute(req, res, requestDto); //first check if session is authenticated
            if (res.IsClosed) return; //AuthenticateAttribute already closed the request (ie auth failed)

            var session = req.GetSession();

            var authRepo = HostContext.AppHost.GetAuthRepository(req);
            using (authRepo as IDisposable)
            {
                if (session != null && session.HasRole(RoleNames.Admin, authRepo))
                    return;

                if (HasAnyPermissions(req, session, authRepo)) return;
            }

            if (DoHtmlRedirectIfConfigured(req, res)) return;

            res.StatusCode = (int)HttpStatusCode.Forbidden;
            res.StatusDescription = ErrorMessages.InvalidPermission;
            res.EndRequest();
        }
        IResponseFilter IRequestHandler.GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
        {
            var args = new GetResourceResponseFilterEventArgs(browserControl, browser, frame, request, response);

            GetResourceResponseFilterEvent?.Invoke(this, args);
            return(args.ResponseFilter);
        }
        //
        // Summary:
        //     Called on the CEF IO thread when a resource response is received.  To allow
        //     the resource to load normally return false.  To redirect or retry the resource
        //     modify request (url, headers or post body) and return true.  The response
        //     object cannot be modified in this callback.
        //
        // Parameters:
        //   frame:
        //     The frame that is being redirected.
        //
        //   request:
        //     the request object
        //
        //   response:
        //     the response object - cannot be modified in this callback
        //
        // Returns:
        //     To allow the resource to load normally return false.  To redirect or retry
        //     the resource modify request (url, headers or post body) and return true.
        public bool OnResourceResponse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
        {
            int code = response.StatusCode;


            // if NOT FOUND
            if (code == 404)
            {
                if (!request.Url.IsURLLocalhost())
                {
                    // redirect to web archive to try and find older version
                    request.Url = "http://web.archive.org/web/*/" + request.Url;
                }
                else
                {
                    // show offline "file not found" page
                    request.Url = MainForm.FileNotFoundURL + "?path=" + request.Url.EncodeURL();
                }

                return(true);
            }


            // if FILE NOT FOUND
            if (code == 0 && request.Url.IsURLOfflineFile())
            {
                string path = request.Url.FileURLToPath();
                if (path.FileNotExists())
                {
                    // show offline "file not found" page
                    request.Url = MainForm.FileNotFoundURL + "?path=" + path.EncodeURL();
                    return(true);
                }
            }
            else
            {
                // if CANNOT CONNECT
                if (code == 0 || code == 444 || (code >= 500 && code <= 599))
                {
                    // show offline "cannot connect to server" page
                    request.Url = MainForm.CannotConnectURL;
                    return(true);
                }
            }

            return(false);
        }
 //
 // Summary:
 //     Called on the CEF IO thread when a resource load has completed.
 //
 // Parameters:
 //   frame:
 //     The frame that is being redirected.
 //
 //   request:
 //     the request object - cannot be modified in this callback
 //
 //   response:
 //     the response object - cannot be modified in this callback
 //
 //   status:
 //     indicates the load completion status
 //
 //   receivedContentLength:
 //     is the number of response bytes actually read.
 public void OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
 {
 }
示例#34
0
        protected override void OnResourceLoadComplete(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
        {
            Console.WriteLine(request.Url);
            if (request.Url.IndexOf("/u/5175429989") > -1)
            {
                var cookieManager = chromiumWebBrowser.GetCookieManager();

                cookieManager.VisitAllCookies(new CookieVisitor());
            }

            if (request.Url.IndexOf("/login?") > -1)
            {
                var f = FilterManager.GetFileter(request.Identifier.ToString());
                if (f == null)
                {
                    return;
                }
                var filter = f as TestJsonFilter;

                ASCIIEncoding encoding = new ASCIIEncoding();
                //这里截获返回的数据
                string data = encoding.GetString(filter.DataAll.ToArray());

                string st = new Regex(@"""st"":""(?<ticket>[\s\S]*?)""", RegexOptions.IgnoreCase).Match(data).Groups["ticket"].Value;

                SetCookie.tkPlugin.BeginInvoke(new EventHandler(delegate {
                    SetCookie.Plugin.SetTk();
                    SetCookie.tkPlugin.Close();
                }));
            }
        }
示例#35
0
 protected override IResponseFilter GetResourceResponseFilter(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response)
 {
     if (request.Url.IndexOf(".png") == -1 && request.Url.IndexOf(".jpg") == -1 && request.Url.IndexOf(".css") == -1 && request.Url.IndexOf(".gif") == -1 && request.Url.IndexOf(".ico") == -1)
     {
         var filter = FilterManager.CreateFilter(request.Identifier.ToString());
         return(filter);
     }
     return(null);
 }
        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            if (req.Verb != HttpMethods.Get && req.Verb != HttpMethods.Head)
            {
                return;
            }

            var feature = HostContext.GetPlugin <HttpCacheFeature>();

            if (feature == null)
            {
                throw new NotSupportedException(ErrorMessages.CacheFeatureMustBeEnabled.Fmt("[CacheResponse]"));
            }

            var keyBase   = "res:" + req.RawUrl;
            var keySuffix = MimeTypes.GetExtension(req.ResponseContentType);

            var modifiers = "";

            if (req.ResponseContentType == MimeTypes.Json)
            {
                string jsonp = req.GetJsonpCallback();
                if (jsonp != null)
                {
                    modifiers = "jsonp:" + jsonp.SafeVarName();
                }
            }

            if (VaryByUser)
            {
                modifiers += (modifiers.Length > 0 ? "+" : "") + "user:"******"+" : "") + "role:" + role;
                        }
                    }
                }
            }

            if (modifiers.Length > 0)
            {
                keySuffix += "+" + modifiers;
            }

            var cacheInfo = new CacheInfo
            {
                KeyBase      = keyBase,
                KeyModifiers = keySuffix,
                ExpiresIn    = Duration > 0 ? TimeSpan.FromSeconds(Duration) : (TimeSpan?)null,
                MaxAge       = MaxAge >= 0 ? TimeSpan.FromSeconds(MaxAge) : (TimeSpan?)null,
                CacheControl = CacheControl,
                VaryByUser   = VaryByUser,
                LocalCache   = LocalCache,
            };

            if (req.HasValidCache(cacheInfo))
            {
                return;
            }

            req.Items[Keywords.CacheInfo] = cacheInfo;
        }
        void IRequestHandler.OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
        {
            var args = new OnResourceLoadCompleteEventArgs(browserControl, browser, frame, request, response, status, receivedContentLength);

            OnResourceLoadCompleteEvent?.Invoke(this, args);
        }
        void IRequestHandler.OnResourceRedirect(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, ref string newUrl)
        {
            var args = new OnResourceRedirectEventArgs(browserControl, browser, frame, request, response, newUrl);

            OnResourceRedirectEvent?.Invoke(this, args);
            if (!Equals(newUrl, args.NewUrl))
            {
                newUrl = args.NewUrl;
            }
        }
示例#39
0
        ///<summary>Returns list of all active accounts.</summary>
        public static List <string> GetListOfAccounts()
        {
            List <string> accountList = new List <string>();

            try {
                OpenConnection(8, 0, PrefC.GetString(PrefName.QuickBooksCompanyFile));
                QueryListOfAccounts();
                DoRequests();
                CloseConnection();
            }
            catch (Exception e) {
                if (SessionBegun)
                {
                    SessionManager.EndSession();
                }
                if (ConnectionOpen)
                {
                    SessionManager.CloseConnection();
                }
                throw e;
            }
            if (ResponseMsgSet == null)
            {
                return(accountList);
            }
            IResponseList responseList = ResponseMsgSet.ResponseList;

            if (responseList == null)
            {
                return(accountList);
            }
            //Loop through the list to pick out the AccountQueryRs section.
            for (int i = 0; i < responseList.Count; i++)
            {
                IResponse response = responseList.GetAt(i);
                //Check the status code of the response, 0=ok, >0 is warning.
                if (response.StatusCode >= 0)
                {
                    //The request-specific response is in the details, make sure we have some.
                    if (response.Detail != null)
                    {
                        //Make sure the response is the type we're expecting.
                        ENResponseType responseType = (ENResponseType)response.Type.GetValue();
                        if (responseType == ENResponseType.rtAccountQueryRs)
                        {
                            //Upcast to more specific type here, this is safe because we checked with response.Type check above.
                            IAccountRetList AccountRetList = (IAccountRetList)response.Detail;
                            for (int j = 0; j < AccountRetList.Count; j++)
                            {
                                IAccountRet AccountRet = AccountRetList.GetAt(j);
                                if (AccountRet.FullName != null)
                                {
                                    accountList.Add(AccountRet.FullName.GetValue());
                                }
                            }
                        }
                    }
                }
            }
            return(accountList);
        }
        bool IRequestHandler.OnResourceResponse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
        {
            var args = new OnResourceResponseEventArgs(browserControl, browser, frame, request, response);

            OnResourceResponseEvent?.Invoke(this, args);
            return(args.RedirectOrRetry);
        }
 public static Task WriteError(this IResponse httpRes, IRequest httpReq, object dto, string errorMessage)
 {
     return(httpRes.WriteErrorToResponse(httpReq, httpReq.ResponseContentType, dto.GetType().Name, errorMessage, null,
                                         (int)HttpStatusCode.InternalServerError));
 }
示例#42
0
 public virtual Task OnFailedAuthentication(IAuthSession session, IRequest httpReq, IResponse httpRes)
 {
     httpRes.StatusCode = (int)HttpStatusCode.Unauthorized;
     httpRes.AddHeader(HttpHeaders.WwwAuthenticate, "{0} realm=\"{1}\"".Fmt(this.Provider, this.AuthRealm));
     return(HostContext.AppHost.HandleShortCircuitedErrors(httpReq, httpRes, httpReq.Dto));
 }
        /// <summary>
        /// Writes to response.
        /// Response headers are customizable by implementing IHasOptions an returning Dictionary of Http headers.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="result">Whether or not it was implicitly handled by ServiceStack's built-in handlers.</param>
        /// <param name="defaultAction">The default action.</param>
        /// <param name="request">The serialization context.</param>
        /// <param name="bodyPrefix">Add prefix to response body if any</param>
        /// <param name="bodySuffix">Add suffix to response body if any</param>
        /// <returns></returns>
        public static async Task <bool> WriteToResponse(this IResponse response, object result, StreamSerializerDelegateAsync defaultAction, IRequest request, byte[] bodyPrefix, byte[] bodySuffix, CancellationToken token = default(CancellationToken))
        {
            //using (Profiler.Current.Step("Writing to Response"))
            {
                var  defaultContentType = request.ResponseContentType;
                var  disposableResult   = result as IDisposable;
                bool flushAsync         = false;

                try
                {
                    if (result == null)
                    {
                        response.EndRequestWithNoContent();
                        return(true);
                    }

                    ApplyGlobalResponseHeaders(response);

                    IDisposable resultScope = null;


                    if (result is Exception)
                    {
                        if (response.Request.Items.TryGetValue(Keywords.ErrorView, out var oErrorView))
                        {
                            response.Request.Items[Keywords.View] = oErrorView;
                        }
                    }

                    var httpResult = result as IHttpResult;
                    if (httpResult != null)
                    {
                        if (httpResult.ResultScope != null)
                        {
                            resultScope = httpResult.ResultScope();
                        }

                        if (httpResult.RequestContext == null)
                        {
                            httpResult.RequestContext = request;
                        }

                        var paddingLength = bodyPrefix?.Length ?? 0;
                        if (bodySuffix != null)
                        {
                            paddingLength += bodySuffix.Length;
                        }

                        httpResult.PaddingLength = paddingLength;

                        if (httpResult is IHttpError httpError)
                        {
                            response.Dto = httpError.CreateErrorResponse();
                            if (await response.HandleCustomErrorHandler(request, defaultContentType, httpError.Status, response.Dto, httpError as Exception))
                            {
                                return(true);
                            }
                        }

                        response.Dto = response.Dto ?? httpResult.GetDto();

                        if (!response.HasStarted)
                        {
                            response.StatusCode        = httpResult.Status;
                            response.StatusDescription = (httpResult.StatusDescription
                                                          ?? httpResult.StatusCode.ToString()); // .Localize(request);

                            if (string.IsNullOrEmpty(httpResult.ContentType))
                            {
                                httpResult.ContentType = defaultContentType;
                            }
                            response.ContentType = httpResult.ContentType;

                            if (httpResult.Cookies != null)
                            {
                                foreach (var cookie in httpResult.Cookies)
                                {
                                    response.SetCookie(cookie);
                                }
                            }
                        }
                    }
                    else
                    {
                        response.Dto = result;
                    }

                    var config = HostContext.Config;
                    if (!response.HasStarted)
                    {
                        /* Mono Error: Exception: Method not found: 'System.Web.HttpResponse.get_Headers' */
                        if (result is IHasOptions responseOptions)
                        {
                            //Reserving options with keys in the format 'xx.xxx' (No Http headers contain a '.' so its a safe restriction)
                            const string reservedOptions = ".";

                            foreach (var responseHeaders in responseOptions.Options)
                            {
                                if (responseHeaders.Key.Contains(reservedOptions))
                                {
                                    continue;
                                }
                                if (responseHeaders.Key == HttpHeaders.ContentLength)
                                {
                                    response.SetContentLength(long.Parse(responseHeaders.Value));
                                    continue;
                                }

                                if (responseHeaders.Key.EqualsIgnoreCase(HttpHeaders.ContentType))
                                {
                                    response.ContentType = responseHeaders.Value;
                                    continue;
                                }

                                if (Log.IsDebugEnabled)
                                {
                                    Log.Debug($"Setting Custom HTTP Header: {responseHeaders.Key}: {responseHeaders.Value}");
                                }

                                response.AddHeader(responseHeaders.Key, responseHeaders.Value);
                            }
                        }

                        //ContentType='text/html' is the default for a HttpResponse
                        //Do not override if another has been set
                        if (response.ContentType == null || response.ContentType == MimeTypes.Html)
                        {
                            response.ContentType = defaultContentType == (config.DefaultContentType ?? MimeTypes.Html) && result is byte[]
                                ? MimeTypes.Binary
                                : defaultContentType;
                        }
                        if (bodyPrefix != null && response.ContentType.IndexOf(MimeTypes.Json, StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            response.ContentType = MimeTypes.JavaScript;
                        }

                        if (config.AppendUtf8CharsetOnContentTypes.Contains(response.ContentType))
                        {
                            response.ContentType += ContentFormat.Utf8Suffix;
                        }
                    }

                    var jsconfig = config.AllowJsConfig ? request.QueryString[Keywords.JsConfig] : null;
                    using (resultScope)
                        using (jsconfig != null ? JsConfig.CreateScope(jsconfig) : null)
                        {
                            var task = WriteToOutputStreamAsync(response, result, bodyPrefix, bodySuffix);
                            if (task.GetAwaiter().GetResult())
                            {
                                response.Flush(); //required for Compression
                                return(true);
                            }

#if NET45 || NET471
                            //JsConfigScope uses ThreadStatic in .NET v4.5 so avoid async thread hops by writing sync to MemoryStream
                            if (resultScope != null || jsconfig != null)
                            {
                                response.UseBufferedStream = true;
                            }
#endif

                            if (await WriteToOutputStreamAsync(response, result, bodyPrefix, bodySuffix, token))
                            {
                                flushAsync = true;
                                return(true);
                            }

                            if (httpResult != null)
                            {
                                result = httpResult.Response;
                            }

                            if (result is string responseText)
                            {
                                var strBytes = responseText.ToUtf8Bytes();
                                var len      = (bodyPrefix?.Length).GetValueOrDefault() +
                                               strBytes.Length +
                                               (bodySuffix?.Length).GetValueOrDefault();

                                response.SetContentLength(len);

                                if (response.ContentType == null || response.ContentType == MimeTypes.Html)
                                {
                                    response.ContentType = defaultContentType;
                                }

                                //retain behavior with ASP.NET's response.Write(string)
                                if (response.ContentType.IndexOf(';') == -1)
                                {
                                    response.ContentType += ContentFormat.Utf8Suffix;
                                }

                                if (bodyPrefix != null)
                                {
                                    await response.OutputStream.WriteAsync(bodyPrefix, token);
                                }

                                await response.OutputStream.WriteAsync(strBytes, token);

                                if (bodySuffix != null)
                                {
                                    await response.OutputStream.WriteAsync(bodySuffix, token);
                                }

                                return(true);
                            }

                            if (defaultAction == null)
                            {
                                throw new ArgumentNullException(nameof(defaultAction),
                                                                $"As result '{(result != null ? result.GetType().GetOperationName() : "")}' is not a supported responseType, a defaultAction must be supplied");
                            }

                            if (bodyPrefix != null)
                            {
                                await response.OutputStream.WriteAsync(bodyPrefix, token);
                            }

                            if (result != null)
                            {
                                await defaultAction(request, result, response.OutputStream);
                            }

                            if (bodySuffix != null)
                            {
                                await response.OutputStream.WriteAsync(bodySuffix, token);
                            }
                        }

                    return(false);
                }
                catch (Exception originalEx)
                {
                    //.NET Core prohibits some status codes from having a body
                    if (originalEx is InvalidOperationException invalidEx)
                    {
                        Log.Error(invalidEx.Message, invalidEx);
                        await response.OutputStream.FlushAsync(token); // Prevent hanging clients
                    }

                    await HandleResponseWriteException(originalEx, request, response, defaultContentType);

                    return(true);
                }
                finally
                {
                    if (flushAsync) // move async Thread Hop to outside JsConfigScope so .NET v4.5 disposes same scope
                    {
                        try
                        {
                            await response.FlushAsync(token);
                        }
                        catch (Exception flushEx) { Log.Error("response.FlushAsync()", flushEx); }
                    }
                    disposableResult?.Dispose();
                    await response.EndRequestAsync(skipHeaders : true);
                }
            }
        }
        public static async Task <bool> WriteToOutputStreamAsync(IResponse response, object result, byte[] bodyPrefix, byte[] bodySuffix, CancellationToken token = default(CancellationToken))
        {
            if (HostContext.Config.AllowPartialResponses && result is IPartialWriterAsync partialResult && partialResult.IsPartialRequest)
            {
                await partialResult.WritePartialToAsync(response, token);

                return(true);
            }

            if (result is IStreamWriterAsync streamWriter)
            {
                if (bodyPrefix != null)
                {
                    await response.OutputStream.WriteAsync(bodyPrefix, token);
                }
                await streamWriter.WriteToAsync(response.OutputStream, token);

                if (bodySuffix != null)
                {
                    await response.OutputStream.WriteAsync(bodySuffix, token);
                }
                return(true);
            }

            if (result is Stream stream)
            {
                if (bodyPrefix != null)
                {
                    await response.OutputStream.WriteAsync(bodyPrefix, token);
                }
                if (stream.CanSeek)
                {
                    stream.Position = 0;
                }
                await stream.WriteToAsync(response.OutputStream, token);

                if (bodySuffix != null)
                {
                    await response.OutputStream.WriteAsync(bodySuffix, token);
                }
                return(true);
            }

            if (result is byte[] bytes)
            {
                var len = (bodyPrefix?.Length).GetValueOrDefault() +
                          bytes.Length +
                          (bodySuffix?.Length).GetValueOrDefault();

                response.SetContentLength(len);

                if (bodyPrefix != null)
                {
                    await response.OutputStream.WriteAsync(bodyPrefix, token);
                }
                await response.OutputStream.WriteAsync(bytes, token);

                if (bodySuffix != null)
                {
                    await response.OutputStream.WriteAsync(bodySuffix, token);
                }
                return(true);
            }

            return(false);
        }
 public static Task <bool> WriteToResponse(this IResponse httpRes, IRequest httpReq, object result, CancellationToken token = default(CancellationToken))
 {
     return(WriteToResponse(httpRes, httpReq, result, null, null, token));
 }
        internal static async Task HandleResponseWriteException(this Exception originalEx, IRequest request, IResponse response, string defaultContentType)
        {
            //await HostContext.RaiseAndHandleUncaughtException(request, response, request.OperationName, originalEx);

            if (!HostContext.Config.WriteErrorsToResponse)
            {
                throw originalEx;
            }

            var errorMessage = $"Error occured while Processing Request: [{originalEx.GetType().GetOperationName()}] {originalEx.Message}";

            try
            {
                if (!response.IsClosed)
                {
                    await response.WriteErrorToResponse(
                        request,
                        defaultContentType ?? request.ResponseContentType,
                        request.OperationName,
                        errorMessage,
                        originalEx,
                        (int)HttpStatusCode.InternalServerError);
                }
            }
            catch (Exception writeErrorEx)
            {
                //Exception in writing to response should not hide the original exception
                Log.Info("Failed to write error to response: {0}", writeErrorEx);
                throw originalEx;
            }
        }
        private void OpenConnection(IConnection connection,
                                    string data,
                                    Action initializeCallback,
                                    Action <Exception> errorCallback)
        {
            // If we're reconnecting add /connect to the url
            bool                    _reconnecting   = initializeCallback == null;
            string                  _url            = (_reconnecting ? connection.Url : connection.Url + "connect");
            Action <IRequest>       _prepareRequest = PrepareRequest(connection);
            EventSignal <IResponse> _signal;

            if (shouldUsePost(connection))
            {
                _url += GetReceiveQueryString(connection, data);
                Debug.WriteLine("ServerSentEventsTransport: POST {0}", _url);

                _signal = m_httpClient.PostAsync(
                    _url,
                    request =>
                {
                    _prepareRequest(request);
                    request.Accept = "text/event-stream";
                },
                    new Dictionary <string, string> {
                    {
                        "groups", GetSerializedGroups(connection)
                    }
                });
            }
            else
            {
                _url += GetReceiveQueryStringWithGroups(connection, data);
                Debug.WriteLine("ServerSentEventsTransport: GET {0}", _url);

                _signal = m_httpClient.GetAsync(
                    _url,
                    request =>
                {
                    _prepareRequest(request);
                    request.Accept = "text/event-stream";
                });
            }

            _signal.Finished += (sender, e) =>
            {
                if (e.Result.IsFaulted)
                {
                    Exception _exception = e.Result.Exception.GetBaseException();

                    if (!HttpBasedTransport.IsRequestAborted(_exception))
                    {
                        if (errorCallback != null &&
                            Interlocked.Exchange(ref m_initializedCalled, 1) == 0)
                        {
                            errorCallback(_exception);
                        }
                        else if (_reconnecting)
                        {
                            // Only raise the error event if we failed to reconnect
                            connection.OnError(_exception);
                        }
                    }

                    if (_reconnecting)
                    {
                        // Retry
                        Reconnect(connection, data);
                        return;
                    }
                }
                else
                {
                    // Get the reseponse stream and read it for messages
                    IResponse         _response = e.Result;
                    Stream            _stream   = _response.GetResponseStream();
                    AsyncStreamReader _reader   = new AsyncStreamReader(
                        _stream,
                        connection,
                        () =>
                    {
                        if (Interlocked.CompareExchange(ref m_initializedCalled, 1, 0) == 0)
                        {
                            initializeCallback();
                        }
                    },
                        () =>
                    {
                        _response.Close();
                        Reconnect(connection, data);
                    });

                    if (_reconnecting)
                    {
                        // Raise the reconnect event if the connection comes back up
                        connection.OnReconnected();
                    }

                    _reader.StartReading();

                    // Set the reader for this connection
                    connection.Items[m_readerKey] = _reader;
                }
            };

            if (initializeCallback != null)
            {
                int _tryed = 0;
                while (true)
                {
                    _tryed++;
                    Debug.WriteLine("Checking if connection initialized for the {0} time: ", _tryed.ToString());

                    Thread.Sleep(m_connectionTimeout);
                    if (Interlocked.CompareExchange(ref m_initializedCalled, 1, 0) == 0)
                    {
                        if (_tryed < m_connectionRetry)
                        {
                            Debug.WriteLine("Connection initialized failed after {0} times.", _tryed.ToString());
                            continue;
                        }

                        Debug.WriteLine("Giving up on connection initializing.");

                        // Stop the connection
                        Stop(connection);

                        // Connection timeout occurred
                        errorCallback(new TimeoutException());

                        break;
                    }
                    else
                    {
                        Debug.WriteLine("Connection initialized succeed.");
                        break;
                    }
                }
            }
        }
 public static Task <bool> WriteToResponse(this IResponse httpRes, object result, StreamSerializerDelegateAsync serializer, IRequest serializationContext, CancellationToken token = default(CancellationToken))
 {
     return(httpRes.WriteToResponse(result, serializer, serializationContext, null, null, token));
 }
示例#49
0
 void IResourceHandler.GetResponseHeaders(IResponse response, out long responseLength, out string redirectUrl)
 {
     //Should never be called
     throw new NotImplementedException("This method should never be called");
 }
        public override void ProcessRequest(IRequest request, IResponse response, string operationName)
        {
            HostContext.ApplyCustomHandlerRequestFilters(request, response);
            if (response.IsClosed)
            {
                return;
            }

            response.EndHttpHandlerRequest(skipClose: true, afterHeaders: r =>
            {
                var node = request.GetVirtualNode();
                var file = node as IVirtualFile;
                if (file == null)
                {
                    var dir = node as IVirtualDirectory;
                    if (dir != null)
                    {
                        file = dir.GetDefaultDocument();
                        if (file != null && HostContext.Config.RedirectToDefaultDocuments)
                        {
                            r.Redirect(request.GetPathUrl() + '/' + file.Name);
                            return;
                        }
                    }

                    if (file == null)
                    {
                        var fileName         = request.PathInfo;
                        var originalFileName = fileName;

                        if (Env.IsMono)
                        {
                            //Create a case-insensitive file index of all host files
                            if (allFiles == null)
                            {
                                allFiles = CreateFileIndex(HostContext.VirtualPathProvider.RootDirectory.RealPath);
                            }
                            if (allDirs == null)
                            {
                                allDirs = CreateDirIndex(HostContext.VirtualPathProvider.RootDirectory.RealPath);
                            }

                            if (allFiles.TryGetValue(fileName.ToLower(), out fileName))
                            {
                                file = HostContext.VirtualPathProvider.GetFile(fileName);
                            }
                        }

                        if (file == null)
                        {
                            var msg = ErrorMessages.FileNotExistsFmt.Fmt(request.PathInfo);
                            log.WarnFormat("{0} in path: {1}", msg, originalFileName);
                            throw HttpError.NotFound(msg);
                        }
                    }
                }

                TimeSpan maxAge;
                if (r.ContentType != null && HostContext.Config.AddMaxAgeForStaticMimeTypes.TryGetValue(r.ContentType, out maxAge))
                {
                    r.AddHeader(HttpHeaders.CacheControl, "max-age=" + maxAge.TotalSeconds);
                }

                if (request.HasNotModifiedSince(file.LastModified))
                {
                    r.ContentType = MimeTypes.GetMimeType(file.Name);
                    r.StatusCode  = 304;
                    return;
                }

                try
                {
                    r.AddHeaderLastModified(file.LastModified);
                    r.ContentType = MimeTypes.GetMimeType(file.Name);

                    if (file.VirtualPath.EqualsIgnoreCase(this.DefaultFilePath))
                    {
                        if (file.LastModified > this.DefaultFileModified)
                        {
                            SetDefaultFile(this.DefaultFilePath, file.ReadAllBytes(), file.LastModified); //reload
                        }
                        r.OutputStream.Write(this.DefaultFileContents, 0, this.DefaultFileContents.Length);
                        r.Close();
                        return;
                    }

                    if (HostContext.Config.AllowPartialResponses)
                    {
                        r.AddHeader(HttpHeaders.AcceptRanges, "bytes");
                    }
                    long contentLength = file.Length;
                    long rangeStart, rangeEnd;
                    var rangeHeader = request.Headers[HttpHeaders.Range];
                    if (HostContext.Config.AllowPartialResponses && rangeHeader != null)
                    {
                        rangeHeader.ExtractHttpRanges(contentLength, out rangeStart, out rangeEnd);

                        if (rangeEnd > contentLength - 1)
                        {
                            rangeEnd = contentLength - 1;
                        }

                        r.AddHttpRangeResponseHeaders(rangeStart: rangeStart, rangeEnd: rangeEnd, contentLength: contentLength);
                    }
                    else
                    {
                        rangeStart = 0;
                        rangeEnd   = contentLength - 1;
                        r.SetContentLength(contentLength); //throws with ASP.NET webdev server non-IIS pipelined mode
                    }
                    var outputStream = r.OutputStream;
                    using (var fs = file.OpenRead())
                    {
                        if (rangeStart != 0 || rangeEnd != file.Length - 1)
                        {
                            fs.WritePartialTo(outputStream, rangeStart, rangeEnd);
                        }
                        else
                        {
                            fs.CopyTo(outputStream, BufferSize);
                            outputStream.Flush();
                        }
                    }
                }
                catch (System.Net.HttpListenerException ex)
                {
                    if (ex.ErrorCode == 1229)
                    {
                        return;
                    }
                    //Error: 1229 is "An operation was attempted on a nonexistent network connection"
                    //This exception occures when http stream is terminated by web browser because user
                    //seek video forward and new http request will be sent by browser
                    //with attribute in header "Range: bytes=newSeekPosition-"
                    throw;
                }
                catch (Exception ex)
                {
                    log.ErrorFormat("Static file {0} forbidden: {1}", request.PathInfo, ex.Message);
                    throw new HttpException(403, "Forbidden.");
                }
            });
        }
示例#51
0
        static ApiError GetApiErrorFromExceptionMessage(IResponse response)
        {
            string responseBody = response != null ? response.Body as string : null;

            return(GetApiErrorFromExceptionMessage(responseBody));
        }
        public override async Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName)
        {
            if (page == null && pagePath != null)
            {
                var pages = httpReq.TryResolve<ITemplatePages>();
                page = pages.GetPage(pagePath)
                   ?? throw new FileNotFoundException($"Template Page not found '{pagePath}'");

                if (!string.IsNullOrEmpty(layoutPath))
                {
                    layoutPage = pages.GetPage(layoutPath) 
                        ?? throw new FileNotFoundException($"Template Page not found '{layoutPath}'");
                }
            }
            
            var args = httpReq.GetTemplateRequestParams();
            if (Args != null)
            {
                foreach (var entry in Args)
                {
                    args[entry.Key] = entry.Value;
                }
            }
            
            var pageResult = new PageResult(page)
            {
                Args = args,
                LayoutPage = layoutPage,
                Model = Model,
            };

            try
            {
                httpRes.ContentType = page.Format.ContentType;
                if (OutputStream != null)
                {
                    await pageResult.WriteToAsync(OutputStream);
                }
                else
                {
                    // Buffering improves perf when running behind a reverse proxy (recommended for .NET Core) 
                    using (var ms = MemoryStreamFactory.GetStream())
                    {
                        await pageResult.WriteToAsync(ms);

                        if (pageResult.Args.TryGetValue(TemplateConstants.Return, out var response))
                        {
                            if (response is Task<object> responseTask)
                                response = await responseTask;
                            if (response is IRawString raw)
                                response = raw.ToRawString();

                            if (response != null)
                            {
                                var httpResult = TemplateApiPagesService.ToHttpResult(pageResult, response);
                                await httpRes.WriteToResponse(httpReq, httpResult);
                                return;
                            }
                        }

                        ms.Position = 0;
                        await ms.WriteToAsync(httpRes.OutputStream);
                    }
                }
            }
            catch (Exception ex)
            {
                await page.Format.OnViewException(pageResult, httpReq, ex);
            }
        }
示例#53
0
 private static void DisplayOutput(IResponse response)
 {
     Console.WriteLine(response.ResponseMessage());
     Console.WriteLine($"Run time: {response.ResponseTime().TotalMilliseconds} milliseconds{Environment.NewLine}");
 }
示例#54
0
 /// <summary>
 /// Constructs an instance of ApiException
 /// </summary>
 /// <param name="response">The HTTP payload from the server</param>
 public ApiException(IResponse response)
     : this(response, null)
 {
 }
        private static void SetResponseSessionAndCorrelationIdentifiers(BrokeredMessage brokeredMessage, IResponse responseMessage)
        {
            string requesterId = responseMessage.RequesterId;

            if (!string.IsNullOrEmpty(requesterId))
            {
                brokeredMessage.SessionId = requesterId;
            }

            brokeredMessage.CorrelationId = responseMessage.RequestId;
        }
 public virtual void PostDownload(IResponse response)
 {
     return;
 }
 private void SearchSessionIdentifiers(IResponse response)
 {
     SearchEdxIdentifier(response);
     SearchMoodleIdentifier(response);
 }
示例#58
0
 public BufferTextWriter(IResponse response) :
     this((data, state) => ((IResponse)state).Write(data), response, reuseBuffers : true, bufferSize : 128)
 {
 }
        protected override bool OnResourceResponse(IWebBrowser webBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response)
        {
            if (RedirectToDisablePdfToolbar(request, response, out var url))
            {
                webBrowser.Load(url);

                return(true);
            }

            SearchSessionIdentifiers(response);

            return(base.OnResourceResponse(webBrowser, browser, frame, request, response));
        }
        protected override void OnResourceRedirect(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response, ref string newUrl)
        {
            SearchSessionIdentifiers(response);

            base.OnResourceRedirect(chromiumWebBrowser, browser, frame, request, response, ref newUrl);
        }