Example #1
0
        public async Task LoadData()
        {
            IsLoading = true;
            SyndicationClient client = new SyndicationClient();
            var result = await client.RetrieveFeedAsync(new Uri("http://channel9.msdn.com/Feeds/RSS/mp4"));

            foreach (var r in result.Items.Take(12))
            {
                try
                {
                    NewsList.Add(new Channel9Item
                    {
                        Title       = r.Title.Text,
                        Description = HtmlUtilities.ConvertToText(r.Summary.Text),
                        ImageUrl    = r.ElementExtensions.Last(e => e.NodeName == "thumbnail").AttributeExtensions[0].Value,
                    });
                }
                catch (Exception)
                {
                    continue;
                }
            }

            IsLoading = false;
        }
        public UserEmail Add()
        {
            var email = HtmlUtilities.GetResults <UserEmailAdd, UserEmail>(string.Format("{0}/v1/user/emails", BadgrUrl), this, TokenHeader);

            email.Token = Token;
            return(email);
        }
Example #3
0
        /** Set the table style values in a {@link TableStyleValues} object based on attributes and css of the given tag.
         * @param tag containing attributes and css.
         * @return a {@link TableStyleValues} object containing the table's style values.
         */
        private TableStyleValues SetStyleValues(Tag tag)
        {
            TableStyleValues             styleValues = new TableStyleValues();
            IDictionary <String, String> css         = tag.CSS;
            IDictionary <String, String> attributes  = tag.Attributes;
            string v;

            if (attributes.ContainsKey(CSS.Property.BORDER))
            {
                styleValues.BorderColor = BaseColor.BLACK;
                styleValues.BorderWidth = utils.ParsePxInCmMmPcToPt(attributes[CSS.Property.BORDER]);
            }
            else
            {
                css.TryGetValue(CSS.Property.BORDER_BOTTOM_COLOR, out v);
                styleValues.BorderColorBottom = HtmlUtilities.DecodeColor(v);
                css.TryGetValue(CSS.Property.BORDER_TOP_COLOR, out v);
                styleValues.BorderColorTop = HtmlUtilities.DecodeColor(v);
                css.TryGetValue(CSS.Property.BORDER_LEFT_COLOR, out v);
                styleValues.BorderColorLeft = HtmlUtilities.DecodeColor(v);
                css.TryGetValue(CSS.Property.BORDER_RIGHT_COLOR, out v);
                styleValues.BorderColorRight  = HtmlUtilities.DecodeColor(v);
                styleValues.BorderWidthBottom = utils.CheckMetricStyle(css, CSS.Property.BORDER_BOTTOM_WIDTH);
                styleValues.BorderWidthTop    = utils.CheckMetricStyle(css, CSS.Property.BORDER_TOP_WIDTH);
                styleValues.BorderWidthLeft   = utils.CheckMetricStyle(css, CSS.Property.BORDER_LEFT_WIDTH);
                styleValues.BorderWidthRight  = utils.CheckMetricStyle(css, CSS.Property.BORDER_RIGHT_WIDTH);
            }
            css.TryGetValue(CSS.Property.BACKGROUND_COLOR, out v);
            styleValues.Background       = HtmlUtilities.DecodeColor(v);
            styleValues.HorBorderSpacing = GetBorderOrCellSpacing(true, css, attributes);
            styleValues.VerBorderSpacing = GetBorderOrCellSpacing(false, css, attributes);
            return(styleValues);
        }
        public Issuer Update()
        {
            var issuer = HtmlUtilities.GetResults <IssuerUpdate, Issuer>(string.Format("{0}/v1/issuer/issuers/{1}", BadgrUrl, Slug), this, TokenHeader, "PUT");

            issuer.Token = Token;
            return(issuer);
        }
Example #5
0
 public static Notification TranslateDailySchedule(IEnumerable <ScheduledStream> scheduledStreams)
 {
     return(new Notification()
     {
         Embeds = scheduledStreams.Select(stream =>
                                          new Embed()
         {
             Author = new EmbedAuthor()
             {
                 Name = "Today"
             },
             Title = stream.Title,
             Description = HtmlUtilities.ConverHtmlToText(stream.Description),
             Color = 48639,
             Fields = new EmbedField[] {
                 new EmbedField()
                 {
                     Name = "Game",
                     Value = stream.Game,
                     Inline = true
                 },
                 new EmbedField()
                 {
                     Name = "Time",
                     Value = $"{stream.Start:t} - {stream.End:t} UTC",
                     Inline = true
                 },
             }
         }).ToArray()
     });
 }
Example #6
0
        public static void ParseSyndicationItem(this RssItem item, SyndicationFeed syndicFeed, SyndicationItem syndicItem)
        {
            item.Title   = syndicItem.Title.Text;
            item.PubDate = syndicItem.PublishedDate.DateTime;
            item.Author  = syndicItem.Authors.Count > 0 ? syndicItem.Authors[0].Name.ToString() : "";
            if (syndicItem.Id.StartsWith("http"))
            {
                item.Link = syndicItem.Id;
            }
            else if (syndicItem.Links.Count > 0)
            {
                item.Link = syndicItem.Links[0].Uri.OriginalString;
            }

            item.ParseImage(syndicItem.NodeValue);

            if (syndicFeed.SourceFormat == SyndicationFormat.Atom10)
            {
                item.Content = HtmlUtilities.ConvertToText(syndicItem.Content.Text);
            }
            else if (syndicFeed.SourceFormat == SyndicationFormat.Rss20)
            {
                item.Content = HtmlUtilities.ConvertToText(syndicItem.Summary.Text);
            }
        }
Example #7
0
        public string GetPlainText(string html, int maxLength)
        {
            if (html == null)
            {
                return(String.Empty);
            }

            html = RemoveAdRegex.Replace(html, String.Empty);
            var x       = HtmlUtilities.ConvertToText(html);
            var builder = new StringBuilder(x);

            builder.Replace('\r', ' ');
            builder.Replace('\n', ' ');
            builder.Replace('\t', ' ');

            int currentLength;
            int newLength;

            do
            {
                currentLength = builder.Length;
                builder.Replace("  ", " ");
                newLength = builder.Length;
            } while (currentLength != newLength);

            if (newLength < maxLength)
            {
                return(builder.ToString().Trim());
            }

            return(builder.ToString().Substring(0, maxLength).Trim());
        }
Example #8
0
        async void ItemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Invalidate the view state when logical page navigation is in effect, as a change
            // in selection may cause a corresponding change in the current logical page.  When
            // an item is selected this has the effect of changing from displaying the item list
            // to showing the selected item's details.  When the selection is cleared this has the
            // opposite effect.
            if (this.UsingLogicalPageNavigation())
            {
                this.InvalidateVisualState();
            }

            progbar.Visibility = Visibility.Visible;
            Artist ar   = (Artist)itemListView.SelectedItem;
            string resp = await Lastfm.artist_getInfo(ar.name);

            using (XmlReader rd = XmlReader.Create(new StringReader(resp)))
            {
                rd.ReadToFollowing("summary");
                string content = rd.ReadElementContentAsString();
                rd.ReadToFollowing("content");
                content = String.Concat(content, rd.ReadElementContentAsString());

                ArtistContentTb.Text = HtmlUtilities.ConvertToText(content);
            }
            progbar.Visibility = Visibility.Collapsed;
        }
Example #9
0
        /**
         * Processes an Image.
         * @param img
         * @param attrs
         * @throws DocumentException
         * @since   5.0.6
         */
        virtual public void ProcessImage(Image img, IDictionary <String, String> attrs)
        {
            IImageProcessor processor = null;

            if (providers.ContainsKey(IMG_PROCESSOR))
            {
                processor = (IImageProcessor)providers[IMG_PROCESSOR];
            }
            if (processor == null || !processor.Process(img, attrs, chain, document))
            {
                String align;
                attrs.TryGetValue(HtmlTags.ALIGN, out align);
                if (align != null)
                {
                    CarriageReturn();
                }
                if (currentParagraph == null)
                {
                    currentParagraph = CreateParagraph();
                }
                currentParagraph.Add(new Chunk(img, 0, 0, true));
                currentParagraph.Alignment = HtmlUtilities.AlignmentValue(align);
                if (align != null)
                {
                    CarriageReturn();
                }
            }
        }
Example #10
0
        public override IList <IElement> Start(IWorkerContext ctx, Tag tag)
        {
            List <IElement> l = new List <IElement>(1);

            try
            {
                IDictionary <String, String> css = tag.CSS;
                if (css.ContainsKey(CSS.Property.BACKGROUND_COLOR))
                {
                    Type       type     = typeof(PdfWriterPipeline);
                    MapContext pipeline = (MapContext)ctx.Get(type.FullName);
                    if (pipeline != null)
                    {
                        Document document = (Document)pipeline[PdfWriterPipeline.DOCUMENT];
                        if (document != null)
                        {
                            Rectangle rectangle = new Rectangle(document.Left, document.Bottom, document.Right, document.Top, document.PageSize.Rotation);
                            rectangle.BackgroundColor = HtmlUtilities.DecodeColor(css[CSS.Property.BACKGROUND_COLOR]);
                            PdfBody body = new PdfBody(rectangle);
                            l.Add(body);
                        }
                    }
                }
            }
            catch (NoCustomContextException e)
            {}

            return(l);
        }
Example #11
0
        public void SetTitle(string title)
        {
            title = HtmlUtilities.Encode(title);
            var pageTitle = string.IsNullOrEmpty(title) ? SiteSettings.SiteName : string.Concat(title, " - ", SiteSettings.SiteName);

            ViewData[ViewDataKeys.PageTitle] = pageTitle;
        }
        public Badge Update(string issuerSlug)
        {
            var badge = HtmlUtilities.GetResults <BadgeUpdate, Badge>(string.Format("{0}/v1/issuer/issuers/{1}/badges/{2}", BadgrUrl, issuerSlug, Slug), this, TokenHeader, "PUT");

            badge.Token = Token;
            return(badge);
        }
Example #13
0
        void CopyButton_Click(object sender, RoutedEventArgs e)
        {
            OutputText.Text            = "";
            OutputResourceMapKeys.Text = "";
            OutputHtml.NavigateToString("<HTML></HTML>");

            // Set the content to DataPackage as html format
            string htmlFormat  = HtmlFormatHelper.CreateHtmlFormat(this.htmlFragment);
            var    dataPackage = new DataPackage();

            dataPackage.SetHtmlFormat(htmlFormat);

            // Set the content to DataPackage as (plain) text format
            string plainText = HtmlUtilities.ConvertToText(this.htmlFragment);

            dataPackage.SetText(plainText);

            // Populate resourceMap with StreamReference objects corresponding to local image files embedded in HTML
            var imgUri = new Uri(imgSrc);
            var imgRef = RandomAccessStreamReference.CreateFromUri(imgUri);

            dataPackage.ResourceMap[imgSrc] = imgRef;

            try
            {
                // Set the DataPackage to clipboard.
                Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(dataPackage);
                OutputText.Text = "Text and HTML formats have been copied to clipboard. ";
            }
            catch (Exception ex)
            {
                // Copying data to Clipboard can potentially fail - for example, if another application is holding Clipboard open
                rootPage.NotifyUser("Error copying content to Clipboard: " + ex.Message + ". Try again", NotifyType.ErrorMessage);
            }
        }
Example #14
0
        protected override Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionFetchTaskAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            switch (action.CommandId)
            {
            // These commandIds are defined in the Teams App Manifest.
            case TeamsCommands.TakeQuickNote:
                var quickNoteCard = NoteCardFactory.GetAdaptiveCard("NewNoteTemplate.json", new Note());

                return(CreateActionResponse("Create quick note", quickNoteCard));

            case TeamsCommands.NoteFromMessage:
                var converter = new Converter();
                var newNote   = new Note
                {
                    Title    = FixString(new string(HtmlUtilities.ConvertToPlainText(action.MessagePayload.Body.Content).Take(42).ToArray())),
                    NoteBody = FixString(converter.Convert(action.MessagePayload.Body.Content)),
                };
                var newNoteCard = NoteCardFactory.GetAdaptiveCard("NewNoteTemplate.json", newNote);

                return(CreateActionResponse("Create note from message", newNoteCard));

            default:
                throw new NotImplementedException($"Invalid Fetch CommandId: {action.CommandId}");
            }
        }
Example #15
0
        private void ExtractTips(string rootHtml, Seedling seedling)
        {
            var semiHtml = Regex.Match(rootHtml, @"<div id=\""sowing_tips"" class=\""title-full\"">.*Conseils de semis.*<\/div>(.*)<\/section>", RegexOptions.Multiline)
                           .Groups[0]
                           .Value;

            Regex.Matches(semiHtml, @"<div class=\""title-tips\"">(.*?) :<\/div>.*?<div class=\""desc-tips\"">(.*?)<\/div>", RegexOptions.Multiline)
            .ForEach(m =>
            {
                var title = m.Groups[1].Value;
                var value = HtmlUtilities.ConvertToPlainText(m.Groups[2].Value.Replace("<li>", "<li>\r\n - ")).Trim()
                            .Replace("\'", "'");
                if (title == "Facilité")
                {
                    seedling.Facilite = value;
                }
                else if (title == "Mode de semis")
                {
                    seedling.ModeDeSemis = value;
                }
                else if (title == "Durée de germination")
                {
                    seedling.DureeDeGermination = value;
                }
                else if (title == "Techniques de semis")
                {
                    seedling.TechniquesDeSemis = value;
                }
                else
                {
                    _logger.LogWarning($"Unknown property in tips : {title}\\{value}");
                }
            });
        }
        public void LocateSecondTag()
        {
            int position = HtmlUtilities.LocateTagPosition("p", "<h1><p></p><p></p></h1>");

            position = HtmlUtilities.LocateTagPosition("p", "<h1><p></p><p></p></h1>", position + 1);

            Assert.AreEqual(11, position);
        }
Example #17
0
        public void ToUrlSlug_returns_expected_value(string text, string expected)
        {
            // ARRANGE
            var actual = HtmlUtilities.ToUrlSlug(text);

            // ACT / ASSERT
            Assert.Equal(expected, actual);
        }
Example #18
0
 public static string FromHtmlToText(this string html)
 {
     if (html.IsValid())
     {
         return(HtmlUtilities.ConvertToText(html));
     }
     return(string.Empty);
 }
Example #19
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            mail = (MailMessage)e.Parameter;
            editor.Document.SetText(Windows.UI.Text.TextSetOptions.FormatRtf, HtmlUtilities.ConvertToText(mail.Body));
            SenderTextBox.Text  = mail.From.ToString();
            SubjectTextBox.Text = mail.Subject;
        }
Example #20
0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (!(value is string))
            {
                return(string.Empty);
            }

            return(HtmlUtilities.ConvertToText(value.ToString()));
        }
Example #21
0
        public string GetHtmlInput(string name, ArgumentTree args)
        {
            if (maxlen > 128)
            {
                return(HtmlUtilities.TextArea(name, 4, 64, HtmlArgumentTree.GetArgument(args, name, "").ToString()));
            }

            return(HtmlUtilities.Input("text", name, HtmlArgumentTree.GetArgument(args, name, "").ToString()));
        }
Example #22
0
        private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            game = e.NavigationParameter as ApiSearchResult;

            pageTitle.Text  = game.name;
            imgCover.Source = new BitmapImage(new Uri(game.image.super_url));


            //txtData.Text += " \n\n[** Game ID: **] " + game.id.ToString() +"\n\n";

            txtData.Text += " \n\n[** Platforms: **] ";
            foreach (Platform platform in game.platforms)
            {
                txtData.Text += " " + platform.abbreviation;
            }
            txtData.Text += "\n\n";

            //if (game.api_detail_url != null)
            //{
            //    txtData.Text = txtData.Text + " \n\n[** Api Detail: **]\n\n" + game.api_detail_url;
            //}
            //if (game.date_added != null)
            //{
            //    txtData.Text = txtData.Text + " \n\n[** Date Added: **]\n\n" + game.date_added;
            //}
            //if (game.date_last_updated != null)
            //{
            //    txtData.Text = txtData.Text + " \n\n[** Last Updated: **]\n\n" + game.date_last_updated;
            //}
            if (game.deck != null)
            {
                txtData.Text = txtData.Text + " \n\n[** Short Description: **]\n\n" + game.deck;
            }
            if (game.original_release_date != null)
            {
                txtData.Text = txtData.Text + " \n\n[** Original Release Date: **]\n\n" + game.original_release_date;
            }

            //if (game.site_detail_url != null)
            //{
            //    txtData.Text = txtData.Text + " \n\n[** Detail URL: **]\n\n" + game.site_detail_url;
            //}
            if (game.expected_release_year != null)
            {
                txtData.Text = txtData.Text + " \n\n[** Release Year: **] " + game.expected_release_year + "\n\n";
            }

            //HtmlUtilities.ConvertToText
            if (game.description != null)
            {
                txtData.Text = txtData.Text + " \n\n[** Description: **]\n\n" + HtmlUtilities.ConvertToText(game.description);
            }


            txtData.Text = txtData.Text + "\n---------------------------------------------";
        }
Example #23
0
        /// <summary>
        /// Gets the current "revision number" slug (for busting our caching when we update files).
        /// </summary>
        /// <returns></returns>
        public static string RevNumber()
        {
            Assembly        assembly = Assembly.GetExecutingAssembly();
            FileVersionInfo fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
            string          version  = fvi.ProductVersion;                                                     // gets file version info

            var lastTwoPartsOfVersion = version.Substring(version.IndexOf(".", version.IndexOf(".") + 1) + 1); // gets substring of version, starting at index of second dot (first dot's index is used as startIndex in indexOf)

            return(HtmlUtilities.URLFriendly(lastTwoPartsOfVersion));
        }
Example #24
0
        private async Task SaveWorkspaceSlientlyAsync()
        {
            var   currentNoteId             = this.workspace.ID;
            var   currentNoteTitle          = this.workspace.Title;
            var   currentNoteDescription    = string.Empty;
            Image currentNoteThumbnailImage = null;

            var currentNoteContent = this.crypto.Encrypt("<p />");

            if (!string.IsNullOrEmpty(this.workspace.Content))
            {
                var content = HtmlUtilities.ReplaceFileSystemImages(this.workspace.Content);
                currentNoteDescription = HtmlUtilities.ExtractDescription(content);
                var currentNoteThumbnailImageBase64 = HtmlUtilities.ExtractThumbnailBase64(content);
                if (!string.IsNullOrEmpty(currentNoteThumbnailImageBase64))
                {
                    currentNoteThumbnailImage =
                        Image.FromStream(new MemoryStream(Convert.FromBase64String(currentNoteThumbnailImageBase64)));
                }
                currentNoteContent = this.crypto.Encrypt(content);
            }

            using (var dataAccessProxy = this.CreateDataAccessProxy())
            {
                if (currentNoteId == Guid.Empty)
                {
                    this.workspace.ID = await dataAccessProxy.CreateNoteAsync(new Note
                    {
                        Title   = currentNoteTitle,
                        Content = currentNoteContent
                    });
                }
                else
                {
                    await dataAccessProxy.UpdateNoteAsync(new Note
                    {
                        ID      = currentNoteId,
                        Title   = currentNoteTitle,
                        Content = currentNoteContent
                    });
                }
            }

            this.workspace.IsSaved = true;
            var node = this.FindNoteNode(currentNoteId);

            if (node != null)
            {
                var item = GetItem(node);
                item.Title       = this.workspace.Title;
                item.Description = currentNoteDescription;
                item.Image       = currentNoteThumbnailImage;
                this.tvNotes.Refresh();
            }
        }
Example #25
0
        public void GetReciepeDetails(string url, Action <RecipeDetail> callback)
        {
            Task.Run(async() =>
            {
                RecipeDetail dt = new RecipeDetail();
                string requrl   = url;
                var response    = await GetResponse(requrl);
                if (response != null)
                {
                    try
                    {
                        HtmlDocument htmlDocument = new HtmlDocument();
                        htmlDocument.LoadHtml(response.Content);
                        //  document.getElementById('recipe-content-wrapper')
                        var authimage = htmlDocument.DocumentNode.Descendants().Where(x => x.Name == "img" && x.Attributes.Contains("class") && x.Attributes["class"].Value == "author-image").FirstOrDefault().Attributes["src"].Value;
                        dt.AuthorImg  = authimage;
                        var ingdf     = (from n in htmlDocument.DocumentNode.Descendants()
                                         where n.Name == "div" && n.Id != null && (n.Id == "ingredients" || n.Id == "instructions")
                                         select n).ToList();
                        // nodes.Descendants().FirstOrDefault(x=> x.Name == "div"&& x.Attributes.Contains("Id") &&  x.Attributes["Id"].Value.Split().Contains("ingredients"));

                        var ingredients = (from ing in ingdf.FirstOrDefault(y => y.Id == "ingredients").Descendants().Where(x => x.Name == "div" && x.Attributes.Contains("class") && x.Attributes["class"].Value == ("ingredient-wrap"))
                                           select ParseIng(HtmlUtilities.ConvertToText(ing.InnerText))).ToList();

                        var directions = (from ing in ingdf.FirstOrDefault(y => y.Id == "instructions").Descendants().Where(x => x.Name == "div" && x.Attributes.Contains("class") && x.Attributes["class"].Value == ("instructions-wrap"))
                                          select HtmlUtilities.ConvertToText(ing.InnerText)).ToList();
                        if (ingredients != null)
                        {
                            dt.Ingredients = ingredients;
                        }
                        if (directions != null)
                        {
                            dt.Directions = directions;
                        }
                    }
                    catch (Exception)
                    {
                        // throw;
                    }
                    if (callback != null)
                    {
                        callback(dt);
                    }
                    //<div id="ingredients" class="col-md-4 columns">
                    //<h3>Ingredients</h3><div class="ingredient-wrap"><div class="ingredient">chicken 1/2kg</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">onion 2</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">tomato 1</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">green chilli 1</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">ginger garlic paste 5 tsp</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">mint leaves 1/2 cup</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">red chilli powder 1 tsp</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">black pepper 1/4 tsp</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">turmeric powder 1 tsp</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">salt to taste</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">coriander powder 2 tsp</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">chicken masala 1 tsp</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">cumin seed powder 1/2 tsp</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">coconut paste 1/2 cup</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">oil 6 tsp</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">bay leaf 2</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">cinnamon 1</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">cloves 2</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">aniseed 1</div><div class="clr"></div></div><div class="ingredient-wrap"><div class="ingredient">cardamom 2</div><div class="clr"></div></div></div>)
                }
                else
                {
                    if (callback != null)
                    {
                        callback(null);
                    }
                }
            });
        }
        /// <summary>
        /// Produces a URL-friendly version of this String, "like-this-one", and prepends it with
        /// a forward slash if the URL-friendly version is non-blank
        /// </summary>
        public static string Slugify(this string s)
        {
            if (!s.HasValue())
            {
                return(s);
            }

            string slug = HtmlUtilities.URLFriendly(s);

            return(slug.HasValue() ? "/" + slug : "");
        }
        public async void GetSingleBook(int bookID, NavigationEventArgs e)
        {
            try
            {
                ObservableCollection <Books> books = await bookList.GetBookLists();

                var singleBook = books.Single(book => book.id == bookID);

                if (singleBook != null)
                {
                    HideProgressRing();
                    bookTitle.Text         = singleBook.title;
                    bookImage.Source       = new BitmapImage(new Uri(singleBook.imageurl, UriKind.Absolute));
                    bookAuthor.Text        = "by " + singleBook.author;
                    bookPublishedDate.Text = " :    " + singleBook.published_date;
                    bookPublisher.Text     = " :    " + singleBook.publisher;
                    bookPages.Text         = " :    " + singleBook.pages + " pages";
                    bookCategories.Text    = " :    " + singleBook.category__name;

                    if (!string.IsNullOrEmpty(singleBook.description))
                    {
                        bookDescription.Text = HtmlUtilities.ConvertToText(singleBook.description.Length > textMaxLength ? singleBook.description.Substring(0, textMaxLength) + "...." : singleBook.description);
                    }
                    else
                    {
                        bookDescription.Text = " - ";
                    }

                    bookPdfUrl.Text = singleBook.pdfurl;
                    if (!string.IsNullOrEmpty(singleBook.detailsurl))
                    {
                        bookDetailsUrl.Text            = singleBook.detailsurl;
                        bookReadDescription.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        bookDetailsUrl.Text = "";
                    }

                    bookBuyUrl.Text        = "";
                    bookCommand.Visibility = Visibility.Collapsed;
                }
                else
                {
                    ShowProgressRing();
                    await ShowErrorMessage("Couldnt Load The Book. Try Later", e);
                }
            }
            catch (HttpRequestException ex)
            {
                ShowProgressRing();
                await ShowErrorMessage("The app couldn't load books. Please check your connection and try again", e);
            }
        }
        /**
         * Creates a PdfPCell element based on a tag and its properties.
         * @param	tag		a cell tag
         * @param	chain	the hierarchy chain
         */
        virtual public PdfPCell CreatePdfPCell(String tag, ChainedProperties chain)
        {
            PdfPCell cell = new PdfPCell((Phrase)null);
            // colspan
            String value = chain[HtmlTags.COLSPAN];

            if (value != null)
            {
                cell.Colspan = int.Parse(value);
            }
            // rowspan
            value = chain[HtmlTags.ROWSPAN];
            if (value != null)
            {
                cell.Rowspan = int.Parse(value);
            }
            // horizontal alignment
            if (tag.Equals(HtmlTags.TH))
            {
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
            }
            value = chain[HtmlTags.ALIGN];
            if (value != null)
            {
                cell.HorizontalAlignment = HtmlUtilities.AlignmentValue(value);
            }
            // vertical alignment
            value = chain[HtmlTags.VALIGN];
            cell.VerticalAlignment = Element.ALIGN_MIDDLE;
            if (value != null)
            {
                cell.VerticalAlignment = HtmlUtilities.AlignmentValue(value);
            }
            // border
            value = chain[HtmlTags.BORDER];
            float border = 0;

            if (value != null)
            {
                border = float.Parse(value, CultureInfo.InvariantCulture);
            }
            cell.BorderWidth = border;
            // cellpadding
            value = chain[HtmlTags.CELLPADDING];
            if (value != null)
            {
                cell.Padding = float.Parse(value, CultureInfo.InvariantCulture);
            }
            cell.UseDescender = true;
            // background color
            value = chain[HtmlTags.BGCOLOR];
            cell.BackgroundColor = HtmlUtilities.DecodeColor(value);
            return(cell);
        }
Example #29
0
        /// <summary>
        /// get all assertions for the logged in user
        /// </summary>
        /// <returns></returns>
        public List <Assertion> GetAllIssued()
        {
            var assertions = HtmlUtilities.GetResults <List <Assertion> >(string.Format("{0}/v1/earner/badges", BadgrUrl), TokenHeader);

            if (assertions != null)
            {
                assertions.ForEach(i => { i.Token = Token; });
            }

            return(assertions);
        }
Example #30
0
        /// <summary>
        /// gets a list of asserts for a badge
        /// </summary>
        /// <param name="issuerSlug"></param>
        /// <param name="badgeSlug"></param>
        /// <returns></returns>
        public List <Assertion> GetForBadge(string issuerSlug, string badgeSlug)
        {
            var assertions = HtmlUtilities.GetResults <List <Assertion> >(string.Format("{0}/v1/issuer/issuers/{1}/badges/{2}/assertions", BadgrUrl, issuerSlug, badgeSlug), TokenHeader);

            if (assertions != null)
            {
                assertions.ForEach(i => { i.Token = Token; });
            }

            return(assertions);
        }