示例#1
0
        public IEnumerable<IFeedItem> GetFeed()
        {
            XDocument docs = XDocument.Parse(xml, LoadOptions.None);

            var nodes = docs.Descendants().Where(n => n.Name.LocalName == "entry");

            var feeds = new List<IFeedItem>();
            foreach (var item in nodes)
            {
                var feed = new FeedItem();
                feed.Title = WebUtility.HtmlDecode(item.Descendants().FirstOrDefault(e => e.Name.LocalName == "title").Value);
                var description = item.Descendants().FirstOrDefault(e => e.Name.LocalName == "summary");

                HtmlDocument htmldocs = new HtmlDocument();
                htmldocs.LoadHtml(description.Value);

                feed.Description = WebUtility.HtmlDecode(htmldocs.DocumentNode.InnerText);
                try
                {
                    feed.Thumbnail = htmldocs.DocumentNode.Descendants("img").FirstOrDefault().Attributes["src"].Value;
                }
                catch
                {

                }
                feed.Link = item.Descendants().FirstOrDefault(e => e.Name.LocalName == "link").Attribute("href").Value.Trim();

                feeds.Add(feed);
            }

            return feeds;
        }
示例#2
0
        public void can_parse_russell_feed_custom_date_that_errors()
        {
            var item = new FeedItem { PubDate = "Wed, 08 Aug 2010 01:25:00 PDT" };
            var expected = new DateTime(2010, 8, 8, 1, 25, 00);

            Assert.That (item.PublishedDate, Is.EqualTo (expected));
        }
示例#3
0
        public void can_parse_twitter_custom_date()
        {
            var item = new FeedItem { PubDate = "Thu, 04 Nov 2010 16:44:08 +0000" };
            var expected = new DateTime (2010, 11, 4, 9, 44, 08);

            Assert.That (item.PublishedDate, Is.EqualTo (expected));
        }
        public void set_the_title()
        {
            var subject = new ItemSubject(){
                Title = "first",
                Title2 = "second"
            };

            var target = new SimpleValues<ItemSubject>(subject);

            var map1 = new FeedItem<ItemSubject>();
            map1.Title(x => x.Title);

            var map2 = new FeedItem<ItemSubject>();
            map2.Title(x => x.Title2);

            var item1 = new SyndicationItem();
            map1.As<IFeedItem<ItemSubject>>().ConfigureItem(item1, target);
            item1.Title.Text.ShouldEqual(subject.Title);


            var item2 = new SyndicationItem();
            map2.As<IFeedItem<ItemSubject>>().ConfigureItem(item2, target);
            item2.Title.Text.ShouldEqual(subject.Title2);

        }
示例#5
0
        public void can_parse_russell_feed_custom_date()
        {
            var item = new FeedItem { PubDate = "Thu, 26 Aug 2010 05:00:00 PDT" };
            var expected = new DateTime (2010, 8, 26, 5, 00, 00);

            Assert.That (item.PublishedDate, Is.EqualTo (expected));
        }
示例#6
0
        private static FeedItem CreateFeedItem(SyndicationItem syndicationItem, out string[] searchWords)
        {
            FeedItem newFeedItem = new FeedItem();

            try
            {
                var link = syndicationItem.Links.FirstOrDefault(l => l.RelationshipType == "alternate")
                           ?? syndicationItem.Links.FirstOrDefault(l => l.RelationshipType == "self")
                           ?? syndicationItem.Links.First();
                newFeedItem.Url = link.Uri.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("Syndication item has no links", ex);
            }

            newFeedItem.Published = syndicationItem.PublishDate;

            var builder = new SyndicationItemParser(syndicationItem);
            newFeedItem.Summary = builder.Summary;
            searchWords = builder.Keywords;

            newFeedItem.Title = syndicationItem.Title.Text;
            return newFeedItem;
        }
        public ObservableCollection<FeedItem> GetFeed(string feedXml)
        {
            ObservableCollection<FeedItem> feedItems = new ObservableCollection<FeedItem>();

            XmlReaderSettings xmlSettings = new XmlReaderSettings();
            xmlSettings.DtdProcessing = DtdProcessing.Parse;

            XmlReader reader = XmlReader.Create(new StringReader(feedXml), xmlSettings);
            var media = XNamespace.Get("http://search.yahoo.com/mrss/");
            SyndicationFeed feed = SyndicationFeed.Load(reader);

            foreach (var item in feed.Items)
            {
                FeedItem feedItem = new FeedItem();
                feedItem.Title = Regex.Replace(item.Title.Text, @"\t|\n|\r", "");
                feedItem.Publisher = feed.Title.Text;
                var desc = Regex.Replace(item.Summary.Text, @"\t|\n|\r", "");
                feedItem.Description = desc.Length > 250 ? desc.Substring(0, 245) + "..." : desc;
                feedItem.ItemLink = item.Links[0].Uri.ToString();

                foreach (var extension in item.ElementExtensions)
                {
                    XElement ele = extension.GetObject<XElement>();
                    var xAttribute = ele.Attribute("url");
                    if (xAttribute != null) feedItem.ImageUri = xAttribute.Value;
                }

                feedItems.Add(feedItem);
            }

            reader.Close();

            return feedItems;
        }
        public IEnumerable<IFeedItem> GetFeed()
        {
            XDocument docs = XDocument.Parse(xml, LoadOptions.None);

            var nodes = docs.Descendants().Where(n => n.Name == "item");

            var feeds = new List<IFeedItem>();
            foreach (var item in nodes)
            {
                var feed = new FeedItem();
                feed.Title = WebUtility.HtmlDecode(item.Descendants().FirstOrDefault(e => e.Name == "title").Value);
                var description = item.Descendants().FirstOrDefault(e => e.Name == "description");

                HtmlDocument htmldocs = new HtmlDocument();
                htmldocs.LoadHtml(description.Value);

                feed.Description = WebUtility.HtmlDecode(htmldocs.DocumentNode.InnerText);
                try
                {
                    var sub = item.Descendants().Where(e => e.Name == "{http://search.yahoo.com/mrss/}thumbnail").FirstOrDefault();
                    feed.Thumbnail = sub.Attribute("url").Value;
                }
                catch
                {

                }
                feed.Link = item.Descendants().FirstOrDefault(e => e.Name == "link").Value.Trim();

                feeds.Add(feed);
            }

            return feeds;
        }
        public void AccountCheck()
        {
            var badItem = new FeedItem(Data.account + "me", 1234, "MEGABYTE!", DateTime.Now, 0);

            //make sure if theres a tweet from another user its caught
            //this SHOULD not be a general exception
            Assert.Throws<Exception>(() => { var f = new AccountFeed(Data.account, Data.items.Concat(new [] {badItem })); });
        }
示例#10
0
 public void Construction()
 {
     var f = new FeedItem(Data.account, Data.id, Data.text, Data.createdAt, Data.mentions);
     Assert.AreEqual(Data.account,   f.account);
     Assert.AreEqual(Data.id,        f.id);
     Assert.AreEqual(Data.text,      f.text);
     Assert.AreEqual(Data.createdAt, f.createdAt);
     Assert.AreEqual(Data.mentions,  f.mentions);
 }
示例#11
0
        public void StartFeed(FeedItem fi)
        {
            m_fi = fi;

            InitializeComponent ();

            ucMediaPlayer1.ImageFile = fi.Image;
            ucMediaPlayer1.MovieFile = fi.Movie;
        }
        public static FeedItem ToFeedItem(this SyndicationItem item, SyndicationFormat format)
        {
            string content = string.Empty;
            Uri link = null;
            FeedItem feedItem = new FeedItem();

            if (item.Title != null && !string.IsNullOrEmpty(item.Title.Text))
            {
                feedItem.Title = item.Title.Text;
            }

            if (item.PublishedDate != null)
            {
                feedItem.PubDate = item.PublishedDate.DateTime;
            }

            if (item.Authors != null && item.Authors.Any())
            {
                feedItem.Author = item.Authors.First().Name;
            }

            switch (format)
            {
                case SyndicationFormat.Atom10:
                    if (item.Content != null && !string.IsNullOrEmpty(item.Content.Text))
                    {
                        content = item.Content.Text;
                    }

                    if (!string.IsNullOrEmpty(item.Id))
                    {
                        Uri.TryCreate(item.Id, UriKind.Absolute, out link);
                    }
                    break;

                case SyndicationFormat.Rss20:
                    if (item.Summary != null && !string.IsNullOrEmpty(item.Summary.Text))
                    {
                        content = item.Summary.Text;
                    }

                    if (item.Links != null && item.Links.Any())
                    {
                        link = item.Links.First().Uri;
                    }
                    break;

                default:
                    throw new NotSupportedException("Unhandled SyndicationFormat value.");
            }

            feedItem.Content = content;
            feedItem.Link = link;

            return feedItem;
        }
示例#13
0
 public void Construction_Args_NullEmpty()
 {
     Assert.Throws<ArgumentNullException>(() => { var f = new FeedItem(null,           Data.id, Data.text, Data.createdAt, Data.mentions); });
     Assert.Throws<ArgumentException>(()     => { var f = new FeedItem("",             Data.id, Data.text, Data.createdAt, Data.mentions); });
     Assert.Throws<ArgumentNullException>(() => { var f = new FeedItem(Data.account,   Data.id, null,      Data.createdAt, Data.mentions); });
     Assert.Throws<ArgumentException>(()     => { var f = new FeedItem(Data.account,   Data.id, "",        Data.createdAt, Data.mentions); });
     Assert.Throws<ArgumentException>(()     => { var f = new FeedItem(Data.account,   Data.id, Data.text, Data.createdAt, -1); });
     Assert.Throws<ArgumentException>(()     => { var f = new FeedItem(Data.account,   Data.id, Data.text, DateTime.MinValue, Data.mentions); });
     Assert.Throws<ArgumentException>(()     => { var f = new FeedItem(Data.account,   Data.id, Data.text, DateTime.Now.AddDays(100), Data.mentions); }); //future dates
 }
示例#14
0
 public FeedItemView(FeedItem item)
 {
     Id = item.LongId;
     Title = item.Title;
     Summary = item.Summary;
     Url = item.Url;
     FeedTitle = item.Feed.Title;
     FeedId = item.Feed.Id;
     Published = item.Published;
 }
示例#15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImageFeedItem"/> class.
 /// </summary>
 /// <param name="feedItem">A base FeedItem to convert from.</param>
 internal ImageFeedItem(FeedItem feedItem)
 {
     Uri = feedItem.Uri;
     Date = feedItem.Date;
     Author = feedItem.Author;
     AvatarUri = feedItem.AvatarUri;
     SourceType = feedItem.SourceType;
     BlockReason = feedItem.BlockReason;
     ContentType = ContentType.Image;
 }
示例#16
0
        public void Parse_HasEpisodeName_EpisodeName()
        {
            var item = new FeedItem
            {
                Title = "The.First.48.S06E16.Motel.No.Tell.Brotherly.Love.PROPER.HDTV.XviD-MOMENTUM"
            };

            Episode e = Episode.Parse(item);

            Expect(e.EpisodeName, Is.EqualTo("Motel No Tell Brotherly Love"));
        }
示例#17
0
        public void Parse_HasRelease_Release()
        {
            var item = new FeedItem
            {
                Title = "The.First.48.S06E16.Motel.No.Tell.Brotherly.Love.PROPER.HDTV.XviD-MOMENTUM"
            };

            Episode e = Episode.Parse(item);

            Expect(e.Release, Is.EqualTo("PROPER HDTV XviD MOMENTUM"));
        }
        public void GetFeed(CompanyFeed Company, Action Callback)
        {
            ObservableCollection<FeedsService.FeedItem> temp = new ObservableCollection<FeedsService.FeedItem>();
            FeedItem a = new FeedItem();
            a.Title = "My Title";
            a.Date = DateTime.Today.ToShortDateString();
            a.Description = "this is a really long description this is a really long description this is a really long description this is a really long description this is a really long description this is a really long descriptionthis is a really long descriptionvthis is a really long descriptionthis is a really long descriptionthis is a really long descriptionthis is a really long descriptionthis is a really long descriptionthis is a really long description";
            a.Url = "www.google.com";

            temp.Add(a);

            FeedResults = temp;
        }
示例#19
0
        public void DatabaseAddDelete()
        {
            var feed = new FeedItem();
            Manager.Database.AddItem(feed);
            var number_of_feed_before = Manager.Database.GetItems<FeedItem>().Count();

            Assert.AreEqual(number_of_feed_before + 1, number_of_feed_before);

            Manager.Database.Delete(feed);
            var number_of_feed_after = Manager.Database.GetItems<FeedItem>().Count();

            Assert.AreEqual(number_of_feed_before - 1, number_of_feed_after);
        }
示例#20
0
        public void set_the_id_1()
        {
            var subject = new ItemSubject{
                Id = "001"
            };

            var target = new SimpleValues<ItemSubject>(subject);

            var map = new FeedItem<ItemSubject>(x => x.Id(o => o.Id));

            var item = new SyndicationItem();
            map.As<IFeedItem<ItemSubject>>().ConfigureItem(item, target);

            item.Id.ShouldEqual("001");
        }
        public void set_the_title_item_title_is_null_so_ignore_it()
        {
            var subject = new ItemSubject()
            {
                Title = null
            };

            var target = new SimpleValues<ItemSubject>(subject);

            var map1 = new FeedItem<ItemSubject>();
            map1.Title(x => x.Title);

            var item1 = new SyndicationItem();
            map1.As<IFeedItem<ItemSubject>>().ConfigureItem(item1, target);
            item1.Title.ShouldBeNull();
        }
        public PodcastPlaybackPage(FeedItem item)
        {
            InitializeComponent();
              BindingContext = item;
              webView.Source = item.Link;
              var share = new ToolbarItem
              {
            Icon = "ic_share.png",
            Text = "Share",
            Command = new Command(() =>
              {
            DependencyService.Get<IShare>()
              .ShareText("Listening to @shanselman's " + item.Title + " " + item.Link);
              })
              };

              ToolbarItems.Add(share);
        }
    public PodcastPlaybackPage(FeedItem item)
    {
      InitializeComponent();
      BindingContext = item;
      webView.Source = new HtmlWebViewSource
      {
        Html = item.Description
      };

      var share = new ToolbarItem
      {
        Icon = "ic_share.png",
        Text = "Share",
        Command = new Command(() =>
          {
            DependencyService.Get<IShare>()
          .ShareText("Listening to @shanselman's " + item.Title + " " + item.Link);
          })
      };

      ToolbarItems.Add(share);

      play.Clicked += (sender, args) => player.PlaybackState = 0;
      pause.Clicked += (sender, args) => player.PlaybackState = 1;
      stop.Clicked += (sender, args) => player.PlaybackState = 2;

      if(Device.OS == TargetPlatform.Android || Device.OS == TargetPlatform.WinPhone)
      {
        play.Text = "Play";
        pause.Text = "Pause";
        stop.Text = "Stop";
      }

      if(Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows)
      {
        this.BackgroundColor = Color.White;
        this.title.TextColor = Color.Black;
        this.date.TextColor = Color.Black;
        this.play.TextColor = Color.Black;
        this.pause.TextColor = Color.Black;
        this.stop.TextColor = Color.Black;
      }
 
    }
        /// <summary>
        /// Removes an attribute value from the specified feed item.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID that has the flights feed.</param>
        /// <param name="feedId">The feed ID that contains the target feed item.</param>
        /// <param name="feedItemId">The feed item ID that will be updated.</param>
        /// <param name="placeholdersToFeedAttributesMap">A mapping of FlightPlaceholderFields to
        ///     FeedAttributes.</param>
        /// <param name="flightPlaceholderFieldName">The attributed field name to remove.</param>
        /// <returns>The modified feed item.</returns>
        /// <exception cref="ArgumentException">If the specified attribute was not found in the
        ///     feed item.</exception>
        private FeedItem RemoveAttributeValueFromFeedItem(GoogleAdsClient client, long customerId,
                                                          long feedId, long feedItemId,
                                                          Dictionary <FlightPlaceholderField, FeedAttribute> placeholdersToFeedAttributesMap,
                                                          FlightPlaceholderField flightPlaceholderFieldName)
        {
            // Gets the ID of the FeedAttribute for the placeholder field.
            long attributeId = placeholdersToFeedAttributesMap[flightPlaceholderFieldName].Id.Value;

            // Retrieves the feed item and its associated attributes based on its resource name.
            FeedItem feedItem = GetFeedItem(client, customerId, feedId, feedItemId);

            //Creates the FeedItemAttributeValue that will be updated.
            FeedItemAttributeValue feedItemAttributeValue = new FeedItemAttributeValue
            {
                FeedAttributeId = attributeId
            };

            // Gets the index of the attribute value that will be removed.
            // int attributeIndex = GetAttributeIndex(feedItem, feedItemAttributeValue);
            int attributeIndex = feedItem.AttributeValues
                                 .Select((item, index) => new { item, index })
                                 .Where(itemIndexPair =>
                                        itemIndexPair.item.FeedAttributeId.Value ==
                                        feedItemAttributeValue.FeedAttributeId.Value)
                                 .Select(itemIndexPair => itemIndexPair.index + 1)
                                 .FirstOrDefault() - 1;

            if (attributeIndex == -1)
            {
                throw new ArgumentException("No matching feed attribute found for " +
                                            $"value '{feedItemAttributeValue}'.");
            }

            // Returns the feed item with the removed FeedItemAttributeValue. Any
            // FeedItemAttributeValues that are not included in the updated FeedItem will be removed
            // from the FeedItem, which is why you must create the FeedItem from the existing
            // FeedItem and set the field(s) that will be removed.
            feedItem.AttributeValues.RemoveAt(attributeIndex);
            return(feedItem);
        }
示例#25
0
        /// <summary>
        /// Creates a FeedItemOperation that will create a FeedItem with the
        /// specified values and ad group target when sent to
        /// FeedItemService.mutate.
        /// </summary>
        /// <param name="adCustomizerFeed">The ad customizer feed.</param>
        /// <param name="name">The value for the name attribute of the FeedItem.
        /// </param>
        /// <param name="price">The value for the price attribute of the FeedItem.
        /// </param>
        /// <param name="date">The value for the date attribute of the FeedItem.
        /// </param>
        /// <param name="adGroupId">The ID of the ad group to target with the
        /// FeedItem.</param>
        /// <returns>A new FeedItemOperation for adding a FeedItem.</returns>
        private static FeedItemOperation CreateFeedItemAddOperation(AdCustomizerFeed adCustomizerFeed,
                                                                    string name, string price, String date, long adGroupId)
        {
            FeedItem feedItem = new FeedItem();

            feedItem.feedId = adCustomizerFeed.feedId;
            List <FeedItemAttributeValue> attributeValues = new List <FeedItemAttributeValue>();

            // FeedAttributes appear in the same order as they were created
            // - Name, Price, Date. See CreateCustomizerFeed method for details.
            FeedItemAttributeValue nameAttributeValue = new FeedItemAttributeValue();

            nameAttributeValue.feedAttributeId = adCustomizerFeed.feedAttributes[0].id;
            nameAttributeValue.stringValue     = name;
            attributeValues.Add(nameAttributeValue);

            FeedItemAttributeValue priceAttributeValue = new FeedItemAttributeValue();

            priceAttributeValue.feedAttributeId = adCustomizerFeed.feedAttributes[1].id;
            priceAttributeValue.stringValue     = price;
            attributeValues.Add(priceAttributeValue);

            FeedItemAttributeValue dateAttributeValue = new FeedItemAttributeValue();

            dateAttributeValue.feedAttributeId = adCustomizerFeed.feedAttributes[2].id;
            dateAttributeValue.stringValue     = date;
            attributeValues.Add(dateAttributeValue);

            feedItem.attributeValues = attributeValues.ToArray();

            feedItem.adGroupTargeting = new FeedItemAdGroupTargeting();
            feedItem.adGroupTargeting.TargetingAdGroupId = adGroupId;

            FeedItemOperation feedItemOperation = new FeedItemOperation();

            feedItemOperation.operand   = feedItem;
            feedItemOperation.@operator = Operator.ADD;

            return(feedItemOperation);
        }
        public override void Parse(HtmlDocument doc, FeedItem item)
        {
            var storyNodes = doc.DocumentNode.SelectNodes("//div[@id=\"body\"]/p[not(@class)]");

            SetArticleText(item, storyNodes);

            var tagNodes = doc.DocumentNode.SelectNodes("//script[@type=\"text/javascript\"]");

            foreach (var node in tagNodes)
            {
                if (node.InnerText.Contains("kw:[["))
                {
                    var     js   = node.InnerText.Trim().Substring(15);
                    dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(js);

                    foreach (var element in data["kw"])
                    {
                        AddTag(item, element[1].ToString());
                    }
                }
            }
        }
示例#27
0
        public void TF_GraphOperationByName_FromModel()
        {
            MultiThreadedUnitTestExecuter.Run(8, Core);

            //the core method
            void Core(int tid)
            {
                Console.WriteLine();
                for (int j = 0; j < 100; j++)
                {
                    var sess   = Session.LoadFromSavedModel(modelPath).as_default();
                    var inputs = new[] { "sp", "fuel" };

                    var inp  = inputs.Select(name => sess.graph.OperationByName(name).output).ToArray();
                    var outp = sess.graph.OperationByName("softmax_tensor").output;

                    for (var i = 0; i < 100; i++)
                    {
                        {
                            var        data  = new float[96];
                            FeedItem[] feeds = new FeedItem[2];

                            for (int f = 0; f < 2; f++)
                            {
                                feeds[f] = new FeedItem(inp[f], new NDArray(data));
                            }

                            try
                            {
                                sess.run(outp, feeds);
                            } catch (Exception ex)
                            {
                                Console.WriteLine(ex);
                            }
                        }
                    }
                }
            }
        }
示例#28
0
        public void AddFeedItem(string left, string leftAssist, Color leftColor, string middle, string right, Color rightColor)
        {
            BMPFont font = theme.GetField <BMPFont>(null, "SmallFont");

            if (!string.IsNullOrWhiteSpace(leftAssist))
            {
                if (string.IsNullOrWhiteSpace(left))
                {
                    left = right + " + " + leftAssist;
                }
                else
                {
                    left = left + " + " + leftAssist;
                }
            }

            FeedItem item = new FeedItem(theme, 25, feed.Count,
                                         left, leftColor, middle, right, rightColor, font);

            feed.Add(item);
            area.AddTopLevel(item);
        }
        public ObservableCollection <FeedItem> GetFeed(string feedXml)
        {
            ObservableCollection <FeedItem> feedItems = new ObservableCollection <FeedItem>();

            XmlReaderSettings xmlSettings = new XmlReaderSettings();

            xmlSettings.DtdProcessing = DtdProcessing.Parse;

            XmlReader       reader = XmlReader.Create(new StringReader(feedXml), xmlSettings);
            var             media  = XNamespace.Get("http://search.yahoo.com/mrss/");
            SyndicationFeed feed   = SyndicationFeed.Load(reader);

            foreach (var item in feed.Items)
            {
                FeedItem feedItem = new FeedItem();
                feedItem.Title     = Regex.Replace(item.Title.Text, @"\t|\n|\r", "");
                feedItem.Publisher = feed.Title.Text;
                var desc = Regex.Replace(item.Summary.Text, @"\t|\n|\r", "");
                feedItem.Description = desc.Length > 250 ? desc.Substring(0, 245) + "..." : desc;
                feedItem.ItemLink    = item.Links[0].Uri.ToString();

                foreach (var extension in item.ElementExtensions)
                {
                    XElement ele        = extension.GetObject <XElement>();
                    var      xAttribute = ele.Attribute("url");
                    if (xAttribute != null)
                    {
                        feedItem.ImageUri = xAttribute.Value;
                    }
                }


                feedItems.Add(feedItem);
            }

            reader.Close();

            return(feedItems);
        }
        private async Task <FeedItemViewModel> GetFeedItemViewModel(FeedItem feedItem)
        {
            var returnModel = new FeedItemViewModel();

            var feedItemTags = await GetTags(feedItem.EntityId);

            var comments = await GetComments(feedItem.EntityId);

            returnModel.Tags            = feedItemTags;
            returnModel.Comments        = comments;
            returnModel.NormalizedTitle = feedItem.NormalizedTitle;
            returnModel.Content         = feedItem.Content;
            returnModel.CommentsEnabled = feedItem.CommentsEnabled;
            returnModel.Id          = feedItem.EntityId;
            returnModel.Title       = feedItem.Title;
            returnModel.Description = feedItem.Description;
            returnModel.FeedId      = feedItem.FeedId;
            returnModel.Date        = feedItem.Date;
            returnModel.Modified    = feedItem.Modified;

            return(returnModel);
        }
示例#31
0
        private static void RestrictFeedItemToGeoTarget(AdWordsUser user, FeedItem feedItem,
                                                        long locationId)
        {
            FeedItemCriterionTarget criterionTarget = new FeedItemCriterionTarget()
            {
                feedId     = feedItem.feedId,
                feedItemId = feedItem.feedItemId,
                // The IDs can be found in the documentation or retrieved with the
                // LocationCriterionService.
                criterion = new Location()
                {
                    id = locationId,
                }
            };

            using (FeedItemTargetService feedItemTargetService =
                       (FeedItemTargetService)user.GetService(
                           AdWordsService.v201809.FeedItemTargetService))
            {
                FeedItemTargetOperation operation = new FeedItemTargetOperation()
                {
                    @operator = Operator.ADD,
                    operand   = criterionTarget
                };


                FeedItemTargetReturnValue retval = feedItemTargetService.mutate(
                    new FeedItemTargetOperation[]
                {
                    operation
                });
                FeedItemCriterionTarget newLocationTarget =
                    (FeedItemCriterionTarget)retval.value[0];
                Console.WriteLine(
                    "Feed item target for feed ID {0} and feed item ID {1}" +
                    " was created to restrict serving to location ID {2}", newLocationTarget.feedId,
                    newLocationTarget.feedItemId, newLocationTarget.criterion.id);
            }
        }
示例#32
0
    public static FeedItem operator +(FeedItem c1, FeedItem c2)
    {
        FeedItem returnItem = new FeedItem();

        returnItem.setAmount(+c2.getAmount());
        returnItem.C_content = c1.C_content + c2.C_content;
        returnItem.K_content = c1.K_content + c2.K_content;

        returnItem.code = c1.code + c2.code;
        returnItem.proteinN_digestibility = c1.getAmount() / returnItem.getAmount() * c1.proteinN_digestibility + c2.getAmount() / returnItem.getAmount() * c2.proteinN_digestibility;
        returnItem.dryMatter = c1.getAmount() / returnItem.getAmount() * c1.dryMatter + c2.getAmount() / returnItem.getAmount() * c2.dryMatter;
        returnItem.OMD       = c1.getAmount() / returnItem.getAmount() * c1.OMD + c2.getAmount() / returnItem.getAmount() * c2.OMD;
        returnItem.proteinN_digestibility = c1.getAmount() / returnItem.getAmount() * c1.proteinN_digestibility + c2.getAmount() / returnItem.getAmount() * c2.proteinN_digestibility;
        returnItem.P_digest                = c1.getAmount() / returnItem.getAmount() * c1.P_digest + c2.getAmount() / returnItem.getAmount() * c2.P_digest;
        returnItem.P_content               = c1.getAmount() / returnItem.getAmount() * c1.P_content + c2.getAmount() / returnItem.getAmount() * c2.P_content;
        returnItem.orgN_content            = c1.getAmount() / returnItem.getAmount() * c1.orgN_content + c2.getAmount() / returnItem.getAmount() * c2.orgN_content;
        returnItem.NO3_content             = c1.getAmount() / returnItem.getAmount() * c1.NO3_content + c2.getAmount() / returnItem.getAmount() * c2.NO3_content;
        returnItem.NH4_content             = c1.getAmount() / returnItem.getAmount() * c1.NH4_content + c2.getAmount() / returnItem.getAmount() * c2.NH4_content;
        returnItem.K_content               = c1.getAmount() / returnItem.getAmount() * c1.K_content + c2.getAmount() / returnItem.getAmount() * c2.K_content;
        returnItem.pigFeedUnitsPerItemUnit = c1.getAmount() / returnItem.getAmount() * c1.pigFeedUnitsPerItemUnit + c2.getAmount() / returnItem.getAmount() * c2.pigFeedUnitsPerItemUnit;
        return(returnItem);
    }
示例#33
0
        public async Task UploadFile(
            FeedItem feedItem,
            JunaUser user,
            string mimeType,
            System.IO.Stream fileStream,
            string targetType,
            Board board,
            string description)
        {
            switch (mimeType)
            {
            case ("image/jpeg"):
            case ("image/png"):
            case ("image/gif"):
            case ("image/bmp"):
                await UploadAndSaveFeedItemAsync(feedItem,
                                                 FeedItem.ImageFeedItem, fileStream,
                                                 user, mimeType, targetType, board, description);

                break;

            case ("video/mp4"):
                await UploadAndSaveFeedItemAsync(feedItem,
                                                 FeedItem.VideoFeedItem, fileStream,
                                                 user, mimeType, targetType, board, description);

                break;

            case ("audio/mpeg"):
                await UploadAndSaveFeedItemAsync(feedItem,
                                                 FeedItem.AudioFeedItem, fileStream,
                                                 user, mimeType, targetType, board, description);

                break;

            default:
                throw new InvalidOperationException("Cannot process this file type");
            }
        }
示例#34
0
        private IEnumerable <FeedItem> FetchFeed(string url)
        {
            var reader = XmlReader.Create(url);
            var feed   = SyndicationFeed.Load(reader);

            reader.Close();

            var result = new List <FeedItem>();

            foreach (var feedItem in feed.Items)
            {
                var myFeedItem = new FeedItem
                {
                    Title       = feedItem.Title.Text,
                    Link        = feedItem.Id,
                    PublishDate = feedItem.PublishDate.ToString()
                };

                result.Add(myFeedItem);
            }
            return(result);
        }
示例#35
0
文件: RssJob.cs 项目: scp-cs/Thorn
        private Embed GetAnnouncementEmbed(FeedItem feedItem, FeedConfig feedConfig, string text)
        {
            var title       = Regex.Match(feedItem.Title, "\"(.*)\" - .*").Groups[1].Value;
            var author      = GetUsername(text);
            var description = new StringBuilder("Nový článek na wiki! Yay! \\o/\n");

            if (!(author is null))
            {
                var account = _accounts.GetAccountByWikidot(author);

                // TODO: fix this

                /*
                 * if (!(account is null))
                 * {
                 *  var user = _client.GetUser(account.Id) as SocketGuildUser;
                 *  description.Append($"[{title}]({feedItem.Link}) od uživatele {user?.Mention}");
                 * }
                 */
                // else
                description.Append($"[{title}]({feedItem.Link}) od uživatele `{author}`");
            }
        private void ProcessFeedItems(FeedItem feedItem)
        {
            try
            {
                logger.TrackTrace($"Processing feed item with Title [{feedItem.Title}] of type: [{feedItem.ContentType}]", SeverityLevel.Information);
                logger.TrackTrace("\nInserting newsfeed into the database\n", SeverityLevel.Information);

                logger.TrackTrace($"\n New URL is [{feedItem.Title}]", SeverityLevel.Information);
                logger.TrackTrace(JsonConvert.SerializeObject(feedItem), SeverityLevel.Verbose);

                feedItem = StoreItemWithUniqueUrl(feedItem);
                logger.TrackTrace($"Successfully processed feed item of type [{feedItem.ContentType}] with url [{feedItem.Url}]");
            }
            catch (DuplicateEntityException)
            {
                logger.TrackTrace($"FeedItem with the Url [{feedItem.Url}] already exists. Skipping", SeverityLevel.Warning);
            }
            finally
            {
                logger.TrackTrace($"Insert attempt completed for record with headline: [{feedItem.Title}]", SeverityLevel.Information);
            }
        }
示例#37
0
        private static void Work()
        {
            var status = new Status();
            var opt    = new SessionOptions();

            var tags = new string[] { "serve" };

            var session = Session.LoadFromSavedModel(modelLocation).as_default();

            var inputs = new[] { "sp", "fuel" };

            var inp  = inputs.Select(name => session.graph.OperationByName(name).output).ToArray();
            var outp = session.graph.OperationByName("softmax_tensor").output;

            for (var i = 0; i < 1; i++)
            {
                {
                    var        data  = new float[96];
                    FeedItem[] feeds = new FeedItem[2];

                    for (int f = 0; f < 2; f++)
                    {
                        feeds[f] = new FeedItem(inp[f], new NDArray(data));
                    }

                    try
                    {
                        session.run(outp, feeds);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
            }

            session.graph.Dispose();
            session.close();
        }
示例#38
0
        public void AddItem(FeedItem item, string[] searchTerms, int feedId, DateTime collected)
        {
            //Find the feed and add to its entries
            Feed feed = _feeds[feedId];
            feed.AddItem(item);
            _statistics.TotalFeedItems++;

            //Most recent list
            _mostRecentItems.Add(item);

            //Update search index
            foreach (string keyword in searchTerms)
            {
                if (!_searchIndex.ContainsKey(keyword))
                {
                    _statistics.UniqueKeywords++;
                    _searchIndex[keyword] = new SortedSet<FeedItem>();
                }
                _statistics.TotalKeywords++;
                _searchIndex[keyword].Add(item);
            }
        }
示例#39
0
        /// <inheritdoc/>
        internal override FeedItem ToFeedItem()
        {
            FeedItem fi = new FeedItem(this)
            {
                Author               = this.Author?.ToString(),
                Categories           = this.Categories,
                Content              = this.Content,
                Id                   = this.Id,
                PublishingDate       = this.PublishedDate,
                PublishingDateString = this.PublishedDateString,
                Title                = this.Title,
                UrlImg               = this.UrlImg,
                UrlVideo             = this.UrlVideo
            };

            if (String.IsNullOrEmpty(this.Description))
            {
                fi.Description = this.Summary;
            }

            return(fi);
        }
示例#40
0
        public static Hashtable DeserializeList()
        {
            var itemTable = new Hashtable();

            try
            {
                string[] files = Directory.GetFiles(SavePath, $"*{Extension}", SearchOption.TopDirectoryOnly);
                foreach (string path in files)
                {
                    FeedItem item = BinaryDeserialize(path);
                    if (item != null)
                    {
                        itemTable.Add(item.HashCode, item);
                    }
                }
                return(itemTable);
            }
            catch
            {
                return(itemTable);
            }
        }
        /// <summary>
        /// リストボックスに割り当てる項目をDBからも取得して設定する
        /// </summary>
        /// <param name="db">DBインスタンス</param>
        /// <param name="feedItems">feed項目一覧</param>
        /// <param name="masterID">DB上のマスターID</param>
        /// <param name="isListUpdate">ListBoxの表示を更新するか</param>
        private IEnumerable <FeedItem> GetFeedItems(SQLite db, IEnumerable <FeedItem> feedItems,
                                                    Int32 masterID, Boolean isListUpdate)
        {
            FeedItem.ExistsChashDirectory(masterID.ToString());

            // 更新日時の最新で並べ替える
            var items = GetFeedItemsToDB(db, feedItems, masterID)
                        .OrderByDescending(fd => fd.PublishDate);

            // リストを更新しないのでサムネイル画像は読み込まない。
            if (!isListUpdate)
            {
                return(items);
            }

            if (App.Configure?.IsShowImage ?? false)
            {
                // サムネの読み込み
                foreach (var item in items)
                {
                    item.Thumbnail = CommFunc.GetImage(item.ThumbUri, masterID, item.Host);
                    if (item.ThumbUri != null)
                    {
                        item.ThumbWidth = DEFAULT_PIC_WIDTH;
                    }
                }
            }
            else
            {
                // サムネ表示無効なので幅を調整する
                foreach (var item in items)
                {
                    item.ThumbWidth = 0;
                }
            }
            //this.FeedList.ItemsSource = items;
            return(items);
        }
示例#42
0
        public UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath, FeedItem item)
        {
            if (string.IsNullOrEmpty(item.Id) && string.IsNullOrEmpty(item.AdvertisementUrl))
            {
                if (topCell == null)
                {
                    topCell = new UITableViewCell();
                    topCell.SelectionStyle = UITableViewCellSelectionStyle.None;
                    topCell.Add(view);
                    topCell.AddConstraint(NSLayoutConstraint.Create(view, NSLayoutAttribute.Left, NSLayoutRelation.Equal, topCell, NSLayoutAttribute.Left, 1, 0));
                    topCell.AddConstraint(NSLayoutConstraint.Create(view, NSLayoutAttribute.Top, NSLayoutRelation.Equal, topCell, NSLayoutAttribute.Top, 1, 0));
                    topCell.AddConstraint(NSLayoutConstraint.Create(view, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, topCell, NSLayoutAttribute.Bottom, 1, 0));
                    topCell.AddConstraint(NSLayoutConstraint.Create(view, NSLayoutAttribute.Right, NSLayoutRelation.Equal, topCell, NSLayoutAttribute.Right, 1, 0));
                    //AppDelegate.SetViewFont (topCell);
                }
                topCell.SelectionStyle = UITableViewCellSelectionStyle.None;

                return(topCell);
            }
            if (!string.IsNullOrEmpty(item.AdvertisementUrl))
            {
                var cell = tableView.DequeueReusableCell("AdvertisementCell", indexPath) as AdvertisementCell;
                //cell.Position = indexPath.Row;
                cell.SetData(item);
                cell.SelectionStyle = UITableViewCellSelectionStyle.None;
                return(cell);
            }
            else
            {
                var cell = tableView.DequeueReusableCell("FeedCell", indexPath) as FeedCell;
                cell.Position = indexPath.Row;
                SetNewsFeedCellCommon(cell, item);
                cell.SetNeedsUpdateConstraints();
                cell.SetNeedsLayout();
                cell.SelectionStyle = UITableViewCellSelectionStyle.None;
                return(cell);
            }
        }
        /// <summary>
        /// Creates a FeedItemOperation that will create a FeedItem with the
        /// specified values and ad group target when sent to
        /// FeedItemService.mutate.
        /// </summary>
        /// <param name="name">The value for the name attribute of the FeedItem.
        /// </param>
        /// <param name="price">The value for the price attribute of the FeedItem.
        /// </param>
        /// <param name="date">The value for the date attribute of the FeedItem.
        /// </param>
        /// <param name="adGroupId">The ID of the ad group to target with the
        /// FeedItem.</param>
        /// <param name="dataHolder">The data holder that contains metadata about
        /// the customizer Feed.</param>
        /// <returns>A new FeedItemOperation for adding a FeedItem.</returns>
        private static FeedItemOperation CreateFeedItemAddOperation(string name, string price,
                                                                    String date, long adGroupId, CustomizersDataHolder dataHolder)
        {
            FeedItem feedItem = new FeedItem();

            feedItem.feedId = dataHolder.FeedId;
            List <FeedItemAttributeValue> attributeValues = new List <FeedItemAttributeValue>();

            FeedItemAttributeValue nameAttributeValue = new FeedItemAttributeValue();

            nameAttributeValue.feedAttributeId = dataHolder.NameFeedAttributeId;
            nameAttributeValue.stringValue     = name;
            attributeValues.Add(nameAttributeValue);

            FeedItemAttributeValue priceAttributeValue = new FeedItemAttributeValue();

            priceAttributeValue.feedAttributeId = dataHolder.PriceFeedAttributeId;
            priceAttributeValue.stringValue     = price;
            attributeValues.Add(priceAttributeValue);

            FeedItemAttributeValue dateAttributeValue = new FeedItemAttributeValue();

            dateAttributeValue.feedAttributeId = dataHolder.DateFeedAttributeId;
            dateAttributeValue.stringValue     = date;
            attributeValues.Add(dateAttributeValue);

            feedItem.attributeValues = attributeValues.ToArray();

            feedItem.adGroupTargeting = new FeedItemAdGroupTargeting();
            feedItem.adGroupTargeting.TargetingAdGroupId = adGroupId;

            FeedItemOperation feedItemOperation = new FeedItemOperation();

            feedItemOperation.operand   = feedItem;
            feedItemOperation.@operator = Operator.ADD;

            return(feedItemOperation);
        }
示例#44
0
        public List <FeedItem> LoadItems(string url)
        {
            Trace.TraceInformation($"Request {url}");

            var reader = XmlReader.Create(url);

            var feed = SyndicationFeed.Load(reader);

            var newses = new List <FeedItem>();

            if (feed == null)
            {
                return(null);
            }

            foreach (var item in feed.Items)
            {
                var news = new FeedItem
                {
                    Guid            = item.Id,
                    Title           = item.Title?.Text,
                    PublishDate     = item.PublishDate,
                    Summary         = item.Summary?.Text,
                    Copyright       = item.Copyright?.Text,
                    LastUpdatedTime = item.LastUpdatedTime,
                    Link            = item.Links.FirstOrDefault()?.Uri.OriginalString,
                    Categories      = item.Categories
                                      .Where(x => !string.IsNullOrWhiteSpace(x.Name))
                                      .Select(x => new FeedItemCategory {
                        Name = x.Name
                    }).ToArray()
                };

                newses.Add(news);
            }

            return(newses);
        }
        async private Task parameterSet(string turi)
        {
            textBlockTargetFeed.Text = turi.ToString();
            try
            {
                SyndicationClient client = new SyndicationClient();
                Uri feedUri = new Uri(turi);
                feed = await client.RetrieveFeedAsync(feedUri);

                FeedLsvModel feedData = new FeedLsvModel();

                foreach (SyndicationItem item in feed.Items)
                {
                    FeedItem feedItem = new FeedItem();
                    feedItem.Title   = item.Title.Text;
                    feedItem.PubDate = item.PublishedDate.DateTime;
                    feedItem.Author  = item.Authors[0].Name;
                    // Handle the differences between RSS and Atom feeds.
                    if (feed.SourceFormat == SyndicationFormat.Atom10)
                    {
                        feedItem.Content = item.Content.Text;
                        feedItem.Link    = new Uri(turi + item.Id);
                    }
                    else if (feed.SourceFormat == SyndicationFormat.Rss20)
                    {
                        feedItem.Content = item.Summary.Text;
                        feedItem.Link    = item.Links[0].Uri;
                    }
                    feedData.Items.Add(feedItem);
                }
                ItemListView.DataContext   = feedData.Items;
                ItemListView.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                textBlockTargetFeed.Text = "ネットワークに問題が発生しました。RSSフィードが受信できません。 e:" + ex.ToString();
            }
        }
示例#46
0
    public static List <FeedItem> GetPublicPhotosFromUser(string apiKey, string userId, int maxPhotos = 20)
    {
        maxPhotos = Math.Max(maxPhotos, 0);
        var parameters = new NameValueCollection {
            { "method", "flickr.people.getPublicPhotos" },
            { "api_key", apiKey },
            { "user_id", userId },
            { "format", "json" },
            { "per_page", maxPhotos.ToString() },
            { "extras", "description,date_upload,owner_name,url_t" },
            { "nojsoncallback", "1" }
        };
        Uri uri = PrepareRequest(parameters);

        using (var client = new WebClient()) {
            var     result  = new List <FeedItem>();
            string  content = client.DownloadString(uri);
            dynamic json    = Json.Decode(content);
            if ((string)json.stat == "ok" && json.photos != null && json.photos.photo != null)
            {
                foreach (dynamic photo in json.photos.photo)
                {
                    var feedItem = new FeedItem(
                        id: (string)photo.id,
                        title: (string)photo.title,
                        author: (string)photo.ownername,
                        content: (string)photo.description._content,
                        publishedDate: ConvertFromUnixTimestamp(long.Parse((string)photo.dateupload)),
                        photoUrl: (string)photo.url_t,
                        webUrl: ConstructPhotoWebPageUrl(userId, photo.id)
                        );
                    result.Add(feedItem);
                }
            }

            return(result);
        };
    }
示例#47
0
        public void AddItem(FeedItem item, string[] searchTerms, int feedId, DateTime collected)
        {
            //Find the feed and add to its entries
            Feed feed = _feeds[feedId];

            feed.AddItem(item);
            _statistics.TotalFeedItems++;

            //Most recent list
            _mostRecentItems.Add(item);

            //Update search index
            foreach (string keyword in searchTerms)
            {
                if (!_searchIndex.ContainsKey(keyword))
                {
                    _statistics.UniqueKeywords++;
                    _searchIndex[keyword] = new SortedSet <FeedItem>();
                }
                _statistics.TotalKeywords++;
                _searchIndex[keyword].Add(item);
            }
        }
示例#48
0
        private List <FeedItem> LoadFeed()
        {
            // Load the actual RSS feed
            XmlReader       reader = XmlReader.Create(this.RssUrl);
            SyndicationFeed feed   = SyndicationFeed.Load(reader);

            reader.Close();

            var list = new List <FeedItem>();

            foreach (SyndicationItem item in feed.Items)
            {
                var feedItem = new FeedItem()
                {
                    Title       = item.Title.Text,
                    Description = item.Summary.Text,
                    Url         = item.Links.FirstOrDefault().Uri.ToString(),
                    Timestamp   = item.PublishDate.DateTime
                };
                list.Add(feedItem);
            }
            return(list);
        }
示例#49
0
        private async void GridViewBlogItems_ItemClick(object sender, ItemClickEventArgs e)
        {
            FeedItem feed = e.ClickedItem as FeedItem;

            if (feed != null && (feed.Link != null))
            {
                try
                {
                    if (Window.Current.Bounds.Width <= 1000)
                    {
                        await Windows.System.Launcher.LaunchUriAsync(feed.Link);
                    }
                    else
                    {
                        Frame.Navigate(typeof(WebPage), feed.Link);
                    }
                }
                catch (Exception)
                {
                    // No need to catch the Exception
                }
            }
        }
示例#50
0
        public void ApplyValuesFromTest()
        {
            AssertHelper.ExpectedException <ArgumentNullException>(() => new FeedItem(null, DateTimeOffset.Now, "test", "test", "test"));

            var itemA1 = new FeedItem(new Uri("http://www.test.com/rss/feed"), new DateTimeOffset(2020, 5, 5, 12, 0, 0, new TimeSpan(1, 0, 0)), "name", "desc", "author");

            Assert.AreEqual(new DateTimeOffset(2020, 5, 5, 12, 0, 0, new TimeSpan(1, 0, 0)), itemA1.Date);
            Assert.AreEqual("name", itemA1.Name);
            Assert.AreEqual("desc", itemA1.Description);
            Assert.AreEqual("author", itemA1.Author);

            var itemA2 = new FeedItem(new Uri("http://www.test.com/rss/feed"), new DateTimeOffset(2022, 5, 5, 12, 0, 0, new TimeSpan(1, 0, 0)), "name2", "desc2", "author2");

            itemA1.ApplyValuesFrom(itemA2);
            Assert.AreEqual(new DateTimeOffset(2022, 5, 5, 12, 0, 0, new TimeSpan(1, 0, 0)), itemA1.Date);
            Assert.AreEqual("name2", itemA1.Name);
            Assert.AreEqual("desc2", itemA1.Description);
            Assert.AreEqual("author2", itemA1.Author);

            var itemB1 = new FeedItem(new Uri("http://www.test.com/rss/feed2"), new DateTimeOffset(2020, 5, 5, 12, 0, 0, new TimeSpan(1, 0, 0)), "name", "desc", "author");

            AssertHelper.ExpectedException <InvalidOperationException>(() => itemA1.ApplyValuesFrom(itemB1));
        }
示例#51
0
        public void ViewFeed()
        {
            // Arrange
            var viewModel = this.GetViewModel();

            var expectedFeedItem = new FeedItem();

            Type     actualViewModelType = null;
            FeedItem actualFeedItem      = null;

            this.Navigator.NavigateToViewModelDelegate = (viewModelType, parameter) =>
            {
                actualViewModelType = viewModelType;
                actualFeedItem      = parameter as FeedItem;
            };

            // Act
            viewModel.ViewFeed(expectedFeedItem);

            // Assert
            Assert.AreSame(expectedFeedItem, actualFeedItem, "FeedItem");
            Assert.AreEqual(typeof(FeedItemViewModel), actualViewModelType, "ViewModel Type");
        }
示例#52
0
        public void UndoDisLike(FeedItem feedItem, JunaUser user)
        {
            if (feedItem != null && user != null)
            {
                var activity = _activityRepository.GetByActorVerbAndObject(
                    actor: $"JunaUser:{user.ObjectId}",
                    verb: InteractionMetadata.INTERACTION_DISLIKE,
                    objectString: $"{feedItem.ContentType}:{feedItem.Id}"
                    );
                if (activity != null)
                {
                    var boardFeed = _streamClient.Feed(FeedGroup.BoardFeedType, StreamHelper.GetStreamActorId(activity));
                    boardFeed.RemoveActivity(activity.Id.ToString(), true);
                    _activityRepository.Delete(activity);
                }
                if (feedItem.Interactions.Dislikes > 0)
                {
                    feedItem.Interactions.Dislikes--;
                }

                _feedItemRepository.Upsert(feedItem);
            }
        }
示例#53
0
        private FeedItem SolrFeedItemToFeedItem(Solrs.FeedItem s)
        {
            var feedItem = new FeedItem
            {
                FeedId = s.FeedId.FirstOrDefault(),
                Feed   = new Feed
                {
                    Id       = s.FeedId.FirstOrDefault(),
                    IconUri  = s.FeedIconUri?.FirstOrDefault(),
                    Category = s.FeedCategory?.FirstOrDefault(),
                    Name     = s.FeedName?.FirstOrDefault(),
                },
                Summary          = s.Summary?.FirstOrDefault(),
                Content          = s.Content?.FirstOrDefault(),
                Title            = s.Title?.FirstOrDefault(),
                Id               = s.Id,
                PublishTimeInUtc = s.PublishTimeInUtc.FirstOrDefault(),
                TopicPictureUri  = s.TopicPictureUri?.FirstOrDefault(),
                Uri              = s.Uri.FirstOrDefault(),
            };

            return(feedItem);
        }
示例#54
0
        /// <summary>
        /// Creates a FeedItemOperation that will create a FeedItem with the
        /// specified values when sent to FeedItemService.mutate.
        /// </summary>
        /// <param name="adCustomizerFeed">The ad customizer feed.</param>
        /// <param name="name">The value for the name attribute of the FeedItem.
        /// </param>
        /// <param name="price">The value for the price attribute of the FeedItem.
        /// </param>
        /// <param name="date">The value for the date attribute of the FeedItem.
        /// </param>
        /// <returns>A new FeedItemOperation for adding a FeedItem.</returns>
        private static FeedItemOperation CreateFeedItemAddOperation(
            AdCustomizerFeed adCustomizerFeed, string name, string price, string date)
        {
            FeedItem feedItem = new FeedItem()
            {
                feedId = adCustomizerFeed.feedId,

                // FeedAttributes appear in the same order as they were created
                // - Name, Price, Date. See CreateCustomizerFeed method for details.
                attributeValues = new FeedItemAttributeValue[]
                {
                    new FeedItemAttributeValue()
                    {
                        feedAttributeId = adCustomizerFeed.feedAttributes[0].id,
                        stringValue     = name
                    },

                    new FeedItemAttributeValue()
                    {
                        feedAttributeId = adCustomizerFeed.feedAttributes[1].id,
                        stringValue     = price
                    },

                    new FeedItemAttributeValue()
                    {
                        feedAttributeId = adCustomizerFeed.feedAttributes[2].id,
                        stringValue     = date
                    }
                },
            };

            return(new FeedItemOperation()
            {
                operand = feedItem,
                @operator = Operator.ADD
            });
        }
示例#55
0
    public static List<FeedItem> GetPublicPhotosFromUser(string apiKey, string userId, int maxPhotos = 20)
    {
        maxPhotos = Math.Max(maxPhotos, 0);
        var parameters = new NameValueCollection {
            { "method", "flickr.people.getPublicPhotos" },
            { "api_key", apiKey },
            { "user_id", userId },
            { "format", "json" },
            { "per_page", maxPhotos.ToString()},
            { "extras", "description,date_upload,owner_name,url_t"},
            { "nojsoncallback", "1" }
        };
        Uri uri = PrepareRequest(parameters);

        using (var client = new WebClient()) {
            var result = new List<FeedItem>();
            string content = client.DownloadString(uri);
            dynamic json = Json.Decode(content);
            if ((string)json.stat == "ok" && json.photos != null && json.photos.photo != null) {
                foreach (dynamic photo in json.photos.photo) {
                    var feedItem = new FeedItem(
                        id: (string)photo.id,
                        title: (string)photo.title,
                        author: (string)photo.ownername,
                        content: (string)photo.description._content,
                        publishedDate: ConvertFromUnixTimestamp(long.Parse((string)photo.dateupload)),
                        photoUrl: (string)photo.url_t,
                        webUrl: ConstructPhotoWebPageUrl(userId, photo.id)
                    );
                    result.Add(feedItem);
                }
            }

            return result;
        };
    }
示例#56
0
 internal void AddItem(FeedItem item)
 {
     item.Feed = this;
     item.Id = Items.Count + 1;
     Items.Add(item);
 }
示例#57
0
        public void set_the_updated()
        {
            var subject = new ItemSubject
            {
                Number = 333,
                Updated = DateTime.Today.AddDays(-3)
            };

            var target = new SimpleValues<ItemSubject>(subject);

            var map = new FeedItem<ItemSubject>(x => x.UpdatedByProperty(o => o.Updated));

            var item = new SyndicationItem();
            map.As<IFeedItem<ItemSubject>>().ConfigureItem(item, target);

            item.LastUpdatedTime.Date.ShouldEqual(subject.Updated.Date);
        }
示例#58
0
        private bool IsInDateRange(string filter, FeedItem item)
        {
            bool isGood = false;
            if (filter.Equals("All")) // all
            {
                isGood = true;
            }
            else if (filter.Equals("From last hour")) // from last hour
            {
                DateTime threshold = DateTime.Now;
                threshold = threshold.AddHours(-1);
                isGood = (item.Date.CompareTo(threshold) >= 0);
            }
            else if (filter.Equals("From last 12 hours")) // from last 12 hours
            {
                DateTime threshold = DateTime.Now;
                threshold = threshold.AddHours(-12);
                isGood = (item.Date.CompareTo(threshold) >= 0);
            }
            else if (filter.Equals("From today")) // from today
            {
                DateTime threshold = DateTime.Now;
                isGood = (threshold.DayOfYear == item.Date.DayOfYear &&
                    threshold.Year == item.Date.Year);
            }
            else if (filter.Equals("From yesterday")) // from yesterday
            {
                DateTime threshold = DateTime.Now;
                threshold = threshold.AddDays(-1);
                isGood = (item.Date.CompareTo(threshold) >= 0);
            }
            else if (filter.Equals("From last week")) // from last week
            {
                DateTime threshold = DateTime.Now;
                threshold = threshold.AddDays(-7);
                isGood = (item.Date.CompareTo(threshold) >= 0);
            }
            else if (filter.Equals("From last month")) // from last month
            {
                DateTime threshold = DateTime.Now;
                threshold = threshold.AddMonths(-1);
                isGood = (item.Date.CompareTo(threshold) >= 0);
            }

            return isGood;
        }
示例#59
0
    //method from Feed.aspx.cs
    private string[] GetInfo(FeedItem feedItem)
    {
        string[] ret = new string[3];
        //0 - Title
        //1 - Thumbnail
        //2 - 

        StringBuilder sbTitle = new StringBuilder();
        StringBuilder sbThumb = new StringBuilder();
        StringBuilder sbURL = new StringBuilder();

        object[] parameters = new object[14];

        parameters[1] = feedItem.Thumbnail;
        parameters[2] = feedItem.Text;
        parameters[3] = TimeDistance.TimeAgo(feedItem.DateTime);
        parameters[4] = feedItem.Title;
        parameters[5] = feedItem.FriendNickname1;
        parameters[6] = feedItem.FriendNickname2;
        parameters[7] = "/users/" + feedItem.FriendNickname1;
        parameters[8] = "/users/" + feedItem.FriendNickname2;
        //parameters[11] = "javascript:displayMiniVideo(\"" + feedItem.MainWebID + "\",\"" + Server.HtmlEncode(feedItem.Title) + "\")";
        parameters[9] = feedItem.Url;
        parameters[10] = feedItem.WebPhotoCollectionID;
        parameters[12] = (feedItem.Friend1FullName.Trim() != string.Empty) ? feedItem.Friend1FullName : feedItem.FriendNickname1;
        parameters[13] = (feedItem.Friend2FullName.Trim() != string.Empty) ? feedItem.Friend2FullName : feedItem.FriendNickname2;


        if (feedItem.FeedItemType == FeedItemType.Video)
        {
            sbTitle.AppendFormat(@"{5} has posted a new video: {4}", parameters);
            sbThumb.AppendFormat("{1}", parameters);
        }
        else if (feedItem.FeedItemType == FeedItemType.Photo)
        {
            sbTitle.AppendFormat(@"{5} has posted a new Photo Gallery: {4}", parameters);
            sbThumb.AppendFormat("{1}", parameters);
        }
        else if (feedItem.FeedItemType == FeedItemType.WallComment)
        {
            sbTitle.AppendFormat(@"{5} has written on {6}'s wall", parameters);
            sbThumb.AppendFormat("{1}", parameters);
        }
        else if (feedItem.FeedItemType == FeedItemType.Ask)
        {
            sbTitle.AppendFormat(@"{5} has asked: {2}", parameters);
            sbThumb.AppendFormat("{1}", parameters);
        }
        else if (feedItem.FeedItemType == FeedItemType.NewFriend)
        {
            sbTitle.AppendFormat(@"{5} and {6} are now friends", parameters);
            sbThumb.AppendFormat("/", parameters);
        }
        else if (feedItem.FeedItemType == FeedItemType.Blog)
        {
            sbTitle.AppendFormat(@"{5} has posted a new Blog Entry", parameters);
            sbThumb.AppendFormat("{1}", parameters);
        }
        else if (feedItem.FeedItemType == FeedItemType.BookmarkedVideo)
        {
            sbTitle.AppendFormat(@"{5} would like to share a video: {4}", parameters);
            sbThumb.AppendFormat("{1}", parameters);
        }
        else if (feedItem.FeedItemType == FeedItemType.BookmarkedPhoto)
        {
            sbTitle.AppendFormat(@"{5} would like to share a photo {4}", parameters);
            sbThumb.AppendFormat("{1}", parameters);
        }
        else if (feedItem.FeedItemType == FeedItemType.Mp3Upload)
        {
            sbTitle.AppendFormat(@"{5} has uploaded a new mp3 : {2}", parameters);
            sbThumb.AppendFormat("{1}", parameters);
        }
        else if (feedItem.FeedItemType == FeedItemType.StatusText)
        {
            sbTitle.AppendFormat(@"{5} is : {2}", parameters);
            sbThumb.AppendFormat("{1}", parameters);
        }

        ret[0] = sbTitle.ToString();
        ret[1] = sbThumb.ToString();

        return ret;
    }
示例#60
0
    //method from Feed.aspx.cs
    private string FeedRow(FeedItem feedItem)
    {
        StringBuilder sbRow = new StringBuilder();
        object[] parameters = new object[11];

        parameters[1] = feedItem.Thumbnail;
        parameters[2] = feedItem.Text;
        parameters[3] = TimeDistance.TimeAgo(feedItem.DateTime);
        parameters[4] = feedItem.Title;
        parameters[5] = feedItem.FriendNickname1;
        parameters[6] = feedItem.FriendNickname2;
        parameters[7] = "/users/" + feedItem.FriendNickname1;
        parameters[8] = "/users/" + feedItem.FriendNickname2;
        parameters[9] = feedItem.Url;
        parameters[10] = feedItem.WebPhotoCollectionID;

        if (feedItem.FeedItemType == FeedItemType.Video)
        {
            sbRow.AppendFormat(@"<div class='feeditem clearfix feedvideo'>
						<p class='delete'>{3}</p>
						<p class='head'><strong><a href='{7}'>{5}</a></strong> has posted a new <a href=''>Video</a>:</p>
						<div class='feedcontent'>
							<p class='vid_thumb right'><a href=''><img src='{1}' style='width:80px;height:57px;' alt='{4}' /></a></p>
							<h4><a href='{9}'>{4}</a></h4>
							<p>{2}</p>
						</div>
					</div><hr/>", parameters);
        }
        else if (feedItem.FeedItemType == FeedItemType.Photo)
        {
            sbRow.AppendFormat(@"<div class='feeditem clearfix feedphoto'>
						<p class='delete'>{3}</p>
						<p class='head'><strong><a href='{7}'>{5}</a></strong> has posted a new <a href=''>Photo Gallery</a>:</p>
						<div class='feedcontent'>
							<p class='vid_thumb right'><a href=''><img src='{1}' style='width:80px;height:57px;' alt='' /></a></p>
							<h4><a href=''>{4}</a></h4>
							<p>{2}</p>
						</div>
					</div><hr/>", parameters);
        }
        else if (feedItem.FeedItemType == FeedItemType.WallComment)
        {
            sbRow.AppendFormat(@"<div class='feeditem clearfix feedcomment'>
						<p class='delete'>{3}</p>
						<p class='head'><strong><a href='{7}'>{5}</a></strong> has written on <a href=''>{6}'s wall</a>:</p>

						<div class='feedcontent'>
							{2}
						</div>
					</div><hr/>", parameters);
        }
        else if (feedItem.FeedItemType == FeedItemType.Ask)
        {
            sbRow.AppendFormat(@"<div class='feeditem clearfix feedaskafriend'>

						<p class='delete'>{3}</p>
						<p class='head'><strong><a href='{7}'>{5}</a></strong> has <a href=''>Asked</a>:</p>
						<div class='feedcontent'>
							<h4>Q: <a href=''>{2}</a></h4>
						</div>

					</div><hr/>", parameters);
        }
        else if (feedItem.FeedItemType == FeedItemType.NewFriend)
        {
            sbRow.AppendFormat(@"<div class='feeditem clearfix feedfriend'>
						<p class='delete'>{3}</p>
						<p class='head'><strong><a href='{7}'>{5}</a></strong> and <strong><a href='{8}'>{6}</a></strong> are now friends!</p>

					</div><hr/>", parameters);
        }
        else if (feedItem.FeedItemType == FeedItemType.Blog)
        {
            sbRow.AppendFormat(@"<div class='feeditem clearfix feedcomment'>
						<p class='delete'>{3}</p>
						<p class='head'><strong><a href='{7}'>{5}</a></strong> has posted a new <a href=''>Blog Entry</a>:</p>

						<div class='feedcontent'>
							{2}
						</div>
					</div><hr/>", parameters);
        }
        else if (feedItem.FeedItemType == FeedItemType.BookmarkedVideo)
        {
            sbRow.AppendFormat(@"<div class='feeditem clearfix feedfavourite'>						
						<p class='head'><strong><a href='{7}'>{5}</a></strong> would like to share a video: <a href=''>{4}</a>:</p>
						<div class='feedcontent'>
                            <p class='vid_thumb right'><a href=''><img src='{1}' style='width:80px;height:57px;' alt='{4}' /></a></p>
							{2}
						</div>
					</div><hr/>", parameters);
        }
        else if (feedItem.FeedItemType == FeedItemType.BookmarkedPhoto)
        {
            sbRow.AppendFormat(@"<div class='feeditem clearfix feedfavourite'>
						<p class='delete'>{3}</p>
						<p class='head'><strong><a href='{7}'>{5}</a></strong> would like to share a <a href=''>Photo</a>:</p>

						<div class='feedcontent'>
                            <p class='vid_thumb right'><a href=''><img src='{1}' style='width:80px;height:57px;' alt='' /></a></p>
							{2}
						</div>
					</div><hr/>", parameters);
        }

        return sbRow.ToString();
    }