public static void Run([TimerTrigger("0 */15 * * * 1-5")] TimerInfo myTimer, ILogger log) { ParkingDataFunctions.SetParkingData(); string parkingData = ParkingDataFunctions.ParkingDataAsString(); // Log the full output of the parking data log.LogInformation(parkingData); Garage leastAvailableGarage = ParkingDataFunctions.GetLeastAvailableGarageBySpots(); //If there are fewer than 100 spots left, tweet! if (leastAvailableGarage.SpotsAvailable < 100) { //get Twitter API keys from Key Vault and authenticate with Twitter TwitterHelper.LoginToTwitter(); bool isTweetPublished = TwitterHelper.PublishTweet(parkingData); if (isTweetPublished) { log.LogInformation($"Tweet published at {DateTime.UtcNow} UTC!"); TwitterHelper.CleanUpTimeline(3); } else { log.LogInformation($"Tweet could not be published at {DateTime.UtcNow} UTC!"); } } else { log.LogInformation($"Tweet not published at {DateTime.UtcNow} UTC. Garage with least availability: {leastAvailableGarage.Name} with {leastAvailableGarage.SpotsAvailable} spots free."); } }
public async Task <SocialUser> GetOrCreateTwitterUser(IUser twitterUser) { var user = FindByOriginalId(twitterUser.IdStr, SocialUserSource.Twitter); if (user == null) { user = new SocialUser { OriginalId = twitterUser.IdStr, Name = twitterUser.Name, ScreenName = twitterUser.ScreenName, Avatar = twitterUser.ProfileImageUrl, Source = SocialUserSource.Twitter, Type = SocialUserType.Customer, OriginalLink = TwitterHelper.GetUserUrl(twitterUser.ScreenName) }; await UnitOfWorkManager.RunWithNewTransaction(CurrentUnitOfWork.GetSiteId(), async() => { await Repository.InsertAsync(user); CurrentUnitOfWork.SaveChanges(); }); } if (user.IsDeleted) { user.IsDeleted = false; user.Type = SocialUserType.Customer; Update(user); } return(user); }
public void TweetUrlIsCorrectlyRecognized() { // Arrange var testCases = new Dictionary <string, bool> { { "https://twitter.com/TweetAngi/status/733279889596514304", true }, { "https://twitter.com/dqmhose/status/733279824299630592", true }, { "https://twitter.com/anne_nymus/status/733274507339763712", true }, { "https://twitter.com/LaDolceVegas/status/725649743364370433", true }, { "https://twitter.com/ID_AA_Carmack/status/733275349048381440", true }, { "https://twitter.com/SPORT1/status/733273819994071040", true }, { "https://twitter.com/NetflixDE/status/733279091869286400", true }, { "https://pbs.twimg.com/media/Ci0gimSWEAASP-L.jpg", false }, { "https://twitter.com", false }, { "https://twitter.com/twitterapi", false } }; // Act var results = testCases.ToDictionary(kvp => kvp.Key, kvp => TwitterHelper.IsTweetUrl(new System.Uri(kvp.Key))); // Assert foreach (var kvp in testCases) { Assert.AreEqual(kvp.Value, results[kvp.Key], kvp.Key); } }
public void DragOver(IDropInfo dropInfo) { var data = dropInfo.Data as DataObject; if (data == null) { return; } if (data.ContainsFileDropList()) { var files = data.GetFileDropList(); bool canAttach = false; foreach (var file in files) { if (TwitterHelper.IsSupportedImage(file)) { canAttach = true; } } if (canAttach) { dropInfo.Effects = DragDropEffects.Copy; } } DragDrop.DefaultDropHandler.DragOver(dropInfo); }
protected override async Task OnInitializeAsync(IActivatedEventArgs args) { await Models.Db.NicoVideoDbContext.InitializeAsync(); await Models.Db.HistoryDbContext.InitializeAsync(); await Models.Db.PlayHistoryDbContext.InitializeAsync(); Microsoft.Toolkit.Uwp.UI.ImageCache.Instance.CacheDuration = TimeSpan.FromHours(24); // TwitterAPIの初期化 await TwitterHelper.Initialize(); await RegisterTypes(); var hohoemaApp = Container.Resolve <HohoemaApp>(); SetTitleBar(); #if DEBUG Views.UINavigationManager.Pressed += UINavigationManager_Pressed; #endif await base.OnInitializeAsync(args); }
private void PostTweet() { if (String.IsNullOrEmpty(TweetTextBox.Content)) { return; } ProgressBar.Visibility = Visibility.Visible; ProgressBar.IsIndeterminate = true; var twitter = new TwitterHelper(_twitterSettings); // Successful event handler, navigate back if successful twitter.TweetCompletedEvent += (sender, e) => { ProgressBar.Visibility = Visibility.Collapsed; ProgressBar.IsIndeterminate = false; if (NavigationService.CanGoBack) { NavigationService.GoBack(); } }; // Failed event handler, show error twitter.ErrorEvent += (sender, e) => { ProgressBar.Visibility = Visibility.Collapsed; ProgressBar.IsIndeterminate = false; MessageBox.Show("Connection to Twitter was unsuccessful."); }; twitter.NewTweet(TweetTextBox.Content); }
public void TweetIdCanBeExtractedFromUrl() { // Arrange var testCases = new Dictionary <string, ulong> { { "https://twitter.com/TweetAngi/status/733279889596514304", 733279889596514304 }, { "https://twitter.com/dqmhose/status/733279824299630592", 733279824299630592 }, { "https://twitter.com/anne_nymus/status/733274507339763712", 733274507339763712 }, { "https://twitter.com/LaDolceVegas/status/725649743364370433", 725649743364370433 }, { "https://twitter.com/ID_AA_Carmack/status/733275349048381440", 733275349048381440 }, { "https://twitter.com/SPORT1/status/733273819994071040/", 733273819994071040 }, { "https://twitter.com/NetflixDE/status/733279091869286400?variable=true", 733279091869286400 }, { "https://pbs.twimg.com/media/Ci0gimSWEAASP-L.jpg", 0 }, { "https://twitter.com", 0 }, { "https://twitter.com/twitterapi", 0 } }; // Act var results = testCases.ToDictionary(kvp => kvp.Key, kvp => TwitterHelper.ExtractTweetId(kvp.Key)); // Assert foreach (var kvp in testCases) { Assert.AreEqual(kvp.Value, results[kvp.Key], kvp.Key); } }
private static async Task <User> GetTwitterAccountAsync(string accessToken, string accessToeknSecret) { // https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials var url = "https://api.twitter.com/1.1/account/verify_credentials.json"; var authorization = TwitterHelper.BuildGetAuthorizationHeader(url, accessToken, accessToeknSecret, twitterConfig.ConsumerKey, twitterConfig.ConsumerSecret); var httpClient = new HttpClient(); var requestMsg = new HttpRequestMessage() { Method = HttpMethod.Get, RequestUri = new Uri(url), }; requestMsg.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("OAuth", authorization); var response = await httpClient.SendAsync(requestMsg); var responseText = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { return(null); } dynamic json = JsonConvert.DeserializeObject(responseText); return(new User() { PartitionKey = "twitter", RowKey = json.id_str, Type = "twitter", Name = json.screen_name, ExtraInfo = responseText }); }
public void Initalize() { var character = new Satomi(); twitterHelper = new TwitterHelper(character.TwitterAuthSet); twitterHelper.Initializer(); }
public void SimpleAsciiTextHasSimpleLength() { // Arrange var testCases = new Dictionary <int, string>(); var rand = new Random(); for (int i = 1; i < 140; ++i) { var sb = new StringBuilder(); for (int n = 0; n < i; ++n) { bool upper = rand.Next(0, 1) == 1; sb.Append((char)((upper ? 'A' : 'a') + rand.Next(0, 27))); } testCases.Add(i, sb.ToString()); } // Act var results = testCases.ToDictionary(kvp => kvp.Key, kvp => TwitterHelper.CountCharacters(kvp.Value, MockConfig())); // Assert foreach (int l in testCases.Keys) { Assert.AreEqual(l, results[l]); } }
void AccessTokenQuery_QueryResponse(object sender, WebQueryResponseEventArgs e) { try { var parameters = TwitterHelper.GetQueryParameters((new StreamReader(e.Response)).ReadToEnd()); accessToken = parameters["oauth_token"]; accessTokenSecret = parameters["oauth_token_secret"]; userID = parameters["user_id"]; userScreenName = parameters["screen_name"]; TwitterHelper.SetKeyValue <string>("AccessToken", accessToken); TwitterHelper.SetKeyValue <string>("AccessTokenSecret", accessTokenSecret); TwitterHelper.SetKeyValue <string>("ScreenName", userScreenName); Dispatcher.BeginInvoke(() => { var SignInMenuItem = (Microsoft.Phone.Shell.ApplicationBarMenuItem) this.ApplicationBar.MenuItems[0]; SignInMenuItem.IsEnabled = false; var SignOutMenuItem = (Microsoft.Phone.Shell.ApplicationBarMenuItem) this.ApplicationBar.MenuItems[1]; SignOutMenuItem.IsEnabled = true; var tweetButton = (Microsoft.Phone.Shell.ApplicationBarIconButton) this.ApplicationBar.Buttons[0]; tweetButton.IsEnabled = true; }); this.postMessageToTwitter(); } catch (Exception ex) { Dispatcher.BeginInvoke(() => { MessageBox.Show(ex.Message); }); } }
private async Task RunAsync() { try { while (true) { await Task.Delay(_postEvery); int index = _random.Next(0, _messages.Count()); var selected = _messages.ElementAtOrDefault(index); if (selected == null) { await _log.SendMessageAsync("I couldn't find any messages to swindle <:ShibeSad:231546068960018433>"); return; } var mediaIds = await GetMediaIdsAsync(selected); var status = await _twitter.Statuses.UpdateAsync(selected.Resolve(), possibly_sensitive : true, media_ids : mediaIds); await _log.SendMessageAsync("", embed : TwitterHelper.GetPostedEmbed(selected, status.Id)); _ = _manager.LogAsync(status.Id, selected, _messages); _messages.Clear(); } } catch (Exception ex) { await PrettyConsole.LogAsync(LogSeverity.Error, "SwindleService", ex.ToString()); } }
private void SendRatingTwitter(int score) { var twitterId = App.MobileService.CurrentUser.UserId.Split(':')[1]; TwitterHelper.RetrieveUserInformation(twitterId, async tu => { Rating rating = new Rating() { SessionId = Session.Id, Score = (float)score, RaterName = tu.Handle, ImageUrl = tu.PictureUrl }; await App.MobileService.GetTable <Rating>().InsertAsync(rating); }, async() => { Rating rating = new Rating() { SessionId = Session.Id, Score = (float)score, RaterName = "Someone", ImageUrl = "Assets/NoProfile.png" }; await App.MobileService.GetTable <Rating>().InsertAsync(rating); }); }
public void TwitterConformance() { // Arrange var testCases = new Dictionary <string, int> { { "This is a test.", 15 }, { "http://test.com", 23 }, { "https://test.com", 23 }, { "test.com", 23 }, { "Test https://test.com test https://test.com test.com test", 86 }, // FIXME: This results in 4 :( //{"\U00010000\U0010ffff", 2}, { "저찀쯿쿿", 4 }, { "H\U0001f431☺", 3 } }; // Act var results = testCases.ToDictionary(kvp => kvp.Key, kvp => TwitterHelper.CountCharacters(kvp.Key, MockConfig())); // Assert foreach (var str in testCases.Keys) { Assert.AreEqual(testCases[str], results[str], str); } }
private void GetTwits() { Dispatcher dispatcher = Deployment.Current.Dispatcher; var service = TwitterHelper.Authentication(); var options = (Items.Count() != 0) ? new ListTweetsOnHomeTimelineOptions { Count = PostsDownloadNumber, MaxId = Items.Min(x => x.PostId) } : new ListTweetsOnHomeTimelineOptions { Count = PostsDownloadNumber }; service.ListTweetsOnHomeTimeline(options, (tweets, response) => { if (response.Error != null) { //MessageBox.Show(response.StatusCode.ToString()); return; } if (response.StatusCode == HttpStatusCode.OK) { foreach (var twitterStatuse in tweets) { TwitterStatus tweet = twitterStatuse; dispatcher.BeginInvoke(() => { if (Items.All(t => t.SourceText != tweet.Text)) { Items.Add(new PostViewModel(tweet, _id++)); } }); } } }); }
private async Task <string> GetTokenAsync(string tokenCredentialsEncoded) { using (HttpClient httpClient = TwitterHelper.GetAuthorizationHttpClient(tokenCredentialsEncoded)) { HttpResponseMessage response = await httpClient.PostAsync( configuration["Twitter:OauthUrl"], TwitterHelper.GetAuthorizationHttpContent() ); if (!response.IsSuccessStatusCode) { return(null); } string respose = await response.Content.ReadAsStringAsync(); JObject json = JObject.Parse(respose); string tokenKey = configuration["Twitter:TokenKey"]; if (!json.ContainsKey(tokenKey)) { return(null); } return(json[tokenKey].ToString()); } }
public void AccessTokenGetTest() { TwitterHelper target = new TwitterHelper(); // TODO: Initialize to an appropriate value string authToken = string.Empty; // TODO: Initialize to an appropriate value string verifier = string.Empty; // TODO: Initialize to an appropriate value target.AccessTokenGet(authToken, verifier); Assert.Inconclusive("A method that does not return a value cannot be verified."); }
private string ScreenName(TweetViewModel status) { if (status == null) { return(String.Empty); } return(TwitterHelper.GetSuggestedUser(status).ScreenName ?? String.Empty); }
private static TwitterHelper CreateTwitterHelper() { var oauth = GetOAuthInfo(); var twitter = new TwitterHelper(oauth); return(twitter); }
public ActionResult Index() { var twitter = new TwitterHelper(); var tweets = twitter.GetUserTimeline(null, null, 10, "SalesForce"); ViewBag.Tweets = tweets; return(View()); }
public ulong ExtractQuotedTweetUrl() { var quoteUrl = Model?.Entities?.UrlEntities?.FirstOrDefault(e => TwitterHelper.IsTweetUrl(e.ExpandedUrl)); return(quoteUrl == null ? 0 : TwitterHelper.ExtractTweetId(quoteUrl.ExpandedUrl)); }
private void LoadList(TwitterListType listType, bool refresh, string searchTerm) { string fileName = null; ObservableCollection <ItemViewModel> parentList = null; switch (listType) { case TwitterListType.Statuses: fileName = Constants.StatusesFileName; parentList = Items; break; case TwitterListType.Mentions: fileName = Constants.MentionsFileName; parentList = MentionItems; break; case TwitterListType.DirectMessages: fileName = Constants.DirectMessagesFileName; parentList = DirectMessageItems; break; case TwitterListType.Favorites: fileName = Constants.FavoritesFileName; parentList = FavoriteItems; break; } if (String.IsNullOrEmpty(fileName)) { return; } // If a cached file exists, bind it first then go update unless we are refreshing if (!refresh) { var itemList = Helper.LoadSetting <List <ItemViewModel> >(fileName); if (itemList != null) { BindList(parentList, itemList); } } var twitterHelper = new TwitterHelper(); twitterHelper.LoadList(listType, (parentList != null && parentList.Count > 0) ? parentList[0].Id : 0, searchTerm); twitterHelper.LoadedCompleteEvent += (sender, e) => { var list = Helper.LoadSetting <List <ItemViewModel> >(fileName); if (list == null) { Helper.ShowMessage("Error Loading Data from Twitter."); return; } CheckCount(); Deployment.Current.Dispatcher.BeginInvoke(() => BindList(parentList, list)); }; }
private static IEnumerable <EntityBase> ExtractEntities(Status tweet) { IEnumerable <EntityBase> entities = tweet.Entities.HashTagEntities; entities = entities.Concat(tweet.Entities.MediaEntities); entities = entities.Concat(tweet.Entities.UrlEntities); entities = entities.Concat(tweet.Entities.UserMentionEntities); var tweetText = TwitterHelper.NormalizeText(tweet.Text); var allEntities = entities.ToArray(); foreach (var entity in allEntities) { int length = entity.End - entity.Start - 1; List <string> extractedTextVersions = new List <string> { ExtractEntityText(entity) }; if (entity is UserMentionEntity) { extractedTextVersions.Add(AlternativeAtSign + extractedTextVersions[0].Substring(1)); } else if (entity is HashTagEntity) { extractedTextVersions.Add(AlternativeHashtagSign + extractedTextVersions[0].Substring(1)); } var actualText = tweetText.Substring(entity.Start, length); bool found = false; foreach (var extractedText in extractedTextVersions) { // When the tweet contains emojis, the twitter API returns wrong indices for entities if (extractedText != actualText) { var newIndex = tweetText.IndexOf(extractedText, entity.Start, StringComparison.Ordinal); if (newIndex == -1) { newIndex = tweetText.IndexOf(extractedText, entity.Start, StringComparison.OrdinalIgnoreCase); } if (newIndex == -1) { continue; } found = true; entity.Start = newIndex; entity.End = entity.Start + length + 1; } } Debug.Assert(found); } return(allEntities.OrderBy(e => e.Start)); }
/// <summary> /// Generates a collection of inlines from a tweet. /// </summary> /// <param name="tweet">The tweet to generate inlines from.</param> /// <returns>The generated inlines.</returns> private static IEnumerable <Inline> GenerateInlines(Status tweet) { var allEntities = ExtractEntities(tweet).ToArray(); if (allEntities.Any()) { int lastEnd = 0; foreach (EntityBase entity in allEntities) { if (entity.Start > lastEnd) { string text = tweet.Text.Substring(lastEnd, entity.Start - lastEnd); yield return(new Run(PrepareText(text))); } var tagEntity = entity as HashTagEntity; if (tagEntity != null) { yield return(GenerateHashTag(tagEntity)); } else if (entity is UrlEntity) { if (entity is MediaEntity) { if (!Config.Visual.InlineMedia) { MediaEntity mediaEnttiy = entity as MediaEntity; yield return(GenerateMedia(mediaEnttiy)); } } else { UrlEntity urlEntity = entity as UrlEntity; if (!TwitterHelper.IsTweetUrl(urlEntity.ExpandedUrl)) { yield return(GenerateLink(urlEntity)); } } } else if (entity is UserMentionEntity) { yield return(GenerateMention((UserMentionEntity)entity)); } lastEnd = entity.End; } if (lastEnd < tweet.Text.Length) { yield return(new Run(PrepareText(tweet.Text.Substring(lastEnd)))); } } else { yield return(new Run(PrepareText(tweet.Text))); } }
public ITwitterCredentials GenerateCredentials() { TwitterHelper.TestConnectCredentials(); oauth_consumer_key = ConfigurationManager.AppSettings[Constants.GetVariableName(() => oauth_consumer_key)]; oauth_consumer_secret = ConfigurationManager.AppSettings[Constants.GetVariableName(() => oauth_consumer_secret)]; screen_name = ConfigurationManager.AppSettings[Constants.GetVariableName(() => screen_name)]; return(new TwitterCredentials(oauth_consumer_key, oauth_consumer_secret, screen_name)); }
public void AuthorizationLinkGetTest() { TwitterHelper target = new TwitterHelper(); // TODO: Initialize to an appropriate value string expected = string.Empty; // TODO: Initialize to an appropriate value string actual; actual = target.AuthorizationLinkGet(); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); }
private void SendMsgTwitter() { var service = TwitterHelper.Authentication(); var opts = new SendTweetOptions { Status = Message.Text }; service.SendTweet(opts, (tweets, response) => { }); }
private static IEnumerable <EntityBase> RemoveExtendedTweetUrl(IEnumerable <UrlEntity> urls) { foreach (var url in urls) { if (!TwitterHelper.IsExtendedTweetUrl(url.ExpandedUrl)) { yield return(url); } } }
public async Task ForceAsync(ulong messageId) { var logGuild = Context.Client.GetGuild(ulong.Parse(_config["log_guild_id"])); var log = logGuild.GetTextChannel(ulong.Parse(_config["log_channel_id"])); var msg = (await Context.Channel.GetMessageAsync(messageId)) as IUserMessage; var response = await _twitter.Statuses.UpdateAsync(msg.Resolve(), possibly_sensitive : true); await log.SendMessageAsync("", embed : TwitterHelper.GetPostedEmbed(msg, response.Id)); }
public void WebResponseGetTest() { TwitterHelper target = new TwitterHelper(); // TODO: Initialize to an appropriate value HttpWebRequest webRequest = null; // TODO: Initialize to an appropriate value string expected = string.Empty; // TODO: Initialize to an appropriate value string actual; actual = target.WebResponseGet(webRequest); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); }
public MainWindowViewModel() { TwitterHelper twitterHelper = new TwitterHelper(); twitterHelper.Authorization(); Login login = new Login(); login.ShowDialog(); }
public static async Task <HttpResponseMessage> PostTwitterRequestTokenAsync( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "auth/twitter/request_token")] HttpRequestMessage req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); dynamic data = await req.Content.ReadAsAsync <object>(); string returnUrl = data.returnUrl; var authorization = TwitterHelper.BuildRequestAuthorizationHeader(twitterConfig.RequestTokenUrl, returnUrl, twitterConfig.ConsumerKey, twitterConfig.ConsumerSecret); var httpClient = new HttpClient(); var requestMsg = new HttpRequestMessage() { Method = HttpMethod.Post, RequestUri = new Uri(twitterConfig.RequestTokenUrl) }; requestMsg.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("OAuth", authorization); var response = await httpClient.SendAsync(requestMsg); var responseText = await response.Content.ReadAsStringAsync(); log.Info(responseText); if (!response.IsSuccessStatusCode) { return(req.CreateJsonResponse(response.StatusCode, responseText)); } string oauthToken = null; string oauthTokenSecret = null; var keyValPairs = responseText.Split('&'); for (var i = 0; i < keyValPairs.Length; i++) { var splits = keyValPairs[i].Split('='); switch (splits[0]) { case "oauth_token": oauthToken = splits[1]; break; case "oauth_token_secret": oauthTokenSecret = splits[1]; break; } } return(req.CreateJsonResponse(HttpStatusCode.OK, new { oauthToken, oauthTokenSecret })); }
private void UpdateTextLength() { var len = TwitterHelper.CountCharacters(Text, TwitterConfig); if (QuotedTweet != null) { // Keep the space in mind that separates the tweet text and the status URL len += TwitterConfig.UrlLengthHttps + 1; } TextLength = len; }
public void oAuthWebRequestTest() { TwitterHelper target = new TwitterHelper(); // TODO: Initialize to an appropriate value TwitterHelper.Method method = new TwitterHelper.Method(); // TODO: Initialize to an appropriate value string url = string.Empty; // TODO: Initialize to an appropriate value string postData = string.Empty; // TODO: Initialize to an appropriate value string expected = string.Empty; // TODO: Initialize to an appropriate value string actual; actual = target.oAuthWebRequest(method, url, postData); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); }
private void favoriteIt() { var twitter = new TwitterHelper(); twitter.FavoriteCompletedEvent += (sender2, e2) => { MessageBox.Show("Item added to favorites"); }; twitter.ErrorEvent += (sender2, e2) => { }; //twitter.FavoriteItem(_detailItem.Id); }
public void ConsumerKeyTest() { TwitterHelper target = new TwitterHelper(); // TODO: Initialize to an appropriate value string expected = string.Empty; // TODO: Initialize to an appropriate value string actual; target.ConsumerKey = expected; actual = target.ConsumerKey; Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); }
private void PostTweet(string tweet, TwitterAccess twitteruser) { if (String.IsNullOrEmpty(tweet)) return; var twitter = new TwitterHelper(twitteruser); // Successful event handler, navigate back if successful twitter.TweetCompletedEvent += (sender, e) => { Dispatcher.BeginInvoke(() => { shellProgress.IsVisible = false; MessageBox.Show("You have successfuly posted to your Twitter profile."); browserAuth.Navigated -= Twitter_Navigated; }); //if (NavigationService.CanGoBack) // NavigationService.GoBack(); }; // Failed event handler, show error twitter.ErrorEvent += (sender, e) => { Dispatcher.BeginInvoke(() => { shellProgress.IsVisible = false; MessageBox.Show("There was an error. Please try again later."); browserAuth.Navigated -= Twitter_Navigated; }); }; twitter.NewTweet(tweet); }