public NewsResult[] RequestBiQuanApi() { NewsResult[] reStr; try { reStr = new NewsResult[4]; NewsResult jinseLatestNewsFlash = _jinseService.GetLatestNewsFlash().Result; if (jinseLatestNewsFlash != null) { reStr[0] = jinseLatestNewsFlash; } NewsResult bishijieLatestNewsFlash = _bishijieService.GetLatestNewsFlash().Result; if (bishijieLatestNewsFlash != null) { reStr[1] = bishijieLatestNewsFlash; } CoinNewsModel bitcoinLatestNewsFlash = JsonConvert.DeserializeObject <CoinNewsResultModel <CoinNewsModel> >(HttpUitls.Get(ConfigManager.pushNewsConfig.NewsServerURL + "/News/GetBitcoinLatestNewsFlash")).Data; if (bitcoinLatestNewsFlash != null) { var model = new NewsResult { Success = true, From = "【bitcoin】", Content = bitcoinLatestNewsFlash.Content, NewsLevel = NewsLevel.Importent }; reStr[2] = model; } CoinNewsModel OkexNotice = JsonConvert.DeserializeObject <CoinNewsResultModel <CoinNewsModel> >(HttpUitls.Get(ConfigManager.pushNewsConfig.NewsServerURL + "/News/GetOkexLatestNotice")).Data; if (OkexNotice != null) { var model = new NewsResult { Success = true, From = "【Okex】", Content = OkexNotice.Title + " " + OkexNotice.FromUrl, NewsLevel = NewsLevel.Importent }; reStr[3] = model; } } catch (Exception e) { reStr = new NewsResult[] { new NewsResult { Success = false, Content = e.ToString() + "\n席马达!程序BUG了,快召唤老铁来维修!" } }; } return(reStr); }
private IMessageActivity MakeNewsCards(IDialogContext context, NewsResult news) { var resultMessage = context.MakeMessage(); resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel; resultMessage.Attachments = new List <Attachment>(); foreach (var item in news.value) { var action = new CardAction(); action.Type = "openUrl"; action.Value = item.url; HeroCard heroCard = new HeroCard() { Title = item.name, Text = item.description, Images = new List <CardImage>() { new CardImage() { Url = item.image.thumbnail.contentUrl } }, Tap = action, }; resultMessage.Attachments.Add(heroCard.ToAttachment()); } return(resultMessage); }
public SaveResult Update(NewsResult entity) { return(ExecuteDbWithHandle(_logService, () => { using (var context = new TechOfficeEntities()) { var update = context.News.FirstOrDefault(x => x.Id == entity.Id); if (update == null) { return SaveResult.FAILURE; } update.Title = entity.Title; update.Content = entity.Content; update.Summary = entity.Summary; update.NewsCategoryId = entity.NewsCategoryId; update.UrlImage = entity.UrlImage; update.IsDeleted = entity.IsDeleted; update.LastUpdatedBy = entity.LastUpdatedBy; update.LastUpdated = DateTime.Now; context.Entry(update).State = EntityState.Modified; return context.SaveChanges() > 0 ? SaveResult.SUCCESS : SaveResult.FAILURE; } })); }
private void DoViewPage(W_ViewPage viewPage) { NewsResult result = new NewsResult(); result.Articles.Add(new NewsArticle() { Title = viewPage.VPTitle, Description = viewPage.VPDescription, Url = viewPage.VPURL, PicUrl = viewPage.ImgURL }); if (viewPage.VPTYpe == "single") { this.Response = result; return; } W_ViewPageItemBLL bll = new W_ViewPageItemBLL(); List <W_ViewPageItem> childArticles = bll.GetByViewPage(viewPage); foreach (W_ViewPageItem viewPageItem in childArticles) { result.Articles.Add(new NewsArticle() { Title = viewPageItem.VPItemTitle, Description = viewPageItem.VPItemDescription, Url = viewPageItem.VPItemUrl, PicUrl = viewPageItem.VPItemPicUrl }); } this.Response = result; }
public SaveResult Add(NewsResult entity) { return(ExecuteDbWithHandle(_logService, () => { using (var context = new TechOfficeEntities()) { var add = context.News.Create(); add.Title = entity.Title; add.Content = entity.Content; add.Summary = entity.Summary; add.UrlImage = entity.UrlImage; add.NewsCategoryId = entity.NewsCategoryId; add.IsDeleted = entity.IsDeleted; add.CreatedBy = entity.CreatedBy; add.CreateDate = DateTime.Now; context.Entry(add).State = EntityState.Added; var result = context.SaveChanges() > 0 ? SaveResult.SUCCESS : SaveResult.FAILURE; entity.Id = add.Id; return result; } })); }
private static void EnsureContent(NewsResult newsResult) { const string readabilityAPI = "http://www.readability.com/api/content/v1/parser?url={0}&token=74d77e5e0e1adb82405c222e159cbd1b806975c1"; using (WebClient client = new WebClient()) { string readabilityResponse = client.DownloadString(string.Format(readabilityAPI, HttpUtility.UrlEncode(newsResult.UnescapedUrl))); ReadabilityResponse response = ReadabilityResponseParser.Parse(readabilityResponse); newsResult.Content = RemoveHtmlTags(response.Content); } }
private NewsResult GetResult(NewsResponse newsResponse) { var result = new NewsResult(); if (newsResponse.Status != ResponseStatus.Ok) { result.Error = newsResponse.ErrorCode; return(result); } result.Articles = newsResponse.NewsArticles; result.TotalResults = newsResponse.NewsArticles.Count(); return(result); }
private async Task <object> CallSearchAPI(string location, string searchType) { var client = new HttpClient(); var queryString = HttpUtility.ParseQueryString(string.Empty); // Request headers client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", WebConfigurationManager.AppSettings["CogServices:NewsSearch:ID"]); // Request parameters queryString["count"] = "4"; queryString["offset"] = "0"; queryString["mkt"] = "en-US"; queryString["safeSearch"] = "Moderate"; string uri = null; if (searchType == "news") { queryString["q"] = "Travel related news about " + location; uri = "https://api.cognitive.microsoft.com/bing/v5.0/news/search?" + queryString; } else if (searchType == "destination") { queryString["q"] = "Travel desitnations in " + location; uri = "https://api.cognitive.microsoft.com/bing/v5.0/search?" + queryString; } var response = await client.GetAsync(uri); HttpContent resultContent = response.Content; var result = await resultContent.ReadAsStringAsync(); // Populate a JSON object with the results of the API call if (searchType == "news") { NewsResult news = new NewsResult(); JsonConvert.PopulateObject(result, news); return(news); } else if (searchType == "destination") { DestinationResult destination = new DestinationResult(); JsonConvert.PopulateObject(result, destination); return(destination); } return(null); }
public static AddNewsViewModel ToViewModel(this NewsResult entity) { return(entity == null ? null : new AddNewsViewModel { Id = entity.Id, CreateDate = entity.CreateDate, CreatedBy = entity.CreatedBy, IsDeleted = entity.IsDeleted, LastUpdated = entity.LastUpdated, LastUpdatedBy = entity.LastUpdatedBy, Content = entity.Content, Summary = entity.Summary, NewsCategoryId = entity.NewsCategoryId, Title = entity.Title, UrlImage = entity.UrlImage, }); }
public async Task <SaveResult> DeleteAsync(NewsResult entity) { return(await ExecuteDbWithHandleAsync(_logService, async() => { using (var context = new TechOfficeEntities()) { var cq = context.News.Single(x => x.Id == entity.Id && x.IsDeleted == false); cq.IsDeleted = true; cq.LastUpdatedBy = entity.LastUpdatedBy; cq.LastUpdated = DateTime.Now; context.Entry(cq).State = EntityState.Modified; return await context.SaveChangesAsync() > 0 ? SaveResult.SUCCESS : SaveResult.FAILURE; } })); }
public async Task <IActionResult> ViewSingle(int id, double distance = 0.0D) { string userId = User.FindFirst(ClaimTypes.NameIdentifier).Value; var thisUser = _context.AspNetUsers.FirstOrDefault(x => x.Id == userId); //INSERT call to Mike's code here, MAYBE, that COULD return similar startups from the API and write them to a list of our Startup model //OR we could add a list of API startup model to the viewmodel class, filter by what Mike's code returns, and pass that on... //INSERT call to Jesse's code here, that will return an int for successViewStartupFavorite view = new ViewStartupFavorite() { List <PredictedApiStartup> topMatching = await CompareSuccess(id); Models.Startup startupToView = _context.Startup.Find(id); string nameToSearch = startupToView.Name.Replace(" ", "+"); NewsResult searchResult = (await Utilities.GetApiResponse <NewsResult>("v2", "everything", "https://newsapi.org", "apiKey", NewsApiKey, "q", nameToSearch)).FirstOrDefault(); // "v0 /appFo187B73tuYhyg", "Master List", "https://api.airtable.com", "api_key", ApiKey)).FirstOrDefault(); List <Article> articles = new List <Article>(); for (int i = 0; i < 5; i++) { try { articles.Add(searchResult.articles[i]); } catch { continue; } } FavoritesViewModel view = new FavoritesViewModel() { SingleStartupToView = startupToView, FavoriteStartups = _context.Favorites.Where(x => x.UserId == userId).ToList <Favorites>(), UserAssociation = thisUser.Association, MatchingPredictedStartups = topMatching, Comments = _context.Comment.Where(x => x.StartupId == id && x.Restricted == false).ToList <Comment>(), ExclusiveComments = _context.Comment.Where(x => x.StartupId == id && x.Restricted == true && x.Association == thisUser.Association).ToList <Comment>(), Articles = articles }; ViewBag.Distance = distance; return(View(view)); }
public async Task <SaveResult> UpdateAsync(NewsResult entity) { return(await ExecuteDbWithHandleAsync(_logService, async() => { using (var context = new TechOfficeEntities()) { var update = context.News.Single(x => x.Id == entity.Id && x.IsDeleted == false); update.Title = entity.Title; update.Content = entity.Content; update.Summary = entity.Summary; update.NewsCategoryId = entity.NewsCategoryId; update.UrlImage = entity.UrlImage; update.IsDeleted = entity.IsDeleted; update.LastUpdatedBy = entity.LastUpdatedBy; update.LastUpdated = DateTime.Now; context.Entry(update).State = EntityState.Modified; return await context.SaveChangesAsync() > 0 ? SaveResult.SUCCESS : SaveResult.FAILURE; } })); }
private List <NewsResult> GetBlenedResult_org(out int hitCount, string term, int skip, int take) { var results = BlendedNewsHelper.GetNewsItems(Providers, SearchIndex, out hitCount, Categories, term, skip, take); log.InfoFormat("There are {0}, results, prov:{1}, idx:{2}, term:{3}, take:{4}", results.HitCount, Providers?.Join(","), SearchIndex, Categories?.Join(","), term, take); List <NewsResult> resultSet = new List <NewsResult>(); //log.Info("content, title, Id \r\n"); StringBuilder sb = new StringBuilder(); foreach (var result in results) { //newsResult.DisplayDate = result.GetValue("DisplayDate").ToString(); // try { var ctnType = result.GetValue("ContentType")?.ToString() ?? string.Empty; var featured = result.GetValue("FeaturedRank")?.ToString() ?? string.Empty; NewsResult newsResult = new NewsResult() { ImageId = result.GetValue("ImageId")?.ToString() ?? string.Empty, Title = result.GetValue("Title")?.ToString() ?? string.Empty, Summary = result.GetValue("Summary")?.ToString() ?? string.Empty, Featured = !string.IsNullOrEmpty(featured) && (featured == "1" ? true : false), Content = result.GetValue("Content")?.ToString() ?? string.Empty, Link = result.GetValue("Link")?.ToString() ?? string.Empty }; var dynaManager = DynamicModuleManager.GetManager(); string txtId = result.GetValue("Id")?.ToString() ?? String.Empty; log.InfoFormat("try to get from iD:{0} ofType:{1}-title:{2}", txtId, ctnType, newsResult.Title); try { if (!string.IsNullOrEmpty(ctnType) && !string.IsNullOrEmpty(txtId) && txtId.IsGuid()) { Guid itemId = new Guid(txtId); if (ctnType.IndexOf("BlogPost") > 0) { var manager = BlogsManager.GetManager(); var bp = manager.GetBlogPosts() //.Where(c => c.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Live) .FirstOrDefault(b => b.Id == itemId); if (bp != null) { bp = manager.Lifecycle.GetLive(bp) as BlogPost; log.InfoFormat("has item:{0}-date:{1}", bp?.GetType()?.FullName, bp?.GetValue("DisplayDate")?.ToString() ?? string.Empty); newsResult.DisplayDate = bp?.GetValue("DisplayDate")?.ToString() ?? string.Empty; } } else { var item = dynaManager.GetDataItems(TypeResolutionService.ResolveType(ctnType)) .Where(c => c.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Live) .FirstOrDefault(c => c.Id == itemId); log.InfoFormat("has item:{0}-date:{1}", item?.GetType()?.FullName, item?.GetValue("DisplayDate")?.ToString() ?? string.Empty); newsResult.DisplayDate = item?.GetValue("DisplayDate")?.ToString() ?? string.Empty; } /*if (result.Fields.Any(x => x.Name == "DisplayDate") && item?.GetValue("DisplayDate") != null) * { * newsResult.DisplayDate = item.GetValue("DisplayDate").ToString() ?? string.Empty; * }*/ } } catch (Exception ex) { log.InfoFormat("failedToGetDateItemType:{0}-id:{1}, msg:{2}", ctnType, txtId, ex.Message); } string formatString = "yyyyMMddHHmmssfff"; // seem like there are already assing below if (!String.IsNullOrEmpty(result.GetValue("PublicationDate")?.ToString())) { DateTime pubd = DateTime.MinValue; //DateTime dt = DateTime.ParseExact(result.GetValue("PublicationDate").ToString(), formatString, null); //newsResult.PublicationDate = dt.ToLocalTime(); DateTime.TryParseExact(result.GetValue("PublicationDate").ToString(), formatString, new CultureInfo("en-US"), DateTimeStyles.None, out pubd); newsResult.PublicationDate = pubd; //log.InfoFormat("pubd:{0}", pubd.ToString("MMMM d, yyyy")); //sb.Append("PubDate:").Append(pubd).Append("\r"); } if (result.Fields.Any(x => x.Name == "DateField")) { try { /*DateTime dt2 = DateTime.ParseExact(result.GetValue("DateField").ToString(), "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture); * newsResult.DateField = dt2.ToLocalTime();*/ if (!String.IsNullOrEmpty(result.GetValue("DateField")?.ToString())) { DateTime eDateTime = DateTime.MinValue; DateTime.TryParseExact(result.GetValue("DateField").ToString(), "MM/dd/yyyy HH:mm:ss", new CultureInfo("en-US"), DateTimeStyles.None, out eDateTime); newsResult.DateField = eDateTime; //log.InfoFormat("datef:{0}", eDateTime.ToString("MMMM d, yyyy")); } } catch (Exception ex) { log.ErrorFormat("GetBlendedResult-DateField:{0}, inner:{1}, stack:{2}", ex.Message, ex.InnerException?.Message, ex.StackTrace); } } if (string.IsNullOrWhiteSpace(newsResult.Summary) && !string.IsNullOrWhiteSpace(newsResult.Content)) { newsResult.Summary = SummaryParser.GetSummary(newsResult.Content, new SummarySettings(SummaryMode.Words, 40, true)); } resultSet.Add(newsResult); } catch (Exception ex) { log.InfoFormat("bled-createNewsResult:{0}", ex.Message); } //newsResult.ImageCaption = result.GetValue("ImageCaption").ToString(); // testing below /*if (!String.IsNullOrEmpty(result.GetValue("PublicationDate")?.ToString())) * { * //DateTime dt = DateTime.ParseExact(result.GetValue("PublicationDate").ToString(), formatString, null); * //newsResult.PublicationDate = dt.ToLocalTime(); * DateTime.TryParseExact(result.GetValue("PublicationDate").ToString(), formatString, new CultureInfo("en-US"), DateTimeStyles.None, out eDateTime); * newsResult.DisplayDate = eDateTime.ToLocalTime().ToShortDateString(); * }*/ /// } return(resultSet); }
public async Task Initialize(NewsScope scope) { CurrentNews = await newsService.GetNews(scope); }
public void AddToNewsResultSet(NewsResult newsResult) { base.AddObject("NewsResultSet", newsResult); }
public static NewsResult CreateNewsResult(global::System.Guid ID) { NewsResult newsResult = new NewsResult(); newsResult.ID = ID; return newsResult; }
private void CheckCoinNews() { ConfigManager.Instance().pushProblemCount += 1; if (ConfigManager.Instance().pushProblemCount > (4 * 60 * 60 / ConfigManager.pushNewsConfig.LoopCheckTime)) { var msg = ConfigManager.Instance().problem.description + "\n" + ConfigManager.Instance().problem.example; _mahuaApi.SendGroupMessage("417955323", msg); ConfigManager.Instance().pushProblemCount = 0; } var re = _newsService.RequestBiQuanApi(); NewsResult msg1 = null; NewsResult msg2 = null; NewsResult msg3 = null; NewsResult msg4 = null; if (re[0] != null && !re[0].Content.Equals(lastMsg1)) { lastMsg1 = re[0].Content; msg1 = re[0]; } else { msg1 = null; } if (re[1] != null && !re[1].Content.Equals(lastMsg2)) { lastMsg2 = re[1].Content; msg2 = re[1]; } else { msg2 = null; } if (re[2] != null && !re[2].Content.Equals(lastMsg3)) { lastMsg3 = re[2].Content; msg3 = re[2]; } else { msg3 = null; } if (re[3] != null && !re[3].Content.Equals(lastMsg4)) { lastMsg4 = re[3].Content; msg4 = re[3]; } else { msg4 = null; } if (ConfigManager.pushNewsConfig.UsCompute) { if (msg1 != null) { StringCompute stringcompute1 = new StringCompute(); stringcompute1.Compute(msg1.Content, lastMsg2); if ((float)stringcompute1.ComputeResult.Rate > ConfigManager.pushNewsConfig.ComputeRate) { msg1 = null; } } if (msg2 != null) { StringCompute stringcompute1 = new StringCompute(); stringcompute1.Compute(msg2.Content, lastMsg1); if ((float)stringcompute1.ComputeResult.Rate > ConfigManager.pushNewsConfig.ComputeRate) { msg2 = null; } } if (msg1 != null && msg2 != null) { StringCompute stringcompute1 = new StringCompute(); stringcompute1.Compute(msg1.Content, msg2.Content); if ((float)stringcompute1.ComputeResult.Rate > ConfigManager.pushNewsConfig.ComputeRate) { msg2 = null; } } } var reMsg = string.Empty; if (msg1 != null) { if (msg1.NewsLevel == NewsLevel.Normal) { normalMsgList.Add(msg1.From + msg1.Title + "\n"); } else { reMsg += msg1.From + msg1.Title + "\n"; } } if (msg2 != null) { if (msg2.NewsLevel == NewsLevel.Normal) { normalMsgList.Add(msg2.From + msg2.Content + "\n"); } else { reMsg += msg2.From + msg2.Title + "\n"; } } if (msg3 != null) { if (msg3.NewsLevel == NewsLevel.Normal) { normalMsgList.Add(msg3.From + msg3.Title + "\n"); } else { reMsg += msg3.From + msg3.Title + "\n"; } } if (msg4 != null) { if (msg4.NewsLevel == NewsLevel.Normal) { normalMsgList.Add(msg4.From + msg4.Title + "\n"); } else { reMsg += msg4.From + msg4.Title + "\n"; } } if (!string.IsNullOrEmpty(reMsg)) { //查询币圈 reMsg += _coinmarketcapService.GetTicker("btc").Result; reMsg += "\n" + _huobiService.LegalTender().Result; //涨跌幅排名 //reMsg += "\n【OK涨幅排名】"+_coinService.GetOkexTopTracks(); //reMsg += "\n【OK跌幅排名】" + _coinService.GetOkexBottomTracks(); if (sendCount != 0) { foreach (var group in ConfigManager.pushNewsConfig.CoinNewsPushGroupList) { _mahuaApi.SendGroupMessage(group, reMsg + "\n第" + sendCount + "次主动推送消息"); } } sendCount++; } if (nowNormalNewsPushIntervalCount < ConfigManager.pushNewsConfig.NormalNewsPushIntervalCount) { nowNormalNewsPushIntervalCount++; } else { if (sendCount != 0) { var normalMsg = string.Empty; foreach (var item in normalMsgList) { normalMsg += item; } normalMsgList.Clear(); if (!string.IsNullOrEmpty(normalMsg)) { //查询币圈 normalMsg += _coinmarketcapService.GetTicker("btc").Result; normalMsg += "\n" + _huobiService.LegalTender().Result; foreach (var group in ConfigManager.pushNewsConfig.CoinNewsPushGroupList) { _mahuaApi.SendGroupMessage(group, normalMsg + "\n第" + sendCount + "次主动推送消息"); } } } sendCount++; nowNormalNewsPushIntervalCount = 0; } }