Inheritance: MonoBehaviour
Example #1
0
        public static void UpdateFeedTile(Feed feed)
        {
            // タイルが存在しない場合は何もしない
            if (!SecondaryTile.Exists(feed.Id))
            {
                return;
            }

            // フィード内に記事が無い場合は何もしない
            if (!feed.FeedItems.Any())
            {
                return;
            }

            // 大きなテキスト1つと折り返し3行表示されるテキストを持つテンプレートを取得
            var template = TileUpdateManager.GetTemplateContent(
                TileTemplateType.TileSquareText02);
            // textタグに表示内容を設定
            var texts = template.GetElementsByTagName("text");
            texts[0].InnerText = feed.Title;
            texts[1].InnerText = feed.FeedItems.First().Title;

            // タイルを更新するオブジェクトを取得
            var updater = TileUpdateManager.CreateTileUpdaterForSecondaryTile(feed.Id);
            // 有効期間5分の通知を設定
            updater.Update(new TileNotification(template)
            {
                ExpirationTime = DateTimeOffset.Now.AddMinutes(5)
            });
        }
Example #2
0
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        FeedRepository rfeed = new FeedRepository();
        Utility Util = new Utility();
        Feed feed = new Feed();

        feed.Author = Author.Value;
        feed.Title = title.Value;
        feed.Summary = Summary.Value;
        feed.Description = Description.Value;
        feed.Link = Link.Value;
        feed.CategoryID = Int16.Parse(CategoryName.SelectedValue);
        feed.FeedID = Int32.Parse(FeedID.Value);
        feed.isValid = Int16.Parse(FeedState.SelectedValue);
        feed.DisplayIn = "";
        for (int i = 0; i < CheckBoxDisplayIn.Items.Count; i++)
        {
            if (CheckBoxDisplayIn.Items[i].Selected)
            {
                if (feed.DisplayIn.Length > 0)
                    feed.DisplayIn += ",";
                feed.DisplayIn += CheckBoxDisplayIn.Items[i].Value;
            }
        }
        if (feed.DisplayIn.Length == 0)
            feed.DisplayIn = "-1";
        rfeed.Update(feed);

        feed = null;
        Util = null;
        rfeed = null;
    }
Example #3
0
        private void saveBtn_Click(object sender, EventArgs e)
        {
            feed = new Feed(this.feedTitle.Text, this.feedDesc.Text, this.feedUrl.Text);
            //feed = new Feed();
            feed.mTitle = this.feedTitle.Text;

            // Save feed to xml
            //feed.Save();

            // Add the feed to the correct channel
            foreach (Channel c in channels)
            {
                if (c.mTitle == selected.Text)
                {
                    c._Add(feed);
                }
            }

            // Add feed to current channel
            selected.Nodes.Add(feed.mTitle);

            // !!!!! use user-defined number of articles to display/refresh at a time. 10 is arbitrary number !!!!!
            feed.refresh(10);

            this.Close();
        }
Example #4
0
        public void Obter_Quando_UrlValidaLocal_Deve_RetornarFeed()
        {
            var feed = new Feed();

            var result = feed.Obter(@"C:\Users\LaurenceM\Trabalho\teste\MinutoSeguros\MinutoSeguros.UI\" + Parametro.UrlFeedLocal);
            Assert.IsNotNull(result);
        }
Example #5
0
        public static async Task<bool> CreateTileIfNotExist(Feed feed)
        {
            // 既にタイルが存在する場合は何もしない
            if (SecondaryTile.Exists(feed.Id))
            {
                return false;
            }

            // セカンダリタイルを作成
            var tile = new SecondaryTile(
                // タイルのId
                feed.Id,
                // タイルの短い名前
                feed.Title,
                // タイルの表示名
                feed.Title,
                // タイルからアプリケーションを起動したときに渡される引数
                feed.Id,
                // タイルの名前の表示方法を指定
                TileOptions.ShowNameOnLogo,
                // タイルのロゴを指定
                new Uri("ms-appx:///Assets/Logo.png"));
            // ユーザーにタイルの作成をリクエスト
            return await tile.RequestCreateAsync();
        }
Example #6
0
        public override bool VisibleFor(Feed feed, object data, Guid userId)
        {
            if (!WebItemSecurity.IsAvailableForUser(ProductID.ToString(), userId)) return false;

            var file = (FileEntry)data;

            bool targetCond;
            if (feed.Target != null)
            {
                if (!string.IsNullOrEmpty(file.SharedToMeBy) && file.SharedToMeBy == userId.ToString()) return false;

                var owner = new Guid((string)feed.Target);
                var groupUsers = CoreContext.UserManager.GetUsersByGroup(owner).Select(x => x.ID).ToList();
                if (!groupUsers.Any())
                {
                    groupUsers.Add(owner);
                }
                targetCond = groupUsers.Contains(userId);
            }
            else
            {
                targetCond = true;
            }

            return targetCond &&
                   new FileSecurity(new DaoFactory()).CanRead(file, userId);
        }
Example #7
0
 public void ReadArticles()
 {
     var feedXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
         "<feed xmlns=\"http://www.w3.org/2005/Atom\">" +
         "  <title>Example Feed</title>" +
         "  <link href=\"http://example.org/\"/>" +
         "  <updated>2003-12-13T18:30:02Z</updated>" +
         "  <author>" +
         "    <name>John Doe</name>" +
         "  </author>" +
         "  <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>" +
         "  <entry>" +
         "    <title>Atom-Powered Robots Run Amok</title>" +
         "    <link href=\"http://example.org/2003/12/13/atom03\"/>" +
         "    <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>" +
         "    <published>2003-12-13T18:30:02Z</published>" +
         "    <updated>2004-01-13T18:30:02Z</updated>" +
         "    <summary>Some text.</summary>" +
         "  </entry>" +
         "</feed>";
     var feed = new Feed();
     _target.Read(feed, XDocument.Parse(feedXml));
     Assert.That(feed.GetHeadChunk(null).Articles.Count, Is.EqualTo(1));
     var art = feed.GetHeadChunk(null).Articles.First();
     Assert.That(art.Title, Is.EqualTo("Atom-Powered Robots Run Amok"));
     Assert.That(art.Link, Is.EqualTo(new Uri("http://example.org/2003/12/13/atom03")));
     Assert.That(art.PublishDate, Is.EqualTo(new DateTime(2003, 12, 13, 18, 30, 2)));
     Assert.That(art.Summary, Is.EqualTo("Some text."));
     Assert.That(art.UniqueId, Is.EqualTo("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a"));
 }
        public void DoWork(IRequest request)
        {
            NorthwindConfig config = new NorthwindConfig();
            config.CurrencyCode = "EUR";
            config.CrmUser = "******";
            config.Path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Northwind");

            string fileName = Path.Combine(config.Path, "Northwind.mdb");
            FileInfo fileInfo = new FileInfo(fileName);
            string link = _requestContext.ContractLink + "-";

            DatasetFeedEntry entry = new DatasetFeedEntry();
            entry.Id = link;
            entry.Title = fileInfo.Name;

            entry.Published = fileInfo.CreationTime;
            entry.Updated = fileInfo.LastAccessTime;
            entry.Link = link;

            Feed<DatasetFeedEntry> feed = new Feed<DatasetFeedEntry>();
            feed.Id = "Available Datasets";
            feed.Title = "Available Datasets";
            feed.Entries.Add(entry);
            request.Response.Feed = feed;
        }
        /// <summary>
        /// FanIn
        /// </summary>
        public IEnumerable<Activity> Load(Feed feed)
        {
            var snapshot = new Dictionary<byte[], Queue<Activity>>(activityStreamStore.Count);
            foreach (var item in activityStreamStore)
            {
                snapshot.Add(item.Key, new Queue<Activity>(item.Value));
            }

            SortedSet<Activity> buffer = new SortedSet<Activity>(Activity.Comparer);
            var streams = feed.FeedStreams.ToList();
            var streamsCount = streams.Count;

            //  Init
            for (int streamIndexInsideSubsciption = 0; streamIndexInsideSubsciption < streamsCount; streamIndexInsideSubsciption++)
            {
                var streamId = streams[streamIndexInsideSubsciption];
                var activity = snapshot[streamId].Dequeue();
                buffer.Add(activity);
            }

            while (buffer.Count > 0)
            {
                Activity nextActivity = buffer.FirstOrDefault();
                buffer.Remove(nextActivity);
                var streamQueue = snapshot[nextActivity.StreamId];
                if (streamQueue.Count > 0)
                {
                    var candidate = snapshot[nextActivity.StreamId].Dequeue();
                    buffer.Add(candidate);
                }
                yield return nextActivity;
            }
        }
Example #10
0
 public UserFeed(Feed feed)
 {
     Name = feed.Name;
     Href = feed.Href;
     BaseUrl = feed.BaseUrl;
     Category = feed.Category;
 }
Example #11
0
        // 每日清除过期feed
        public virtual void ClearFeeds()
        {
            DateTime lastClearTime = config.Instance.Site.LastFeedClearTime;
            if (cvt.IsDayEqual( lastClearTime, DateTime.Now )) return;

            Feed feed = new Feed();
            EntityInfo ei = Entity.GetInfo( feed );
            String table = ei.TableName;

            // TODO 支持其他数据库类型,
            // 清除所有30天前的feed
            int dayCount = config.Instance.Site.FeedKeepDay;
            String sql = "";
            DatabaseType dbtype = ei.DbType;
            if (dbtype == DatabaseType.SqlServer)
                sql = "delete from " + table + " where datediff(day, created, getdate())>" + dayCount;
            else if (dbtype == DatabaseType.Access)
                sql = "delete from " + table + " where datediff('d', created, now())>" + dayCount;
            else if( dbtype == DatabaseType.MySql)
                sql = "delete from " + table + " where datediff(created, now())>" + dayCount;
            else
                throw new NotImplementedException( "not implemented database function : datediff" );

            db.RunSql<Feed>( sql );

            config.Instance.Site.Update( "LastFeedClearTime", DateTime.Now );
        }
    public GDataResultAggregator(string playlistURL)
    {
      YouTubeRequestSettings settings = new YouTubeRequestSettings(APPNAME, CLIENTID, DEVELKEY);
      YouTubeRequest request = new YouTubeRequest(settings);

      _videoFeed = request.Get<Video>(new Uri(playlistURL));
    }
        public IEnumerable<Activity> Get(Feed feed, Paging paging)
        {
            SortedSet<Activity> activities = new SortedSet<Activity>(Activity.Comparer);

            foreach (var streamId in feed.Streams)
            {
                var streamIdQuery = Convert.ToBase64String(streamId);

                var prepared = session
                        .Prepare(LoadActivityStreamQueryTemplate)
                        .Bind(streamIdQuery, paging.Timestamp)
                        .SetAutoPage(false)
                        .SetPageSize(paging.Take);

                var rowSet = session.Execute(prepared);
                foreach (var row in rowSet.GetRows())
                {
                    using (var stream = new MemoryStream(row.GetValue<byte[]>("data")))
                    {
                        var storedActivity = (Activity)serializer.Deserialize(stream);
                        activities.Add(storedActivity);
                    }
                }
            }
            return activities.Take(paging.Take);
        }
Example #14
0
		public async Task<EditFeedResponse> AddFeedAsync(FeedDto feed)
        {
            var response = new EditFeedResponse();

            try
            {
                var now = DateTime.Now;

                var newFeed = new Feed
                {
                    Class = feed.Class,
                    Mappings = feed.Mappings,
                    Created = now,
                    Updated = now
                };

                var addedArticle = this.feedRepository.Insert(newFeed);
                await this.unitOfWork.CommitAsync();
                response.Status = ResponseStatus.OK;
            }
            catch (Exception ex)
            {
                //this.logService.LogError(ex, new HttpContextWrapper(HttpContext.Current));
                response.Status = ResponseStatus.SystemError;
            }

            return response;
        }
Example #15
0
 public void Article()
 {
     var feedText = "<?xml version=\"1.0\" ?>" +
         "<rss version=\"2.0\">" +
         "  <channel>" +
         "    <title>StrongBad!!!1</title>" +
         "    <description>Kangaroo Jack's colby jack</description>" +
         "    <link>http://strongbad.example.org/feed</link>" +
         "    <item>" +
         "      <title>Incredipede</title>" +
         "      <description>This is a multiline sequence possibly containing HTML.</description>" +
         "      <link>https://dignitas.com/team/tamewymild</link>" +
         "      <author>Team Dignitas</author>" +
         "      <pubDate>Sun, 19 May 2002 15:21:36 GMT</pubDate>" +
         "    </item>" +
         "  </channel>" +
         "</rss>";
     var feed = new Feed();
     _target.Read(feed, XDocument.Parse(feedText));
     var article = feed.GetHeadChunk(null).Articles.First();
     Assert.That(article.Title, Is.EqualTo("Incredipede"));
     Assert.That(article.Description, Is.EqualTo("This is a multiline sequence possibly containing HTML."));
     Assert.That(article.Link, Is.EqualTo(new Uri("https://dignitas.com/team/tamewymild")));
     Assert.That(article.Authors.Count, Is.EqualTo(1));
     Assert.That(article.Authors.First().Name, Is.EqualTo("Team Dignitas"));
     Assert.That(article.PublishDate, Is.EqualTo(new DateTime(2002, 5, 19, 15, 21, 36)));
 }
        public void Parse(Feed<Video> videoFeed, VideoList videoList)
        {
            foreach (Video video in videoFeed.Entries)
            {
                string id = video.VideoId;
                string title = video.Title;

                if (video.Thumbnails != null && video.Thumbnails.Count > 0)
                {
                    foreach (MediaContent mediaContent in video.Contents)
                    {
                        if ("5".Equals(mediaContent.Format))
                        {
                            if ("120".Equals(video.Thumbnails[0].Width) && "90".Equals(video.Thumbnails[0].Height))
                            {
                                VideoItem videoItem = new VideoItem(id, title, ProviderEnum.YouTube);
                                videoItem.ThumbnailImageURL = video.Thumbnails[0].Url;
                                videoItem.ThumbnailImageWidth = video.Thumbnails[0].Width;
                                videoItem.ThumbnailImageHeight = video.Thumbnails[0].Height;

                                videoList.AddVideo(videoItem);
                            }
                        }
                    }
                }
            }
        }
		public static void AddFeed(Feed post)
		{
			string action = string.Empty;
			if (post is FeedNews)
			{
				action = NewsResource.UserActivity_AddNewsFeed;
			}
			else if (post is FeedPoll)
			{
				action = NewsResource.UserActivity_AddPollFeed;
			}
			if (!string.IsNullOrEmpty(action))
			{
				UserActivity ua = ApplyCustomeActivityParams(
					post,
					ComposeActivityByFeed(post),
					action,
					new Guid(post.Creator),
					UserActivityConstants.ContentActionType,
					UserActivityConstants.NormalContent
				);
			    ua.HtmlPreview = post.Text;
				PublishInternal(ua);
			}
		}
Example #18
0
 public void FeedData()
 {
     var feedText = "<?xml version=\"1.0\" ?>" +
         "<rss version=\"2.0\">" +
         "  <channel>" +
         "    <title>StrongBad!!!1</title>" +
         "    <description>Kangaroo Jack's colby jack</description>" +
         "    <webMaster>[email protected]</webMaster>" +
         "    <image>" +
         "      <url>http://strongbad.example.org/content/sb.png</url>" +
         "      <title>Link master</title>" +
         "      <link>http://miku.vocaloid.ru/waffle</link>" +
         "    </image>" +
         "    <link>http://strongbad.example.org/feed</link>" +
         "  </channel>" +
         "</rss>";
     var feed = new Feed();
     _target.Read(feed, XDocument.Parse(feedText));
     Assert.That(feed.Title, Is.EqualTo("StrongBad!!!1"));
     Assert.That(feed.Description, Is.EqualTo("Kangaroo Jack's colby jack"));
     Assert.That(feed.LogoUri, Is.EqualTo(new Uri("http://strongbad.example.org/content/sb.png")));
     Assert.That(feed.ImageLinkTarget, Is.EqualTo(new Uri("http://miku.vocaloid.ru/waffle")));
     Assert.That(feed.ImageTitle, Is.EqualTo("Link master"));
     Assert.That(feed.Link, Is.EqualTo(new Uri("http://strongbad.example.org/feed")));
 }
        public void TestAddAccessPoints()
        {
            var capabilityList = CapabilityListTest.CreateTestCapabilityList();
            var feed1 = new Feed {Name = "Test", CapabilityLists = {capabilityList}};
            var feed2 = new Feed {Name = "Test", CapabilityLists = {capabilityList}};
            using (var applyFlag1 = new TemporaryFlagFile("0install-unit-tests"))
            using (var applyFlag2 = new TemporaryFlagFile("0install-unit-tests"))
            {
                var accessPoints1 = new AccessPoint[] {new MockAccessPoint {ID = "id1", Capability = "my_ext1", ApplyFlagPath = applyFlag1}};
                var accessPoints2 = new AccessPoint[] {new MockAccessPoint {ID = "id2", Capability = "my_ext2", ApplyFlagPath = applyFlag2}};

                Assert.AreEqual(0, _integrationManager.AppList.Entries.Count);
                var appEntry1 = _integrationManager.AddApp(new FeedTarget(FeedTest.Test1Uri, feed1));
                _integrationManager.AddAccessPoints(appEntry1, feed1, accessPoints1);
                Assert.AreEqual(1, _integrationManager.AppList.Entries.Count, "Should implicitly create missing AppEntries");
                Assert.IsTrue(applyFlag1.Set, "Should apply AccessPoint");
                applyFlag1.Set = false;

                Assert.DoesNotThrow(() => _integrationManager.AddAccessPoints(appEntry1, feed1, accessPoints1), "Duplicate access points should be silently reapplied");
                Assert.IsTrue(applyFlag1.Set, "Duplicate access points should be silently reapplied");

                _integrationManager.AddAccessPoints(appEntry1, feed1, accessPoints2);
                applyFlag2.Set = false;

                var appEntry2 = _integrationManager.AddApp(new FeedTarget(FeedTest.Test2Uri, feed2));
                Assert.Throws<ConflictException>(() => _integrationManager.AddAccessPoints(appEntry2, feed2, accessPoints2), "Should prevent access point conflicts");
                Assert.IsFalse(applyFlag2.Set, "Should prevent access point conflicts");
            }
        }
Example #20
0
        public override bool VisibleFor(Feed feed, object data, Guid userId)
        {
            if (!WebItemSecurity.IsAvailableForUser(ProductID.ToString(), userId)) return false;

            var tuple = (Tuple<File, SmallShareRecord>)data;
            var file = tuple.Item1;
            var shareRecord = tuple.Item2;

            bool targetCond;
            if (feed.Target != null)
            {
                if (shareRecord != null && shareRecord.ShareBy == userId) return false;

                var owner = (Guid)feed.Target;
                var groupUsers = CoreContext.UserManager.GetUsersByGroup(owner).Select(x => x.ID).ToList();
                if (!groupUsers.Any())
                {
                    groupUsers.Add(owner);
                }
                targetCond = groupUsers.Contains(userId);
            }
            else
            {
                targetCond = true;
            }

            return targetCond && new FileSecurity(new DaoFactory()).CanRead(file, userId);
        }
Example #21
0
        public void Obter_Quando_UrlValidaExterna_Deve_RetornarFeed()
        {
            var feed = new Feed();

            var result = feed.Obter(Parametro.UrlFeed);
            Assert.IsNotNull(result);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RestMsMessageConsumer"/> class.
 /// </summary>
 /// <param name="configuration">The configuration of the RestMS broker</param>
 /// <param name="queueName">Name of the queue.</param>
 /// <param name="routingKey">The routing key.</param>
 public RestMsMessageConsumer(RestMSMessagingGatewayConfiguration configuration, string queueName, string routingKey) 
     : base(configuration)
 {
     _queueName = queueName;
     _routingKey = routingKey;
     _feed = new Feed(this);
     _domain = new Domain(this);
 }
Example #23
0
 public void CancelUpdate(Feed feed)
 {
     lock (update_task_group.SyncRoot) {
         if (update_feed_map.ContainsKey (feed)) {
             update_feed_map[feed].CancelAsync ();
         }
     }
 }
 public MainPage() { 
     InitializeComponent();
     _lists = new DownloadLists(OnDownloadStatusChange);
     _webView = new WebViewWrapper(WebBrowser);
     _webView.Navigating += (sender, args) => Loading();
     DownloadStatusGrid.DataContext = _lists;
     DownloadStatusGrid.ItemsSource = _lists.Entries;
 }
Example #25
0
 public void Avaliar_Quando_FeedValido_Deve_RetornarAnalise()
 {
     var feed = new Feed();
     var rss = feed.Obter(Parametro.UrlFeed);
     Assert.IsNotNull(rss);
     var result = new AvaliaFeed().Avaliar(rss);
     Assert.IsNotNull(result);
 }
Example #26
0
 static string printVideoFeed(Feed<Video> feed)
 {
     foreach (Video entry in feed.Entries)
     {
         string output = printVideoEntry(entry);
         return output;
     }
     return "error";
 }
Example #27
0
        public void InvalidUrlReturnsNotValid()
        {
            FeedManager.ClearFeeds();

            Feed feed = new Feed();
            feed.Name = "sample feed";
            feed.Url = "htt://example.com";

            Assert.IsFalse(feed.IsValid());
        }
        public PodcastFeedPropertiesDialog (PodcastSource source, Feed feed)
        {
            this.source = source;
            this.feed = feed;

            Title = feed.Title;
            //IconThemeUtils.SetWindowIcon (this);

            BuildWindow ();
        }
Example #29
0
        /// <summary>
        /// Creates a new feed node.
        /// </summary>
        /// <param name="feed">The <see cref="Feed"/> to be represented by this node.</param>
        /// <param name="cache">The <see cref="IFeedCache"/> the <see cref="Feed"/> is located in.</param>
        public FeedNode([NotNull] Feed feed, [NotNull] IFeedCache cache)
        {
            #region Sanity checks
            if (cache == null) throw new ArgumentNullException("cache");
            if (feed == null) throw new ArgumentNullException("feed");
            #endregion

            _cache = cache;
            _feed = feed;
        }
        public FeedDownloadCompletedEventArgs(Feed feed,
                                               FeedDownloadError error)
            : base(feed)
        {
            if (error < FeedDownloadError.None ||
                error > FeedDownloadError.DownloadSizeLimitExceeded) {
                throw new ArgumentException ("error:  Value out of range");
            }

            this.error = error;
        }
Example #31
0
        public IActionResult Dodaj(CreateTakmicenjeVM objekat)
        {
            if (ModelState.IsValid)
            {
                TakmicenjaInsert objekatValidator             = mapko.Map <TakmicenjaInsert>(objekat);
                List <(string key, string error)> listaerrora = validator
                                                                .VratiListuErroraAkcijaDodaj(objekatValidator);

                if (listaerrora.Count() == 0)
                {
                    using (var transakcija = db.Database.BeginTransaction())//sigurnost u opasnim situacijama
                    {
                        try
                        {
                            //ovaj posao ce odraditi IMapper
                            Takmicenje novo = new Takmicenje();
                            mapko.Map(objekat, novo);
                            var idUser = db.Users.Where(x => x.UserName == HttpContext.User.Identity.Name).FirstOrDefault();
                            novo.KreatorID = idUser.Id;
                            Feed TakmicenjeFeed = new Feed
                            {
                                Naziv             = novo.Naziv + " feed",
                                DatumModifikacije = DateTime.Now
                            };
                            db.Feeds.Add(TakmicenjeFeed);
                            db.SaveChanges();
                            novo.FeedID = TakmicenjeFeed.ID;

                            db.Add(novo);
                            db.SaveChanges();

                            //dobaviti igrace iz regexa
                            if (objekat.RucniOdabir)
                            {
                                validator._listaIgraca = db.Igraci.ToList();
                                List <Igrac> svi = validator.GetListaRucnihIgraca(objekat.RucnoOdabraniIgraci);
                                foreach (Igrac i in svi)
                                {
                                    Prijava novaPrijava = new Prijava
                                    {
                                        DatumPrijave = DateTime.Now,
                                        isTim        = false,
                                        Naziv        = i.PrikaznoIme,
                                        TakmicenjeID = novo.ID
                                    };

                                    novaPrijava.StanjePrijave = new Stanje_Prijave(novaPrijava.ID);
                                    db.Prijave.Add(novaPrijava);
                                    db.SaveChanges();

                                    Prijava_igrac PrijavaIgracPodatak = new Prijava_igrac
                                    {
                                        IgracID   = i.ID,
                                        PrijavaID = novaPrijava.ID
                                    };
                                    db.PrijaveIgraci.Add(PrijavaIgracPodatak);
                                    db.SaveChanges();
                                }
                            }
                            transakcija.Commit();
                            return(Redirect("/Takmicenje/Prikaz/" + novo.ID));
                        }
                        catch (DbUpdateException)
                        {
                            transakcija.Rollback();
                            ModelState.AddModelError("", "Doslo je do greške prilikom spašavanja u bazu");
                        }
                    }
                }
                else
                {
                    //ako je validator vratio errore ovdje cemo ih pametno stavit u modelstate kako bi se prikazali na viewu
                    foreach ((string key, string err)i in listaerrora)
                    {
                        ModelState.AddModelError(i.key, i.err);
                    }
                }
            }
            LoadViewBag();
            return(View(objekat));
        }
Example #32
0
        /// <summary>
        /// Create and Add Parse error to the current feed result.
        /// </summary>
        /// <param name="errorType">Type of parse error.</param>
        /// <param name="nodeInformation">Current node base information.</param>
        /// <param name="feed">Current feed result.</param>
        /// <param name="content">Current node content data. (Optonal)</param>
        /// <param name="message">Parse error message. (Optional)</param>
        protected void SetParseError(ParseErrorType errorType, NodeInformation nodeInformation, Feed feed, string?content = null, string?message = null)
        {
            //Create and Add Parse error to the current feed result
            var error = ParseError.Create(nodeInformation, ToString(), errorType, feed.CurrentParseType, content, message);

            (feed.ParseError ??= new List <ParseError>()).Add(error);
            Debug.WriteLine(error);
        }
Example #33
0
        public void FeedTest()
        {
            var feed1 = new Feed();

            feed1.FeedType = FeedType.News;
            feed1.Caption  = "aaa";
            feed1.Text     = "bbb";
            var feed1Id = feedStorage.SaveFeed(feed1, TODO, TODO).Id;

            feedStorage.SaveFeed(feed1, TODO, TODO);

            var feed2 = new Feed();

            feed2.FeedType = FeedType.Order;
            feed2.Caption  = "ccca";
            feed2.Text     = "ddd";
            var feed2Id = feedStorage.SaveFeed(feed2, TODO, TODO).Id;

            var feeds = feedStorage.GetFeeds(FeedType.News, Guid.Empty, 0, 0);

            CollectionAssert.AreEquivalent(new[] { feed1 }, feeds);
            feeds = feedStorage.GetFeeds(FeedType.Order, Guid.Empty, 0, 0);
            CollectionAssert.AreEquivalent(new[] { feed2 }, feeds);
            feeds = feedStorage.GetFeeds(FeedType.Advert, Guid.Empty, 0, 0);
            CollectionAssert.IsEmpty(feeds);

            feeds = feedStorage.GetFeeds(FeedType.All, Guid.NewGuid(), 0, 0);
            CollectionAssert.IsEmpty(feeds);

            feeds = feedStorage.SearchFeeds("c", FeedType.All, Guid.Empty, 0, 0);
            CollectionAssert.AreEquivalent(new[] { feed2 }, feeds);
            feeds = feedStorage.SearchFeeds("a");
            CollectionAssert.AreEquivalent(new[] { feed1, feed2 }, feeds);

            var feedTypes = feedStorage.GetUsedFeedTypes();

            CollectionAssert.AreEquivalent(new[] { FeedType.News, FeedType.Order }, feedTypes);

            feed2 = feedStorage.GetFeed(feed2Id);
            Assert.IsAssignableFrom(typeof(FeedNews), feed2);
            Assert.AreEqual(FeedType.Order, feed2.FeedType);
            Assert.AreEqual("ccca", feed2.Caption);
            Assert.AreEqual("ddd", feed2.Text);

            var c1 = new FeedComment(feed1Id)
            {
                Comment = "c1", Inactive = true
            };
            var c2 = new FeedComment(feed1Id)
            {
                Comment = "c2"
            };
            var c3 = new FeedComment(feed2Id)
            {
                Comment = "c3"
            };
            var c1Id = feedStorage.SaveFeedComment(c1).Id;
            var c2Id = feedStorage.SaveFeedComment(c2).Id;

            feedStorage.SaveFeedComment(c3);
            feedStorage.SaveFeedComment(c3);

            var comments = feedStorage.GetFeedComments(feed2Id);

            CollectionAssert.AreEquivalent(new[] { c3 }, comments);

            comments = feedStorage.GetFeedComments(feed1Id);
            CollectionAssert.AreEquivalent(new[] { c1, c2 }, comments);

            feedStorage.RemoveFeedComment(c2Id);
            comments = feedStorage.GetFeedComments(feed1Id);
            CollectionAssert.AreEquivalent(new[] { c1 }, comments);

            c1 = feedStorage.GetFeedComment(c1Id);
            Assert.AreEqual("c1", c1.Comment);
            Assert.IsTrue(c1.Inactive);

            feedStorage.ReadFeed(feed2Id, SecurityContext.CurrentAccount.ID.ToString());

            feedStorage.RemoveFeed(feed2Id);
            feedStorage.RemoveFeed(feed1Id);
            feed1 = feedStorage.GetFeed(feed1Id);
            Assert.IsNull(feed1);
            comments = feedStorage.GetFeedComments(feed1Id);
            CollectionAssert.IsEmpty(comments);
        }
 public override bool VisibleFor(Feed feed, object data, Guid userId)
 {
     return(base.VisibleFor(feed, data, userId) && CRMSecurity.CanAccessTo((Contact)data));
 }
Example #35
0
        private void cmbx_siteadi_SelectedIndexChanged(object sender, EventArgs e)
        {
            lstbx_basliklar.Items.Clear();
            News news = (News)cmbx_siteadi.SelectedItem;

            Feed feed = FeedReader.Read(news.Url);

            foreach (var item in feed.Items)
            {
                News n = new News();
                n.ID          = item.Id;
                n.Title       = item.Title.Replace("&#39;", "'").Replace("&quot;", "");
                n.Description = item.Description.Replace("&#39;", "'").Replace("&quot;", "");
                n.Url         = item.Link;
                n.Date        = item.PublishingDate;
                lstbx_basliklar.Items.Add(n);
            }
            #region
            //if (cmbx_siteadi.Text == "NTV")
            //{
            //    lstbx_basliklar.Items.Clear();
            //    Ntv ntv = new Ntv();
            //    Feed feed = FeedReader.Read(ntv.Url);
            //    foreach (var item in feed.Items)
            //    {
            //        ntv.ID = item.Id;
            //        ntv.Link = item.Link;
            //        ntv.Title = item.Title;
            //        ntv.Description = item.Description;
            //        lstbx_basliklar.Items.Add(ntv);
            //    }

            //}
            //else if (cmbx_siteadi.Text == "CNN")
            //{
            //    lstbx_basliklar.Items.Clear();
            //    Cnn cnn = new Cnn();
            //    Feed feed = FeedReader.Read(cnn.Url);
            //    foreach (var item in feed.Items)
            //    {
            //        cnn.ID = item.Id;
            //        cnn.Link = item.Link;
            //        cnn.Title = item.Title;
            //        cnn.Description = item.Description;
            //        lstbx_basliklar.Items.Add(cnn);
            //    }
            //}
            //else if (cmbx_siteadi.Text == "HABERTURK")
            //{
            //    lstbx_basliklar.Items.Clear();
            //    Haberturk hbrtrk = new Haberturk();
            //    Feed feed = FeedReader.Read(hbrtrk.Url);
            //    foreach (var item in feed.Items)
            //    {
            //        hbrtrk.ID = item.Id;
            //        hbrtrk.Link = item.Link;
            //        hbrtrk.Title = item.Title;
            //        hbrtrk.Description = item.Description;
            //        lstbx_basliklar.Items.Add(hbrtrk);
            //    }

            #endregion
        }
Example #36
0
 /// <summary>
 /// Handles the Click event of the buttonUpdateFeed control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
 private void ButtonUpdateFeed_Click(object sender, RoutedEventArgs e)
 {
     this.feedControl.Feed = Feed.Read(new Uri(this.textBoxFeedUrl.Text));
 }
Example #37
0
        public IActionResult DownNews()
        {
            //var newFeed = new Feed { };
            var     sessionId      = Guid.NewGuid().ToString();
            int     totalRecords   = 0;
            decimal numPages       = 0;
            int     numPagesInt    = 0;
            int     pageSize       = 100;
            var     runDate        = DateTime.Now;
            var     lastPubDate    = DateTime.Now;
            var     q              = "trump";
            var     sources        = string.Empty;
            var     domains        = string.Empty;
            var     excludeDomains = string.Empty;
            var     from           = DateTime.Now.AddDays(-3);
            var     to             = DateTime.Now;
            var     language       = "en";
            var     sortBy         = "PublishedAt";
            var     page           = 1;

            // init with your API key
            var newsApiClient    = new NewsApiClient("de67b2237afe4fb1b77bfbe773987fca");
            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Q        = q,
                SortBy   = SortBys.PublishedAt,
                Language = Languages.EN,
                From     = from,
                PageSize = pageSize,
                Page     = page
            });

            if (articlesResponse.Status == Statuses.Ok)
            {
                totalRecords = articlesResponse.TotalResults;
                numPages     = totalRecords / pageSize;
                numPagesInt  = Convert.ToInt32(Math.Ceiling(numPages));

                foreach (var article in articlesResponse.Articles)
                {
                    var newFeed = new Feed();
                    newFeed.SessionId    = sessionId;
                    newFeed.TotalResults = articlesResponse.TotalResults;
                    newFeed.SourceId     = 0; //what format?
                    newFeed.SourceName   = article.Source.Name;
                    newFeed.Author       = article.Author;
                    newFeed.Description  = article.Description;
                    newFeed.PublishedAt  = Convert.ToDateTime(article.PublishedAt);
                    newFeed.Title        = article.Title;
                    newFeed.Url          = article.Url;
                    newFeed.UrlToImage   = article.UrlToImage;
                    newFeed.Content      = string.Empty;
                    //feedList.Content = article.Content;  //not available in .net. Available in JS.
                    //add to table
                    _feed.Add(newFeed);
                }
            }

            var newAdmin = new Admin
            {
                SessionId      = sessionId,
                RunDate        = runDate,
                LastPubDate    = _admin.GetLastPubDate(),
                Q              = q,
                Sources        = sources,
                Domains        = domains,
                ExcludeDomains = excludeDomains,
                From           = from,
                To             = to,
                Language       = language,
                SortBy         = sortBy,
                PageSize       = pageSize,
                Page           = page
            };

            //todo: add to Admin
            _admin.Add(newAdmin);

            return(RedirectToAction("Index"));
        }
Example #38
0
 public async Task <Feed> CreateAsync(Feed toFeed)
 {
     return(await _unitOfWork.Feeds.CreateAsync(toFeed));
 }
Example #39
0
 public ManagedAtomFeed(Feed feed)
     : base(feed)
 {
 }
        private int InserirPedidoVenda(SAPbobsCOM.Company oCompany, Pedido pedidoVtex, Feed evento)
        {
            try
            {
                if (oCompany.Connected)
                {
                    OrdersDAL order        = new OrdersDAL(oCompany);
                    string    messageError = "";
                    int       oOrderNum    = 0;
                    Boolean   inserir      = true;

                    foreach (ItemVtex item in pedidoVtex.items)
                    {
                        if (item.refId == null && inserir)
                        {
                            this.log.WriteLogTable(oCompany, EnumTipoIntegracao.PedidoVenda, pedidoVtex.orderId, "", EnumStatusIntegracao.Erro, "Um ou mais item(s) do pedido está com o código de referência inválido.");
                            //throw new ArgumentException("Não foi possível criar o Pedido de Venda para o pedido "+pedidoVtex.orderId+" pois um ou mais item(s) do pedido está com o código de referência inválido.");
                            inserir = false;
                        }
                    }

                    if (inserir)
                    {
                        oOrderNum = order.InsertOrder(pedidoVtex, out messageError);

                        if (oOrderNum == 0)
                        {
                            Repositorio repositorio = new Repositorio();

                            //Pedido inserido no SAP, removendo pedido da fila de enventos(Feed), para não ser mais processado.

                            Task <HttpResponseMessage> response = repositorio.AtualizaFilaEnvetoPedido(evento.handle);

                            if (response.Result.IsSuccessStatusCode)
                            {
                                this.log.WriteLogPedido("Pedido " + pedidoVtex.orderId + " removido da fila de eventos (Feed).");
                            }
                            else
                            {
                                this.log.WriteLogPedido("Não foi possível remover o pedido " + pedidoVtex.orderId + " da fila de eventos (Feed)." + response.Result.ReasonPhrase);
                            }

                            Task <HttpResponseMessage> responseIniciarManuseio = repositorio.InciarManuseio(pedidoVtex.orderId);

                            if (responseIniciarManuseio.Result.IsSuccessStatusCode)
                            {
                                //this.log.WriteLogPedido("Alterado status do pedido "+pedidoVtex.orderId+" para Iniciar Manuseio.");
                            }
                            else
                            {
                                this.log.WriteLogPedido("Não foi possível alterar status do pedido " + pedidoVtex.orderId + " para Iniciar Manuseio." + response.Result.ReasonPhrase);
                            }
                        }
                    }
                }

                return(0);
            }
            catch (Exception e)
            {
                this.log.WriteLogPedido("Exception InserirPedidoVenda " + e.Message);
                throw;
            }
        }
Example #41
0
        /// <summary>
        /// Creates feed items, which fill out the feed table with data.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="feed">The feed for which the operation will be created.</param>
        /// <returns>A list of string Feed Item Resource Names.</returns>
        private List <string> CreateFeedItems(GoogleAdsClient client, long customerId, Feed feed)
        {
            FeedItemServiceClient feedItemService = client.GetService(Services.V4.FeedItemService);

            List <FeedItemOperation> operations = new List <FeedItemOperation>
            {
                NewFeedItemOperation(feed, "Home", "http://www.example.com",
                                     "Home line 1", "Home line 2"),
                NewFeedItemOperation(feed, "Stores",
                                     "http://www.example.com/stores", "Stores line 1", "Stores line 2"),
                NewFeedItemOperation(feed, "On Sale",
                                     "http://www.example.com/sale", "On Sale line 1", "On Sale line 2"),
                NewFeedItemOperation(feed, "Support",
                                     "http://www.example.com/support", "Support line 1", "Support line 2"),
                NewFeedItemOperation(feed, "Products",
                                     "http://www.example.com/catalogue",
                                     "Products line 1", "Products line 2"),
                NewFeedItemOperation(feed, "About Us", "http://www.example.com/about",
                                     "About Us line 1", "About Us line 2")
            };

            MutateFeedItemsResponse response =
                feedItemService.MutateFeedItems(customerId.ToString(), operations);

            // We will need the resource name of each feed item to use in targeting.
            List <string> feedItemResourceNames = new List <string>();

            Console.WriteLine("Created the following feed items:");
            foreach (MutateFeedItemResult feedItemResult in response.Results)
            {
                Console.WriteLine($"\t{feedItemResult.ResourceName}");

                feedItemResourceNames.Add(feedItemResult.ResourceName);
            }

            return(feedItemResourceNames);
        }
Example #42
0
    //--------------------//

    #region Add
    /// <inheritdoc/>
    public void AddAccessPointCategories(AppEntry appEntry, Feed feed, params string[] categories)
    {
        #region Sanity checks
        if (appEntry == null)
        {
            throw new ArgumentNullException(nameof(appEntry));
        }
        if (feed == null)
        {
            throw new ArgumentNullException(nameof(feed));
        }
        if (categories == null)
        {
            throw new ArgumentNullException(nameof(categories));
        }
        #endregion

        // Parse categories list
        bool capabilities = categories.Contains(CapabilityRegistration.TagName);
        bool menu         = categories.Contains(MenuEntry.TagName);
        bool desktop      = categories.Contains(DesktopIcon.TagName);
        bool sendTo       = categories.Contains(SendTo.TagName);
        bool alias        = categories.Contains(AppAlias.TagName);
        bool autoStart    = categories.Contains(AutoStart.TagName);
        bool defaults     = categories.Contains(DefaultAccessPoint.TagName);

        // Build capability list
        var accessPointsToAdd = new List <AccessPoint>();
        if (capabilities)
        {
            accessPointsToAdd.Add(new CapabilityRegistration());
        }
        if (menu)
        {
            accessPointsToAdd.Add(Suggest.MenuEntries(feed));
        }
        if (desktop)
        {
            accessPointsToAdd.Add(Suggest.DesktopIcons(feed));
        }
        if (sendTo)
        {
            accessPointsToAdd.Add(Suggest.SendTo(feed));
        }
        if (alias)
        {
            accessPointsToAdd.Add(Suggest.Aliases(feed));
        }
        if (autoStart)
        {
            accessPointsToAdd.Add(Suggest.AutoStart(feed));
        }
        if (defaults)
        {
            // Add AccessPoints for all suitable Capabilities
            accessPointsToAdd.Add((
                                      from capability in appEntry.CapabilityLists.CompatibleCapabilities().OfType <DefaultCapability>()
                                      where !capability.WindowsMachineWideOnly || MachineWide || !WindowsUtils.IsWindows
                                      where !capability.ExplicitOnly
                                      select capability.ToAccessPoint()));
        }

        try
        {
            AddAccessPointsInternal(appEntry, feed, accessPointsToAdd);
            if (menu && MachineWide)
            {
                ToggleIconsVisible(appEntry, true);
            }
        }
        catch (KeyNotFoundException ex)
        {
            // Wrap exception since only certain exception types are allowed
            throw new InvalidDataException(ex.Message, ex);
        }
        finally
        {
            Finish();
        }
    }
        private bool EnsureValidSettings(bool throwException = true)
        {
            string message = string.Empty;
            bool   valid   = true;

            if (Feed != BeastSaberFeedName.CuratorRecommended)
            {
                if (string.IsNullOrEmpty(BeastSaberFeedSettings.Username))
                {
                    message = $"{nameof(BeastSaberFeedSettings)}.{nameof(BeastSaberFeedSettings.Username)} cannot be null or empty for the {Feed.ToString()} feed.";
                    valid   = false;
                }
            }
            if (!valid && throwException)
            {
                throw new InvalidFeedSettingsException(message);
            }
            return(valid);
        }
Example #44
0
 /// <summary>
 /// A callback that receives RSS feed.
 /// </summary>
 /// <param name="feed"></param>
 public virtual void Receive(Feed feed)
 {
 }
        public static Feed ToFeed(XElement channel)
        {
            if (channel.Name.LocalName.ToLower() == "channel")
            {
                Feed feed = new Feed();
                foreach (XElement prpNode in channel.Elements())
                {
                    try
                    {
                        switch (prpNode.Name.LocalName.ToLower())
                        {
                        case "category":
                            feed.Category      = new Category();
                            feed.Category.Name = prpNode.Value;
                            if (MyHelper.EnumToArray(prpNode.Attributes()).Length == 1)
                            {
                                feed.Category.Domain = new Uri(prpNode.Attribute(XName.Get("domain")).Value);
                            }
                            break;

                        case "cloud":
                            feed.Cloud = new Cloud();
                            foreach (XAttribute att in prpNode.Attributes())
                            {
                                switch (att.Name.LocalName.ToLower())
                                {
                                case "domain":
                                    feed.Cloud.Domain = new Uri(att.Value);
                                    break;

                                case "path":
                                    feed.Cloud.Path = att.Value;
                                    break;

                                case "registerprocedure":
                                    feed.Cloud.RegisterProcedure = att.Value;
                                    break;

                                case "protocol":
                                    feed.Cloud.Protocol = att.Value;
                                    break;

                                case "port":
                                    int n;
                                    if (int.TryParse(att.Value, out n))
                                    {
                                        feed.Cloud.Port = n;
                                    }
                                    break;
                                }
                            }

                            break;

                        case "copyright":
                            feed.Copyright = prpNode.Value;
                            break;

                        case "description":
                            feed.Description = prpNode.Value;
                            break;

                        case "docs":
                            feed.Documentation = new Uri(prpNode.Value);
                            break;

                        case "generator":
                            feed.Generator = prpNode.Value;
                            break;

                        case "link":
                            feed.Link = new Uri(prpNode.Value);
                            break;

                        case "language":
                            feed.Language = new System.Globalization.CultureInfo(prpNode.Value);
                            break;

                        case "lastbuilddate":
                            feed.LastBuildDate = RFC822DateFromString(prpNode.Value);
                            break;

                        case "managingeditor":
                            feed.ManagingEditor = Rss2MailToMailAddress(prpNode.Value);
                            break;

                        case "name":
                            feed.Name = prpNode.Value;
                            break;

                        case "image":
                            feed.Image = new Image();
                            foreach (XElement nodeChild in prpNode.Elements())
                            {
                                switch (nodeChild.Name.LocalName.ToLower())
                                {
                                case "url":
                                    feed.Image.URL = new Uri(nodeChild.Value);
                                    break;

                                case "link":
                                    feed.Image.Link = new Uri(nodeChild.Value);
                                    break;

                                case "title":
                                    feed.Image.Title = nodeChild.Value;
                                    break;

                                case "description":
                                    feed.Image.Description = nodeChild.Value;
                                    break;

                                case "width":
                                    int n;
                                    if (int.TryParse(nodeChild.Value, out n))
                                    {
                                        feed.Image.Width = n;
                                    }
                                    break;

                                case "height":
                                    if (int.TryParse(nodeChild.Value, out n))
                                    {
                                        feed.Image.Height = n;
                                    }
                                    break;
                                }
                            }

                            break;

                        case "item":
                            FeedItem rssItem = ToFeedItem(prpNode);
                            if (rssItem != null)
                            {
                                feed.Items.Add(rssItem);
                            }
                            break;

                        case "pubdate":
                            feed.PublishDate = RFC822DateFromString(prpNode.Value);
                            break;

                        case "rating":
                            feed.Rating = prpNode.Value;
                            break;

                        case "skiphours":
                            List <int> lst1 = new List <int>();
                            foreach (XElement nodeChild in prpNode.Elements())
                            {
                                if (nodeChild.Name.LocalName.ToLower() == "hour")
                                {
                                    int @int = 0;
                                    if (int.TryParse(nodeChild.Value, out @int))
                                    {
                                        lst1.Add(@int);
                                    }
                                }
                            }

                            feed.Skiphours = lst1.ToArray();
                            break;

                        case "skipdays":
                            List <DayOfWeek> lst2 = new List <DayOfWeek>();
                            foreach (XElement nodeChild in prpNode.Elements())
                            {
                                if (nodeChild.Name.LocalName.ToLower() == "day")
                                {
                                    for (int i = 0; i <= (int)DayOfWeek.Saturday; i++)
                                    {
                                        if (((DayOfWeek)i).ToString().ToUpper() == nodeChild.Value.ToUpper())
                                        {
                                            lst2.Add((DayOfWeek)i);
                                            break;     // TODO: might not be correct. Was : Exit For
                                        }
                                    }
                                }
                            }

                            feed.Skipdays = lst2.ToArray();
                            break;

                        case "textinput":
                            feed.TextInput = new TextInputBox();
                            foreach (XElement nodeChild in prpNode.Elements())
                            {
                                switch (nodeChild.Name.LocalName.ToLower())
                                {
                                case "name":
                                    feed.TextInput.Name = nodeChild.Value;
                                    break;

                                case "link":
                                    feed.TextInput.Link = new Uri(nodeChild.Value);
                                    break;

                                case "title":
                                    feed.TextInput.Title = nodeChild.Value;
                                    break;

                                case "description":
                                    feed.TextInput.Description = nodeChild.Value;
                                    break;
                                }
                            }


                            break;

                        case "title":
                            feed.Title = prpNode.Value;
                            break;

                        case "ttl":
                            feed.Ttl = Convert.ToInt32(prpNode.Value);

                            break;

                        case "webmaster":
                            feed.Webmaster = Rss2MailToMailAddress(prpNode.Value);
                            break;

                        default:
                            break;
                            //Debug.WriteLine(node.Name)
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
                return(feed);
            }
            else
            {
                return(null);
            }
        }
Example #46
0
 public void Delete(Feed feed)
 {
     Delete(feed.Id.Value);
 }
        /// <inheritdoc/>
        public override void Apply(AppEntry appEntry, Feed feed, IIconStore iconStore, bool machineWide)
        {
            #region Sanity checks
            if (appEntry == null)
            {
                throw new ArgumentNullException(nameof(appEntry));
            }
            if (iconStore == null)
            {
                throw new ArgumentNullException(nameof(iconStore));
            }
            #endregion

            var capabilities = appEntry.CapabilityLists.CompatibleCapabilities().ToList();
            var target       = new FeedTarget(appEntry.InterfaceUri, feed);

            foreach (var capability in capabilities)
            {
                switch (capability)
                {
                case Model.Capabilities.FileType fileType:
                    if (WindowsUtils.IsWindows)
                    {
                        Windows.FileType.Register(target, fileType, iconStore, machineWide);
                    }
                    else if (UnixUtils.IsUnix)
                    {
                        Unix.FileType.Register(target, fileType, iconStore, machineWide);
                    }
                    break;

                case Model.Capabilities.UrlProtocol urlProtocol:
                    if (WindowsUtils.IsWindows)
                    {
                        Windows.UrlProtocol.Register(target, urlProtocol, iconStore, machineWide);
                    }
                    else if (UnixUtils.IsUnix)
                    {
                        Unix.UrlProtocol.Register(target, urlProtocol, iconStore, machineWide);
                    }
                    break;

                case Model.Capabilities.AutoPlay autoPlay:
                    if (WindowsUtils.IsWindows)
                    {
                        Windows.AutoPlay.Register(target, autoPlay, iconStore, machineWide);
                    }
                    break;

                case AppRegistration appRegistration:
                    if ((WindowsUtils.IsWindows && machineWide) || WindowsUtils.IsWindows8)
                    {
                        Windows.AppRegistration.Register(target, appRegistration, capabilities.OfType <VerbCapability>(), iconStore, machineWide);
                    }
                    break;

                case Model.Capabilities.DefaultProgram defaultProgram:
                    if (WindowsUtils.IsWindows && machineWide)
                    {
                        Windows.DefaultProgram.Register(target, defaultProgram, iconStore);
                    }
                    else if (UnixUtils.IsUnix)
                    {
                        Unix.DefaultProgram.Register(target, defaultProgram, iconStore, machineWide);
                    }
                    break;

                case ComServer comServer:
                    if (WindowsUtils.IsWindows)
                    {
                        Windows.ComServer.Register(target, comServer, iconStore, machineWide);
                    }
                    break;
                }
            }
        }
 /// <summary>
 /// Called on a feed item was added succesful.
 /// </summary>
 /// <param name="sender">Sender.</param>
 /// <param name="feed">Feed.</param>
 void OnAddItemMessageRequested(SettingsViewModel sender, Feed feed)
 {
     AddFeedPostListPage(feed);
     SelectedItem = Children[0];
 }
Example #49
0
        public void Approval(int id, string content = null, bool result = true, int toUserId = 0)
        {
            var info            = Core.FormInfoManager.GetModel(id);
            var currentNodeData = info.FlowData.GetLastNodeData();

            if (currentNodeData.UserId != Identity.ID)
            {
                currentNodeData = info.FlowData.GetChildNodeData(currentNodeData.ID);
            }
            if (currentNodeData == null)
            {
                throw new Exception("您没有参与此次流程审核");
            }
            currentNodeData.Result  = result;
            currentNodeData.Content = content;

            Core.FlowNodeDataManager.Submit(currentNodeData);
            Core.UserFormInfoManager.Save(new UserFormInfo
            {
                InfoId     = id,
                FlowStatus = FlowStatus.Done,
                UserId     = Identity.ID
            });
            var model = Core.FormInfoExtend1Manager.GetModel(id);

            if (toUserId > 0)
            {
                Core.FlowNodeDataManager.CreateChildNodeData(currentNodeData, toUserId);
                Core.UserFormInfoManager.Save(new UserFormInfo
                {
                    InfoId     = id,
                    FlowStatus = FlowStatus.Doing,
                    UserId     = toUserId
                });

                var feed = new Feed
                {
                    Action     = UserAction.Submit,
                    InfoId     = id,
                    Title      = info.Title,
                    FromUserId = Identity.ID,
                    ToUserId   = toUserId,
                    Type       = FeedType.Info,
                };
                Core.FeedManager.Save(feed);
                Core.MessageManager.Add(feed);

                model.ApprovalUserId = toUserId;
                model.UpdateTime     = DateTime.Now;
            }
            else
            {
                model.ApprovalUserId = Identity.ID;
                model.Result         = result;
                model.UpdateTime     = DateTime.Now;
                Core.FlowDataManager.Complete(info);

                var feed = new Feed
                {
                    Action      = UserAction.Submit,
                    Type        = FeedType.Info,
                    FromUserId  = Identity.ID,
                    ToUserId    = model.UserId,
                    Title       = "你申请的假期已审核通过",
                    Description = info.Title,
                    InfoId      = info.ID,
                };
                Core.FeedManager.Save(feed);
                Core.MessageManager.Add(feed);
            }
            Core.FormInfoExtend1Manager.Save(model);
        }
 public override bool VisibleFor(Feed feed, object data, Guid userId)
 {
     return(base.VisibleFor(feed, data, userId) && ProjectSecurity.CanGoToFeed((Message)data, userId));
 }
Example #51
0
 /// <summary>
 /// Returns the itunes elements of a rss feed
 /// </summary>
 /// <param name="feed">the rss feed</param>
 /// <returns>ItunesChannel object which contains itunes:... properties</returns>
 public static ItunesChannel GetItunesChannel(this Feed feed)
 {
     return(new ItunesChannel(feed.SpecificFeed.Element));
 }
Example #52
0
        public List <ConciseContact> GetContactsWithBirthdaysToday()
        {
            RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord);

            // AutoPaging results in automatic paging in order to retrieve all contacts
            rs.AutoPaging = true;
            ContactsRequest cr = new ContactsRequest(rs);

            ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));

            query.StartDate        = new DateTime(2000, 1, 1);
            query.NumberToRetrieve = int.MaxValue;
            //query.OrderBy =

            query.ModifiedSince = DateTime.Now.AddDays(-10000);

            List <ConciseContact> ccList = new List <ConciseContact>();
            DateTime today = DateTime.Now.Date;

            Feed <Contact> feed = cr.Get <Contact>(query);
            Contact        dbgC = null;

            foreach (Contact c in feed.Entries)
            {
                try
                {
                    dbgC = c;

                    if (string.IsNullOrEmpty(c.ContactEntry.Birthday))
                    {
                        continue;
                    }

                    DateTime birthday = DateTime.Parse(c.ContactEntry.Birthday);

                    if (birthday.Month != today.Month || birthday.Day != today.Day)
                    {
                        continue;
                    }

                    // Birthdays today found
                    ConciseContact cc = new ConciseContact();
                    cc.FirstName = c.Name.GivenName;
                    cc.LastName  = c.Name.FamilyName;

                    if (c.Organizations.Count > 0)
                    {
                        cc.Title = c.Organizations[0].Title;
                    }

                    //c.PrimaryPhonenumber
                    //c.PrimaryPhonenumber
                    //c.Phonenumbers[0]
                    if (c.Phonenumbers.Count > 0)
                    {
                        cc.PhoneNumber = c.Phonenumbers[0].Value;
                    }

                    ccList.Add(cc);

                    Console.WriteLine(c.Title);
                    Console.WriteLine("Name: " + c.Name.FullName);
                }
                catch (Exception ex)
                {
                    Logger.LogException(ex, dbgC.Name.GivenName + " " + dbgC.Name.FamilyName);
                }
            }

            return(ccList);
        }
Example #53
0
        public void GetContacts()
        {
            RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord);

            // AutoPaging results in automatic paging in order to retrieve all contacts
            rs.AutoPaging = true;
            ContactsRequest cr = new ContactsRequest(rs);

            Feed <Contact> f = cr.GetContacts();

            foreach (Contact entry in f.Entries)
            {
                if (entry.Name != null)
                {
                    Name name = entry.Name;
                    if (!string.IsNullOrEmpty(name.FullName))
                    {
                        Console.WriteLine("\t\t" + name.FullName);
                    }
                    else
                    {
                        Console.WriteLine("\t\t (no full name found)");
                    }
                    if (!string.IsNullOrEmpty(name.NamePrefix))
                    {
                        Console.WriteLine("\t\t" + name.NamePrefix);
                    }
                    else
                    {
                        Console.WriteLine("\t\t (no name prefix found)");
                    }
                    if (!string.IsNullOrEmpty(name.GivenName))
                    {
                        string givenNameToDisplay = name.GivenName;
                        if (!string.IsNullOrEmpty(name.GivenNamePhonetics))
                        {
                            givenNameToDisplay += " (" + name.GivenNamePhonetics + ")";
                        }
                        Console.WriteLine("\t\t" + givenNameToDisplay);
                    }
                    else
                    {
                        Console.WriteLine("\t\t (no given name found)");
                    }
                    if (!string.IsNullOrEmpty(name.AdditionalName))
                    {
                        string additionalNameToDisplay = name.AdditionalName;
                        if (string.IsNullOrEmpty(name.AdditionalNamePhonetics))
                        {
                            additionalNameToDisplay += " (" + name.AdditionalNamePhonetics
                                                       + ")";
                        }
                        Console.WriteLine("\t\t" + additionalNameToDisplay);
                    }
                    else
                    {
                        Console.WriteLine("\t\t (no additional name found)");
                    }
                    if (!string.IsNullOrEmpty(name.FamilyName))
                    {
                        string familyNameToDisplay = name.FamilyName;
                        if (!string.IsNullOrEmpty(name.FamilyNamePhonetics))
                        {
                            familyNameToDisplay += " (" + name.FamilyNamePhonetics + ")";
                        }
                        Console.WriteLine("\t\t" + familyNameToDisplay);
                    }
                    else
                    {
                        Console.WriteLine("\t\t (no family name found)");
                    }
                    if (!string.IsNullOrEmpty(name.NameSuffix))
                    {
                        Console.WriteLine("\t\t" + name.NameSuffix);
                    }
                    else
                    {
                        Console.WriteLine("\t\t (no name suffix found)");
                    }
                }
                else
                {
                    Console.WriteLine("\t (no name found)");
                }

                foreach (EMail email in entry.Emails)
                {
                    Console.WriteLine("\t" + email.Address);
                }
            }
        }
Example #54
0
 public void CreateFeed(Feed feed)
 {
     this._context.Add(feed);
     this._context.SaveChangesAsync();
 }
Example #55
0
 /// <summary>
 /// Abstract implementation of IParser method.
 /// </summary>
 /// <param name="parent">Parent stack for current node.</param>
 /// <param name="reader">Current xml feed reader.</param>
 /// <param name="feed">Current feed result.</param>
 /// <param name="root">Flag indicating if parser is the default root parser.</param>
 /// <returns>Flag indicating if current node should be parsed or if next node should be retrieved.</returns>
 public abstract Task <bool> Parse(Stack <NodeInformation> parent, XmlReader reader, Feed feed, bool root = true);
Example #56
0
 async Task IFeedService.DeleteFeed(Feed feed)
 {
     _unitOfWork.Feeds.Remove(feed);
     await _unitOfWork.CommitAsync();
 }
Example #57
0
        public void Run(MessageInterest messageInterest, CultureInfo culture)
        {
            Console.WriteLine(string.Empty);
            Console.WriteLine("Running the OddsFeed SDK SportEvent Info example");

            var configuration = Feed.GetConfigurationBuilder().SetAccessTokenFromConfigFile().SelectIntegration().LoadFromConfigFile().Build();
            var oddsFeed      = new Feed(configuration);

            AttachToFeedEvents(oddsFeed);

            Console.WriteLine("Creating IOddsFeedSessions");

            var session = oddsFeed.CreateBuilder()
                          .SetMessageInterest(messageInterest)
                          .Build();

            var sportEntityWriter = new SportEntityWriter(_taskProcessor, culture);

            Console.WriteLine("Creating entity specific dispatchers");
            var matchDispatcher           = session.CreateSportSpecificMessageDispatcher <IMatch>();
            var stageDispatcher           = session.CreateSportSpecificMessageDispatcher <IStage>();
            var tournamentDispatcher      = session.CreateSportSpecificMessageDispatcher <ITournament>();
            var basicTournamentDispatcher = session.CreateSportSpecificMessageDispatcher <IBasicTournament>();
            var seasonDispatcher          = session.CreateSportSpecificMessageDispatcher <ISeason>();

            Console.WriteLine("Creating event processors");
            var defaultEventsProcessor         = new EntityProcessor(session, sportEntityWriter);
            var matchEventsProcessor           = new SpecificEntityProcessor <IMatch>(_log, matchDispatcher, sportEntityWriter);
            var stageEventsProcessor           = new SpecificEntityProcessor <IStage>(_log, stageDispatcher, sportEntityWriter);
            var tournamentEventsProcessor      = new SpecificEntityProcessor <ITournament>(_log, tournamentDispatcher, sportEntityWriter);
            var basicTournamentEventsProcessor = new SpecificEntityProcessor <IBasicTournament>(_log, basicTournamentDispatcher, sportEntityWriter);
            var seasonEventsProcessor          = new SpecificEntityProcessor <ISeason>(_log, seasonDispatcher, sportEntityWriter);

            Console.WriteLine("Opening event processors");
            defaultEventsProcessor.Open();
            matchEventsProcessor.Open();
            stageEventsProcessor.Open();
            tournamentEventsProcessor.Open();
            basicTournamentEventsProcessor.Open();
            seasonEventsProcessor.Open();

            Console.WriteLine("Opening the feed instance");
            oddsFeed.Open();
            Console.WriteLine("Example successfully started. Hit <enter> to quit");
            Console.WriteLine(string.Empty);
            Console.ReadLine();

            Console.WriteLine("Closing / disposing the feed");
            oddsFeed.Close();

            DetachFromFeedEvents(oddsFeed);

            Console.WriteLine("Closing event processors");
            defaultEventsProcessor.Close();
            matchEventsProcessor.Close();
            stageEventsProcessor.Close();
            tournamentEventsProcessor.Close();
            basicTournamentEventsProcessor.Close();
            seasonEventsProcessor.Close();

            Console.WriteLine("Waiting for asynchronous operations to complete");
            var waitResult = _taskProcessor.WaitForTasks();

            Console.WriteLine($"Waiting for tasks completed. Result:{waitResult}");

            Console.WriteLine("Stopped");
        }
Example #58
0
 public Feed GetById(int feedId)
 {
     return(Feed.findById(feedId));
 }
        /// <summary>
        /// Creates a new integration state View-Model.
        /// </summary>
        /// <param name="integrationManager">The integration manager used to apply selected integration options.</param>
        /// <param name="appEntry">The application being integrated.</param>
        /// <param name="feed">The feed providing additional metadata, icons, etc. for the application.</param>
        public IntegrationState([NotNull] IIntegrationManager integrationManager, [NotNull] AppEntry appEntry, [NotNull] Feed feed)
        {
            #region Sanity checks
            if (integrationManager == null)
            {
                throw new ArgumentNullException("integrationManager");
            }
            if (appEntry == null)
            {
                throw new ArgumentNullException("appEntry");
            }
            if (feed == null)
            {
                throw new ArgumentNullException("feed");
            }
            #endregion

            _integrationManager = integrationManager;
            AppEntry            = appEntry;
            Feed = feed;

            CapabilitiyRegistration = (AppEntry.AccessPoints == null) || AppEntry.AccessPoints.Entries.OfType <AccessPoints.CapabilityRegistration>().Any();

            LoadCommandAccessPoints();
            LoadDefaultAccessPoints();
        }
Example #60
0
        public override void Render(CellContext context, double cellWidth, double cellHeight)
        {
            if (BoundObject == null)
            {
                return;
            }

            if (!(BoundObject is Feed))
            {
                throw new InvalidCastException("ColumnCellPodcast can only bind to Feed objects");
            }

            Feed feed = (Feed)BoundObject;

            bool         is_default = false;
            ImageSurface image      = artwork_manager == null ? null
                : artwork_manager.LookupScaleSurface(PodcastService.ArtworkIdFor(feed), image_size, true);

            if (image == null)
            {
                image      = default_cover_image;
                is_default = true;
            }

            // int image_render_size = is_default ? image.Height : (int)cellHeight - 8;
            int image_render_size = image_size;
            int x = image_spacing;
            int y = ((int)cellHeight - image_render_size) / 2;

            ArtworkRenderer.RenderThumbnail(context.Context, image, false, x, y,
                                            image_render_size, image_render_size, !is_default, context.Theme.Context.Radius);

            int fl_width = 0, fl_height = 0, sl_width = 0, sl_height = 0;

            context.Widget.StyleContext.Save();
            context.Widget.StyleContext.AddClass("cell");
            context.StyleContext.State |= context.State;
            Cairo.Color text_color = CairoExtensions.GdkRGBAToCairoColor(context.Widget.StyleContext.GetColor(context.StyleContext.State));
            context.Widget.StyleContext.Restore();
            text_color.A = 0.75;

            Pango.Layout layout = context.Layout;
            layout.Width     = (int)((cellWidth - cellHeight - x - 10) * Pango.Scale.PangoScale);
            layout.Ellipsize = Pango.EllipsizeMode.End;
            layout.FontDescription.Weight = Pango.Weight.Bold;

            // Compute the layout sizes for both lines for centering on the cell
            int old_size = layout.FontDescription.Size;

            layout.SetText(feed.Title ?? String.Empty);
            layout.GetPixelSize(out fl_width, out fl_height);

            if (feed.DbId > 0)
            {
                layout.FontDescription.Weight = Pango.Weight.Normal;
                layout.FontDescription.Size   = (int)(old_size * Pango.Scale.Small);
                layout.FontDescription.Style  = Pango.Style.Italic;

                if (feed.LastDownloadTime == DateTime.MinValue)
                {
                    layout.SetText(Catalog.GetString("Never updated"));
                }
                else if (feed.LastDownloadTime.Date == DateTime.Now.Date)
                {
                    layout.SetText(String.Format(Catalog.GetString("Updated at {0}"), feed.LastDownloadTime.ToShortTimeString()));
                }
                else
                {
                    layout.SetText(String.Format(Catalog.GetString("Updated {0}"), Hyena.Query.RelativeTimeSpanQueryValue.RelativeToNow(feed.LastDownloadTime).ToUserQuery()));
                }
                layout.GetPixelSize(out sl_width, out sl_height);
            }

            // Calculate the layout positioning
            x = ((int)cellHeight - x) + 10;
            y = (int)((cellHeight - (fl_height + sl_height)) / 2);

            // Render the second line first since we have that state already
            if (feed.DbId > 0)
            {
                context.Context.MoveTo(x, y + fl_height);
                context.Context.SetSourceColor(text_color);
                Pango.CairoHelper.ShowLayout(context.Context, layout);
            }

            // Render the first line, resetting the state
            layout.SetText(feed.Title ?? String.Empty);
            layout.FontDescription.Weight = Pango.Weight.Bold;
            layout.FontDescription.Size   = old_size;
            layout.FontDescription.Style  = Pango.Style.Normal;

            layout.SetText(feed.Title ?? String.Empty);

            context.Context.MoveTo(x, y);
            text_color.A = 1;
            context.Context.SetSourceColor(text_color);
            Pango.CairoHelper.ShowLayout(context.Context, layout);
        }