override protected void OnInsertValidate() { var db = new BaseRepository(); var r = db.GetEntitie <LivePig>(p => p.raiserID == this.raiserID); if (r == null) { throw(new Exception(string.Format("养户编号\"{0}\"不存在", raiserID))); } if (db.GetEntitie <tbFeedGrant>(p => p.PigID == r.ID && p.checkState == 0) != null) { throw(new Exception(string.Format("养户\"{0}\"有未审核的发料记录", raiserID))); } this.PigID = r.ID; this.fromDays = r.feedGrantToDays + 1; this.realNum = r.extantNum; this.checkState = (r.feedSurplusDays + this.delayDays + this.addDays) > AppGlobal.grantFeedDay ? 0 : 1; var f = FeedHelper.GetFeeds(this.fromDays, this.fromDays + this.addDays - 1, r.extantNum); this.feeds = FeedHelper.GetRegexStr(f); this.referPerson = Account.currentUser == null? "" : Account.currentUser.userName; this.checkPerson = this.referPerson; this.referTime = DateTime.Now; this.checkTime = DateTime.Now; }
public async Task <ActionResult> Get(string search = null) { DateTime utcNow = DateTime.UtcNow; DateTime now = TimeZoneInfo.ConvertTimeFromUtc(utcNow, _timeZone); DateTime dateFrom = now.AddMonths(-1); RigaBuildingPermit[] buildingPermits = await _repository.GetBuildingPermits(dateFrom, search); string title = "Rīgas būvatļaujas"; if (!string.IsNullOrEmpty(search)) { title += $" - {search}"; } SyndicationFeed feed = new SyndicationFeed(title, null, new Uri(RigaBuildingPermitRepository.BaseUrl)); try { feed.Items = buildingPermits .Select(buildingPermit => CreateSyndicationItem(buildingPermit)) .ToArray(); } catch (Exception e) { FeedHelper.AddExceptionToFeed(feed, e); } return(new FeedActionResult(feed)); }
/// <summary> /// Handles the Create N upload_ click event. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void CreateNUpload_Click(object sender, EventArgs e) { var album = new PhotoAlbumObject(AlbumName.Text.TrimEnd(' ')); ErrMsg.Visible = false; if (AlbumName.Text.TrimEnd(' ').Length >= 20) { ErrMsg.Text = "The length of album name has to be less then 20 characters."; ErrMsg.Visible = true; } else { if (!album.CreatePhotoAlbumItem(AlbumName.Text.TrimEnd(' '), string.Empty)) { if (!string.IsNullOrEmpty(album.PageErrorMsg)) { ErrMsg.Text = album.PageErrorMsg; ErrMsg.Visible = true; } // check message property in class and show this message on registration page } else { FeedHelper.CreateUserAlbumsFeed(album.CurrentAlbumItem); FeedHelper.CreateAlbumFeed(album.CurrentAlbumItem); // redirect to upload page PhotoAlbumObject.RedirectToAlbumPage(Sitecore.Configuration.Settings.GetSetting("uploadPhotosPageItemID"), album.CurrentAlbumItem.ID.ToString()); } } }
private static async Task <IDictionary <Guid, int> > UpdateDownloadedFeedsAsync(IDictionary <Guid, Feed> subscribedFeeds, string fileName, IPersistentManager dbContext) { var feedsUpdated = await dbContext.ReadSerializedCopyAsync <List <Feed> >(fileName); if (feedsUpdated == null || feedsUpdated.Count == 0) { return(null); } var updatedFeeds = new Dictionary <Guid, int>(); feedsUpdated.ForEach(f => { if (!subscribedFeeds.ContainsKey(f.Id)) { return; } var persistentFeed = subscribedFeeds[f.Id]; var updatedItemCount = FeedHelper.UpdateFeedItems(persistentFeed, f.Items); if (updatedItemCount > 0) { updatedFeeds.Add(persistentFeed.Id, updatedItemCount); } persistentFeed.LastUpdatedTime = f.LastUpdatedTime; }); return(updatedFeeds); }
public string GetFeed(string name, int index) { List <string> result = new List <string>(); feeds.ForEach(a => { List <Feed> fd = FeedHelper.GetFeeds(a.feeds); DateTime dt = a.referTime; double nv = 0; fd.ForEach(f => { if (f.name == name) { nv += f.nValue * 40; } }); if (nv > 0) { string s = string.Format("{0:MM-dd} / {1}", dt, nv); result.Add(s); } }); if (result.Count <= index) { return(""); } return(result.ElementAt(index)); }
public ActionResult AnswerAccept(string AId) { NullChecker.NullCheck(new object[] { AId }); var answer = unitOfWork.AnswerRepository.GetByID(EncryptionHelper.Unprotect(AId)); if (AuthorizationHelper.isRelevant(answer.Question.questionerID)) { if (answer.accept) { answer.accept = false; unitOfWork.AnswerRepository.Update(answer); unitOfWork.Save(); return(Json(new { Success = true, Result = false })); } else { answer.accept = true; unitOfWork.Save(); unitOfWork.AnswerRepository.Update(answer); NotificationHelper.NotificationInsert(NotificationType.AnswerAccept, elemId: answer.answerID); FeedHelper.FeedInsert(FeedType.AnswerAccept, answer.questionID, answer.answererID ); ScoreHelper.Update(new ScoreVars { type = ScoreType.Aacc, elemId = answer.answerID, sign = 1 }); return(Json(new { Success = true, Result = true })); } } throw new JsonCustomException(ControllerError.ajaxErrorAnswerAcception); }
public ActionResult Share(ShareViewModel newShareToInsert, string PId) { NullChecker.NullCheck(new object[] { PId }); int user = WebSecurity.CurrentUserId; int pid = (int)EncryptionHelper.Unprotect(PId); var postToshare = unitOfWork.PostRepository.GetByID(pid); if (postToshare.Shares.Any(ts => ts.SharerUserID == user)) { throw new JsonCustomException(ControllerError.ajaxErrorPatentUser); } if (ModelState.IsValid) { Share finalshareToInsrt = newShareToInsert.Share; finalshareToInsrt.SharerUserID = user; finalshareToInsrt.sharedPostID = postToshare.postID; finalshareToInsrt.shareNote = newShareToInsert.Share.shareNote; finalshareToInsrt.insertdate = DateTime.UtcNow; unitOfWork.ShareRepository.Insert(finalshareToInsrt); unitOfWork.Save(); FeedHelper.FeedInsert(FeedType.SessionOfferLike, postToshare.postID, WebSecurity.CurrentUserId); return(Json(new { Success = true, Message = Resource.Resource.sharedSuccessfully })); } throw new ModelStateException(this.ModelState); }
private SyndicationItem CreateSyndicationItem(RigaBuildingPermit buildingPermit) { string searchString = buildingPermit.Object .Replace('(', ' ') .Replace(')', ' '); while (searchString.Contains(" ")) { searchString = searchString.Replace(" ", " "); } Dictionary <string, string> query = new Dictionary <string, string> { ["search"] = searchString }; query["date_to"] = query["date_from"] = buildingPermit.PreparationDate.ToString(RigaBuildingPermitRepository.DateFormat); UriBuilder uriBuilder = new UriBuilder(RigaBuildingPermitRepository.BaseUrl) { Query = RepositoryHelper.GetQueryString(query), }; SyndicationItem item = new SyndicationItem(buildingPermit.Object, buildingPermit.ObjectAddress, uriBuilder.Uri) { PublishDate = FeedHelper.GetDateTimeOffsetLV(buildingPermit.PreparationDate), }; return(item); }
/// <summary> /// 发料详细列表 /// </summary> /// <returns></returns> public List <Feed> GetFeedsList() { List <Feed> fs = new List <Feed>(); fs.AddRange(FeedHelper.GetFeeds(feeds)); return(fs); }
public ActionResult Create([Bind(Include = "title,titleEN,coName,coNameEN,description,descriptionEN,attendDate,untilDate,stateID")] Experience exp, string CoId) { if (!String.IsNullOrEmpty(CoId)) { ModelState.Remove("coName"); ModelState.Remove("coNameEN"); } if (ModelState.IsValid) { if (!String.IsNullOrEmpty(CoId)) { var coid = EncryptionHelper.Unprotect(CoId); var companyToExperience = unitOfWork.NotExpiredCompanyRepository.GetByID(coid); exp.coName = companyToExperience.coName; exp.coNameEN = companyToExperience.coNameEN; exp.CoId = coid; } exp.userID = WebSecurity.CurrentUserId; unitOfWork.ExperienceRepository.Insert(exp); unitOfWork.Save(); FeedHelper.FeedInsert(FeedType.Experience, exp.experienceID, exp.userID ); UnitOfWork newContext = new UnitOfWork(); var newExperience = newContext.ExperienceRepository.GetByID(exp.experienceID); return(Json(new { Result = RenderPartialViewHelper.RenderPartialView(this, "ExperiencePartial", newExperience), Message = Resource.Resource.createdSuccessfully })); } throw new ModelStateException(this.ModelState); }
public void Execute(IJobExecutionContext context) { List <Source> sources = db.Sources.ToList(); if (sources == null) { return; } foreach (var source in db.Sources) { DateTimeOffset?entityLastDateTime = db.Entities.Where(e => e.SourceId == source.Id).Max(e => e.PublicationDate); List <Entity> entities = FeedHelper.GetEntitiesFromFeed(source.Link).ToList(); foreach (Entity item in entities) { if (item.PublicationDate > entityLastDateTime || entityLastDateTime == null) { db.Entities.Add(new Entity() { Title = item.Text, PublicationDate = item.PublicationDate, Link = item.Link, SourceId = source.Id }); } } } db.SaveChangesAsync(); }
public ActionResult Get(string afterTimestamp = "", string afterId = "") { long?lafterTimestamp = null, lafterId = null; long lafterTimestampTemp, lafterIdTemp; if (long.TryParse(afterTimestamp, out lafterTimestampTemp)) { lafterTimestamp = lafterTimestampTemp; } if (long.TryParse(afterId, out lafterIdTemp)) { lafterId = lafterIdTemp; } //var sessionContainer = FeedHelper.GetSessions(lafterTimestamp, lafterId); var sessionContainer = FeedHelper.GetSessions_v1(lafterTimestamp, lafterId); if (!string.IsNullOrEmpty(sessionContainer?.Next) && sessionContainer?.Items?.Count <= 0) { if (!sessionContainer.Next.Contains("?")) { if (!string.IsNullOrEmpty(afterTimestamp)) { sessionContainer.Next += "?afterTimestamp=" + afterTimestamp; if (!string.IsNullOrEmpty(afterId)) { sessionContainer.Next += "&afterId=" + afterId; } } } } return(Ok(sessionContainer)); }
public ActionResult GetEventActivityWise(string activityName = null, string location = null, string latitude = null, string longitude = null) { string Model = string.Concat("{activityName:", activityName, " , location:", location, " , latitude:", latitude, " , longitude:", longitude); LogHelper.InsertServiceLogs("search/list (GetEventActivityWise)", Model); var sessions = FeedHelper.GetEventActivityWise(activityName, location, latitude, longitude); return(Ok(new { activities = sessions })); }
private SyndicationItem CreateSyndicationItem(AgricultureProject agricultureProject) { SyndicationItem item = new SyndicationItem(agricultureProject.Name, agricultureProject.Description, agricultureProject.Url) { PublishDate = FeedHelper.GetDateTimeOffsetLV(agricultureProject.PublishDate), }; return(item); }
private SyndicationItem CreateSyndicationItem(TransportProject transportProject) { SyndicationItem item = new SyndicationItem(transportProject.Name, transportProject.ApplyingInfo, TransportProjectRepository.BaseUrl) { PublishDate = FeedHelper.GetDateTimeOffsetLV(transportProject.PublishDate), }; return(item); }
protected override async void OnNavigatedTo(NavigationEventArgs e) { Loading.IsActive = true; FeedHelper helper = new FeedHelper(); var items = await helper.GetNewsAsync("https://blogs.windows.com/feed"); News.ItemsSource = items; Loading.IsActive = false; }
public void RebroadcastServerManager_FeedsChanged_Removes_Old_Feeds() { _Manager.Initialise(); FeedHelper.RemoveFeed(_Feeds, _Listeners, 1); _FeedManager.Raise(r => r.FeedsChanged += null, EventArgs.Empty); Assert.AreEqual(0, _Manager.RebroadcastServers.Count); }
public ActionResult GetSubEventDetails(string sessionId, string startDate) { string Model = string.Concat("{sessionId:", sessionId, "startDate:", startDate, "}"); LogHelper.InsertServiceLogs("search/sessionId/subevent/startDate (GetSubEventDetails)", Model); //var events = FeedHelper.GetSubEventDetailsBySessionIdDynamically(sessionId?.Split('-')[0], startDate, sessionId?.Split('-')[1]); var events = FeedHelper.GetSubEventDetailsBySessionIdDynamically(sessionId?.Substring(sessionId.IndexOf("-") + 1).Trim(), startDate, sessionId?.Substring(0, sessionId.IndexOf("-")).Trim()); return(Ok(events)); }
public ActionResult GetOrganisations(double?lat, double?lng, double?radius, [FromQuery] string[] activity, [FromQuery] string[] disabilitySupport, [FromQuery] string[] source, [FromQuery] string[] tag, [FromQuery] string[] excludeTag, string gender = null, long?minAge = null, long?maxAge = null, long?page = 1, long?limit = 50, string from = null, string to = null) { #region Variable declaration or assignment lat = lat ?? defaultLatitude; lng = lng ?? defaultLongitude; radius = radius ?? defaultRadius; string sources = null; string tags = null; string excludeTags = null; string activities = null; string disabilitySupports = null; if (source.Length > 0) { sources = string.Join(",", source); } if (tag.Length > 0) { tags = string.Join(",", tag); } if (excludeTag.Length > 0) { excludeTags = string.Join(",", excludeTag); } if (activity.Length > 0) { activities = string.Join(",", activity); } if (disabilitySupport.Length > 0) { disabilitySupports = string.Join(",", disabilitySupport); } if (page == null || page == 0) { page = 1; } if (limit == null || limit == 0) { limit = 50; } #endregion string Model = string.Concat("{lat:", lat, " ,lng:", lng, " ,radius:", radius, " , sources:", sources, " , tags:", tags, " , excludeTags:", excludeTags, " , activities:", activities, " ,page:", page, " , limit:", limit, "}"); LogHelper.InsertServiceLogs("search/organisations (GetOrganisations)", Model); var organisations = FeedHelper.GetOrganisations(lat, lng, radius, activities, disabilitySupports, gender, minAge, maxAge, page, limit, from, to, sources, tags, excludeTags); return(Ok(organisations)); }
/// <summary> /// 不同种类饲料的包数和 /// </summary> /// <returns></returns> public double GetFeedBagNum() { List <Feed> feed = FeedHelper.GetFeeds(this.feeds); if (feed.Count == 0) { return(0.0); } return(feed.Sum(p => p.nValue)); }
/// <summary> /// 体重增量 /// </summary> /// <returns></returns> public double WeightInc() { List <Feed> feed = FeedHelper.GetFeeds(this.feeds); if (feed.Count == 0) { return(0.0); } return(feed.Sum(p => p.weight)); }
public void RebroadcastServerManager_ConfigurationChanged_Disposes_Of_Server_If_Listener_Goes_Away() { _Manager.Initialise(); FeedHelper.RemoveFeed(_Feeds, _Listeners, 1); _ConfigurationStorage.Raise(r => r.ConfigurationChanged += null, EventArgs.Empty); Assert.AreEqual(0, _Manager.RebroadcastServers.Count); _Server.Verify(r => r.Dispose(), Times.Once()); _Connector.Verify(r => r.Dispose(), Times.Once()); }
/// <summary> /// Retrieves the Cache Key for the given Id /// </summary> /// <typeparam name="T">Type of Resource which derive from /// <typeparamref name="Microsoft.Famulus.Core.Resource"/></typeparam> /// <param name="id">The id for the key</param> /// <param name="feedBy">The associated feedby object</param> /// <returns>string format for the key</returns> private string GetCacheKey <T>(string name, FeedBy feedBy) where T : Core.Resource { StringBuilder cacheKey = new StringBuilder(FeedHelper.TypeOfResource <T>()); cacheKey.Append("@"); cacheKey.Append(feedBy.ToString()); cacheKey.Append("@"); cacheKey.Append(name.ToString()); return(cacheKey.ToString()); }
public ActionResult GetOrganisationDetails(long?organisationId) { string Model = string.Concat("{organisationId:", organisationId, "}"); var oRequestCode = new Random().Next(0, int.MaxValue); var oRequestTime = DateTime.Now; LogHelper.InsertServiceLogs("search/organisationId (GetOrganisationDetails)(" + oRequestCode + ")", Model, oRequestTime); var organisation = FeedHelper.GetOrganisationDetailsById(organisationId); LogHelper.InsertServiceLogs("search/organisationId (GetOrganisationDetails)- Response(" + oRequestCode + ")", Model, oRequestTime, DateTime.Now); return(Ok(organisation)); }
public void MainPresenter_GetReceiverFeeds_Excludes_Merged_Feeds() { var mergedFeedListeners = new List <Mock <IMergedFeedListener> >(); FeedHelper.AddMergedFeeds(_Feeds, mergedFeedListeners, 3); var feeds = _Presenter.GetReceiverFeeds(); Assert.AreEqual(2, feeds.Length); Assert.IsTrue(feeds.Contains(_Feeds[0].Object)); Assert.IsTrue(feeds.Contains(_Feeds[1].Object)); }
public void RebroadcastServerManager_Dispose_Prevents_FeedManager_Changes_From_Creating_New_Servers() { FeedHelper.RemoveFeed(_Feeds, _Listeners, 1); _Manager.Initialise(); _Manager.Dispose(); FeedHelper.AddFeeds(_Feeds, _Listeners, 1); _FeedManager.Raise(r => r.FeedsChanged += null, EventArgs.Empty); Assert.AreEqual(0, _Manager.RebroadcastServers.Count); _Server.Verify(r => r.Initialise(), Times.Never()); }
static RssUtility() { LinkUtility.TryAddHandler(LinkType.RSS, async(link, channel, cancellationToken) => { var listUrls = new List <string>(); var url = link.Value; var feed = FeedHelper.ParseRss(url); var items = feed.Items .Where(item => !LinkUtility.LinkItemExists(link, item.Guid, StringComparison.CurrentCultureIgnoreCase)) .Where(item => item.PublishDate.ToUniversalTime() > link.Date.ToUniversalTime()) .Reverse(); if (items.Count() > 0) { var retryCount = 0; for (int i = 0; i < items.Count(); i++) { if (cancellationToken.IsCancellationRequested) { return(listUrls); } var item = items.ElementAt(i); try { Log.Info($"Posting \"{item.Title}\" ({LinkType.RSS.ToString()}) in \"{link.Guild.Name}:{link.Channel.Name}\""); // Posting "10,408 Mysterious Necklaces" (Reddit) in "Team Aqua:general" await channel.EmbedAsync(ParseEmbed(item.Link, channel.Guild, feed.Channel?.Title), options: new RequestOptions() { RetryMode = RetryMode.AlwaysFail } ); listUrls.Add(item.Guid ?? item.Link); retryCount = 0; } catch (Exception ex) { if (!await LinkUtility.SendRetryLinkMessageAsync( link.Type, retryCount++, ex is Discord.Net.RateLimitedException ? null : ex )) { break; } i--; } } } return(listUrls); }); }
private ActionResult FeedPreview() { string raiserID = Request["raiserID"]; var pig = new FarmRepository().GetEntitie <LivePig>(p => p.raiserID == raiserID); if (pig == null) { return(Json(new { success = false, message = string.Format("养户编号 \"{0}\" 没有对应的在养批次", raiserID) }, JsonRequestBehavior.AllowGet)); } string addDays = Request["addDays"]; string delayDays = Request["delayDays"]; int n2, n3; if (!Int32.TryParse(addDays, out n2)) { n2 = pig.GetLastGrantFeedDays(); } if (!Int32.TryParse(delayDays, out n3)) { n3 = pig.feedSurplusDays < 0 ? 0 - pig.feedSurplusDays : 0; } int n1 = pig.feedGrantToDays + 1; //int n2 = addDays.HasValue ? addDays.Value : pig.GetLastGrantFeedDays(); //int n3 = delayDays.HasValue ? delayDays.Value : (pig.feedSurplusDays < 0 ? 0 - pig.feedSurplusDays : 0); int n4 = pig.extantNum; var f = FeedHelper.GetFeeds(n1, n1 + n2 - 1, n4); var ylts = pig.feedSurplusDays + n2 + n3; var ylrq = DateTime.Today.AddDays(ylts); var model = new { success = true, raiserName = pig.raiserName, areaName = pig.areaName, from = n1, add = n2, delay = n3, num = n4, feeds = f, check = (ylts <= AppGlobal.grantFeedDay), feedinfo = string.Format("可用至{0:d},余料天数{1} ", ylrq, ylts) }; return(Json(model, JsonRequestBehavior.AllowGet)); }
public ActionResult Create([Bind(Include = "title,abtrct,print,translator,writer")] Book book, string professionTags, string UserTags, string filesToUpload) { if (ModelState.IsValid) { book.date = DateTime.UtcNow; unitOfWork.BookRepository.Insert(book); UpdSertBookProffs(professionTags, book); UpSertBookUsers(UserTags, book); var filesString = filesToUpload.Split(','); switch (filesString.Count()) { case 0: throw new JsonCustomException(ControllerError.bookMustUpload); case 1: if (!UploadHelper.CheckExtenstionFast(filesString.First(), UploadHelper.FileTypes.doc)) { throw new JsonCustomException(ControllerError.bookMustUploadOneDoc); } break; case 2: if (!(filesString.Any(i => UploadHelper.CheckExtenstionFast(i, UploadHelper.FileTypes.doc)) && filesString.Any(i => UploadHelper.CheckExtenstionFast(i, UploadHelper.FileTypes.image)))) { throw new JsonCustomException(ControllerError.bookMustUploadOneDocAndImage); } break; default: throw new JsonCustomException(ControllerError.fileCountExceeded); } var fileUploadResult = UploadHelper.UpdateUploadedFiles(filesToUpload, null, "Book"); book.image = fileUploadResult.ImagesToUpload; book.file = fileUploadResult.DocsToUpload; unitOfWork.BookRepository.Update(book); unitOfWork.Save(); foreach (var user in book.Users) { FeedHelper.FeedInsert(FeedType.Book, book.BookId, user.UserId); } return(Json(new { URL = Url.Action("Detail", "Book", new { BId = book.BookId, BName = StringHelper.URLName(book.title) }) })); } throw new ModelStateException(this.ModelState); }
public void RebroadcastServerManager_ConfigurationChanged_Chooses_Correct_Feed() { _RebroadcastSettings.Enabled = false; _Manager.Initialise(); _RebroadcastSettings.ReceiverId = 2; FeedHelper.AddFeeds(_Feeds, _Listeners, 2); _RebroadcastSettings.Enabled = true; _ConfigurationStorage.Raise(r => r.ConfigurationChanged += null, EventArgs.Empty); Assert.AreEqual(1, _Manager.RebroadcastServers.Count); Assert.AreSame(_Feeds[1].Object, _Manager.RebroadcastServers[0].Feed); }