private static FeedData GetFeed(SyndicationFeed feed, string contentType, WriteTo writeTo) { var feedData = new FeedData { ContentType = contentType }; if (feed.Items.Any()) { SyndicationItem item = (from syndicationItem in feed.Items orderby syndicationItem.PublishDate descending select syndicationItem).First(); feedData.LastModifiedDate = item.PublishDate.DateTime; } else { feedData.LastModifiedDate = DateTime.MinValue; } var xmlWriterSettings = new XmlWriterSettings { Encoding = new UTF8Encoding(false) }; var memoryStream = new MemoryStream(); using (XmlWriter writer = XmlWriter.Create(memoryStream, xmlWriterSettings)) { writeTo(writer); } memoryStream.Position = 0; var sr = new StreamReader(memoryStream); feedData.Content = sr.ReadToEnd(); feedData.ETag = feedData.Content.GetHashCode().ToString(); //} return feedData; }
public FeedSourceMemberData[] Fetch(FeedData parentData) { var data = MockDb.FeedSourceMembers .Where(row => row.FeedId == parentData.FeedId); data = data.Select(this.Fetch); return data.ToArray(); }
public FeedData Update(FeedData data) { var feed = MockDb.Feeds .Where(row => row.FeedId == data.FeedId) .Single(); Csla.Data.DataMapper.Map(data, feed); return data; }
internal static void Map(FeedData source, Feed destination) { destination.FeedId = source.FeedId; destination.Action = source.Action; destination.Description = source.Description; destination.SourceId = source.SourceId; destination.SourceTypeId = source.SourceTypeId; destination.CreatedBy = source.CreatedBy; destination.CreatedDate = source.CreatedDate; }
public FeedData Fetch(FeedData data) { data.Source = MockDb.Sources .Where(row => row.SourceId == data.SourceId && row.SourceTypeId == data.SourceTypeId) .Single(); data.CreatedByUser = MockDb.Users .Where(row => row.UserId == data.CreatedBy) .Single(); return data; }
public FeedData Insert(FeedData data) { if (MockDb.Feeds.Count() == 0) { data.FeedId = 1; } else { data.FeedId = MockDb.Feeds.Select(row => row.FeedId).Max() + 1; } MockDb.Feeds.Add(data); return data; }
public FeedData Fetch(FeedDataCriteria criteria) { using (var ctx = Csla.Data.ObjectContextManager<ApplicationEntities> .GetManager(Database.ApplicationConnection, false)) { var feed = this.Fetch(ctx, criteria) .Single(); var feedData = new FeedData(); this.Fetch(feed, feedData); return feedData; } }
public Feed GetLatestFeed(string siteHost) { FeedData feedData = _feedRepository.GetLatestFeedData(siteHost); if (feedData == null) { return(null); } var serializer = new XmlSerializer(typeof(Feed), Ns); using (var ms = new MemoryStream(feedData.FeedBytes)) { return(serializer.Deserialize(ms) as Feed); } }
public async Task <Quote> GetAsync(string baseAssetId, string quoteAssetId) { string directAssetPairId = $"{baseAssetId}{quoteAssetId}"; if (baseAssetId == quoteAssetId) { return(new Quote(directAssetPairId, DateTime.UtcNow, 1, 1)); } IReadOnlyCollection <AssetPair> assetPairs = await _assetsServiceWithCache.GetAllAssetPairsAsync(); bool inverted = false; AssetPair assetPair = assetPairs .SingleOrDefault(o => o.BaseAssetId == baseAssetId && o.QuotingAssetId == quoteAssetId); if (assetPair == null) { inverted = true; assetPair = assetPairs .SingleOrDefault(o => o.BaseAssetId == quoteAssetId && o.QuotingAssetId == baseAssetId); } if (assetPair == null) { throw new InvalidOperationException($"Asset pair does not exist for '{baseAssetId}'/'{quoteAssetId}'"); } MarketProfile marketProfile = await GetMarketProfileAsync(); FeedData feedData = marketProfile.Profile.FirstOrDefault(o => o.Asset == assetPair.Id); if (feedData == null) { throw new InvalidOperationException($"No quote for asset pair '{assetPair.Id}'"); } if (inverted) { return(new Quote(assetPair.Id, feedData.DateTime, 1 / (decimal)feedData.Ask, 1 / (decimal)feedData.Bid)); } return(new Quote(assetPair.Id, feedData.DateTime, (decimal)feedData.Ask, (decimal)feedData.Bid)); }
private void Child_Fetch(FeedData parentData) { using (var dalManager = DataFactoryManager.GetManager()) { var dalFactory = dalManager.GetProvider <IFeedSourceMemberDataFactory>(); var data = dalFactory.Fetch(parentData); this.RaiseListChangedEvents = false; foreach (var item in data) { this.Add(Csla.DataPortal.FetchChild <FeedSource>(item)); } this.RaiseListChangedEvents = true; } }
protected async Task OnCrawlData(FeedData feedData) { if (MongoDbFeedData == null) { return; } await MongoDbFeedData.UpsertAsync(Builders <FeedData> .Filter.Eq(x => x.Url, feedData.Url)& Builders <FeedData> .Filter.Eq(x => x.Href, feedData.Href), feedData, async (feedData) => { if (OnCrawlDataDelegate != null) { await OnCrawlDataDelegate.Invoke(feedData); } }); }
public FeedData Insert(FeedData data) { using (var ctx = Csla.Data.ObjectContextManager <ApplicationEntities> .GetManager(Database.ApplicationConnection, false)) { var feed = new Feed(); DataMapper.Map(data, feed); ctx.ObjectContext.AddToFeeds(feed); ctx.ObjectContext.SaveChanges(); data.FeedId = feed.FeedId; return(data); } }
public FeedData Update(FeedData data) { using (var ctx = Csla.Data.ObjectContextManager <ApplicationEntities> .GetManager(Database.ApplicationConnection, false)) { var feed = new Feed { FeedId = data.FeedId }; ctx.ObjectContext.Feeds.Attach(feed); DataMapper.Map(data, feed); ctx.ObjectContext.SaveChanges(); return(data); } }
public void SerializeForPost(FeedData feedData, string pathToConfigurationFile) { var previousFeedData = Deserialize(pathToConfigurationFile); if (previousFeedData.FeedUrls.Contains(feedData.FeedUrls)) { return; } if (previousFeedData.FeedUrls.Length == 0) { previousFeedData.FeedUrls = feedData.FeedUrls; } else { previousFeedData.FeedUrls += "," + feedData.FeedUrls; } Serialize(previousFeedData, pathToConfigurationFile); }
// Sets the UI text to be filled with player data public void updateData(FeedData feedData) { // reset index dataIndex = 0; // update username usernameText.text = "<style=c3>" + feedData.username + "</style>"; // update data array dataArray = new string [9] { "level: " + string.Format("{0,1:###,###,###.##}", feedData.level) + "", "clicks: " + string.Format("{0,1:###,###,###.##}", feedData.clicks) + "", "score: " + string.Format("{0,1:###,###,###.##}", feedData.score) + "", "played: " + string.Format("{0,1:###,###,###.##}", (feedData.time / 60)) + " minutes", "battles fought: " + string.Format("{0,1:###,###,###.##}", (feedData.capturedTotal + feedData.missedTotal)) + "", "monsters captured: " + string.Format("{0,1:###,###,###.##}", feedData.capturedTotal) + "", "scrolled: " + string.Format("{0,1:###,###,###.##}", (feedData.pageActionScrollDistance / 1000000)) + " km", "trackers seen: " + string.Format("{0,1:###,###,###.##}", feedData.trackersSeen) + "", "trackers blocked: " + string.Format("{0,1:###,###,###.##}", feedData.trackersBlocked) + "", }; StopStartCouroutine(); }
private void Child_Fetch(FeedData data) { this.FeedId = data.FeedId; this.Action = data.Action; this.Description = data.Description; this.SourceId = data.SourceId; this.SourceName = data.Source.Name; this.SourceTypeId = data.SourceTypeId; this.CreatedBy = data.CreatedBy; this.CreatedByEmail = data.CreatedByUser.Email; this.CreatedByName = data.CreatedByUser.Name; this.CreatedDate = data.CreatedDate; this.Sources = new List <FeedSourceInfo>(); foreach (var source in data.Sources) { this.Sources.Add(Csla.DataPortal.FetchChild <FeedSourceInfo>(source)); } }
private async Task GetRSSFeed() { SyndicationClient client = new SyndicationClient(); Uri feedUri = new Uri("http://blogs.msdn.com/b/egtechtalk/rss.aspx"); SyndicationFeed feed = await client.RetrieveFeedAsync(feedUri); FeedData feedData = new FeedData(); 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("http://blogs.msdn.com/b/egtechtalk/" + 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; }
internal static Feed CreateFeedFromFeedData(FeedData feedData) { Feed newFeed = new Feed(); newFeed.Title = string.IsNullOrEmpty(feedData.Data.Title?.Text) ? feedData.Url : feedData.Data.Title.Text; newFeed.Url = feedData.Url; newFeed.LastUpdated = feedData.Data.LastUpdatedTime.UtcDateTime; foreach (SyndicationItem newFeedDataItem in feedData.Data.Items) { FeedItem newFeedItem = new FeedItem { Title = newFeedDataItem.Title?.Text ?? "No Title", Content = newFeedDataItem.Content?.ToString() ?? newFeedDataItem.Summary?.Text ?? "No Content", PublishedOn = newFeedDataItem.PublishDate.UtcDateTime }; newFeed.FeedItems.Add(newFeedItem); } return(newFeed); }
/** * Create a new player */ public bool CreateNewPlayer(FeedData feedData) { // make sure the player doesn't already exist if (playerDict.ContainsKey(feedData.username)) { return(false); } // get a position that doesn't contain any other colliders Vector3 spawnPosition = GetClearSpawnPosition(); // get the spawn rotation Quaternion spawnRotation = new Quaternion(); // random rotation - on local x only //spawnRotation.eulerAngles = new Vector3 (Random.Range (0.0f, 360.0f), 90f, 0f); // no random rotation spawnRotation.eulerAngles = new Vector3(0f, 0f, 0f); // if clear spawn position if (spawnPosition != Vector3.zero) { // instantiate prefab @ spawn position GameObject obj = (GameObject)Instantiate(playerPrefab, spawnPosition, spawnRotation); // call Init() on Player obj.GetComponent <Player> ().Init(feedData); // set name in Unity Editor obj.name = feedData.username; // parent under PlayerManger obj.transform.parent = gameObject.transform; // finaly, add to dict playerDict.Add(feedData.username, obj); // sets a reference to the cameraManager obj.GetComponent <Player> ().cameraManager = cameraManager; // Allow the player to be selected by the camera cameraManager.AddPlayer(feedData.username); } return(true); }
private void OnDetectFeeds(FeedData feedData, string data) { if (feedData != null) { Log.Debug("ExampleAlchemyLanguage", "status: {0}", feedData.status); if (feedData == null || feedData.feeds.Length == 0) { Log.Debug("ExampleAlchemyLanguage", "No feeds found!"); } else { foreach (Feed feed in feedData.feeds) { Log.Debug("ExampleAlchemyLanguage", "text: {0}", feed.feed); } } } else { Log.Debug("ExampleAlchemyLanguage", "Failed to find Feeds!"); } }
public FeedData[] FetchLookupInfoList(FeedDataCriteria criteria) { using (var ctx = Csla.Data.ObjectContextManager<ApplicationEntities> .GetManager(Database.ApplicationConnection, false)) { var feeds = this.Fetch(ctx, criteria) .AsEnumerable(); var feedDataList = new List<FeedData>(); foreach (var feed in feeds) { var feedData = new FeedData(); this.Fetch(feed, feedData); feedDataList.Add(feedData); } return feedDataList.ToArray(); } }
public FeedData[] FetchLookupInfoList(FeedDataCriteria criteria) { using (var ctx = Csla.Data.ObjectContextManager <ApplicationEntities> .GetManager(Database.ApplicationConnection, false)) { var feeds = this.Fetch(ctx, criteria) .AsEnumerable(); var feedDataList = new List <FeedData>(); foreach (var feed in feeds) { var feedData = new FeedData(); this.Fetch(feed, feedData); feedDataList.Add(feedData); } return(feedDataList.ToArray()); } }
private void Fetch(Feed feed, FeedData feedData) { DataMapper.Map(feed, feedData); feedData.Source = new SourceData(); DataMapper.Map(feed.Source, feedData.Source); feedData.CreatedByUser = new UserData(); DataMapper.Map(feed.CreatedByUser, feedData.CreatedByUser); foreach (var feedSourceMember in feed.FeedSourceMembers) { var feedSourceMemberData = new FeedSourceMemberData(); DataMapper.Map(feedSourceMember, feedSourceMemberData); var sourceData = new SourceData(); DataMapper.Map(feedSourceMember.Source, sourceData); feedSourceMemberData.Source = sourceData; feedData.Sources.Add(feedSourceMemberData); } }
public FeedSourceMemberData[] Fetch(FeedData parentData) { using (var ctx = Csla.Data.ObjectContextManager<ApplicationEntities> .GetManager(Database.ApplicationConnection, false)) { var feedSourceMembers = this.Fetch(ctx, new FeedSourceMemberDataCriteria { FeedId = parentData.FeedId }) .AsEnumerable(); var feedSourceMemberDataList = new List<FeedSourceMemberData>(); foreach (var feedSourceMember in feedSourceMembers) { var feedSourceMemberData = new FeedSourceMemberData(); this.Fetch(feedSourceMember, feedSourceMemberData); feedSourceMemberDataList.Add(feedSourceMemberData); } return feedSourceMemberDataList.ToArray(); } }
protected override void DataPortal_Insert() { using (var dalManager = DataFactoryManager.GetManager()) { var dalFactory = dalManager.GetProvider<IFeedDataFactory>(); var data = new FeedData(); using (this.BypassPropertyChecks) { this.CreatedBy = ((IBusinessIdentity)Csla.ApplicationContext.User.Identity).UserId; this.CreatedDate = DateTime.Now; this.Insert(data); data = dalFactory.Insert(data); this.FeedId = data.FeedId; } this.FieldManager.UpdateChildren(this); } }
public static void Run() { var data = FeedData.FromSeq(new[] { 1, 2, 3, 4, 5 }).ShuffleData(); //var data = FeedData.FromJson<User>("users_feed_data.json"); //var data = FeedData.FromCsv<User>("users_feed_data.csv"); var feed = Feed.CreateCircular("numbers", data); //var feed = Feed.CreateConstant("numbers", data); //var feed = Feed.CreateRandom("numbers", data); var step = Step.Create("step", feed, async context => { await Task.Delay(TimeSpan.FromSeconds(1)); context.Logger.Information("Data from feed: {FeedItem}", context.FeedItem); return(Response.Ok()); }); var scenario = ScenarioBuilder.CreateScenario("Hello World!", new[] { step }); NBomberRunner.RegisterScenarios(scenario) .RunInConsole(); }
public async void Init(bool force = false) { if (!_loaded || force) { FavAnime.Clear(); CurrentData = await new ProfileQuery().GetHumProfileData(); foreach (var fav in CurrentData.favorites) { var data = await ViewModelLocator.AnimeList.TryRetrieveAuthenticatedAnimeItem(fav.item_id); if (data != null) { FavAnime.Add(data as AnimeItemViewModel); } } RaisePropertyChanged(() => CurrentData); FeedData = await new ProfileQuery(true).GetHumFeedData(); SocialFeedData = FeedData.Where(o => o.story_type == "comment").ToList(); FeedData = FeedData.Where(o => o.story_type == "media_story").ToList(); RaisePropertyChanged(() => FeedData); } }
public void RemoveOldVersions(int numberOfGeneratedFeeds) { var items = _applicationDbContext.FeedData .Select(x => new { x.Id, x.CreatedUtc }).OrderByDescending(x => x.CreatedUtc).ToList(); if (items.Count > numberOfGeneratedFeeds) { for (var i = items.Count - 1; i >= numberOfGeneratedFeeds; i--) { var feedData = new FeedData { Id = items[i].Id }; _applicationDbContext.FeedData.Attach(feedData); _applicationDbContext.FeedData.Remove(feedData); } _applicationDbContext.SaveChanges(); } }
public FeedSourceMemberData[] Fetch(FeedData parentData) { using (var ctx = Csla.Data.ObjectContextManager <ApplicationEntities> .GetManager(Database.ApplicationConnection, false)) { var feedSourceMembers = this.Fetch(ctx, new FeedSourceMemberDataCriteria { FeedId = parentData.FeedId }) .AsEnumerable(); var feedSourceMemberDataList = new List <FeedSourceMemberData>(); foreach (var feedSourceMember in feedSourceMembers) { var feedSourceMemberData = new FeedSourceMemberData(); this.Fetch(feedSourceMember, feedSourceMemberData); feedSourceMemberDataList.Add(feedSourceMemberData); } return(feedSourceMemberDataList.ToArray()); } }
private void CleanSysPack(FeedData feed) { List <PictureSaveData> saves = feed.saves; string @string = PlayerPrefs.GetString("sysPackKey", string.Empty); if (string.IsNullOrEmpty(@string)) { return; } int num = 0; for (int i = saves.Count - 1; i >= 0; i--) { if (saves[i].PackId == -1) { num++; saves.RemoveAt(i); } } PlayerPrefs.SetString("sysPackKey", string.Empty); PlayerPrefs.SetString("feedKey", JsonUtility.ToJson(feed)); PlayerPrefs.Save(); AnalyticsManager.SysCleanup(num); }
IEnumerator PlayBattleEffects(FeedData feed) { //Debug.Log ("PlayBattle() feed = " + feed.ToString ()); // start battle AttachDetachAnimation(battleSpriteAnimFront, false, 2.5f, 2f); AttachDetachAnimation(attackSpriteAnim, true, 2.5f, -1); AttachDetachAnimation(battleSpriteAnimBack, false, 2.5f, 2.1f); yield return(new WaitForSeconds(1f)); // play another attack AttachDetachAnimation(attackSpriteAnim, true, 2.5f, -1); yield return(new WaitForSeconds(1f)); // remove battle AudioManager.Instance.Play("battle-won"); }
/** * Play a player event * - The logic that determines effects. * - For example, whether a GO with sprite animation or particle effect animation is attached, and what timeline animation (when tally twirls, etc.) is played. */ public void PlayEvent(FeedData feed) { //Debug.Log (DebugManager.GetSymbol ("smilingFace") + " PlayerManager.PlayEvent() [1] feed = " + feed.username.ToString ()); // PLAYER OBJECT REFERENCES // get the player from the dict playerDict.TryGetValue(feed.username, out currentPlayerObj); if (!currentPlayerObj) { return; } // reference to script (contains all the other references we need) currentPlayerScript = currentPlayerObj.GetComponent <Player> (); // store FeedData for zoom currentPlayerScript.feedData = feed; // show event in public var currentEventType = feed.eventType; // EFFECTS // BATTLES ARE MORE COMPLEX if (feed.eventType == "monster") { StartCoroutine(PlayBattleEffects(feed)); } else { // STREAM (CLICK or LIKE) if (feed.eventType == "stream") { AttachDetachAnimation(rippleAnim, false, 1f, 3.5f); // play the timeline animation currentPlayerScript.animControllerScript.animName = "Pop_Shake_md"; // check to see if there are monsters following the player if (feed.monsters != "") { //Debug.Log ("PlayerManager.PlayEvent() monsters = " + feed.monsters); } } // ATTACK else if (feed.eventType == "attack") { AttachDetachAnimation(attackAnim, false, 1f, 3f); // play the timeline animation currentPlayerScript.animControllerScript.animName = "Swirl_r_sm"; } // BADGE else if (feed.eventType == "badge") { AttachDetachAnimation(badgeAnim, false, 1f, 3.5f); // play the timeline animation currentPlayerScript.animControllerScript.animName = "Swirl_r_sm"; } // CONSUMABLE else if (feed.eventType == "consumable") { AttachDetachAnimation(consumableAnim, false, 1f, 2.5f); // play the timeline animation currentPlayerScript.animControllerScript.animName = "Pop_sm"; } // DISGUISE else if (feed.eventType == "disguise") { AttachDetachAnimation(disguiseAnim, false, 1f, 4f); // play the timeline animation currentPlayerScript.animControllerScript.animName = "Rotate_Pop_sm"; } // TRACKER else if (feed.eventType == "tracker") { AttachDetachAnimation(trackerAnim, false, 1f, 5f); // play the timeline animation currentPlayerScript.animControllerScript.animName = "Rotate_md"; } // LEADERBOARD - not currently storing / sending with API else if (feed.eventType == "leaderboard") { AttachDetachAnimation(leaderboardAnim, false, 1f, 3f); // play the timeline animation currentPlayerScript.animControllerScript.animName = "Pop_Shake_sm"; } // play matching sound AudioManager.Instance.Play(feed.eventType); } // test //StartCoroutine (PlayBattle (feed)); }
public void Run() { var data = FeedData.FromSeq(new[] { 1, 2, 3, 4, 5 }); var dataFeed = Feed.CreateRandom("random_feed", data); var webSocketConnectionPool = ConnectionPoolArgs.Create( name: "web_socket_pool", getConnectionCount: () => 10, openConnection: async(number, token) => { await Task.Delay(1_000); return(new FakeSocketClient { Id = number }); }, closeConnection: (connection, token) => { Task.Delay(1_000).Wait(); return(Task.CompletedTask); }); var step1 = Step.Create("step_1", webSocketConnectionPool, dataFeed, async context => { // you can do any logic here: go to http, websocket etc // context.CorrelationId - every copy of scenario has correlation id // context.Connection - fake websocket connection taken from pool // context.FeedItem - item taken from data feed // context.Logger // context.StopScenario("hello_world_scenario", reason = "") // context.StopTest(reason = "") await Task.Delay(TimeSpan.FromMilliseconds(200)); return(Response.Ok(42)); // this value will be passed as response for the next step // return Response.Ok(42, sizeBytes: 100, latencyMs: 100); - you can specify response size and custom latency // return Response.Fail(); - in case of fail, the next step will be skipped }); var step2 = Step.Create("step_2", async context => { // you can do any logic here: go to http, websocket etc await Task.Delay(TimeSpan.FromMilliseconds(200)); var value = context.GetPreviousStepResponse <int>(); // 42 return(Response.Ok()); }); var scenario = ScenarioBuilder .CreateScenario("hello_world_scenario", new[] { step1, step2 }) .WithTestInit(TestInit) .WithTestClean(TestClean) .WithWarmUpDuration(TimeSpan.FromSeconds(10)) // .WithoutWarmUp() - disable warm up .WithLoadSimulations(new [] { Simulation.RampConcurrentScenarios(copiesCount: 20, during: TimeSpan.FromSeconds(20)), Simulation.KeepConcurrentScenarios(copiesCount: 20, during: TimeSpan.FromMinutes(1)), // Simulation.RampScenariosPerSec(copiesCount: 10, during: TimeSpan.FromSeconds(20)), // Simulation.InjectScenariosPerSec(copiesCount: 10, during: TimeSpan.FromMinutes(1)) }); NBomberRunner .RegisterScenarios(new[] { scenario }) //.LoadConfigJson("config.json") // nbomber config for test settings only //.LoadInfraConfigJson("infra_config.json") // infra config for infra settings only //.LoadConfigYaml("config.yaml") // you can use yaml instead of json (https://github.com/PragmaticFlow/NBomber/blob/dev/tests/NBomber.IntegrationTests/Configuration/test_config.yaml) //.LoadInfraConfigYaml("infra_config.yaml") .RunInConsole(); }
private async Task<FeedData> RefreshFeedAsync(FeedData oldfeedData) { var cts = new CancellationTokenSource(); Task<string> eTag = GetETagAsync(oldfeedData.Link, cts); FeedData feedData = await RetrieveFeedAsync(oldfeedData.Link); if (feedData == null) { cts.Cancel(); oldfeedData.Error = FeedError.DownloadFeedError; return oldfeedData; } feedData.Id = oldfeedData.Id; feedData.Category = oldfeedData.Category; feedData.Order = oldfeedData.Order; feedData.ETag = await eTag; _feedDataRepository.Update(feedData); var feedsToRemove = _feedItemRepository .Find(feed => int.Equals(feed.FeedDataId, feedData.Id)) .Except(feedData.Items, FeedComparer<FeedItem>.Instance) .ToList(); foreach (FeedItem feedItem in feedsToRemove) { this._feedItemRepository.Remove(feedItem); } var feedsToAdd = feedData.Items.Except ( _feedItemRepository .Find(feed => int.Equals(feed.FeedDataId, feedData.Id)), FeedComparer<FeedItem>.Instance ) .ToList(); foreach (FeedItem feedItem in feedsToAdd) { feedItem.FeedDataId = feedData.Id; _feedItemRepository.Add(feedItem); } return feedData; }
/**************************************************** OTHER METHODS ******************************************************/ /// <summary> /// <para>parses and returns the FeedData in the form of list</para> /// </summary> /// <param name="ParsedJson"></param> /// <returns></returns> private List <FeedData> ParseFeeds(dynamic ParsedJson) { // CREATE FEEDDATA LIST List <FeedData> Data = new List <FeedData>(); foreach (dynamic Post in ParsedJson.data) { // CREATE FEEDDATA OBJECT FeedData Feed = new FeedData(); // CREATE ATTRIBUTION OBJECT; if (Post.attribution == null) { Feed.Attribution = null; } else { AttributionData Attribution = new AttributionData(); Attribution.Website = Post.Attribution.website; Attribution.ItunesUrl = Post.Attribution.itunes_url; Attribution.Name = Post.Attribution.name; Feed.Attribution = Attribution; } // SET TAGS List <String> Tags = new List <String>(); foreach (dynamic Tag in Post.tags) { Tags.Add(Tag.ToString()); } Feed.Tags = Tags; // SET TYPE Feed.Type = Post.type; // SET LOCATION if (Post.location == null) { Feed.Location = null; } else { LocationData Location = new LocationData(); Location.Id = Post.location.id; Location.Latitude = Post.location.latitude; Location.Longitude = Post.location.longitude; Location.Name = Post.location.name; Feed.Location = Location; } // SET COMMENTS CommentData Comments = new CommentData(); Comments.Count = Post.comments.count; List <Comment> CommentData = new List <Comment>(); foreach (dynamic EachComment in Post.comments.data) { // CREATE COMMENT OBJECT Comment Comment = new Comment(); Comment.CreatedTime = new DateTime(long.Parse(EachComment.created_time.ToString())); Comment.Id = EachComment.id; Comment.Text = EachComment.text; // CREATE USER OBJECT User CommentedBy = new User(); CommentedBy.UserName = EachComment.from.username; CommentedBy.ProfilePicture = EachComment.from.profile_pciture; CommentedBy.Id = EachComment.from.id; CommentedBy.FullName = EachComment.from.full_name; // ASSOCIATE COMMENT WITH USER Comment.From = CommentedBy; // ADD COMMENT TO THE LIST CommentData.Add(Comment); } Comments.Data = CommentData; Feed.Comments = Comments; // SET FILTER Feed.Filter = Post.filter; // SET CREATED TIME Feed.CreatedTime = new DateTime(long.Parse(Post.created_time.ToString())); // SET LINK Feed.Link = Post.link; // SET LIKES LikesData Likes = new LikesData(); Likes.Count = Post.likes.count; List <User> LikedByUsers = new List <User>(); foreach (dynamic EachLike in Post.likes.data) { // CREATE USER OBJECT User LikedBy = new User(); LikedBy.UserName = EachLike.username; LikedBy.ProfilePicture = EachLike.profile_picture; LikedBy.Id = EachLike.id; LikedBy.FullName = EachLike.full_name; // ADD USER TO THE LIST LikedByUsers.Add(LikedBy); } Likes.Data = LikedByUsers; Feed.Likes = Likes; // SET VIDEO if (Feed.Type.Equals("video")) { VideosData VideoData = new VideosData(); LowResolutionVideo LRVideo = new LowResolutionVideo(); LRVideo.url = Post.videos.low_resolution.url; LRVideo.width = Post.videos.low_resolution.width; LRVideo.height = Post.videos.low_resolution.height; VideoData.LowResolution = LRVideo; StandardResolutionVideo SRVideo = new StandardResolutionVideo(); SRVideo.url = Post.videos.standard_resolution.url; SRVideo.width = Post.videos.standard_resolution.width; SRVideo.height = Post.videos.standard_resolution.height; VideoData.StandardResolution = SRVideo; Feed.Videos = VideoData; } else { Feed.Videos = null; } // SET IMAGES ImagesData Images = new ImagesData(); StandardResolutionImage SRImage = new StandardResolutionImage(); SRImage.url = Post.images.standard_resolution.url; SRImage.width = Post.images.standard_resolution.width; SRImage.height = Post.images.standard_resolution.height; Images.StandardResolution = SRImage; ThumbnailImage TImage = new ThumbnailImage(); TImage.url = Post.images.thumbnail.url; TImage.width = Post.images.thumbnail.width; TImage.height = Post.images.thumbnail.height; Images.Thumbnail = TImage; LowResolutionImage LRImage = new LowResolutionImage(); LRImage.url = Post.images.low_resolution.url; LRImage.width = Post.images.low_resolution.width; LRImage.height = Post.images.low_resolution.height; Images.LowResolution = LRImage; Feed.Images = Images; // SET CAPTIONS CaptionData Caption = new CaptionData(); if (Post.caption != null) { Caption.CreratedTime = new DateTime(long.Parse(Post.caption.created_time.ToString())); Caption.Text = Post.caption.text; Caption.Id = Post.caption.id; User CaptionedBy = new User(); CaptionedBy.UserName = Post.caption.from.username; CaptionedBy.ProfilePicture = Post.caption.from.profile_pciture; CaptionedBy.Id = Post.caption.from.id; CaptionedBy.FullName = Post.caption.from.full_name; Caption.From = CaptionedBy; } Feed.Caption = Caption; // SET TAGGED USER List <TaggedUser> UserInPhotos = new List <TaggedUser>(); if (Post.users_in_photo != null) { foreach (dynamic UserTag in Post.users_in_photo) { // CREATE TAGGED USER OBJECT TaggedUser TUser = new TaggedUser(); // SET USER User TaggedUser = new User(); TaggedUser.UserName = UserTag.user.username; TaggedUser.FullName = UserTag.user.full_name; TaggedUser.Id = UserTag.user.id; TaggedUser.ProfilePicture = UserTag.user.profile_picture; TUser.User = TaggedUser; // SET POSITION Position TagPosition = new Position(); TagPosition.x = float.Parse(UserTag.position.x.ToString()); TagPosition.y = float.Parse(UserTag.position.y.ToString()); TUser.Position = TagPosition; // ADD TO LIST UserInPhotos.Add(TUser); } } Feed.UsersInPhoto = UserInPhotos; // SET USER LIKE Feed.UserHasLiked = Post.user_has_liked; // SET ID Feed.Id = Post.id; // SET USER User FeedBy = new User(); FeedBy.UserName = Post.user.username; FeedBy.Website = Post.user.webste; FeedBy.ProfilePicture = Post.user.profile_picture; FeedBy.FullName = Post.user.full_name; FeedBy.Bio = Post.user.bio; FeedBy.Id = Post.user.id; Feed.User = FeedBy; // ADD FEED TO LIST Data.Add(Feed); } return(Data); }
public static void Run() { var userFeed = Feed.CreateRandom( "userFeed", FeedData.FromJson <UserId>("./HttpTests/Configs/user-feed.json") ); var httpFactory = HttpClientFactory.Create(); var getUser = Step.Create("get_user", httpFactory, userFeed, async context => { var userId = context.FeedItem; var url = $"https://jsonplaceholder.typicode.com/users?id={userId}"; var request = Http.CreateRequest("GET", url) .WithCheck(async response => { var json = await response.Content.ReadAsStringAsync(); // parse JSON var users = JsonConvert.DeserializeObject <UserResponse[]>(json); return(users?.Length == 1 ? Response.Ok(users.First()) // we pass user object response to the next step : Response.Fail("not found user")); }); var response = await Http.Send(request, context); return(response); }); // this 'getPosts' will be executed only if 'getUser' finished OK. var getPosts = Step.Create("get_posts", httpFactory, async context => { var user = context.GetPreviousStepResponse <UserResponse>(); var url = $"https://jsonplaceholder.typicode.com/posts?userId={user.Id}"; var request = Http.CreateRequest("GET", url) .WithCheck(async response => { var json = await response.Content.ReadAsStringAsync(); // parse JSON var posts = JsonConvert.DeserializeObject <PostResponse[]>(json); return(posts?.Length > 0 ? Response.Ok() : Response.Fail($"not found posts for user: {user.Id}")); }); var response = await Http.Send(request, context); return(response); }); var scenario = ScenarioBuilder .CreateScenario("rest_api", getUser, getPosts); NBomberRunner .RegisterScenarios(scenario) .WithWorkerPlugins(new PingPlugin()) .LoadConfig("./HttpTests/Configs/config.json") .LoadInfraConfig("./HttpTests/Configs/infra-config.json") .Run(); }
public FeedData Insert(FeedData data) { using (var ctx = Csla.Data.ObjectContextManager<ApplicationEntities> .GetManager(Database.ApplicationConnection, false)) { var feed = new Feed(); DataMapper.Map(data, feed); ctx.ObjectContext.AddToFeeds(feed); ctx.ObjectContext.SaveChanges(); data.FeedId = feed.FeedId; return data; } }
public List<FeedData> ReadData() { //Load the document XmlDocument doc = new XmlDocument(); XmlNamespaceManager namespaces = new XmlNamespaceManager(doc.NameTable); namespaces.AddNamespace("ns", "urn:hl7-org:v3"); doc.Load(_masterFile); var nodeList = doc.DocumentElement.SelectNodes("channel/item"); foreach (XmlNode node in nodeList) { string title = node["title"]?.InnerText; string description = node["description"]?.InnerText; string link = string.Empty; string pubdate = string.Empty; if (node["link"] != null) { link = node["link"]?.InnerText; } else if (node["a10:link"] != null) { link = node["a10:link"].Attributes[0].InnerText; //link = node["a10:link"].InnerText; } if (node["pubDate"] != null) { pubdate = node["pubDate"].InnerText; } else if (node["a10:updated"] != null) { pubdate = node["a10:updated"].InnerText; } fdata = new FeedData(); fdata.publishdate = Convert.ToDateTime(pubdate); fdata.link = link; fdata.title = title; if (Regex.Replace(description, "<[^>]*>", "").Length > 300) { fdata.description = Regex.Replace(description, "<[^>]*>", "").Substring(0, 299) + "..."; } else { fdata.description = Regex.Replace(description, "<[^>]*>", ""); } feedData.Add(fdata); } return feedData; }
static void Main(string[] args) { IFeed <RequestInfo> urlsDataFeed = Feed.CreateConstant("Requests", FeedData.FromSeq(relativeUrlsToTest)); IStep relativeUrlsHttpRequestStep = HttpStep.Create( name: $"Fetch random Ebriza data intensive URLs", feed: urlsDataFeed, ctx => { string cookies = httpClientHandler.CookieContainer.GetCookieHeader(new Uri($"{webProtocol}{webDomain}")); NBomber.Http.HttpRequest result = Http.CreateRequest(ctx.FeedItem.Method, $"{webProtocol}{webDomain}{ctx.FeedItem.RelativeUrl}") .WithHeader("Cookie", cookies) .WithCheck(async res => res.IsSuccessStatusCode && res.RequestMessage.RequestUri.ToString().Contains(ctx.FeedItem.RelativeUrl, StringComparison.InvariantCultureIgnoreCase) ? Response.Ok() : Response.Fail(res.StatusCode.ToString())) ; if (ctx.FeedItem.Body != null) { result = result.WithBody(new StringContent(JsonConvert.SerializeObject(ctx.FeedItem.Body), Encoding.UTF8, ctx.FeedItem.ContentType)); } return(result); }, completionOption: HttpCompletionOption.ResponseContentRead ); NBomber.Contracts.Scenario userPerSecondScenario = ScenarioBuilder .CreateScenario(name: $"Load Testing Scenario for {webDomain} with {usersPerSecondToSimulate} users per second", relativeUrlsHttpRequestStep) .WithWarmUpDuration(defaultWarmupDuration) .WithInit(async ctx => { using (HttpResponseMessage response = await http.PostAsync( $"{webProtocol}{webDomain}/Login/Login", new StringContent( JsonConvert.SerializeObject( new { CompanyHandle = companyHandle, UserName = username, Password = password, } ), Encoding.UTF8, "application/json" ) ) ) { response.EnsureSuccessStatusCode(); }; }) .WithClean(ctx => { http.CancelPendingRequests(); httpClientHandler.Dispose(); http.Dispose(); return(System.Threading.Tasks.Task.CompletedTask); }) .WithLoadSimulations(new NBomber.Contracts.LoadSimulation[] { Simulation.InjectPerSec(rate: usersPerSecondToSimulate, during: defaultSimulationDuration), //RATE scenarios per second, for a timespan of DURING seconds) }); PingPluginConfig pingPluginConfig = PingPluginConfig.CreateDefault(new string[] { webDomain }); PingPlugin pingPlugin = new PingPlugin(pingPluginConfig); NBomberRunner .RegisterScenarios(userPerSecondScenario) .WithTestSuite("Ebriza Load Testing") .WithTestName($"Load test {webDomain}") .WithWorkerPlugins(pingPlugin) .Run(); }
public FeedData Update(FeedData data) { using (var ctx = Csla.Data.ObjectContextManager<ApplicationEntities> .GetManager(Database.ApplicationConnection, false)) { var feed = new Feed { FeedId = data.FeedId }; ctx.ObjectContext.Feeds.Attach(feed); DataMapper.Map(data, feed); ctx.ObjectContext.SaveChanges(); return data; } }
protected void Insert(FeedData data) { this.Update(data); }
private void Fetch(Feed feed, FeedData feedData) { DataMapper.Map(feed, feedData); feedData.Source = new SourceData(); DataMapper.Map(feed.Source, feedData.Source); feedData.CreatedByUser = new UserData(); DataMapper.Map(feed.CreatedByUser, feedData.CreatedByUser); foreach (var feedSourceMember in feed.FeedSourceMembers) { var feedSourceMemberData = new FeedSourceMemberData(); DataMapper.Map(feedSourceMember, feedSourceMemberData); var sourceData = new SourceData(); DataMapper.Map(feedSourceMember.Source, sourceData); feedSourceMemberData.Source = sourceData; feedData.Sources.Add(feedSourceMemberData); } }
public SyndicationActionResult(FeedData feedData) { FeedData = feedData; }
private static async Task<FeedData> RetrieveFeedAsync(Uri feedLink) { var feed = new SyndicationFeed(); var client = new SyndicationClient(); var feedData = new FeedData(); client.SetRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); client.BypassCacheOnRetrieve = true; try { feed = await client.RetrieveFeedAsync(feedLink); } catch (Exception e) { SyndicationErrorStatus syndicationError = SyndicationError.GetStatus(e.HResult); if (syndicationError == SyndicationErrorStatus.Unknown) { WebErrorStatus webError = WebError.GetStatus(e.HResult); if (webError == WebErrorStatus.Unknown) { throw; } } return null; } if (feed.Title != null && !string.IsNullOrEmpty(feed.Title.Text)) { feedData.Title = feed.Title.Text; } if (feed.Subtitle != null && !string.IsNullOrEmpty(feed.Subtitle.Text)) { feedData.Description = feed.Subtitle.Text; } feedData.Link = feedLink; if (feed.Items != null && feed.Items.Any()) { feedData.PubDate = feed.Items.First().PublishedDate.DateTime; foreach (SyndicationItem item in feed.Items) { feedData.Items.Add(item.ToFeedItem(feed.SourceFormat)); } } return feedData; }
public static void Run() { var userFeed = Feed.CreateRandom( name: "userFeed", provider: FeedData.FromSeq(new[] { "1", "2", "3", "4", "5" }) ); var getUser = HttpStep.Create("get_user", userFeed, context => { var userId = context.FeedItem; var url = $"https://jsonplaceholder.typicode.com/users?id={userId}"; return(Http.CreateRequest("GET", url) .WithCheck(async response => { var json = await response.Content.ReadAsStringAsync(); // parse JSON var users = JsonConvert.DeserializeObject <UserResponse[]>(json); return users?.Length == 1 ? Response.Ok(users.First()) // we pass user object response to the next step : Response.Fail($"not found user: {userId}"); })); }); // this 'getPosts' will be executed only if 'getUser' finished OK. var getPosts = HttpStep.Create("get_posts", context => { var user = context.GetPreviousStepResponse <UserResponse>(); var url = $"https://jsonplaceholder.typicode.com/posts?userId={user.Id}"; return(Http.CreateRequest("GET", url) .WithCheck(async response => { var json = await response.Content.ReadAsStringAsync(); // parse JSON var posts = JsonConvert.DeserializeObject <PostResponse[]>(json); return posts?.Length > 0 ? Response.Ok() : Response.Fail($"not found posts for user: {user.Id}"); })); }); var scenario = ScenarioBuilder .CreateScenario("rest_api", getUser, getPosts) .WithWarmUpDuration(TimeSpan.FromSeconds(5)) .WithLoadSimulations(new[] { Simulation.InjectPerSec(rate: 100, during: TimeSpan.FromSeconds(30)) }); var pingPluginConfig = PingPluginConfig.CreateDefault(new[] { "jsonplaceholder.typicode.com" }); var pingPlugin = new PingPlugin(pingPluginConfig); NBomberRunner .RegisterScenarios(scenario) .WithPlugins(pingPlugin) .WithTestSuite("http") .WithTestName("advanced_test") .Run(); }
private void buttonLoadFeeds_Click(object sender, EventArgs e) { _feedData = FeedData.GetData(); gridFeeds.DataSource = _feedData; gridFeeds.RefreshDataSource(); }