public void MediaTypeMappingTakesPrecedenceOverAcceptHeader() { // Prepare the request message _request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); _request.Headers.Add("Browser", "IE"); _request.Headers.Add("Cookie", "ABC"); // Prepare the formatters List<MediaTypeFormatter> formatters = new List<MediaTypeFormatter>(); formatters.Add(new JsonMediaTypeFormatter()); formatters.Add(new XmlMediaTypeFormatter()); PlainTextFormatter frmtr = new PlainTextFormatter(); frmtr.SupportedMediaTypes.Clear(); frmtr.MediaTypeMappings.Clear(); frmtr.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml")); frmtr.MediaTypeMappings.Add(new MyMediaTypeMapping(new MediaTypeHeaderValue(("application/xml")))); formatters.Add(frmtr); // Act var result = _negotiator.Negotiate(typeof(string), _request, formatters); // Assert Assert.NotNull(result); Assert.Equal("application/xml", result.MediaType.MediaType); Assert.IsType<PlainTextFormatter>(result.Formatter); }
public void Type_specific_formatter_is_preferred_over_generic_formatter() { // There is a specific default formatter registered for ReadOnlyMemory<char>, check // it is selected var formatter = PlainTextFormatter.GetBestFormatterFor(typeof(ReadOnlyMemory <char>)); formatter.GetType().Should().Be(typeof(PlainTextFormatter <ReadOnlyMemory <char> >)); formatter.Type.Should().Be(typeof(ReadOnlyMemory <char>)); var formatter2 = PlainTextFormatter.GetBestFormatterFor(typeof(ReadOnlyMemory <int>)); formatter2.Type.Should().Be(typeof(ReadOnlyMemory <>)); }
public void Formatter_expands_IEnumerable() { var list = new List <string> { "this", "that", "the other thing" }; var formatter = PlainTextFormatter.GetBestFormatterFor(list.GetType()); var formatted = list.ToDisplayString(formatter); formatted.Should() .Be("[ this, that, the other thing ]"); }
public void Formatter_expands_properties_of_ExpandoObjects() { dynamic expando = new ExpandoObject(); expando.Name = "socks"; expando.Parts = null; var formatter = PlainTextFormatter.GetBestFormatterFor <ExpandoObject>(); var expandoString = ((object)expando).ToDisplayString(formatter); expandoString.Should().Be("{ Name: socks, Parts: <null> }"); }
public void It_expands_properties_of_structs() { var id = new EntityId("the typename", "the id"); var formatter = PlainTextFormatter.GetPreferredFormatterFor(id.GetType()); var formatted = id.ToDisplayString(formatter); formatted.Should() .Contain("TypeName: the typename") .And .Contain("Id: the id"); }
public void Recursive_formatter_calls_do_not_cause_exceptions() { var widget = new Widget(); widget.Parts = new List <Part> { new Part { Widget = widget } }; var formatter = PlainTextFormatter.GetPreferredFormatterFor(widget.GetType()); widget.Invoking(w => w.ToDisplayString(formatter)).Should().NotThrow(); }
private string GetNamespacePerLanguage(ILanguage language, string @namespace) { var formatter = new PlainTextFormatter(new StringWriter()); IWriterSettings settings = new WriterSettings(writeExceptionsAsComments: true, renameInvalidMembers: true); ILanguageWriter writer = language.GetWriter(formatter, SimpleExceptionFormatter.Instance, settings); writer.ExceptionThrown += OnExceptionThrown; writer.WriteNamespaceNavigationName(@namespace); writer.ExceptionThrown -= OnExceptionThrown; return(formatter.ToString()); }
public void It_emits_the_property_names_and_values_for_a_specific_type() { var formatter = PlainTextFormatter.GetPreferredFormatterFor <Widget>(); var writer = new StringWriter(); formatter.Format(new Widget { Name = "Bob" }, writer); var s = writer.ToString(); s.Should().Contain("Name: Bob"); }
public void It_emits_a_configurable_maximum_number_of_properties() { var formatter = PlainTextFormatter.GetPreferredFormatterFor <Dummy.DummyClassWithManyProperties>(); PlainTextFormatter.MaxProperties = 1; var writer = new StringWriter(); formatter.Format(new Dummy.DummyClassWithManyProperties(), writer); var s = writer.ToString(); s.Should().Be("{ Dummy.DummyClassWithManyProperties: X1: 1, .. }"); }
public void When_Zero_properties_chosen_just_ToString_is_used() { var formatter = PlainTextFormatter.GetPreferredFormatterFor <Dummy.DummyClassWithManyProperties>(); PlainTextFormatter.MaxProperties = 0; var writer = new StringWriter(); formatter.Format(new Dummy.DummyClassWithManyProperties(), writer); var s = writer.ToString(); s.Should().Be("Dummy.DummyClassWithManyProperties"); }
public void PlainTextFormatter_returns_plain_for_BigInteger() { var formatter = PlainTextFormatter.GetPreferredFormatterFor(typeof(BigInteger)); var writer = new StringWriter(); var instance = BigInteger.Parse("78923589327589332402359"); formatter.Format(instance, writer); writer.ToString() .Should() .Be("78923589327589332402359"); }
public void It_expands_fields_of_objects() { var formatter = PlainTextFormatter.GetPreferredFormatterFor <SomeStruct>(); var today = DateTime.Today; var tomorrow = DateTime.Today.AddDays(1); var id = new SomeStruct { DateField = today, DateProperty = tomorrow }; var output = id.ToDisplayString(formatter); output.Should().Contain("DateField: "); output.Should().Contain("DateProperty: "); }
public void TestGetFormattedText_WithTemplate() { var sr = new StructuredText(); sr.AddHeader1("Überschrift 1"); sr.AddParagraph(MassText); sr.AddDefinitionListLine("Def1", "Value1"); sr.AddDefinitionListLine("Definition 2", "Value1234"); sr.AddDefinitionListLine("Defini 3", "Value234556666"); sr.AddParagraph(""); sr.AddParagraph(MassText); sr.AddListItem("Bahnhof"); sr.AddListItem("HauptBahnhof"); sr.AddListItem("SüdBahnhof"); sr.AddHeader1("Überschrift 2"); sr.AddParagraph(MassText); sr.AddParagraph(MassText); sr.AddHeader1("Überschrift 2"); sr.AddParagraph(MassText); sr.AddHeader1("Überschrift 1"); sr.AddParagraph(MassText); sr.AddParagraph(MassText); sr.AddParagraph(MassText); sr.AddHeader1("Überschrift 2"); sr.AddParagraph(MassText); sr.AddParagraph(MassText); sr.AddParagraph(MassText); sr.AddParagraph(MassText); sr.AddHeader1("Überschrift 2"); sr.AddParagraph(MassText); sr.AddHeader1("Überschrift 1"); sr.AddParagraph(MassText); sr.AddParagraph(MassText); var f = new PlainTextFormatter { StructuredText = sr, Template = "<<<Start>>>{0}<<<Ende>>>" }; var result = f.GetFormattedText(); Debug.Print(result); Assert.IsTrue(!string.IsNullOrEmpty(result)); }
public void CreateForMembers_emits_the_specified_property_names_and_values_for_a_specific_type() { var formatter = PlainTextFormatter <SomethingWithLotsOfProperties> .CreateForMembers( o => o.DateProperty, o => o.StringProperty); var s = new SomethingWithLotsOfProperties { DateProperty = DateTime.MinValue, StringProperty = "howdy" }.ToDisplayString(formatter); s.Should().Contain("DateProperty: 0001-01-01 00:00:00Z"); s.Should().Contain("StringProperty: howdy"); s.Should().NotContain("IntProperty"); s.Should().NotContain("BoolProperty"); s.Should().NotContain("UriProperty"); }
public async Task <IHttpActionResult> UpdateOne(string id, [NotNull] ArticleCommentUpdateOneRequestDto requestDto) { var comment = await _dbContext.ArticleComments.FindAsync(id); if (comment == null) { return(NotFound()); } var userId = User.Identity.GetUserId(); if (comment.CommentatorId != userId && !User.IsInRole(KeylolRoles.Operator)) { return(Unauthorized()); } comment.Content = ArticleController.SanitizeRichText(requestDto.Content); comment.UnstyledContent = PlainTextFormatter.FlattenHtml(comment.Content, false); if (requestDto.ReplyToComment != null) { var replyToComment = await _dbContext.ArticleComments .Where(c => c.ArticleId == comment.ArticleId && c.SidForArticle == requestDto.ReplyToComment) .SingleOrDefaultAsync(); if (replyToComment != null) { comment.ReplyToComment = replyToComment; } } else { comment.ReplyToCommentId = null; } await _dbContext.SaveChangesAsync(); _mqChannel.SendMessage(string.Empty, MqClientProvider.ImageGarageRequestQueue, new ImageGarageRequestDto { ContentType = ImageGarageRequestContentType.ArticleComment, ContentId = comment.Id }); return(Ok()); }
public void Should_write_string_to_stream() { var formatter = new PlainTextFormatter(); var contentHeader = new StringContent(string.Empty).Headers; contentHeader.Clear(); var memoryStream = new MemoryStream(); var value = "Hello World"; var resultTask = formatter.WriteToStreamAsync(typeof(string), value, memoryStream, contentHeader, transportContext: null); resultTask.Wait(); memoryStream.Position = 0; string serializedString = new StreamReader(memoryStream).ReadToEnd(); serializedString.ShouldEqual(value); }
public void Formatter_truncates_expansion_of_long_IDictionary() { var list = new Dictionary <string, int>(); for (var i = 1; i < 11; i++) { list.Add("number " + i, i); } Formatter.ListExpansionLimit = 4; var formatter = PlainTextFormatter.GetPreferredFormatterFor(list.GetType()); var formatted = list.ToDisplayString(formatter); formatted.Contains("number 1").Should().BeTrue(); formatted.Contains("number 4").Should().BeTrue(); formatted.Should().NotContain("number 5"); formatted.Contains("6 more").Should().BeTrue(); }
public void Should_write_UTF8_string_to_stream() { var formatter = new PlainTextFormatter(Encoding.UTF8); var content = new StringContent(string.Empty); content.Headers.Clear(); var memoryStream = new MemoryStream(); var value = "Bonjour tout le monde français"; var resultTask = formatter.WriteToStreamAsync(typeof(string), value, memoryStream, content, transportContext: null); resultTask.Wait(); memoryStream.Position = 0; string serializedString = new StreamReader(memoryStream, Encoding.UTF8).ReadToEnd(); serializedString.ShouldEqual(value); }
public void Formatter_truncates_expansion_of_long_IEnumerable() { var list = new List <string>(); for (var i = 1; i < 11; i++) { list.Add("number " + i); } Formatter.ListExpansionLimit = 4; var formatter = PlainTextFormatter.Create(list.GetType()); var formatted = list.ToDisplayString(formatter); formatted.Contains("number 1").Should().BeTrue(); formatted.Contains("number 4").Should().BeTrue(); formatted.Should().NotContain("number 5"); formatted.Contains("6 more").Should().BeTrue(); }
public void Formatter_truncates_expansion_of_ICollection() { var list = new List <string>(); for (var i = 1; i < 11; i++) { list.Add("number " + i); } Formatter.ListExpansionLimit = 4; var formatter = PlainTextFormatter.GetPreferredFormatterFor(typeof(ICollection)); var formatted = list.ToDisplayString(formatter); formatted.Contains("number 1").Should().BeTrue(); formatted.Contains("number 4").Should().BeTrue(); formatted.Should().NotContain("number 5"); formatted.Should().Contain("6 more"); }
public void Formatter_recursively_formats_types_within_IEnumerable() { var list = new List <Widget> { new Widget { Name = "widget x" }, new Widget { Name = "widget y" }, new Widget { Name = "widget z" } }; var formatter = PlainTextFormatter.GetPreferredFormatterFor <List <Widget> >(); var formatted = list.ToDisplayString(formatter); formatted.Should().Be("[ { Microsoft.DotNet.Interactive.Formatting.Tests.Widget: Name: widget x, Parts: <null> }, { Microsoft.DotNet.Interactive.Formatting.Tests.Widget: Name: widget y, Parts: <null> }, { Microsoft.DotNet.Interactive.Formatting.Tests.Widget: Name: widget z, Parts: <null> } ]"); }
public void Formatter_recursively_formats_types_within_IEnumerable() { var list = new List <Widget> { new Widget { Name = "widget x" }, new Widget { Name = "widget y" }, new Widget { Name = "widget z" } }; var formatter = PlainTextFormatter <List <Widget> > .Create(); var formatted = list.ToDisplayString(formatter); formatted.Should().Be("[ { Widget: Name: widget x, Parts: <null> }, { Widget: Name: widget y, Parts: <null> }, { Widget: Name: widget z, Parts: <null> } ]"); }
public static void Register(HttpConfiguration config) { // Web API configuration and services PlainTextFormatter = new PlainTextFormatter(); XmlMediaTypeFormatter = config.Formatters.XmlFormatter; JsonMediaTypeFormatter = config.Formatters.JsonFormatter; config.Services.Add(typeof(IExceptionLogger), new ElmahExceptionLogger()); config.Formatters.Add(PlainTextFormatter); config.Formatters.JsonFormatter.Indent = true; config.Formatters.XmlFormatter.UseXmlSerializer = true; config.Formatters.XmlFormatter.WriterSettings.OmitXmlDeclaration = false; // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
public void Formatter_does_not_expand_string() { var widget = new Widget { Name = "hello" }; widget.Parts = new List <Part> { new Part { Widget = widget } }; var formatter = PlainTextFormatter.GetPreferredFormatterFor <Widget>(); // this should not throw var s = widget.ToDisplayString(formatter); s.Should() .Contain("hello") .And .NotContain("{ h },{ e }"); }
public void InstanceMethods_ShouldHaveCorrectGuardClauses() { var sut = new PlainTextFormatter(); typeof(PlainTextFormatter).VerifyInstanceMethodGuards(sut).Should().Be(1); }
public async Task <IHttpActionResult> CreateOne([NotNull] ArticleCreateOrUpdateOneRequestDto requestDto) { var userId = User.Identity.GetUserId(); if (!await _coupon.CanTriggerEventAsync(userId, CouponEvent.发布文章)) { return(Unauthorized()); } var article = new Models.Article { AuthorId = userId, Title = requestDto.Title, Content = SanitizeRichText(requestDto.Content), CoverImage = SanitizeCoverImage(requestDto.CoverImage) }; article.UnstyledContent = PlainTextFormatter.FlattenHtml(article.Content, true); if (!string.IsNullOrWhiteSpace(requestDto.Subtitle)) { article.Subtitle = requestDto.Subtitle; } var targetPoint = await _dbContext.Points.Where(p => p.Id == requestDto.TargetPointId).SingleOrDefaultAsync(); if (targetPoint == null) { return(this.BadRequest(nameof(requestDto), nameof(requestDto.TargetPointId), Errors.NonExistent)); } targetPoint.LastActivityTime = DateTime.Now; article.TargetPointId = targetPoint.Id; requestDto.AttachedPointIds = requestDto.AttachedPointIds.Select(id => id.Trim()) .Where(id => id != targetPoint.Id).Distinct().ToList(); article.AttachedPoints = JsonConvert.SerializeObject(requestDto.AttachedPointIds); if (targetPoint.Type == PointType.Game || targetPoint.Type == PointType.Hardware) { article.Rating = requestDto.Rating; article.Pros = JsonConvert.SerializeObject(requestDto.Pros ?? new List <string>()); article.Cons = JsonConvert.SerializeObject(requestDto.Cons ?? new List <string>()); } if (requestDto.ReproductionRequirement != null) { article.ReproductionRequirement = JsonConvert.SerializeObject(requestDto.ReproductionRequirement); } _dbContext.Articles.Add(article); article.SidForAuthor = await _dbContext.Articles.Where(a => a.AuthorId == article.AuthorId) .Select(a => a.SidForAuthor) .DefaultIfEmpty(0) .MaxAsync() + 1; await _dbContext.SaveChangesAsync(); await _coupon.UpdateAsync(await _userManager.FindByIdAsync(userId), CouponEvent.发布文章, new { ArticleId = article.Id }); _mqChannel.SendMessage(string.Empty, MqClientProvider.PushHubRequestQueue, new PushHubRequestDto { Type = ContentPushType.Article, ContentId = article.Id }); _mqChannel.SendMessage(string.Empty, MqClientProvider.ImageGarageRequestQueue, new ImageGarageRequestDto { ContentType = ImageGarageRequestContentType.Article, ContentId = article.Id }); SteamCnProvider.TriggerArticleUpdate(); return(Ok(article.SidForAuthor)); }
public void Non_generic_GetBestFormatter_uses_default_formatter_for_object() { PlainTextFormatter.GetBestFormatterFor(typeof(Widget)) .Should() .BeOfType <PlainTextFormatter <object> >(); }
public void GetBestFormatter_for_List_uses_default_formatter_for_enumerable() { PlainTextFormatter.GetBestFormatterFor(typeof(List <int>)) .Should() .BeOfType <PlainTextFormatter <IEnumerable> >(); }
public void Non_generic_Create_creates_generic_formatter() { PlainTextFormatter.Create(typeof(Widget)) .Should() .BeOfType <PlainTextFormatter <Widget> >(); }
public async Task <IHttpActionResult> UpdateOne(string id, [NotNull] ArticleCreateOrUpdateOneRequestDto requestDto) { var article = await _dbContext.Articles.FindAsync(id); if (article == null) { return(NotFound()); } var userId = User.Identity.GetUserId(); if (article.AuthorId != userId && !User.IsInRole(KeylolRoles.Operator)) { return(Unauthorized()); } article.Title = requestDto.Title; article.Subtitle = string.IsNullOrWhiteSpace(requestDto.Subtitle) ? string.Empty : requestDto.Subtitle; article.Content = SanitizeRichText(requestDto.Content); article.UnstyledContent = PlainTextFormatter.FlattenHtml(article.Content, true); article.CoverImage = SanitizeCoverImage(requestDto.CoverImage); var targetPoint = await _dbContext.Points.Where(p => p.Id == requestDto.TargetPointId) .Select(p => new { p.Id, p.Type }).SingleOrDefaultAsync(); if (targetPoint == null) { return(this.BadRequest(nameof(requestDto), nameof(requestDto.TargetPointId), Errors.NonExistent)); } if (targetPoint.Type == PointType.Game || targetPoint.Type == PointType.Hardware) { article.Rating = requestDto.Rating; article.Pros = JsonConvert.SerializeObject(requestDto.Pros ?? new List <string>()); article.Cons = JsonConvert.SerializeObject(requestDto.Cons ?? new List <string>()); } else { article.Rating = null; article.Pros = string.Empty; article.Cons = string.Empty; } article.ReproductionRequirement = requestDto.ReproductionRequirement == null ? string.Empty : JsonConvert.SerializeObject(requestDto.ReproductionRequirement); await _dbContext.SaveChangesAsync(); var oldAttachedPoints = Helpers.SafeDeserialize <List <string> >(article.AttachedPoints) ?? new List <string>(); if (requestDto.TargetPointId != article.TargetPointId || !requestDto.AttachedPointIds.OrderBy(s => s).SequenceEqual(oldAttachedPoints.OrderBy(s => s))) { article.TargetPointId = targetPoint.Id; requestDto.AttachedPointIds = requestDto.AttachedPointIds.Select(pointId => pointId.Trim()) .Where(pointId => pointId != targetPoint.Id.Trim()).Distinct().ToList(); article.AttachedPoints = JsonConvert.SerializeObject(requestDto.AttachedPointIds); await _dbContext.SaveChangesAsync(); _mqChannel.SendMessage(string.Empty, MqClientProvider.PushHubRequestQueue, new PushHubRequestDto { Type = ContentPushType.Article, ContentId = article.Id }); } _mqChannel.SendMessage(string.Empty, MqClientProvider.ImageGarageRequestQueue, new ImageGarageRequestDto { ContentType = ImageGarageRequestContentType.Article, ContentId = article.Id }); return(Ok()); }
public async Task <IHttpActionResult> CreateOne([NotNull] ArticleCommentCreateOneRequestDto requestDto) { var article = await _dbContext.Articles.Include(a => a.Author) .Where(a => a.Id == requestDto.ArticleId) .SingleOrDefaultAsync(); if (article == null) { return(this.BadRequest(nameof(requestDto), nameof(requestDto.ArticleId), Errors.NonExistent)); } var userId = User.Identity.GetUserId(); if (article.Archived != ArchivedState.None && userId != article.AuthorId && !User.IsInRole(KeylolRoles.Operator)) { return(Unauthorized()); } var comment = new Models.ArticleComment { ArticleId = article.Id, CommentatorId = userId, Content = ArticleController.SanitizeRichText(requestDto.Content), SidForArticle = await _dbContext.ArticleComments.Where(c => c.ArticleId == article.Id) .Select(c => c.SidForArticle) .DefaultIfEmpty(0) .MaxAsync() + 1 }; comment.UnstyledContent = PlainTextFormatter.FlattenHtml(comment.Content, false); if (requestDto.ReplyToComment != null) { var replyToComment = await _dbContext.ArticleComments .Include(c => c.Commentator) .Where(c => c.ArticleId == article.Id && c.SidForArticle == requestDto.ReplyToComment) .SingleOrDefaultAsync(); if (replyToComment != null) { comment.ReplyToComment = replyToComment; } } _dbContext.ArticleComments.Add(comment); await _dbContext.SaveChangesAsync(); await _cachedData.ArticleComments.IncreaseArticleCommentCountAsync(article.Id, 1); var messageNotifiedArticleAuthor = false; var steamNotifiedArticleAuthor = false; var unstyledContentWithNewLine = PlainTextFormatter.FlattenHtml(comment.Content, true); unstyledContentWithNewLine = unstyledContentWithNewLine.Length > 512 ? $"{unstyledContentWithNewLine.Substring(0, 512)} …" : unstyledContentWithNewLine; if (comment.ReplyToComment != null && comment.ReplyToComment.CommentatorId != comment.CommentatorId && !comment.ReplyToComment.DismissReplyMessage) { if (comment.ReplyToComment.Commentator.NotifyOnCommentReplied) { messageNotifiedArticleAuthor = comment.ReplyToComment.CommentatorId == article.AuthorId; await _cachedData.Messages.AddAsync(new Message { Type = MessageType.ArticleCommentReply, OperatorId = comment.CommentatorId, ReceiverId = comment.ReplyToComment.CommentatorId, ArticleCommentId = comment.Id }); } if (comment.ReplyToComment.Commentator.SteamNotifyOnCommentReplied) { steamNotifiedArticleAuthor = comment.ReplyToComment.CommentatorId == article.AuthorId; await _userManager.SendSteamChatMessageAsync(comment.ReplyToComment.Commentator, $"{comment.Commentator.UserName} 回复了你在《{article.Title}》下的评论:\n\n{unstyledContentWithNewLine}\n\nhttps://www.keylol.com/article/{article.Author.IdCode}/{article.SidForAuthor}#{comment.SidForArticle}"); } } if (comment.CommentatorId != article.AuthorId && !article.DismissCommentMessage) { if (!messageNotifiedArticleAuthor && article.Author.NotifyOnArticleReplied) { await _cachedData.Messages.AddAsync(new Message { Type = MessageType.ArticleComment, OperatorId = comment.CommentatorId, ReceiverId = article.AuthorId, ArticleCommentId = comment.Id }); } if (!steamNotifiedArticleAuthor && article.Author.SteamNotifyOnArticleReplied) { await _userManager.SendSteamChatMessageAsync(article.Author, $"{comment.Commentator.UserName} 评论了你的文章《{article.Title}》:\n\n{unstyledContentWithNewLine}\n\nhttps://www.keylol.com/article/{article.Author.IdCode}/{article.SidForAuthor}#{comment.SidForArticle}"); } } _mqChannel.SendMessage(string.Empty, MqClientProvider.ImageGarageRequestQueue, new ImageGarageRequestDto { ContentType = ImageGarageRequestContentType.ArticleComment, ContentId = comment.Id }); return(Ok(comment.SidForArticle)); }