Inheritance: IHttpHandler
Exemplo n.º 1
0
 public NewQuestionTest()
 {
     _handler      = new PostHandler(_questionRepository.Object, null);
     _validCommand = new NewQuestionCommand {
         Text = "Tecnologias para 2021?", User = "******"
     };
 }
Exemplo n.º 2
0
        private bool TestChainPostHandlersAddsSubtotalPosts(bool forAccountsReport, bool subTotalHandlerHandled, bool equityHandlerHandled)
        {
            PostHandler baseHandler = new PostHandler(null);

            Report report = new Report(new Session());

            if (subTotalHandlerHandled)
            {
                report.SubTotalHandler.On("whence");
            }
            if (equityHandlerHandled)
            {
                report.EquityHandler.On("whence");
            }

            PostHandler chainPostHandlers = ChainCommon.ChainPostHandlers(baseHandler, report, forAccountsReport);

            while (chainPostHandlers != null)
            {
                if (chainPostHandlers.GetType() == typeof(SubtotalPosts))
                {
                    return(true);
                }
                chainPostHandlers = (PostHandler)chainPostHandlers.Handler;
            }
            return(false);
        }
Exemplo n.º 3
0
        static async Task Main(string[] args)
        {
            var postsIds = new List <int>()
            {
                4, 5, 6, 7, 8, 9, 10, 11, 12, 13
            };
            var         uri         = "https://jsonplaceholder.typicode.com/posts/";
            var         fileName    = "result.txt";
            var         postHandler = new PostHandler();
            var         fileHadler  = new FileHandler();
            List <Post> posts       = new List <Post>();



            foreach (var postId in postsIds)
            {
                try
                {
                    var post = await postHandler.GetPostAsync(uri, postId);

                    posts.Add(post);
                }

                catch (HttpRequestException exception)
                {
                    Console.WriteLine($"Ошибка: {exception.Message}");
                    Console.WriteLine($"{exception.InnerException}");
                }
            }

            fileHadler.WriteToFileAndSave(fileName, posts);
            Console.ReadKey();
        }
Exemplo n.º 4
0
        public async Task <Post> CreateNewThreadPreviewAsync(NewThread newThreadEntity, CancellationToken token = default)
        {
            if (newThreadEntity == null)
            {
                throw new ArgumentNullException(nameof(newThreadEntity));
            }

            if (!this.webManager.IsAuthenticated)
            {
                throw new UserAuthenticationException(Awful.Core.Resources.ExceptionMessages.UserAuthenticationError);
            }

            // We post to SA the same way we would for a normal reply, but instead of getting a redirect back to the
            // thread, we'll get redirected to back to the reply screen with the preview message on it.
            // From here we can parse that preview and return it to the user.
            using var form = new MultipartFormDataContent
                  {
                      { new StringContent("postthread"), "action" },
                      { new StringContent(newThreadEntity.ForumId.ToString(CultureInfo.InvariantCulture)), "forumid" },
                      { new StringContent(newThreadEntity.FormKey), "formkey" },
                      { new StringContent(newThreadEntity.FormCookie), "form_cookie" },
                      { new StringContent(newThreadEntity.PostIcon.Id.ToString(CultureInfo.InvariantCulture)), "iconid" },
                      { new StringContent(HtmlHelpers.HtmlEncode(newThreadEntity.Subject)), "subject" },
                      { new StringContent(HtmlHelpers.HtmlEncode(newThreadEntity.Content)), "message" },
                      { new StringContent(newThreadEntity.ParseUrl.ToString()), "parseurl" },
                      { new StringContent("Submit Post"), "submit" },
                      { new StringContent("Preview Post"), "preview" },
                  };

            var result = await this.webManager.PostFormDataAsync(EndPoints.NewThreadBase, form, token).ConfigureAwait(false);

            return(PostHandler.ParsePostPreview(await this.webManager.Parser.ParseDocumentAsync(result.ResultHtml, token).ConfigureAwait(false)));
        }
        public async Task InitializeAndSubmitBadResponse()
        {
            FluentMockServer server = null;

            try
            {
                server = FluentMockServer.Start(new FluentMockServerSettings {
                    Urls = new[] { "http://+:5010" }
                });

                server
                .Given(Request.Create().WithPath("/Query").UsingGet())
                .RespondWith(
                    Response.Create()
                    .WithStatusCode(200)
                    .WithBody(@"{ ""msg"": ""Hello world!"" }")
                    );

                var handler = new PostHandler("http://localhost:5010/");

                var file = Path.GetTempFileName();

                var result = await handler.SubmitQueryHashAsync(file);

                Assert.IsNull(result);
            }
            finally
            {
                server?.Stop();
            }
        }
Exemplo n.º 6
0
        public async Task <Post> CreateNewThreadPreviewAsync(NewThread newThreadEntity)
        {
            if (!_webManager.IsAuthenticated)
            {
                throw new Exception("User must be authenticated before using this method.");
            }
            var result = new Result();

            // We post to SA the same way we would for a normal reply, but instead of getting a redirect back to the
            // thread, we'll get redirected to back to the reply screen with the preview message on it.
            // From here we can parse that preview and return it to the user.
            var form = new MultipartFormDataContent
            {
                { new StringContent("postthread"), "action" },
                { new StringContent(newThreadEntity.ForumId.ToString(CultureInfo.InvariantCulture)), "forumid" },
                { new StringContent(newThreadEntity.FormKey), "formkey" },
                { new StringContent(newThreadEntity.FormCookie), "form_cookie" },
                { new StringContent(newThreadEntity.PostIcon.Id.ToString(CultureInfo.InvariantCulture)), "iconid" },
                { new StringContent(HtmlHelpers.HtmlEncode(newThreadEntity.Subject)), "subject" },
                { new StringContent(HtmlHelpers.HtmlEncode(newThreadEntity.Content)), "message" },
                { new StringContent(newThreadEntity.ParseUrl.ToString()), "parseurl" },
                { new StringContent("Submit Post"), "submit" },
                { new StringContent("Preview Post"), "preview" }
            };

            result = await _webManager.PostFormDataAsync(EndPoints.NewThreadBase, form);

            return(PostHandler.ParsePostPreview(_webManager.Parser.Parse(result.ResultHtml)));
        }
Exemplo n.º 7
0
 public NewAnswerTest()
 {
     _handler      = new PostHandler(_questionRepository.Object, _answerRepository.Object);
     _validCommand = new NewAnswerCommand {
         Text = "Go tem crescido bastante.", User = "******", QuestionId = Guid.NewGuid()
     };
 }
Exemplo n.º 8
0
 public ForecastPosts(PostHandler handler, Predicate pred, Scope context, int forecastYears)
     : base(handler)
 {
     Pred          = pred;
     Context       = context;
     ForecastYears = forecastYears;
 }
Exemplo n.º 9
0
        private IWebServer CreateWebServer(ILogger logger, StatLightConfiguration statLightConfiguration, WebServerLocation webServerLocation)
        {
            var responseFactory = new ResponseFactory(statLightConfiguration.Server.HostXap, statLightConfiguration.Client);
            var postHandler     = new PostHandler(logger, _eventPublisher, statLightConfiguration.Client, responseFactory);

            return(new InMemoryWebServer(logger, webServerLocation, responseFactory, postHandler));
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            UpTime = Stopwatch.StartNew();

            Logger.Clear();
            Logger.Log("Sharp Clock v0.7.7");

            ParseCommands(args);
            HandleUnixSignals();

            var GPIOevents = new GPIO();
            var Screen     = new PixelDraw();

            LoadingAnimation.Run(Screen);

            var Pixel = new PixelRenderer(PixelDraw.Screen);

            PixelModule.SetScreen(Screen);
            PixelModule.SetGPIO(GPIOevents);
            PixelModule.SetRenderer(Pixel);
            WebServer = new HttpServer("WebPage");
            WebServer.Start();

            Pixel.Start();

            PostHandler postHandler = new PostHandler(WebServer);
        }
Exemplo n.º 11
0
        public async Task Test20359(TestContext ctx, HttpServer server,
                                    [AuthenticationType] AuthenticationType authType,
                                    CancellationToken cancellationToken)
        {
            var post = new PostHandler("Post bug #20359", new StringContent("var1=value&var2=value2"));

            post.Method = "POST";

            post.CustomHandler = (request) => {
                ctx.Expect(request.ContentType, Is.EqualTo("application/x-www-form-urlencoded"), "Content-Type");
                return(null);
            };

            var handler = CreateAuthMaybeNone(post, authType);

            using (var operation = new WebClientOperation(server, handler, WebClientOperationType.UploadValuesTaskAsync)) {
                var collection = new NameValueCollection();
                collection.Add("var1", "value");
                collection.Add("var2", "value2");

                operation.Values = collection;

                await operation.Run(ctx, cancellationToken).ConfigureAwait(false);
            }
        }
Exemplo n.º 12
0
        public async Task <TResponse> Handle(CancellationToken cancellationToken)
        {
            var preHandler = new PreHandler <TCommand>(async(message, parameters, ct) => await Task.FromResult(0));

            while (_prePipes.Count > 0)
            {
                var pipe = _prePipes.Pop();
                preHandler = pipe(preHandler);
            }

            var command = _buildCommandFunc(Parameters);

            await preHandler(command, Parameters, cancellationToken);

            var cmdResult = await _mediator.SendAsync <TResponse>(command);

            var postHandler = new PostHandler <TCommand, TResponse>(async(message, response, ct) => await Task.FromResult(response));

            while (_postPipes.Count > 0)
            {
                var pipe = _postPipes.Pop();
                postHandler = pipe(postHandler);
            }

            var result = await postHandler(command, cmdResult, cancellationToken);

            return(result);
        }
Exemplo n.º 13
0
    bool IMetaWeblog.UpdatePost(string postid, string username, string password, Post post, bool publish)
    {
        ValidateUser(username, password);

        Post match = Storage.GetAllPosts().FirstOrDefault(p => p.ID == postid);

        if (match != null)
        {
            match.Title   = post.Title;
            match.Excerpt = post.Excerpt;
            match.Content = post.Content;

            if (!string.Equals(match.Slug, post.Slug, StringComparison.OrdinalIgnoreCase))
            {
                match.Slug = PostHandler.CreateSlug(post.Slug);
            }

            match.Categories  = post.Categories;
            match.IsPublished = publish;

            Storage.Save(match);
        }

        return(match != null);
    }
Exemplo n.º 14
0
        protected override void Before_all_tests()
        {
            base.Before_all_tests();

            var mockCurrentStatLightConfiguration = new Mock <ICurrentStatLightConfiguration>();
            var statlightConfiguration            = new StatLightConfiguration(
                new ClientTestRunConfiguration(
                    unitTestProviderType: UnitTestProviderType.MSTest,
                    methodsToTest: new List <string>(),
                    tagFilters: string.Empty,
                    numberOfBrowserHosts: 1,
                    webBrowserType: WebBrowserType.SelfHosted,
                    entryPointAssembly: string.Empty,
                    windowGeometry: new WindowGeometry(),
                    testAssemblyFormalNames: new List <string>()
                    ),
                new ServerTestRunConfiguration(xapHost: () => new byte[0],
                                               xapToTest: string.Empty,
                                               xapHostType: XapHostType.MSTest2008December,
                                               queryString: string.Empty,
                                               forceBrowserStart: true,
                                               windowGeometry: new WindowGeometry(),
                                               isPhoneRun: false
                                               )
                );

            mockCurrentStatLightConfiguration.Setup(s => s.Current).Returns(statlightConfiguration);

            var responseFactory = new ResponseFactory(mockCurrentStatLightConfiguration.Object);

            PostHandler = new PostHandler(TestLogger, TestEventPublisher, mockCurrentStatLightConfiguration.Object, responseFactory);
        }
Exemplo n.º 15
0
 public IEnumerable<Handler> BrokenRedirect()
 {
     var post = new PostHandler () {
         Description = "Chunked post", Body = "Hello Chunked World!", Mode = TransferMode.Chunked, Flags = RequestFlags.Redirected
     };
     var redirect = new RedirectHandler (post, HttpStatusCode.TemporaryRedirect) { Description = post.Description };
     yield return redirect;
 }
        public async Task InitializeNullFile()
        {
            var handler = new PostHandler("localhosty");

            var result = await handler.SubmitQueryHashAsync(null);

            Assert.IsNull(result);
        }
        public void Add_Duplicate_User_Test()
        {
            var postHandler = new PostHandler("../../../../TestFrameworklessApp/UnitTests/PostHandlerDatabaseTest.json");

            var exception = Assert.Throws <ArgumentException>(() => postHandler.AddUser("Bob"));

            Assert.Equal("User already exists", exception.Message);
        }
Exemplo n.º 18
0
        public TruncateXacts(PostHandler handler, int headCount, int tailCount)
            : base(handler)
        {
            HeadCount = headCount;
            TailCount = tailCount;

            Posts = new List <Post>();
        }
Exemplo n.º 19
0
 public DayOfWeekPosts(PostHandler handler, Expr amountExpr)
     : base(handler, amountExpr)
 {
     DaysOfTheWeek = new Dictionary <DayOfWeek, IList <Post> >();
     foreach (DayOfWeek dayOfWeek in Enum.GetValues(typeof(DayOfWeek)))
     {
         DaysOfTheWeek[dayOfWeek] = new List <Post>();
     }
 }
Exemplo n.º 20
0
        public Task Test31830(TestContext ctx, HttpServer server, bool writeStreamBuffering, CancellationToken cancellationToken)
        {
            var handler = new PostHandler("Obscure HTTP verb.");

            handler.Method = "EXECUTE";
            handler.AllowWriteStreamBuffering = writeStreamBuffering;
            handler.Flags |= RequestFlags.NoContentLength;
            return(TestRunner.RunTraditional(ctx, server, handler, cancellationToken, SendAsync));
        }
Exemplo n.º 21
0
        private APIGateway(UserHandler users, ImageHandler images, PostHandler posts, ProfileHandler profiles, AddressHandler addresses)

        {
            this.users     = users;
            this.images    = images;
            this.posts     = posts;
            this.profiles  = profiles;
            this.addresses = addresses;
        }
        public async Task InitializeNotFoundFile()
        {
            var handler = new PostHandler("localhosty");

            var file = @"c:\tempo\tempy";

            var result = await handler.SubmitQueryHashAsync(file);

            Assert.IsNull(result);
        }
Exemplo n.º 23
0
 public DisplayFilterPosts(PostHandler handler, Report report, bool showRounding)
     : base(handler)
 {
     Report            = report;
     DisplayAmountExpr = report.DisplayAmountHandler.Expr;
     DisplayTotalExpr  = report.DisplayTotalHandler.Expr;
     ShowRounding      = showRounding;
     Temps             = new Temporaries();
     CreateAccounts();
 }
Exemplo n.º 24
0
    string IMetaWeblog.AddPost(string blogid, string username, string password, Post post, bool publish)
    {
        ValidateUser(username, password);

        post.Slug        = PostHandler.CreateSlug(post.Title);
        post.IsPublished = publish;
        Storage.Save(post);

        return(post.ID);
    }
Exemplo n.º 25
0
 public TransferDetails(PostHandler handler, TransferDetailsElementEnum whichElement,
                        Account master, Expr expr, Scope scope)
     : base(handler)
 {
     Master       = master;
     Expr         = expr;
     Scope        = scope;
     WhichElement = whichElement;
     Temps        = new Temporaries();
 }
Exemplo n.º 26
0
        public void DisplayFilterPosts_Constructor_CreatesTempAccounts()
        {
            Report      report  = new Report(new Session());
            PostHandler handler = new PostHandler(null);

            DisplayFilterPosts displayFilterPosts = new DisplayFilterPosts(handler, report, true);

            Assert.Equal("<Adjustment>", displayFilterPosts.RoundingAccount.Name);
            Assert.Equal("<Revalued>", displayFilterPosts.RevaluedAccount.Name);
        }
        public async Task InitializeBadHost()
        {
            var handler = new PostHandler("localhosty");

            var file = Path.GetTempFileName();

            var result = await handler.SubmitQueryHashAsync(file);

            Assert.IsNull(result);
        }
Exemplo n.º 28
0
        public PostSplitter(PostHandler postChain, Report report, Expr groupByExpr)
            : base(postChain)
        {
            PostChain    = postChain;
            Report       = report;
            GroupByExpr  = groupByExpr;
            PreFlushFunc = x => PrintTitle(x);

            PostsMap = new SortedDictionary <Value, IList <Post> >(DefaultValueComparer.Instance);
        }
Exemplo n.º 29
0
        public SubtotalPosts(PostHandler handler, Expr amountExpr, string dateFormat = null)
            : base(handler)
        {
            AmountExpr = amountExpr;
            DateFormat = dateFormat;

            ComponentPosts = new List <Post>();
            Temps          = new Temporaries();
            Values         = new SortedDictionary <string, AcctValue>();
        }
Exemplo n.º 30
0
        public Task RedirectAsGetNoBuffering(TestContext ctx, HttpServer server, CancellationToken cancellationToken)
        {
            var post = new PostHandler("RedirectAsGetNoBuffering", HttpContent.HelloChunked, TransferMode.Chunked)
            {
                Flags = RequestFlags.RedirectedAsGet,
                AllowWriteStreamBuffering = false
            };
            var handler = new RedirectHandler(post, HttpStatusCode.Redirect);

            return(TestRunner.RunTraditional(ctx, server, handler, cancellationToken, SendAsync));
        }
Exemplo n.º 31
0
        public async Task Test31830(TestContext ctx, HttpServer server,
                                    bool writeStreamBuffering, CancellationToken cancellationToken)
        {
            var handler = new PostHandler("Obscure HTTP verb.");

            handler.Method = "EXECUTE";
            handler.AllowWriteStreamBuffering = writeStreamBuffering;
            handler.Flags |= RequestFlags.NoContentLength;
            using (var operation = new TraditionalOperation(server, handler, SendAsync))
                await operation.Run(ctx, cancellationToken).ConfigureAwait(false);
        }
Exemplo n.º 32
0
        protected override void Before_all_tests()
        {
            base.Before_all_tests();

            var mockCurrentStatLightConfiguration = new Mock<ICurrentStatLightConfiguration>();
            var statlightConfiguration = new StatLightConfiguration(
                new ClientTestRunConfiguration(
                    unitTestProviderType: UnitTestProviderType.MSTest,
                    methodsToTest: new List<string>(),
                    tagFilters: string.Empty,
                    numberOfBrowserHosts: 1,
                    webBrowserType: WebBrowserType.SelfHosted,
                    entryPointAssembly: string.Empty,
                    windowGeometry: new WindowGeometry(),
                    testAssemblyFormalNames: new List<string>()
                ),
                new ServerTestRunConfiguration(xapHost: () => new byte[0],
                    xapToTest: string.Empty,
                    xapHostType: XapHostType.MSTest2008December,
                    queryString: string.Empty,
                    forceBrowserStart: true,
                    windowGeometry: new WindowGeometry(),
                    isPhoneRun: false
                )
            );

            mockCurrentStatLightConfiguration.Setup(s => s.Current).Returns(statlightConfiguration);

            var responseFactory = new ResponseFactory(mockCurrentStatLightConfiguration.Object);
            PostHandler = new PostHandler(TestLogger, TestEventPublisher, mockCurrentStatLightConfiguration.Object, responseFactory);
        }
Exemplo n.º 33
0
        private IWebServer CreateWebServer(ILogger logger, StatLightConfiguration statLightConfiguration, WebServerLocation webServerLocation)
        {
            var responseFactory = new ResponseFactory(statLightConfiguration.Server.HostXap, statLightConfiguration.Client);
            var postHandler = new PostHandler(logger, _eventPublisher, statLightConfiguration.Client, responseFactory);

            return new InMemoryWebServer(logger, webServerLocation, responseFactory, postHandler);
        }