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());
            }
        }
        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());
            }
        }
Beispiel #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);
        }
Beispiel #4
0
        /// <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();
        }
Beispiel #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);
        }
Beispiel #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);
        }
 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."));
     }
 }
        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());
            }
        }
        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."));
            }
        }
        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."));
            }
        }
        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."));
            }
        }
        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}."));
            }
        }
Beispiel #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)));
    }
Beispiel #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();
        }
Beispiel #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>();
        }
        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."));
            }
        }
Beispiel #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);
        }
        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());
            }
        }
Beispiel #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();
        }
Beispiel #21
0
        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);
        }
        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."));
            }
        }
        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());
            }
        }
Beispiel #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);
        }
Beispiel #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);
        }
Beispiel #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();
        }
        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);
            }
        }
 public IActionResult GetVersion([FromServices] IAdminService instrumentation)
 {
     return(ResponseFormatter.ResponseOK((new JProperty("Version", instrumentation.version()))));
 }
 public IActionResult GetPing()
 {
     return(ResponseFormatter.ResponseOK((new JProperty("Ping", "Success"))));
 }
 public IActionResult Kill([FromServices] IAdminService instrument)
 {
     return(ResponseFormatter.ResponseOK(instrument.kill()));
 }