public JsonResult DeleteTweet(TweetEntity personTweets) { personTweets.user_id = Session["UserName"].ToString(); var response = _ITwitterClone.DeleteTweet(personTweets); return(Json(response, JsonRequestBehavior.AllowGet)); }
public void Save(TweetModel tweetModel) { var userId = _tweetContext.Users.Where(x => x.Username == tweetModel.Username).Select(x => x.UserId).FirstOrDefault(); var twittedBy = _tweetContext.Users.Where(x => x.Username == tweetModel.TwittedBy).Select(x => x.UserId).FirstOrDefault(); // TODO: User device should come from UI/Client once user logs in to the APP. var userDeviceId = _tweetContext.UserDevices.Where(x => x.UserId == twittedBy).Select(x => x.UserDeviceId).FirstOrDefault(); // user tweets from new device if (userDeviceId == 0) { UserDeviceEntity userDeviceEntity = new UserDeviceEntity() { UserId = userId, DeviceName = "Test device", // TODO: Pass device name from UI/Client DeviceTypeId = (int)UserDeviceType.Desktop, // TODO: Pass device type from UI/Client }; _tweetContext.UserDevices.Add(userDeviceEntity); _tweetContext.SaveChanges(); } var tweetEntity = new TweetEntity() { TweetContent = tweetModel.TweetContent, TwittedBy = twittedBy, UserId = userId, UserDeviceId = userDeviceId, TweetTime = DateTime.Now }; _tweetContext.Tweets.Add(tweetEntity); _tweetContext.SaveChanges(); }
// // GET: /Home/ public string AjaxSaveToDB() { if (Session["LoggedASP"] != null) { TimelineOptions options = new TimelineOptions(); options.Count = 200; options.IncludeRetweets = true; OAuthTokens token = new OAuthTokens(); token.ConsumerKey = ConfigurationManager.AppSettings["consumerKey"]; token.ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]; token.AccessToken = ((User)Session["LoggedUser"]).TwitterToken; token.AccessTokenSecret = ((User)Session["LoggedUser"]).TwitterTokenSecret; TwitterResponse <TwitterStatusCollection> truc = TwitterTimeline.HomeTimeline(token, options); TweetEntity tweetEntity = new TweetEntity(); tweetEntity.RemoveTweetFromOwner(((User)Session["LoggedUser"]).ID); foreach (var item in truc.ResponseObject) { //int lol = ; tweetEntity.AddTweet(item.Id, item.Text, item.User.ScreenName, item.User.ProfileImageLocation, ((User)Session["LoggedUser"]).ID, ((int)((TimeSpan)(item.CreatedDate - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime())).TotalSeconds)); } return("Success"); } else { return("Fail"); } }
private List <TweetEntity> PrepararInsert(List <TweetEntity> entity) { List <TagEntity> listaTag = entity.SelectMany(x => x.Tags2).Distinct().ToList(); List <PaisEntity> listaPais = entity.Select(x => x.Pais).Distinct().ToList(); List <UsuarioEntity> listaUsuario = entity.Select(x => x.Usuario).Distinct().ToList(); List <IdiomaEntity> listaIdioma = entity.Select(x => x.Idioma).Distinct().ToList(); List <TweetEntity> inserir = new List <TweetEntity>(); foreach (var item in entity) { var itemPreparado = new TweetEntity(); itemPreparado.DataCriacao = item.DataCriacao; itemPreparado.Mensagem = item.Mensagem; itemPreparado.Pais = listaPais?.Where(x => x.Nome == item?.Pais?.Nome)?.FirstOrDefault() ?? new PaisEntity(); itemPreparado.Idioma = listaIdioma?.Where(x => x.Nome == item?.Idioma?.Nome)?.FirstOrDefault() ?? new IdiomaEntity(); itemPreparado.Usuario = listaUsuario?.Where(x => x.Nome == item?.Usuario?.Nome)?.FirstOrDefault() ?? new UsuarioEntity(); //EJM foreach (var itemTag in item.Tags2) { itemPreparado.Tags2.Add(listaTag.Where(x => x.Descricao == itemTag.Descricao).FirstOrDefault() ?? new TagEntity()); } inserir.Add(itemPreparado); } return(inserir); }
public void Update(TweetEntity entity) { context.LabTweets.Attach(entity); var entry = context.Entry(entity); entry.Property(e => e.Content).IsModified = true; context.SaveChanges(); }
public void Update(TweetEntity tweet) { context.Tweets.Attach(tweet); var entry = context.Entry(tweet); entry.Property(a => a.Head).IsModified = true; entry.Property(a => a.Content).IsModified = true; context.SaveChanges(); }
public void Delete(int id) { var oldEntity = new TweetEntity { Id = id }; context.Tweets.Attach(oldEntity); context.Tweets.Remove(oldEntity); context.SaveChanges(); }
public void Delete(int id) { var entity = new TweetEntity { TweetId = id }; context.LabTweets.Attach(entity); context.LabTweets.Remove(entity); context.SaveChanges(); }
private TweetModel GenerateTweetModelFrom(TweetEntity tweet) { // Split text and embed url string fullText, embedUrl; int index = tweet.FullText.IndexOf("http"); if (index == 0) { fullText = string.Empty; embedUrl = tweet.FullText.Split(' ', '\n')?[0]; } else if (index > 0) { fullText = tweet.FullText.Substring(0, index); embedUrl = tweet.FullText.Substring(index).Split(' ', ',', ',', '\n')?[0]; } else { fullText = tweet.FullText; embedUrl = string.Empty; } // Determine tweet date / time string tweetDateTime; TimeSpan span = DateTime.Now.Subtract(tweet.CreatedAt); if ((int)span.TotalHours == 0) { tweetDateTime = ((int)span.TotalMinutes > 0) ? $"{(int)span.TotalMinutes}m" : $"{(int)span.TotalSeconds}s"; } else if (span.TotalHours < 24) { int hours = (int)(span.TotalMinutes > 0 ? span.TotalHours + 1 : span.TotalHours); tweetDateTime = $"{hours}h"; } else { tweetDateTime = string.Format("{0:t} ", tweet.CreatedAt) + string.Format("{0:MMM d}", tweet.CreatedAt); } return(new TweetModel { TweetId = tweet.Id, TweetUrl = $"https://twitter.com/{tweet.CreatedBy.ScreenName}/status/{tweet.Id}", TweetFullText = fullText, TweetEmbedUrl = embedUrl, TweetImageUrl = tweet.Entities?.MediaList?[0].MediaUrl, TweetDateTime = tweetDateTime, TweetCreatedAt = tweet.CreatedAt }); }
public string EditGet(string id) { if (Session["LoggedASP"] != null && Session["LoggedTwitter"] != null) { Tweet tweet = new TweetEntity().GetTweet(Decimal.Parse(id)); return(tweet.Text); } else { return("Fail"); } }
public static DAL.Tweet FromEntityToDal(TweetEntity tweet) { var dalTweet = new DAL.Tweet() { Date = tweet.DateCreation, Text = tweet.Message, }; if (tweet.Identity != null) { dalTweet.Identifier = tweet.Identity; } return(dalTweet); }
public string DeleteTweet(TweetEntity tweets) { try { using (var Connection = new TwitterApplicationEntities()) { Connection.Entry(tweets).State = EntityState.Deleted; Connection.SaveChanges(); } return("Tweet Deleted Successfully"); } catch (Exception exception) { throw new Exception(exception.Message.ToString(), exception); } }
public void URLEntitiesTest() { var autolink = new Autolink(); var entity = new TweetEntity(0, 19, "http://t.co/0JG5Mcq", TweetEntityType.Url); entity.DisplayUrl = "blog.twitter.com/2011/05/twitte…"; entity.ExpandedUrl = "http://blog.twitter.com/2011/05/twitter-for-mac-update.html"; var entities = new List <TweetEntity>(); entities.Add(entity); string tweet = "http://t.co/0JG5Mcq"; string expected = "<a href=\"http://t.co/0JG5Mcq\" title=\"http://blog.twitter.com/2011/05/twitter-for-mac-update.html\" rel=\"nofollow\"><span class='tco-ellipsis'><span style='position:absolute;left:-9999px;'> </span></span><span style='position:absolute;left:-9999px;'>http://</span><span class='js-display-url'>blog.twitter.com/2011/05/twitte</span><span style='position:absolute;left:-9999px;'>r-for-mac-update.html</span><span class='tco-ellipsis'><span style='position:absolute;left:-9999px;'> </span>…</span></a>"; var actual = autolink.AutoLinkEntities(tweet, entities); Assert.AreEqual(expected, actual); }
internal static TweetEntity FetchTweetFromStorage(string tweetId) { CloudTable table = tableClient.GetTableReference("visiontweet"); if (string.IsNullOrEmpty(tweetId) || tweetId.Length < 16) { return(null); } var partitionKey = tweetId.Substring(0, 5); var rowKey = tweetId.Substring(5); TableOperation retrieveOperation = TableOperation.Retrieve <TweetEntity>(partitionKey, rowKey); TweetEntity tweetEntity = table.Execute(retrieveOperation).Result as TweetEntity; if (tweetEntity != null) { tweetEntity.TweetId = tweetId; } return(tweetEntity); }
public string EditPost(string id, string text) { if (Session["LoggedASP"] != null && Session["LoggedTwitter"] != null) { Tweet tweet = new TweetEntity().GetTweet(Decimal.Parse(id)); new TweetEntity().EditTweet(int.Parse(id), text); new TweetEntity().EditTweet(int.Parse(id), ((int)((TimeSpan)(DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime())).TotalSeconds)); OAuthTokens token = new OAuthTokens(); token.ConsumerKey = ConfigurationManager.AppSettings["consumerKey"]; token.ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]; token.AccessToken = ((User)Session["LoggedUser"]).TwitterToken; token.AccessTokenSecret = ((User)Session["LoggedUser"]).TwitterTokenSecret; if (TwitterStatus.Delete(token, Decimal.Parse(tweet.IDTwitter.ToString())).ErrorMessage == null) { TwitterResponse <TwitterStatus> status = TwitterStatus.Update(token, text); if (status.ErrorMessage == null) { new TweetEntity().EditTweet(int.Parse(id), status.ResponseObject.Id, ((int)((TimeSpan)(status.ResponseObject.CreatedDate - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime())).TotalSeconds)); return("Success"); } else { return("Fail"); } } else { return("Fail1"); } } else { return("Fail2"); } }
public string UpdateTweet(TweetEntity tweets) { try { var person = new TWEET() { tweet_id = tweets.tweet_id, user_id = tweets.user_id, message = tweets.message, created = tweets.created }; using (var Connection = new TwitterApplicationEntities()) { Connection.TWEETs.Add(person); Connection.SaveChanges(); } return("Tweet Updated Successfully"); } catch (Exception exception) { throw new Exception(exception.Message.ToString(), exception); } }
private static void DumpToConsole(TweetEntity tweet) { System.Console.WriteLine($"FullText: {tweet.FullText}"); System.Console.WriteLine($"At : {tweet.CreatedAt}"); System.Console.WriteLine($"By : {tweet.CreatedBy}"); if (tweet.LegacyEntities != null) { if (tweet.LegacyEntities.UrlList != null) { System.Console.WriteLine($"Urls : {tweet.LegacyEntities.UrlList.Count()}"); if (tweet.LegacyEntities.UrlList.Any()) { foreach (var item in tweet.LegacyEntities.UrlList) { System.Console.WriteLine($" {item.Url}"); } } } if (tweet.LegacyEntities.MediaList != null) { System.Console.WriteLine($"Media : {tweet.LegacyEntities.MediaList.Count()}"); } } }
public async Task AddTweetHandler(AddTweetDto request) { ClaimsPrincipal user = _iHttpContextAccessor.HttpContext.User; int creatorID = int.Parse(ClaimExtensions.GetUserId(user)); var newTweet = new TweetEntity() { Content = request.Content, CreatedAt = DateTime.Now, CreatorId = creatorID, LikeCount = 0, RetweetCount = 0, IsRetweet = false, }; await _dbContext.Tweets.AddAsync(newTweet); await _dbContext.SaveChangesAsync(); if (request.HashTags != null && request.HashTags.Count > 0) { var list = new List <TweetHashtagRelationEntity>(); foreach (var hashtag in request.HashTags) { var tag = await searchHashtag(hashtag); if (tag is null) { tag = new HashtagEntity(); tag.Content = hashtag.Content.ToLower(); tag.UsageCount = 1; await _dbContext.Hashtags.AddAsync(tag); await _dbContext.SaveChangesAsync(); } else { tag.UsageCount++; _dbContext.Hashtags.Update(tag); await _dbContext.SaveChangesAsync(); } var relationht = new HashtagTweetRelationEntity(); relationht.HashtagId = tag.Id; relationht.TweetId = newTweet.Id; await _dbContext.HashtagTweetRelations.AddAsync(relationht); await _dbContext.SaveChangesAsync(); list.Add(new TweetHashtagRelationEntity() { TweetId = newTweet.Id, HashtagId = tag.Id, }); } await _dbContext.TweetHashtagRelations.AddRangeAsync(list); } await _dbContext.SaveChangesAsync(); var relationtu = new UserTweetRelationEntity(); relationtu.TweetId = newTweet.Id; relationtu.UserId = creatorID; await _dbContext.UserTweetRelations.AddRangeAsync(relationtu); await _dbContext.SaveChangesAsync(); }
public static async Task Run( [QueueTrigger("visionscanner")] string tweetQuery, [Table("visiontweet")] CloudTable visionTweetTable, [Queue("visionscanned")] IAsyncCollector <string> visionScannedQueue, TraceWriter log) { log.Info($"VisionScanner processing TweetId: {tweetQuery}"); long tweetId = long.Parse(tweetQuery); long originalTweetId = tweetId; List <string> screenNamesToReplyTo = new List <string>(); var service = Helper.TwitterService(); TwitterStatus tweet = null; TweetEntity tweetEntity = null; while (tweet == null) { //moving this check inside the while loop to stop processing retweets var tweetDetails = Helper.FetchTweetFromStorage(tweetId.ToString()); if (tweetDetails != null) //already processed { log.Info($"VisionScanner Already Processed TweetId: {tweetId}"); return; } tweet = service.GetTweet(new GetTweetOptions { Id = tweetId, IncludeEntities = true, TweetMode = TweetMode.Extended }); //build up mentions list for replyto - will distinct later screenNamesToReplyTo.Add("@" + tweet.User.ScreenName); foreach (var mention in tweet.Entities.Mentions) { screenNamesToReplyTo.Add("@" + mention.ScreenName); } tweetEntity = new TweetEntity(tweet); //no media? try the parent if (!tweet.Entities.Media.Any()) { log.Info($"VisionScanner No media found in TweetId: {tweetQuery}"); // Documentation Link: Add an entity to a table - https://cda.ms/nn visionTweetTable.Execute(TableOperation.Insert(tweetEntity)); if (tweet.InReplyToStatusId == null) { //walked up the whole chain - no media found return; } else { tweetId = ((long)tweet.InReplyToStatusId); tweet = null; } } } var mediaDesc = new MediaDescription(tweet.Id); var photos = tweet.Entities.Media.Where(m => m.MediaType == TwitterMediaType.Photo); foreach (var media in photos) { log.Info($"VisionScanner FetchVisionDescriptionAsync TweetId/MediaId: {tweetQuery}/{media.Id}"); var vision = await Helper.FetchVisionDescriptionAsync(tweet, media); mediaDesc.VisionDescription.Add(media.IdAsString, vision); } tweetEntity.VisionJson = JsonConvert.SerializeObject(mediaDesc); // Documentation Link: Add an entity to a table - https://cda.ms/nn visionTweetTable.Execute(TableOperation.Insert(tweetEntity)); var dto = new TweetScannedDTO { TwitterStatus = tweetEntity.BuildTwitterStatus(), OriginalTweetId = originalTweetId, UsersToReplyTo = screenNamesToReplyTo.Distinct().ToArray(), MediaDescription = mediaDesc }; log.Info($"VisionScanner Queuing VisionScanned TweetId: {tweetQuery}"); await visionScannedQueue.AddAsync(JsonConvert.SerializeObject(dto)); log.Info($"VisionScanner processed TweetId: {tweetQuery}"); }
public TweetEntity Create(TweetEntity entity) { context.LabTweets.Add(entity); context.SaveChanges(); return(entity); }
public string GetTweetCode(string id) { Tweet item = new TweetEntity().GetTweet(Decimal.Parse(id)); return("<div class='editTweet'><a class='editTweetA' rel='" + item.ID.ToString() + "' href='/Tweet/EditGet/" + item.ID.ToString() + "'>Edit</a> <a class='deleteLink' href='/Tweet/Delete/" + item.IDTwitter.ToString() + "'>Delete</a></div><div class='tweetP'><img class='inTweetImg' src='" + item.Avatar + "' /><a href=\"/User/" + item.Username + "\">" + item.Username + "</a> ---- " + item.Text + "</div>"); }
public void Create(TweetEntity tweet) { context.Tweets.Add(tweet); context.SaveChanges(); }
public ActionResult Index() { if (Session["LoggedASP"] != null && Session["DatabaseMode"] != null) { User myUser = (User)Session["LoggedUser"]; ViewData["Username"] = myUser.Username; TweetEntity entity = new TweetEntity(); List <Tweet> list = entity.GetTweetsForOwner(((User)Session["LoggedUser"]).ID); OAuthTokens token = new OAuthTokens(); token.ConsumerKey = ConfigurationManager.AppSettings["consumerKey"]; token.ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]; token.AccessToken = ((User)Session["LoggedUser"]).TwitterToken; token.AccessTokenSecret = ((User)Session["LoggedUser"]).TwitterTokenSecret; //string loggedUserName = TwitterUser.Show(token, Decimal.Parse(((User)Session["LoggedUser"]).TwitterID)).ResponseObject.ScreenName.ToLower(); if (list.Count != 0) { foreach (var item in list) { ViewData["message"] += "<div class='message'><div class='editTweet'><a class='editTweetA' rel='" + item.ID.ToString() + "' href='/Tweet/EditGet/" + item.ID.ToString() + "'>Edit</a> <a class='deleteLink' href='/Tweet/Delete/" + item.IDTwitter.ToString() + "'>Delete</a></div><div class='tweetP'><img class='inTweetImg' src='" + item.Avatar + "' /><a href=\"/User/" + item.Username + "\">" + item.Username + "</a> ---- " + item.Text + "</div></div>"; } } else { ViewData["message"] = "<p style='text-align: center;'>Aucun rang dans la base de donnée. :(</p>"; } return(View()); } else { if (Session["LoggedASP"] != null) { User myUser = (User)Session["LoggedUser"]; ViewData["Username"] = myUser.Username; } if (Session["LoggedTwitter"] != null) { TimelineOptions options = new TimelineOptions(); options.Count = 200; options.IncludeRetweets = true; OAuthTokens token = new OAuthTokens(); token.ConsumerKey = ConfigurationManager.AppSettings["consumerKey"]; token.ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]; token.AccessToken = ((User)Session["LoggedUser"]).TwitterToken; token.AccessTokenSecret = ((User)Session["LoggedUser"]).TwitterTokenSecret; try { TwitterResponse <TwitterStatusCollection> truc = TwitterTimeline.HomeTimeline(token, options); foreach (var item in truc.ResponseObject) { ViewData["message"] += "<p class='tweetP'><img class='inTweetImg' src='" + item.User.ProfileImageLocation + "' /><a href=\"/User/" + item.User.ScreenName + "\">" + item.User.ScreenName + "</a> ---- " + item.Text + "</p>"; } } catch (WebException exception) { ViewData["message"] = "<p style='text-align:center;'>Erreur : " + exception.Message + "</p>"; } catch (Exception exception) { ViewData["message"] = "<p style='text-align:center;'>Erreur : " + exception.Message + "</p>"; } } else { if (Session["LoggedASP"] != null) { ViewData["message"] = "<p style='text-align:center;'>Bonjour " + ((User)Session["LoggedUser"]).Username + ", ton compte existe mais il n'est pas associé a un compte Twitter pour le moment, si tu veux associer ton compte Twitter avec ton Compte Tweetasse, rends toi sur la page Manage via le menu en haut.</p><hr />"; } try { TwitterResponse <TwitterStatusCollection> publicTimeline = TwitterTimeline.PublicTimeline(); if (String.IsNullOrEmpty(publicTimeline.ErrorMessage)) { foreach (var item in publicTimeline.ResponseObject) { ViewData["message"] += "<p class='tweetP'><img class='inTweetImg' src='" + item.User.ProfileImageLocation + "' /><a href=\"/User/" + item.User.ScreenName + "\">" + item.User.ScreenName + "</a> ---- " + item.Text + "</p>"; } } else { ViewData["message"] = "<p style='text-align:center;'>Bonjour shagasse, l'application a excedé le nombre de demandes maximum sur l'API Twitter Publique sans Login oAuth pour cette heure. Démerdes-toi, merssi!</p>"; } } catch (WebException exception) { ViewData["message"] = "<p style='text-align:center;'>Erreur : " + exception.Message + "</p>"; return(View()); } catch (Exception exception) { ViewData["message"] = "<p style='text-align:center;'>Erreur : " + exception.Message + "</p>"; } } return(View()); } }
public string AddTweet(TweetEntity tweets) { return(_ITwitterClone.AddTweet(tweets)); }
public TweetEntity CreateTweet(TweetEntity tweet) { return(FromDalToEntity(this.TweetDal.AddTweet(tweet.Message))); }
public string DeleteTweet(TweetEntity tweets) { return(_ITwitterClone.DeleteTweet(tweets)); }
public string UpdateTweet(TweetEntity tweets) { return(_ITwitterClone.UpdateTweet(tweets)); }