コード例 #1
0
        public void WriteAutoCompleteResultTest(
            string indexName,
            int numDocs,
            Dictionary <string, string> commitUserData,
            int topDocsTotalHits,
            float topDocsMaxScore,
            int skip,
            int take,
            bool includeExplanation,
            string expected)
        {
            var searcher = new MockSearcher(indexName, numDocs, commitUserData);
            var topDocs  = new TopDocs(topDocsTotalHits, Constants.ScoreDocs, topDocsMaxScore);

            var sb = new StringBuilder();
            var sw = new StringWriter(sb);

            using (var writer = new JsonTextWriter(sw))
            {
                ResponseFormatter.WriteAutoCompleteResult(writer, searcher, topDocs, skip, take, includeExplanation, NuGetQuery.MakeQuery("test"));

                Assert.Equal(string.Format(expected,
                                           searcher.LastReopen,
                                           Constants.MockBase,
                                           Constants.LucenePropertyId,
                                           Constants.MockExplanationBase), sb.ToString());
            }
        }
コード例 #2
0
        public void WriteDiagStatsResultTest(
            string indexName,
            int numDocs,
            Dictionary <string, string> commitUserData,
            Dictionary <string, DateTime?> auxFileData,
            string expected)
        {
            var currentTime = DateTime.UtcNow;
            var searcher    = new MockSearcher(indexName, numDocs, commitUserData, versions: null, reloadTime: currentTime, lastModifiedTimeForAuxFiles: auxFileData, machineName: "TestMachineX");

            var sb = new StringBuilder();
            var sw = new StringWriter(sb);

            using (var writer = new JsonTextWriter(sw))
            {
                ResponseFormatter.WriteStatsResult(writer, searcher);
                var expectedResult = string.Format(
                    expected,
                    searcher.Manager.MachineName.ToString(),
                    searcher.LastReopen.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'FFFFFFFK"),
                    searcher.Manager.LastIndexReloadTime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'FFFFFFFK"),
                    searcher.Manager.LastAuxiliaryDataLoadTime.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'FFFFFFFK")
                    );

                Assert.Equal(expectedResult, sb.ToString());
            }
        }
コード例 #3
0
        public void FormatarResposta_TipoRequisicao_GET_Lista()
        {
            var notificador       = new Notificador();
            var responseFormatter = new ResponseFormatter(notificador);
            var editoras          = new List <EditoraViewModel>
            {
                new()
                {
                    Id    = Guid.NewGuid(),
                    Nome  = "Editora",
                    Email = "*****@*****.**",
                    Pais  = "Brasil"
                }
            };

            var resposta = new Response <IEnumerable <EditoraViewModel> >(editoras, notificador);

            var resultado = responseFormatter.FormatarResposta(TipoRequisicao.Get, editoras);

            resultado.Should().BeOfType <OkObjectResult>()
            .Which.Value.Should().BeEquivalentTo(resposta);

            resultado.Should().BeOfType <OkObjectResult>()
            .Which.StatusCode.Should().Be((int)HttpStatusCode.OK);
        }
コード例 #4
0
ファイル: SMHelp.cs プロジェクト: PaulHutson/SlackMUDRPG
        /// <summary>
        /// SMHelp class constructor, populate commandsList
        /// </summary>
        public SMHelp(string UserId)
        {
            this.commandList = this.GetCommandsList();

            this.character = new SlackMud().GetCharacter(UserId);

            this.responseFormatter = ResponseFormatterFactory.Get();
        }
コード例 #5
0
        public async void Update([FromBody] Update update)
        {
            if (update.Type != UpdateType.Message)
            {
                return;
            }

            long chatId = update.Message.Chat.Id;

            try
            {
                AssureTextMessage(update.Message);
                if (string.Equals(update.Message.Text, "/start", StringComparison.InvariantCultureIgnoreCase))
                {
                    await bot.SendTextMessageAsync(chatId, "Hello! This bot will download videos from YouTube for you.\nJust send me the link.");

                    return;
                }
            }
            catch (ArgumentException)
            {
                await bot.SendTextMessageAsync(chatId,
                                               "_Sorry, I don't understand you.\n I **only** understand links from **YouTube**._",
                                               ParseMode.Markdown);

                return;
            }

            string fullVideoUrl = update.Message.Text;
            IList <DownloadLink> links;

            try
            {
                links = await YoutubeVideoDownloader.GetDownloadLinksAsync(
                    videoDownloadSettings,
                    fullVideoUrl,
                    () => OnNotLoading(chatId),
                    shortenLinks : true,
                    bitLySettings : bitLySettings
                    );
            }
            catch (HttpRequestException)
            {
                await bot.SendTextMessageAsync(chatId,
                                               "_Sorry, looks like the link you provided is **invalid**.\nOr the service is down =( Maybe try later._",
                                               ParseMode.Markdown);

                return;
            }

            var response = ResponseFormatter.GetFormattedResponse(links);

            foreach (var kv in response)
            {
                await bot.SendTextMessageAsync(chatId, kv.Key, parseMode : ParseMode.Markdown, replyMarkup : kv.Value);
            }
        }
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            Type resultType = context.Result.GetType();

            ResponseFormatter appropriateFormatter = _responseFormatters
                                                     .Single(formatter => formatter.ResultTypeToFormat == resultType);

            appropriateFormatter.ContextResult(context);
        }
コード例 #7
0
        public void FormatarResposta_SemRetorno_TipoRequisicao_GET_Lista()
        {
            var notificador       = new Notificador();
            var responseFormatter = new ResponseFormatter(notificador);
            var editoras          = new List <EditoraViewModel>();

            var resultado = responseFormatter.FormatarResposta(TipoRequisicao.Get, editoras);

            resultado.Should().BeOfType <NoContentResult>()
            .Which.StatusCode.Should().Be((int)HttpStatusCode.NoContent);
        }
コード例 #8
0
 public async Task <IActionResult> CreateRepositoryObject([FromServices] IRepositoryService repositoryService, string database, string collection, [FromBody] Repository repoObject)
 {
     try
     {
         return(ResponseFormatter.ResponseOK(await repositoryService.Create(database, collection, repoObject), "Created"));
     }
     catch (Exception exc)
     {
         return(ResponseFormatter.ResponseBadRequest(exc, "Create failed."));
     }
 }
コード例 #9
0
        public void WriteV2CountResultTest(int totalHits, string expected)
        {
            var sb = new StringBuilder();
            var sw = new StringWriter(sb);

            using (var writer = new JsonTextWriter(sw))
            {
                ResponseFormatter.WriteV2CountResult(writer, totalHits);

                Assert.Equal(expected, sb.ToString());
            }
        }
コード例 #10
0
        public async Task <IActionResult> GetAllRepositoryObjects([FromServices] IRepositoryService repositoryService, string database, string collection, string _id)
        {
            try
            {
                List <Repository> found = repositoryService.ReadAll(database, collection);

                return(ResponseFormatter.ResponseOK(found));
            }
            catch (Exception exc)
            {
                return(ResponseFormatter.ResponseBadRequest(exc, "Read All failed."));
            }
        }
コード例 #11
0
        public async Task <IActionResult> GetRepositoryObject([FromServices] IRepositoryService repositoryService, string database, string collection, string _id)
        {
            try
            {
                Repository found = await repositoryService.Read(_id, database, collection);

                return(ResponseFormatter.ResponseOK(found));
            }
            catch (Exception exc)
            {
                return(ResponseFormatter.ResponseBadRequest(exc, "Read failed."));
            }
        }
コード例 #12
0
        public async Task <IActionResult> GetCollections([FromServices] IRepositoryService repositoryService, string database)
        {
            try
            {
                List <string> found = await repositoryService.GetCollections(database);

                return(ResponseFormatter.ResponseOK(found));
            }
            catch (Exception exc)
            {
                return(ResponseFormatter.ResponseBadRequest(exc, "Get collections failed."));
            }
        }
コード例 #13
0
        public async Task <IActionResult> DeleteRepositoryObject([FromServices] IRepositoryService repositoryService, string database, string collection, string _id, [FromBody] Repository repoObject)
        {
            try
            {
                await repositoryService.Delete(database, collection, _id);

                return(ResponseFormatter.ResponseOK($"_id: {_id} deleted."));
            }
            catch (Exception exc)
            {
                return(ResponseFormatter.ResponseBadRequest(exc, $"Delete failed for _id: {_id}."));
            }
        }
コード例 #14
0
    public async Task <Result> ProcessAsync(UserMessage request)
    {
        if (string.IsNullOrWhiteSpace(request.Message))
        {
            return(new Result.Error(new ArgumentException("Cannot be empty or whitespace", nameof(request.Message))));
        }

        var userCommands = await _storage.GetUserCommandsAsync(request.UserId);

        var(query, shard) = MessageParser.Parse(userCommands, request);
        await _storage.SaveAsync(shard);

        return(ResponseFormatter.Format(query, await _storage.FetchAsync(query)));
    }
コード例 #15
0
        static void WriteResponseForGetTime(HttpRequest request, HttpResponse response)
        {
            var body = new ResponseFormatter(response, formatBody: true);

            body.Format(@"<html><head><title>Time</title></head><body>{0:O}</body></html>", DateTime.UtcNow);

            WriteCommonHeaders(response, HttpVersion.V1_1, 200, "OK", keepAlive: false);
            var headers = new ResponseFormatter(response, formatBody: false);

            headers.Append("Content-Length : ");
            headers.Append(response.BodyLength);
            headers.AppendHttpNewLine();
            headers.AppendHttpNewLine();
        }
コード例 #16
0
        public void FormatarResposta_TipoRequisicao_DELETE()
        {
            var notificador = new Notificador();
            var formatter   = new ResponseFormatter(notificador);
            var editora     = new EditoraViewModel
            {
                Id    = Guid.NewGuid(),
                Nome  = "Editora",
                Email = "*****@*****.**",
                Pais  = "Brasil"
            };

            var resultado = formatter.FormatarResposta(TipoRequisicao.Delete, editora);

            resultado.Should().BeOfType <NoContentResult>();
        }
コード例 #17
0
        public async Task <IActionResult> QueryByTagRepositoryObject([FromServices] IRepositoryService repositoryService, string database, string collection, string tag)
        {
            try
            {
                List <Repository> found = repositoryService.QueryByTag(database, collection, tag);

                if (found.Count == 0)
                {
                    return(ResponseFormatter.ResponseNotFound(string.Format("check query string argument tag={0}", tag)));
                }

                return(ResponseFormatter.ResponseOK(found));
            }
            catch (Exception exc)
            {
                return(ResponseFormatter.ResponseBadRequest(exc, "Query failed."));
            }
        }
コード例 #18
0
        public void FormatarResposta_ComErroComStatusCodeNotFound_ObjetoUnico()
        {
            var notificador = new Notificador();

            notificador.AdicionarErro("erro", "mensagem", HttpStatusCode.NotFound);
            var responseFormatter = new ResponseFormatter(notificador);
            var editora           = new EditoraViewModel
            {
                Id    = Guid.NewGuid(),
                Nome  = "Editora",
                Email = "*****@*****.**",
                Pais  = "Brasil"
            };

            var resultado = responseFormatter.FormatarResposta(TipoRequisicao.Get, editora);

            resultado.Should().BeOfType <ObjectResult>()
            .Which.StatusCode.Should().Be((int)HttpStatusCode.NotFound);
        }
コード例 #19
0
        public void WriteSearchResultTest(
            string indexName,
            int numDocs,
            Dictionary <string, string> commitUserData,
            int topDocsTotalHits,
            float topDocsMaxScore,
            int skip,
            int take,
            bool includePrerelease,
            bool includeExplanation,
            NuGetVersion semVerlLevel,
            string scheme,
            string expectedBaseUrl,
            string expected)
        {
            var searcher = new MockSearcher(indexName, numDocs, commitUserData, versions: Constants.VersionResults);
            var topDocs  = new TopDocs(topDocsTotalHits, Constants.ScoreDocs, topDocsMaxScore);

            var sb = new StringBuilder();
            var sw = new StringWriter(sb);

            using (var writer = new JsonTextWriter(sw))
            {
                ResponseFormatter.WriteSearchResult(writer, searcher, scheme, topDocs, skip, take, includePrerelease, includeExplanation, semVerlLevel, NuGetQuery.MakeQuery("test"));

                Assert.Equal(string.Format(expected,
                                           expectedBaseUrl,
                                           searcher.LastReopen,
                                           Constants.MockBase.ToLower(),
                                           Constants.LucenePropertyId.ToLower(),
                                           Constants.MockBase,
                                           Constants.LucenePropertyId,
                                           Constants.LucenePropertyFullVersion,
                                           Constants.LucenePropertyDescription,
                                           Constants.LucenePropertySummary,
                                           Constants.LucenePropertyTitle,
                                           Constants.LucenePropertyIconUrl,
                                           Constants.LucenePropertyLicenseUrl,
                                           Constants.LucenePropertyProjectUrl), sb.ToString());
            }
        }
コード例 #20
0
        static void WriteResponseForHelloWorld(HttpRequest request, HttpResponse response)
        {
            var body = new ResponseFormatter(response, formatBody: true);

            body.Append("Hello, World");

            var headers = new ResponseFormatter(response, formatBody: false);

            headers.AppendHttpStatusLine(HttpVersion.V1_1, 200, new Utf8String("OK"));
            headers.Append("Content-Length : ");
            headers.Append(response.BodyLength);
            headers.AppendHttpNewLine();
            headers.Append("Content-Type : text/plain; charset=UTF-8");
            headers.AppendHttpNewLine();
            headers.Append("Server : .NET Core Sample Server");
            headers.AppendHttpNewLine();
            headers.Append("Date : ");
            headers.Append(DateTime.UtcNow, 'R');
            headers.AppendHttpNewLine();
            headers.AppendHttpNewLine();
        }
コード例 #21
0
ファイル: Interpreter.cs プロジェクト: NeuroXiq/Vinca
        private void SendHeader(Session session, ResponseHeader responseSession)
        {
            ResponseFormatter formatter = new ResponseFormatter();
            int len = formatter.FormattedLength(responseSession);

            byte[] buf = BufferPool.Take(len);

            len = formatter.GetBytes(buf, 0, responseSession);
            string response = Encoding.ASCII.GetString(buf, 0, len);

            try
            {
                session.Send(buf, 0, len);
            }
            catch (Exception e)
            {
                BufferPool.Free(buf);
                throw;
            }
            BufferPool.Free(buf);
        }
コード例 #22
0
        public async Task <IActionResult> UpdateRepositoryObject([FromServices] IRepositoryService repositoryService, string database, string collection, [FromBody] Repository repoObject)
        {
            try
            {
                await repositoryService.Update(database, collection, repoObject);
            }
            catch (Exception exc)
            {
                return(ResponseFormatter.ResponseBadRequest(exc, "Update failed."));
            }
            try
            {
                await repositoryService.Update(database, collection, repoObject);

                return(ResponseFormatter.ResponseOK(repoObject, "Updated"));
            }
            catch (Exception exc)
            {
                return(ResponseFormatter.ResponseBadRequest(exc, "Retreiving Update failed. Record may still have been written."));
            }
        }
コード例 #23
0
        public void WriteAutoCompleteVersionResultTest(
            string indexName,
            int numDocs,
            Dictionary <string, string> commitUserData,
            int topDocsTotalHits,
            float topDocsMaxScore,
            bool includePrerelease,
            string expected)
        {
            var searcher = new MockSearcher(indexName, numDocs, commitUserData, versions: Constants.VersionResults);
            var topDocs  = new TopDocs(topDocsTotalHits, Constants.ScoreDocs, topDocsMaxScore);

            var sb = new StringBuilder();
            var sw = new StringWriter(sb);

            using (var writer = new JsonTextWriter(sw))
            {
                ResponseFormatter.WriteAutoCompleteVersionResult(writer, searcher, includePrerelease, SemVerHelpers.SemVer2Level, topDocs);

                Assert.Equal(string.Format(expected, searcher.LastReopen), sb.ToString());
            }
        }
コード例 #24
0
        public void FormatarResposta_TipoRequisicao_PATCH()
        {
            var notificador = new Notificador();
            var formatter   = new ResponseFormatter(notificador);
            var editora     = new EditoraViewModel
            {
                Id    = Guid.NewGuid(),
                Nome  = "Editora",
                Email = "*****@*****.**",
                Pais  = "Brasil"
            };

            var resposta = new Response <EditoraViewModel>(editora, notificador);

            var resultado = formatter.FormatarResposta(TipoRequisicao.Patch, editora);

            resultado.Should().BeOfType <AcceptedResult>()
            .Which.Value.Should().BeEquivalentTo(resposta);

            resultado.Should().BeOfType <AcceptedResult>()
            .Which.StatusCode.Should().Be((int)HttpStatusCode.Accepted);
        }
コード例 #25
0
        public void FormatarResposta_ComErroSemStatusCode_Lista()
        {
            var notificador = new Notificador();

            notificador.AdicionarErro("erro", "mensagem");
            var responseFormatter = new ResponseFormatter(notificador);
            var editora           = new List <EditoraViewModel>
            {
                new()
                {
                    Id    = Guid.NewGuid(),
                    Nome  = "Editora",
                    Email = "*****@*****.**",
                    Pais  = "Brasil"
                }
            };

            var resultado = responseFormatter.FormatarResposta(TipoRequisicao.Get, editora);

            resultado.Should().BeOfType <BadRequestObjectResult>()
            .Which.StatusCode.Should().Be((int)HttpStatusCode.BadRequest);
        }
コード例 #26
0
        void WriteResponseForPostJson(HttpRequest request, HttpResponse response)
        {
            // read request json
            int requestedCount;

            // TODO: this should not conver to span
            using (var dom = JsonObject.Parse(request.Body.ToSpan())) {
                requestedCount = (int)dom["Count"];
            }

            // write response JSON
            var jsonWriter = new JsonWriter <ResponseFormatter>(new ResponseFormatter(response, formatBody: true), prettyPrint: false);

            jsonWriter.WriteObjectStart();
            jsonWriter.WriteArrayStart();
            for (int i = 0; i < requestedCount; i++)
            {
                jsonWriter.WriteString("hello!");
            }
            jsonWriter.WriteArrayEnd();
            jsonWriter.WriteObjectEnd();

            // write headers
            var headers = new ResponseFormatter(response, formatBody: false);

            headers.AppendHttpStatusLine(HttpVersion.V1_1, 200, new Utf8String("OK"));
            headers.Append("Content-Length : ");
            headers.Append(response.BodyLength);
            headers.AppendHttpNewLine();
            headers.Append("Content-Type : text/plain; charset=UTF-8");
            headers.AppendHttpNewLine();
            headers.Append("Server : .NET Core Sample Server");
            headers.AppendHttpNewLine();
            headers.Append("Date : ");
            headers.Append(DateTime.UtcNow, 'R');
            headers.AppendHttpNewLine();
            headers.AppendHttpNewLine();
        }
コード例 #27
0
        public void WriteV2ResultTest(
            string indexName,
            int numDocs,
            Dictionary <string, string> commitUserData,
            int topDocsTotalHits,
            float topDocsMaxScore,
            int skip,
            int take,
            string expected)
        {
            var searcher = new MockSearcher(indexName, numDocs, commitUserData, versions: Constants.VersionResults);
            var topDocs  = new TopDocs(topDocsTotalHits, Constants.ScoreDocs, topDocsMaxScore);

            var sb = new StringBuilder();
            var sw = new StringWriter(sb);

            using (var writer = new JsonTextWriter(sw))
            {
                ResponseFormatter.WriteV2Result(writer, searcher, topDocs, skip, take, SemVerHelpers.SemVer2Level);

                var result = sb.ToString();
                Assert.Equal(expected, result);
            }
        }
コード例 #28
0
 public IActionResult GetVersion([FromServices] IAdminService instrumentation)
 {
     return(ResponseFormatter.ResponseOK((new JProperty("Version", instrumentation.version()))));
 }
コード例 #29
0
 public IActionResult GetPing()
 {
     return(ResponseFormatter.ResponseOK((new JProperty("Ping", "Success"))));
 }
コード例 #30
0
 public IActionResult Kill([FromServices] IAdminService instrument)
 {
     return(ResponseFormatter.ResponseOK(instrument.kill()));
 }