Exemplo n.º 1
0
 public FeatureViewModel(Feature feature)
 {
     Text         = MarkdownHelper.Markdown(feature.Text.ConvertingLinksToMarkdownUrls());
     FriendlyTime = feature.Time.ToFriendly();
     Author       = feature.User.UserName;
     GravatarUrl  = (string.IsNullOrEmpty(feature.User.AvatarUrl)) ? feature.User.Email.ToGravatarUrl(40) : feature.User.AvatarUrl;
 }
Exemplo n.º 2
0
        private static async Task GetLatest(bool rebuildTable)
        {
            if (rebuildTable)
            {
                List <Service> onlineServiceList = await HtmlHelper.ParseAwsServices("https://aws.amazon.com/products/");

                List <Service> master = ServiceListHelper.OrderServiceListByShortName(onlineServiceList);

                await DynamoHelper.RebuildTable(master);

                List <Service> serviceList = await DynamoHelper.QueryTable();

                List <Tags> tagList = await HtmlHelper.ParseBlogTags("https://msimpson.co.nz/tags/aws/");

                List <TableEntry> tableList = MarkdownHelper.BuildTable(serviceList, tagList);

                MarkdownHelper.BuildMarkdown(tableList);
            }
            else
            {
                List <Service> serviceList = await DynamoHelper.QueryTable();

                List <Tags> tagList = await HtmlHelper.ParseBlogTags("https://msimpson.co.nz/tags/aws/");

                List <TableEntry> tableList = MarkdownHelper.BuildTable(serviceList, tagList);

                MarkdownHelper.BuildMarkdown(tableList);
            }
        }
        public async void SendNewMessageNoticeToChatUsersAsync(MessageDto newMessage, ClientConnection connection, bool sendPush = true)
        {
            try
            {
                List <ChatUserVm> chatUsers = await loadChatsService.GetChatUsersAsync(newMessage.ConversationId, null).ConfigureAwait(false);

                if (sendPush)
                {
                    pushNotificationsService.SendMessageNotificationAsync(
                        newMessage,
                        chatUsers.Select(opt => new NotificationUser(opt.UserId, opt.IsMuted.Value)).ToList());
                }
                List <Task> noticeTasks = new List <Task>();
                foreach (var chatUser in chatUsers)
                {
                    var clientConnections = connectionsService.GetUserClientConnections(chatUser.UserId);
                    if (clientConnections != null)
                    {
                        noticeTasks.Add(Task.Run(async() =>
                        {
                            NewMessageNotice notice = new NewMessageNotice(
                                MessageConverter.GetMessageVm(newMessage, chatUser.UserId),
                                MarkdownHelper.ContainsMarkdownUserCalling(newMessage.Text, chatUser.UserId));
                            await SendNoticeToClientsAsync(clientConnections.Where(clientConnection => clientConnection != connection), notice).ConfigureAwait(false);
                        }));
                    }
                }
                await Task.WhenAll(noticeTasks).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
            }
        }
Exemplo n.º 4
0
        private static void GenerateFilePerClass(MarkdownBuilder homeBuilder, string dest, MarkdownableType[] types)
        {
            foreach (var g in types.GroupBy(x => x.Namespace).OrderBy(x => x.Key))
            {
                string namespacePath = Path.Combine(dest, g.Key);

                homeBuilder.Header(2, g.Key);
                homeBuilder.AppendLine();

                if (!Directory.Exists(namespacePath))
                {
                    Directory.CreateDirectory(namespacePath);
                }

                foreach (var item in g.OrderBy(x => x.Name))
                {
                    var sb = new StringBuilder();
                    homeBuilder.ListLink(MarkdownHelper.RenderCode(item.DisplayName), g.Key + "/" + item.ProcessedName);
                    sb.Append(item.ToString());

                    File.WriteAllText(Path.Combine(namespacePath, item.ProcessedName + ".md"), sb.ToString());
                }

                homeBuilder.AppendLine();
            }
        }
Exemplo n.º 5
0
 public FeatureViewModel(Feature feature)
 {
     Text         = MarkdownHelper.Markdown(feature.Text);
     FriendlyTime = FriendlyTimeHelper.Parse(feature.Time);
     Author       = feature.User.UserName;
     GravatarUrl  = (string.IsNullOrEmpty(feature.User.AvatarUrl)) ? feature.User.Email.ToGravatarUrl(40) : feature.User.AvatarUrl;
 }
Exemplo n.º 6
0
 string GetAboutText(string htmlAbout)
 {
     if (!string.IsNullOrEmpty(htmlAbout))
     {
         return(HtmlUtils.StripTags(MarkdownHelper.PreprocessHtml(HttpUtility.HtmlDecode(HttpUtility.HtmlDecode(htmlAbout))), true));
     }
     return(null);
 }
Exemplo n.º 7
0
        public override IEnumerable <string> GetWriteLines(string readMeFilePath)
        {
            var url = FullPath.Replace(readMeFilePath, "").Replace('\\', '/').Replace(" ", "%20").TrimStart('/');

            yield return(MarkdownHelper.LinkRowInner(Name, url));

            yield return(null);
        }
Exemplo n.º 8
0
 public HomeModule(IIdeaRepository ideas, ISettingsRepository settings)
 {
     Get["/"] = _ => View["Home/Index", new
                          {
                              Ideas = ideas.GetAll(),
                              Title = settings.Title,
                              WelcomeMessage = MarkdownHelper.Markdown(settings.WelcomeMessage)
                          }];
 }
Exemplo n.º 9
0
        public async Task <IncidentBasePayload> AddIncidentAsync(AddIncidentInput input,
                                                                 [ScopedService] ApplicationDbContext context, [FromServices] IFluentEmail email, CancellationToken cancellationToken)
        {
            DateTime?endedAt = null;

            if (input.EndedAt.HasValue)
            {
                endedAt = input.EndedAt;
            }

            var incident = new Incident
            {
                Title           = input.Title,
                Description     = input.Description !,
                DescriptionHtml = MarkdownHelper.ToHtml(input.Description),
                Service         = await context.Service.DeferredFirst(x => x.Id == input.ServiceId).FromCacheAsync(cancellationToken),
                StartedAt       = input.StartedAt,
                EndedAt         = endedAt,
                Author          = await context.User.DeferredFirst(x => x.Id == Int32.Parse(_httpContextAccessor.HttpContext !.User.FindFirst(ClaimTypes.Name) !.Value)).FromCacheAsync(cancellationToken)
            };
            await context.Incident.AddAsync(incident, cancellationToken);

            await context.SaveChangesAsync(cancellationToken);

            var template = await context.Settings.Where(x => x.Key == "backend.email.template.incident.create").DeferredFirst().FromCacheAsync(cancellationToken);

            var emailDomain = await context.Settings.Where(x => x.Key == "backend.email.domain").DeferredFirst().FromCacheAsync(cancellationToken);

            try
            {
                await context.Subscriber.ForEachAsync((subscriber) =>
                {
                    if (!template.Value.IsNullOrEmpty())
                    {
                        email.To(subscriber.Email).Subject($"Incident Created: {incident.Service.Name}").UsingTemplate(template.Value, new
                        {
                            Title        = incident.Title,
                            Description  = incident.Description,
                            ServiceName  = incident.Service.Name,
                            StartedAd    = incident.StartedAt.ToString(CultureInfo.InvariantCulture),
                            EndedAt      = incident.EndedAt?.ToString(CultureInfo.InvariantCulture),
                            Attachements = incident.Files
                        });
                        // We set the message ID so we can reference it in status updates and what not.
                        email.Header("Message-ID", $"<{incident.Id}@{emailDomain.Value}>");
                        email.Send();
                    }
                }, cancellationToken);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            QueryCacheManager.ExpireType <Incident>();
            return(new IncidentBasePayload(incident));
        }
Exemplo n.º 10
0
        /// <summary>
        /// 获取readme.md的头部信息
        /// </summary>
        /// <returns></returns>
        private IEnumerable <string> GetHeaderInfos()
        {
            var heading = ConfigHelper.GetAppSettingValue("Heading");

            yield return(null);

            yield return(MarkdownHelper.Heading1(heading));

            yield return(null);
        }
Exemplo n.º 11
0
        public void ConvertToMarkDownTest()
        {
            // Convert good
            var    html = "Something to <strong>convert</strong>";
            string md   = MarkdownHelper.ConvertToMarkDown(html);
            int    i    = 0;

            // Html2Markdown return always same as input string
            html = "<!--StartFragment--><span style=\"color: rgb(0, 0, 128); font - family: Arial, Helvetica, sans - serif; font - size: 16px; font - style: normal; font - variant - ligatures: normal; font - variant - caps: normal; font - weight: 400; letter - spacing: normal; orphans: 2; text - align: start; text - indent: 0px; text - transform: none; white - space: normal; widows: 2; word - spacing: 0px; -webkit - text - stroke - width: 0px; background - color: rgb(255, 255, 255); text - decoration - style: initial; text - decoration - color: initial; display: inline !important; float: none; \">They<span>�</span></span><strong style=\"color: rgb(0, 0, 128); font - family: Arial, Helvetica, sans - serif; font - size: 16px; font - style: normal; font - variant - ligatures: normal; font - variant - caps: normal; letter - spacing: normal; orphans: 2; text - align: start; text - indent: 0px; text - transform: none; white - space: normal; widows: 2; word - spacing: 0px; -webkit - text - stroke - width: 0px; background - color: rgb(255, 255, 255); text - decoration - style: initial; text - decoration - color: initial; \">will have completed</strong><span style=\"color: rgb(0, 0, 128); font - family: Arial, Helvetica, sans - serif; font - size: 16px; font - style: normal; font - variant - ligatures: normal; font - variant - caps: normal; font - weight: 400; letter - spacing: normal; orphans: 2; text - align: start; text - indent: 0px; text - transform: none; white - space: normal; widows: 2; word - spacing: 0px; -webkit - text - stroke - width: 0px; background - color: rgb(255, 255, 255); text - decoration - style: initial; text - decoration - color: initial; display: inline !important; float: none; \"><span>�</span>the project before the deadline.</span><!--EndFragment-->";
        }
Exemplo n.º 12
0
        public ActionResult MessageBody(int messageId = invalidId)
        {
            if (messageId == invalidId)
            {
                return(NoId());
            }

            var msg  = messageQueries.Get(messageId, null);
            var body = MarkdownHelper.TranformMarkdown(msg.Body);

            return(Content(body));
        }
Exemplo n.º 13
0
        public List <string> SendKickerToMarkdown(
            PlayerReportModel playerModel,
            int[] weeksOfInterest = null,
            bool sendToObsidian   = false)
        {
            var line = new List <string>();

            if (weeksOfInterest == null)
            {
                weeksOfInterest = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }
            }
            ;
            line.Add($"{playerModel.PlayerName} {playerModel.Season}");
            line.Add(string.Empty);
            var totals      = new GameStats();
            var grandtotals = new GameStats();
            var isFirst     = false;

            foreach (var game in playerModel.GameLog)
            {
                if (weeksOfInterest.Contains(
                        game.Week))
                {
                    if (isFirst &&
                        (game.Week.Equals(5) ||
                         game.Week.Equals(9) ||
                         game.Week.Equals(13)))
                    {
                        WriteKickerTotalLine(totals, line);
                        totals = new GameStats();
                        Console.WriteLine();
                    }
                    line.Add($"  {game.KickerStats()}");
                    totals.FieldGoalsMade       += game.FieldGoalsMade;
                    totals.ExtraPointsMade      += game.ExtraPointsMade;
                    grandtotals.FieldGoalsMade  += game.FieldGoalsMade;
                    grandtotals.ExtraPointsMade += game.ExtraPointsMade;
                    isFirst = true;
                }
            }
            WriteKickerTotalLine(totals, line);
            line.Add(string.Empty);
            WriteKickerTotalLine(grandtotals, line);
            line.Add(string.Empty);
            if (sendToObsidian)
            {
                var fileName = $"{playerModel.PlayerName} {playerModel.Season}";
                MarkdownHelper.SendToObsidian(
                    line,
                    fileName);
            }
            return(line);
        }
Exemplo n.º 14
0
        public ActivityViewModel(Activity activity)
        {
            FriendlyTime = FriendlyTimeHelper.Parse(activity.Time);

            var comment = activity as Comment;

            if (comment != null)
            {
                Text = MarkdownHelper.Markdown(comment.Text);
                // TODO: not hard code these
                Author      = activity.User.UserName;
                GravatarUrl = (string.IsNullOrEmpty(activity.User.AvatarUrl)) ? activity.User.Email.ToGravatarUrl(40) : activity.User.AvatarUrl;
            }
        }
Exemplo n.º 15
0
        public ActionResult MessageBody(int messageId = invalidId)
        {
            if (messageId == invalidId)
            {
                return(NoId());
            }

            var msg = messageQueries.Get(messageId, null);
            //return PartialView("Message", messageQueries.Get(messageId, new GravatarUserIconFactory(20)));
            //return LowercaseJson(msg);
            var body = MarkdownHelper.TranformMarkdown(msg.Body);

            return(Content(body));
        }
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            if (output.TagName == "markdown")
            {
                output.TagName = null;
            }

            var content = await GetContent(output);

            var markdown = content;
            var html     = MarkdownHelper.CoventToHtml(markdown);

            output.Content.SetHtmlContent(html.Value);
        }
Exemplo n.º 17
0
        public async Task Podcast()
        {
            Response.ContentType = "application/rss+xml";

            List <SyndicationItem>        items    = new List <SyndicationItem>();
            List <Podcast.Models.Podcast> podcasts = _dbContext.Podcasts.Where(p => p.Published).OrderByDescending(p => p.Episode).ToList();

            if (podcasts != null)
            {
                foreach (Podcast.Models.Podcast podcast in podcasts)
                {
                    SyndicationItem item = new SyndicationItem()
                    {
                        Id          = podcast.Episode.ToString(),
                        Title       = podcast.Title,
                        Description = MarkdownHelper.Markdown(podcast.Description).Value,
                        Published   = podcast.DatePublished
                    };

                    item.AddLink(new SyndicationLink(new Uri(Url.SubRouteUrl("podcast", "Podcast.View", new { episode = podcast.Episode }))));

                    foreach (Podcast.Models.PodcastFile file in podcast.Files)
                    {
                        SyndicationLink enclosure = new SyndicationLink(new Uri(Url.SubRouteUrl("podcast", "Podcast.Download", new { episode = podcast.Episode, fileName = file.FileName })));
                        item.AddLink(enclosure);
                    }

                    items.Add(item);
                }
            }

            using (var xmlWriter = CreateXmlWriter())
            {
                var feedWriter = new RssFeedWriter(xmlWriter);

                await feedWriter.WriteTitle(_config.PodcastConfig.Title);

                await feedWriter.WriteDescription(_config.PodcastConfig.Description);

                await feedWriter.Write(new SyndicationLink(new Uri(Url.SubRouteUrl("podcast", "Podcast.Index"))));

                foreach (SyndicationItem item in items)
                {
                    await feedWriter.Write(item);
                }

                await xmlWriter.FlushAsync();
            }
        }
Exemplo n.º 18
0
        public void CreateReport_Notify_ReportTypeNameAndNotes()
        {
            var editor = user2;

            repository.Save(ArchivedSongVersion.Create(song, new SongDiff(), new AgentLoginData(editor), SongArchiveReason.PropertiesUpdated, String.Empty));
            queries.CreateReport(song.Id, SongReportType.BrokenPV, "39.39.39.39", "It's Miku, not Rin", null);

            var entryLink = MarkdownHelper.CreateMarkdownLink(entryLinkFactory.GetFullEntryUrl(song), song.DefaultName);

            var notification = repository.List <UserMessage>().FirstOrDefault();

            Assert.IsNotNull(notification, "notification was created");
            Assert.AreEqual(string.Format(EntryReportStrings.EntryVersionReportTitle, song.DefaultName), notification.Subject, "Notification subject");
            Assert.AreEqual(string.Format(EntryReportStrings.EntryVersionReportBody, entryLink, "Broken PV (It's Miku, not Rin)"), notification.Message, "Notification body");
        }
Exemplo n.º 19
0
        public MappingProfile()
        {
            SlugHelper helper = new SlugHelper();

            CreateMap <WikiPageEntity, WikiPageDTO>()
            .ForMember(dest => dest.BodyMarkDown, (expr) => expr.MapFrom <string>(x => x.Body))
            .ForMember(dest => dest.BodyHtml, (expr) => expr.MapFrom <string>(x => MarkdownHelper.ConvertToHtml(x.Body)))
            .ReverseMap();



            CreateMap <WikiPageBO, WikiPageEntity>()
            .ForMember(dest => dest.Body, (expr) => expr.MapFrom <string>(x => x.BodyMarkDown))
            .ForMember(dest => dest.Slug, (expr) => expr.MapFrom <string>(x => helper.GenerateSlug(x.Title)));
        }
Exemplo n.º 20
0
        public IdeaViewModel(Idea idea)
        {
            Id           = idea.Id;
            Title        = idea.Title;
            Status       = idea.Status;
            Time         = idea.Time;
            Description  = MarkdownHelper.Markdown(idea.Description);
            UserHasVoted = idea.UserHasVoted;
            TotalVotes   = idea.Votes.Count;
            Author       = idea.Author;
            GravatarUrl  = (string.IsNullOrEmpty(Author.AvatarUrl)) ? Author.Email.ToGravatarUrl(40) : Author.AvatarUrl;
            Features     = idea.Features.Select(f => new FeatureViewModel(f)).ToList();
            Activities   = idea.Activities.Select(f => new ActivityViewModel(f)).ToList();

            Images = idea.Images.ToList();
        }
        private async Task SendChannelMessageNotificationAsyhc(MessageDto message, List <NotificationUser> notificationsUsers)
        {
            try
            {
                var administratorsChannel = await loadChannelsService.GetAdministrationChannelUsersAsync(message.ConversationId).ConfigureAwait(false);

                IEnumerable <TokenVm> tokens = await tokensService.GetAllUsersTokensAsync(
                    notificationsUsers.Where(user => user.UserId != message.SenderId).Select(user => user.UserId)).ConfigureAwait(false);

                foreach (var user in notificationsUsers)
                {
                    bool           isCall      = MarkdownHelper.ContainsMarkdownUserCalling(message.Text, user.UserId);
                    var            userTokens  = GetOfflineUserTokens(tokens.ToList(), user.UserId);
                    List <TokenVm> adminTokens = tokens.Where(token => administratorsChannel.Any(admin => admin.UserId == token.UserId))?.ToList();
                    if (adminTokens != null && adminTokens.Any())
                    {
                        adminTokens = GetOfflineUserTokens(adminTokens, user.UserId);
                        var messageVm = MessageConverter.GetMessageVm(message, user.UserId);
                        if (messageVm.Attachments?.Any(attach => attach.Type == AttachmentType.EncryptedMessage) ?? false)
                        {
                            messageVm.Attachments = null;
                        }

                        if (adminTokens != null && (!user.IsMuted || isCall))
                        {
                            await SendNotificationRequestAsync(
                                adminTokens.Select(opt => opt.DeviceTokenId),
                                new NewMessageNotice(messageVm, isCall))
                            .ConfigureAwait(false);
                        }
                    }
                    else if (!user.IsMuted || isCall)
                    {
                        MessageVm subMessage = MessageConverter.GetMessageVm(message, user.UserId);
                        subMessage.SenderId = null;
                        await SendNotificationRequestAsync(
                            userTokens.Select(opt => opt.DeviceTokenId),
                            new NewMessageNotice(subMessage, isCall))
                        .ConfigureAwait(false);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
            }
        }
Exemplo n.º 22
0
        public override IEnumerable <string> GetWriteLines(string readMeFilePath)
        {
            if (LinkInfos.Count > 0)
            {
                yield return(MarkdownHelper.Heading2(Name));

                yield return(null);

                foreach (var linkInfo in LinkInfos)
                {
                    foreach (var item in linkInfo.GetWriteLines(readMeFilePath))
                    {
                        yield return(item);
                    }
                }
            }
        }
        public async void SendNewMessageNoticeToChannelUsersAsync(MessageDto newMessage, ClientConnection clientConnection = null, bool sendPush = true)
        {
            try
            {
                var channelUsers = await loadChannelsService.GetChannelUsersAsync(newMessage.ConversationId, null, null).ConfigureAwait(false);

                if (sendPush)
                {
                    pushNotificationsService.SendMessageNotificationAsync(
                        newMessage,
                        channelUsers.Select(opt => new NotificationUser(opt.UserId, opt.IsMuted.Value)).ToList());
                }
                var administrationUsers = await loadChannelsService.GetAdministrationChannelUsersAsync(newMessage.ConversationId).ConfigureAwait(false);

                foreach (var channelUser in channelUsers)
                {
                    var clientConnections = connectionsService.GetUserClientConnections(channelUser.UserId);
                    if (clientConnections != null)
                    {
                        clientConnections = clientConnections.Where(opt => opt != clientConnection).ToList();
                        NewMessageNotice notice;
                        if (channelUser.UserId == newMessage.SenderId || administrationUsers.Any(opt => opt.UserId == channelUser.UserId))
                        {
                            notice = new NewMessageNotice(
                                MessageConverter.GetMessageVm(newMessage, channelUser.UserId),
                                MarkdownHelper.ContainsMarkdownUserCalling(newMessage.Text, channelUser.UserId));
                        }
                        else
                        {
                            MessageVm tempMessage = new MessageVm(MessageConverter.GetMessageVm(newMessage, channelUser.UserId))
                            {
                                SenderId = null
                            };
                            notice = new NewMessageNotice(
                                tempMessage,
                                MarkdownHelper.ContainsMarkdownUserCalling(tempMessage.Text, channelUser.UserId));
                        }
                        await SendNoticeToClientsAsync(clientConnections, notice).ConfigureAwait(false);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
            }
        }
        public async Task <IncidentMessageBasePayload> UpdateIncidentMessage(UpdateIncidentMessageInput input,
                                                                             [ScopedService] ApplicationDbContext context, CancellationToken cancellationToken)
        {
            var incidentMessage = await context.IncidentMessage
                                  .Include(x => x.Incident)
                                  .ThenInclude(x => x.Service)
                                  .DeferredFirst(x => x.Id == input.MessageId).FromCacheAsync(cancellationToken);

            if (incidentMessage is null)
            {
                return(new IncidentMessageBasePayload(
                           new UserError("Incident with that id not found.", "INCIDENT_MESSAGE_NOT_FOUND")));
            }

            if (input.StatusId.HasValue)
            {
                var status = await context.Status.DeferredFirst(x => x.Id == input.StatusId).FromCacheAsync(cancellationToken);

                incidentMessage.Status = status;
                incidentMessage.Incident.Service.Status = status;
            }

            if (input.Message.HasValue)
            {
                incidentMessage.Message     = input.Message !;
                incidentMessage.MessageHtml = MarkdownHelper.ToHtml(input.Message);
            }

            if (input.IncidentId.HasValue)
            {
                var incident = await context.Incident.DeferredFirst(x => x.Id == input.IncidentId).FromCacheAsync(cancellationToken);

                incidentMessage.Incident = incident;
            }

            if (input.AttachedFilesIds.HasValue)
            {
                incidentMessage.Attachments = await addAttachments(input.AttachedFilesIds.Value, context, cancellationToken);;
            }
            await context.BulkSaveChangesAsync(cancellationToken);

            QueryCacheManager.ExpireType <IncidentMessage>();
            return(new IncidentMessageBasePayload(incidentMessage));
        }
Exemplo n.º 25
0
        private static void GenerateFilePerNamespace(MarkdownBuilder homeBuilder, string dest, MarkdownableType[] types)
        {
            foreach (var g in types.GroupBy(x => x.Namespace).OrderBy(x => x.Key))
            {
                homeBuilder.HeaderWithLink(2, g.Key, g.Key);
                homeBuilder.AppendLine();

                var sb = new StringBuilder();
                foreach (var item in g.OrderBy(x => x.Name))
                {
                    homeBuilder.ListLink(MarkdownHelper.RenderCode(item.DisplayName), g.Key + "#" + item.ProcessedName.ToLower());

                    sb.Append(item.ToString());
                }

                File.WriteAllText(Path.Combine(dest, g.Key + ".md"), sb.ToString());
                homeBuilder.AppendLine();
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Implements the logic for <see cref="LoadDocsCommand"/>.
        /// </summary>
        /// <param name="name">The name of the docs file to load.</param>
        private async Task LoadDocsAsync(string name)
        {
            // Skip if the loading has already started
            if (!(LoadDocsCommand.ExecutionTask is null))
            {
                return;
            }

            var path = Path.Combine(FilesServices.InstallationPath, "Assets", "docs", $"{name}.md");

            using var stream = await FilesServices.OpenForReadAsync(path);

            using var reader = new StreamReader(stream);
            var text = await reader.ReadToEndAsync();

            texts = MarkdownHelper.GetParagraphs(text);

            OnPropertyChanged(nameof(GetParagraph));
        }
Exemplo n.º 27
0
        public Query(IBooksDataSource booksDataSource)
        {
            Name = "Query";

            Field <BookType>(
                "book",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <IdGraphType> > {
                Name = "id", Description = "id of the book"
            }
                    ),
                resolve: context => booksDataSource.GetBook(context.GetArgument <int>("id"))
                );

            Field <StringGraphType>(
                "source",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <IdGraphType> > {
                Name = "id", Description = "id of the markdown source"
            }
                    ),
                resolve: context => MarkdownHelper.GetMarkdown(context.GetArgument <string>("id"))
                );

            Field <ListGraphType <BookType> >(
                "books",
                arguments: new QueryArguments(
                    new QueryArgument <IntGraphType> {
                Name = "from", Description = "first pagination index"
            },
                    new QueryArgument <IntGraphType> {
                Name = "to", Description = "last pagination index"
            }
                    ),
                resolve: context => booksDataSource.GetBooks()
                );

            Field <IntGraphType>(
                "total",
                resolve: context => booksDataSource.GetBooks().Count
                );
        }
Exemplo n.º 28
0
        public string GetTableOfContents(IEnumerable <HeaderSet> headers)
        {
            var strBuilder = new StringBuilder();

            foreach (var header in headers)
            {
                if (header.Heading > 1)
                {
                    strBuilder.Append(new String(' ', (header.Heading - 1) * 2));
                }

                strBuilder.Append("*");
                strBuilder.Append(" " + MarkdownHelper.GetLinkFromAnchor(header.Text, header.GetAnchorLink()));
                if (header != headers.LastOrDefault())
                {
                    strBuilder.AppendLine();
                }
            }
            return(strBuilder.ToString());
        }
Exemplo n.º 29
0
        //static void AppendIf(StringBuilder sb, string category, string? value)
        //{
        //    if (!value.IsNullOrEmpty())
        //        sb.AppendLine($"|**{category}**|{value}|");
        //}


        static string RenderService(IDocument document, Package package, PackageService service)
        {
            var tabGroup       = BuildTabGroup(package, service);
            var contentBuilder = new StringBuilder();

            contentBuilder.AppendLine("<div class=\"tab-wrap\">");

            var first = true;

            foreach (var tab in tabGroup.Tabs)
            {
                contentBuilder.AppendLine($"<input type=\"radio\" id=\"{tabGroup.Id}-{tab.Id}\" name=\"{tabGroup.Id}\" class=\"tab\" {(first ? "checked" : string.Empty)}><label for=\"{tabGroup.Id}-{tab.Id}\" >{tab.Name}</label>");
                first = false;
            }

            foreach (var tab in tabGroup.Tabs)
            {
                contentBuilder.AppendLine("<div class=\"tab__content\">");
                contentBuilder.AppendLine();

                using (var writer = new StringWriter())
                {
                    MarkdownHelper.RenderMarkdown(
                        document,
                        tab.Content,
                        writer,
                        false,    //prependLinkRoot
                        "common", //configuration,
                        null
                        );
                    contentBuilder.AppendLine(writer.ToString());
                }

                contentBuilder.AppendLine();
                contentBuilder.AppendLine("</div>");
            }

            contentBuilder.AppendLine("</div>");

            return(contentBuilder.ToString());
        }
Exemplo n.º 30
0
        public void CreateReport_Version()
        {
            var version = ArchivedSongVersion.Create(song, new SongDiff(), new AgentLoginData(user), SongArchiveReason.PropertiesUpdated, String.Empty);

            repository.Save(version);
            CallCreateReport(SongReportType.Other, version.Version);

            var report = repository.List <SongReport>().First();

            Assert.AreEqual(version.Version, report.VersionNumber, "Version number");
            Assert.IsNotNull(report.VersionBase, "VersionBase");

            var notification = repository.List <UserMessage>().FirstOrDefault();

            Assert.IsNotNull(notification, "Notification was created");
            Assert.AreEqual(user, notification.Receiver, "Notification receiver");
            Assert.AreEqual(string.Format(EntryReportStrings.EntryVersionReportTitle, song.DefaultName), notification.Subject, "Notification subject");
            Assert.AreEqual(string.Format(EntryReportStrings.EntryVersionReportBody,
                                          MarkdownHelper.CreateMarkdownLink(entryLinkFactory.GetFullEntryUrl(song), song.DefaultName), "It's Miku, not Rin"),
                            notification.Message, "Notification message");
        }