• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# LinqToTwitter.TwitterContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中LinqToTwitter.TwitterContext的典型用法代码示例。如果您正苦于以下问题:C# TwitterContext类的具体用法?C# TwitterContext怎么用?C# TwitterContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



TwitterContext类属于LinqToTwitter命名空间,在下文中一共展示了TwitterContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: GetImageInfo

        protected string GetImageInfo(string twitterName, string defaultURL)
        {
            if (twitterName == null)
                return defaultURL;

            var twitterUrl = defaultURL;

            var auth = new MvcAuthorizer
            {
                CredentialStore = new SessionStateCredentialStore
                {
                    ConsumerKey = "fUpi8KuU3hMWsCHueZIww",
                    ConsumerSecret = "4gCFXwi5zW5CYIoGSNgydL9dmqVM9T9BUS9ElrMI"
                }
            };

            var twitterCtx = new TwitterContext(auth) {ReadWriteTimeout = 300};
            try
            {
                var userResponse =
                     (from user in twitterCtx.User
                      where user.Type == UserType.Show &&
                            user.ScreenName == twitterName.Replace("@", "")
                      select user).ToArray();

                var firstOrDefault = userResponse.FirstOrDefault();
                if (firstOrDefault != null) twitterUrl = firstOrDefault.ProfileImageUrl;
            }
            catch(Exception)
            {
                return defaultURL;
            }
            return twitterUrl;
        }
开发者ID:cfranciscodev,项目名称:WebSite,代码行数:34,代码来源:BaseController.cs


示例2: ShowFavoritesAsync

        static async Task ShowFavoritesAsync(TwitterContext twitterCtx)
        {
            const int PerQueryFavCount = 200;

            // set from a value that you previously saved
            ulong sinceID = 1; 

            var favsResponse =
                await
                    (from fav in twitterCtx.Favorites
                     where fav.Type == FavoritesType.Favorites &&
                           fav.Count == PerQueryFavCount
                     select fav)
                    .ToListAsync();

            if (favsResponse == null)
            {
                Console.WriteLine("No favorites returned from Twitter.");
                return;
            }

            var favList = new List<Favorites>(favsResponse);

            // first tweet processed on current query
            ulong maxID = favList.Min(fav => fav.StatusID) - 1;

            do
            {
                favsResponse =
                    await
                        (from fav in twitterCtx.Favorites
                         where fav.Type == FavoritesType.Favorites &&
                               fav.Count == PerQueryFavCount &&
                               fav.SinceID == sinceID &&
                               fav.MaxID == maxID
                         select fav)
                        .ToListAsync();

                if (favsResponse == null || favsResponse.Count == 0) break;

                // reset first tweet to avoid re-querying the
                // same list you just received
                maxID = favsResponse.Min(fav => fav.StatusID) - 1;
                favList.AddRange(favsResponse);

            } while (favsResponse.Count > 0);

            favList.ForEach(fav => 
            {
                if (fav != null && fav.User != null)
                    Console.WriteLine(
                        "Name: {0}, Tweet: {1}",
                        fav.User.ScreenNameResponse, fav.Text);
            });

            // save this in your db for this user so you can set
            // sinceID accurately the next time you do a query
            // and avoid querying the same tweets again.
            ulong newSinceID = favList.Max(fav => fav.SinceID);
        }
开发者ID:prog-moh,项目名称:LinqToTwitter,代码行数:60,代码来源:FavoriteDemos.cs


示例3: InitTweetViewModel

        public async Task InitTweetViewModel()
        {
            var auth = new ApplicationOnlyAuthorizer()
            {
                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey = "dYNbMI3KFn4zFrHIaAKIWCFYQ",
                    ConsumerSecret = "mQhDSmPov7bbJXb8jPwaVghBbUbgELpQqyHG2QRyf89CsQWKyb",
                },
            };
            await auth.AuthorizeAsync();

            var ctx = new TwitterContext(auth);

            var searchResponse = await
                (from search in ctx.Search
                 where search.Type == SearchType.Search &&
                       search.Query == "\"LINQ to Twitter\""
                 select search)
                .SingleAsync();

            Tweets =
                (from tweet in searchResponse.Statuses
                 select new Tweet
                 {
                     StatusID = tweet.StatusID,
                     ScreenName = tweet.User.ScreenNameResponse,
                     Text = tweet.Text,
                     ImageUrl = tweet.User.ProfileImageUrl
                 })
                .ToList();
        }
开发者ID:rockcliff15,项目名称:LinqToTwitter,代码行数:32,代码来源:TweetViewModel.cs


示例4: InitializeTwitterContext

        async Task<TwitterContext> InitializeTwitterContext()
        {
            await Task.Delay(1);
            var authMock = new Mock<IAuthorizer>();
            var execMock = new Mock<ITwitterExecute>();

            var tcsAuth = new TaskCompletionSource<IAuthorizer>();
            tcsAuth.SetResult(authMock.Object);

            var tcsResponse = new TaskCompletionSource<string>();
            tcsResponse.SetResult(SingleStatusResponse);

            var tcsMedia = new TaskCompletionSource<string>();
            tcsMedia.SetResult(MediaResponse);

            execMock.SetupGet(exec => exec.Authorizer).Returns(authMock.Object);
            execMock.Setup(exec =>
                exec.PostToTwitterAsync<Status>(
                    It.IsAny<string>(),
                    It.IsAny<IDictionary<string, string>>(),
                    It.IsAny<CancellationToken>()))
                .Returns(tcsResponse.Task);
            execMock.Setup(exec =>
                exec.PostMediaAsync(
                    It.IsAny<string>(),
                    It.IsAny<IDictionary<string, string>>(),
                    It.IsAny<byte[]>(),
                    It.IsAny<string>(),
                    It.IsAny<string>(),
                    It.IsAny<string>(),
                    It.IsAny<CancellationToken>()))
                .Returns(tcsMedia.Task);
            var ctx = new TwitterContext(execMock.Object);
            return ctx;
        }
开发者ID:neilhighley,项目名称:LinqToTwitter,代码行数:35,代码来源:StatusCommandsTests.cs


示例5: Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        auth = new WebOAuthAuthorization(InMemoryTokenManager.Instance, InMemoryTokenManager.AccessToken);

        if (!Page.IsPostBack)
        {
             // try to complete a pending authorization in case there is one.
            string accessToken = auth.CompleteAuthorize();
            if (accessToken != null)
            {
                // Store the access token in session state so we can get at it across page refreshes.
                // In a real app, you'd want to associate this access token with the user that is
                // logged into your app at this point.
                InMemoryTokenManager.AccessToken = accessToken;

                // Clear away the OAuth message so that users can refresh the page without problems.
                Response.Redirect(Page.Request.Path);
            }
        }

        if (string.IsNullOrEmpty(InMemoryTokenManager.Instance.ConsumerKey) || string.IsNullOrEmpty(InMemoryTokenManager.Instance.ConsumerSecret))
        {
            // The user needs to set up the web.config file to include Twitter consumer key and secret.
            PrivateDataMultiView.SetActiveView(SetupTwitterConsumer);
        }
        else if (auth.CachedCredentialsAvailable)
        {
            auth.SignOn(); // acquire the screen name, and ensure the access token is still valid.
            screenNameLabel.Text = auth.ScreenName;
            PrivateDataMultiView.SetActiveView(ViewPrivateUpdates);
            updateBox.Focus();
        }
        else
        {
            PrivateDataMultiView.SetActiveView(AuthorizeTwitter);
        }

        twitterCtx = auth.CachedCredentialsAvailable ? new TwitterContext(auth) : new TwitterContext();

        var tweets =
            from tweet in twitterCtx.Status
            where tweet.Type == (auth.CachedCredentialsAvailable ? StatusType.Friends : StatusType.Public)
            select tweet;

        TwitterListView.DataSource = tweets;
        TwitterListView.DataBind();

        // demonstrate serialization

        var serializableUser =
            (from user in twitterCtx.User
             where user.Type == UserType.Show &&
                   user.ScreenName == "JoeMayo"
             select user)
             .FirstOrDefault();

        // if you have ASP.NET state server turned on
        // this will still work because User is serializable
        Session["SerializableUser"] = serializableUser;
    }
开发者ID:giggio,项目名称:tweetercloud,代码行数:60,代码来源:Default.aspx.cs


示例6: RunAsync

        internal static async Task RunAsync(TwitterContext twitterCtx)
        {
            char key;

            do
            {
                ShowMenu();

                key = Console.ReadKey(true).KeyChar;

                switch (key)
                {
                    case '0':
                        Console.WriteLine("\n\tSearching...\n");
                        await DoSearchAsync(twitterCtx);
                        break;
                    case 'q':
                    case 'Q':
                        Console.WriteLine("\nReturning...\n");
                        break;
                    default:
                        Console.WriteLine(key + " is unknown");
                        break;
                }

            } while (char.ToUpper(key) != 'Q');
        }
开发者ID:prog-moh,项目名称:LinqToTwitter,代码行数:27,代码来源:SearchDemos.cs


示例7: AsyncSearchSample

        static void AsyncSearchSample(TwitterContext twitterCtx)
        {
            (from search in twitterCtx.Search
             where search.Type == SearchType.Search &&
                   search.Query == "LINQ To Twitter"
             select search)
            .MaterializedAsyncCallback(resp =>
            {
                if (resp.Status != TwitterErrorStatus.Success)
                {
                    Exception ex = resp.Exception;
                    // handle error
                    throw ex;
                }

                Search srch = resp.State.First();
                Console.WriteLine("\nQuery: {0}\n", srch.SearchMetaData.Query);

                srch.Statuses.ForEach(entry =>
                    Console.WriteLine(
                        "ID: {0, -15}, Source: {1}\nContent: {2}\n",
                        entry.StatusID, entry.Source, entry.Text));

                Console.WriteLine("\n More Search demos can be downloaded from LINQ to Twitter's on-line samples at http://linqtotwitter.codeplex.com/wikipage?title=LINQ%20to%20Twitter%20Samples&referringTitle=Home");
            });
        }
开发者ID:prog-moh,项目名称:LinqToTwitter,代码行数:26,代码来源:SearchDemos.cs


示例8: HandleQueryExceptionDemo

        /// <summary>
        /// shows how to handle a TwitterQueryException with a query
        /// </summary>
        /// <param name="twitterCtx">TwitterContext</param>
        private static void HandleQueryExceptionDemo(TwitterContext twitterCtx)
        {
            // force the error by supplying bad credentials
            twitterCtx.AuthorizedClient = new UsernamePasswordAuthorization
            {
                UserName = "BadUserName",
                Password = "BadPassword",
            };

            try
            {
                var statuses =
                        from status in twitterCtx.Status
                        where status.Type == StatusType.Mentions
                        select status;

                var statusList = statuses.ToList();
            }
            catch (TwitterQueryException tqe)
            {
                // log it to the console
                Console.WriteLine(
                    "\nHTTP Error Code: {0}\nError: {1}\nRequest: {2}\n",
                    tqe.HttpError,
                    tqe.Response.Error,
                    tqe.Response.Request);
            }
        }
开发者ID:giggio,项目名称:tweetercloud,代码行数:32,代码来源:ErrorHandlingDemos.cs


示例9: RunAsync

        internal static async Task RunAsync(TwitterContext twitterCtx)
        {
            char key;

            do
            {
                ShowMenu();

                key = Console.ReadKey(true).KeyChar;

                switch (key)
                {
                    case '0':
                        Console.WriteLine("\n\tGetting trends...\n");
                        await GetTrendsForPlaceAsync(twitterCtx);
                        break;
                    case '1':
                        Console.WriteLine("\n\tGetting available trend locations...\n");
                        await GetAvailableTrendLocationsAsync(twitterCtx);
                        break;
                    case '2':
                        Console.WriteLine("\n\tGetting trends...\n");
                        await GetClosestTrendsAsync(twitterCtx);
                        break;
                    case 'q':
                    case 'Q':
                        Console.WriteLine("\nReturning...\n");
                        break;
                    default:
                        Console.WriteLine(key + " is unknown");
                        break;
                }

            } while (char.ToUpper(key) != 'Q');
        }
开发者ID:prog-moh,项目名称:LinqToTwitter,代码行数:35,代码来源:TrendDemos.cs


示例10: BindDemo

        private void BindDemo()
        {
            ITwitterAuthorizer autentikasi = GetInformasiKredensial();

            var TwitterDataContext = new TwitterContext(autentikasi);

            string _screen_name = "kicaubobotoh"; //screen name yang melakukan retweet

            var liststatus = (from tweet in TwitterDataContext.Status
                              where tweet.Type == StatusType.RetweetedByUser &&
                                    tweet.ScreenName == _screen_name
                              select tweet.RetweetedStatus)
                .ToList();

            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("name");
            dt.Columns.Add("text");

            foreach (Status item in liststatus)
            {
                dt.Rows.Add(item.User.Name, item.Text);
            }

            gvMain.DataSource = dt;
            gvMain.DataBind();
        }
开发者ID:go2ismail,项目名称:JurusTwitterAPISourceCode,代码行数:26,代码来源:Default.aspx.cs


示例11: Run

 /// <summary>
 /// Run all error handling related demos
 /// </summary>
 /// <param name="twitterCtx">TwitterContext</param>
 public static void Run(TwitterContext twitterCtx)
 {
     //HandleQueryExceptionDemo(twitterCtx);
     //HandleSideEffectExceptionDemo(twitterCtx);
     //HandleSideEffectWithFilePostExceptionDemo(twitterCtx);
     //HandleTimeoutErrors(twitterCtx);
 }
开发者ID:giggio,项目名称:tweetercloud,代码行数:11,代码来源:ErrorHandlingDemos.cs


示例12: UpdateStatus

 public static void UpdateStatus(string tweet, IOAuthCredentials credentials) {
     var singleUserAuthorizer = new SingleUserAuthorizer {
         Credentials = credentials
     };
     var twitterCtx = new TwitterContext(singleUserAuthorizer);
     twitterCtx.UpdateStatus(tweet);
 }
开发者ID:slieser,项目名称:sandbox,代码行数:7,代码来源:Linq2TwitterSpikes.cs


示例13: Execute

        /// <summary>
        /// 実行
        /// </summary>
        public void Execute()
        {
            //
            // get user credentials and instantiate TwitterContext
            //
            ITwitterAuthorization auth;

            if (String.IsNullOrEmpty(Properties.Settings.Default.UserID))
            {
                m_logger.Info("Skipping OAuth authorization demo because twitterConsumerKey and/or twitterConsumerSecret are not set in your .config file.");
                m_logger.Info("Using username/password authorization instead.");

                // For username/password authorization demo...
                auth = new UsernamePasswordAuthorization(Utilities.GetConsoleHWnd());
            }
            else
            {
                //Console.WriteLine("Discovered Twitter OAuth consumer key in .config file.  Using OAuth authorization.");

                m_logger.InfoFormat("Using '{0}'/**** authorization instead.", Properties.Settings.Default.UserID);

                auth = new UsernamePasswordAuthorization();
                var desktopAuth = (UsernamePasswordAuthorization)auth;
                desktopAuth.AllowUIPrompt = false;
                desktopAuth.UserName = Properties.Settings.Default.UserID;
                desktopAuth.Password = Properties.Settings.Default.Password;
            }

            // TwitterContext is similar to DataContext (LINQ to SQL) or ObjectContext (LINQ to Entities)

            // For Twitter
            using (var twitterCtx = new TwitterContext(auth, "https://api.twitter.com/1/", "http://search.twitter.com/"))
            {
                // If we're using OAuth, we need to configure it with the ConsumerKey etc. from the user.
                if (twitterCtx.AuthorizedClient is OAuthAuthorization)
                {
                    InitializeOAuthConsumerStrings(twitterCtx);
                }

                // Whatever authorization module we selected... sign on now.
                // See the bottom of the method for sign-off procedures.
                try
                {
                    auth.SignOn();
                }
                catch (OperationCanceledException)
                {
                    Console.WriteLine("Login canceled. Demo exiting.");
                    return;
                }

                // Search & Retweet
                SearchAndRetweet(twitterCtx);

                //
                // Sign-off, including optional clearing of cached credentials.
                //
                auth.SignOff();
            }
        }
开发者ID:amay077,项目名称:ReTweeter,代码行数:63,代码来源:Program.cs


示例14: DoPinAuth

        private void DoPinAuth()
        {
            m_pinAuth = new PinAuthorizer
            {
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = "",
                    ConsumerSecret = ""
                },
                UseCompression = true,
                GoToTwitterAuthorization = pageLink =>
                    Dispatcher.BeginInvoke(() => WebBrowser.Navigate(new Uri(pageLink)))
            };

            m_pinAuth.BeginAuthorize(resp =>
                Dispatcher.BeginInvoke(() =>
                {
                    switch (resp.Status)
                    {
                        case TwitterErrorStatus.Success:
                            break;
                        case TwitterErrorStatus.TwitterApiError:
                        case TwitterErrorStatus.RequestProcessingException:
                            MessageBox.Show(
                                resp.Error.ToString(),
                                resp.Message,
                                MessageBoxButton.OK);
                            break;
                    }
                }));

            m_twitterCtx = new TwitterContext(m_pinAuth, "https://api.twitter.com/1/", "https://search.twitter.com/");
        }
开发者ID:CheyPMK,项目名称:linqtotwitter,代码行数:33,代码来源:FriendsStatusQuery.xaml.cs


示例15: Application_Start

        protected void Application_Start( object sender, EventArgs e )
        {
            ThreadPool.QueueUserWorkItem( _ =>
                                            {
                                                var connectionContext = GlobalHost.ConnectionManager.GetConnectionContext<TweetsConnection>( );
                                                var auth = new SingleUserAuthorizer
                                                               {
                                                                   CredentialStore = new SingleUserInMemoryCredentialStore
                                                                   {
                                                                       ConsumerKey = "",
                                                                       ConsumerSecret = "",
                                                                       AccessToken = "",
                                                                       AccessTokenSecret = ""
                                                                   }
                                                               };

                                                while ( true )
                                                {
                                                    using ( TwitterContext context = new TwitterContext( auth ) )
                                                    {
                                                        var tweets = ( from search in context.Search
                                                                       where search.Type == SearchType.Search && search.Query == "#fnord"
                                                                       select search ).SingleOrDefault( );

                                                        if ( tweets != null && tweets.Statuses != null )
                                                            connectionContext.Connection.Broadcast( tweets.Statuses.Select( t => t.Text ).ToList( ) );
                                                    }
                                                    Thread.Sleep( 5000 );
                                                }
                                            } );
        }
开发者ID:julid29,项目名称:confsamples,代码行数:31,代码来源:Global.asax.cs


示例16: GetTwitterAccount

        public async Task<Account> GetTwitterAccount(string userId, string screenName)
        {
            var authTwitter = new SingleUserAuthorizer
            {
                CredentialStore = new SingleUserInMemoryCredentialStore
                {
                    ConsumerKey = twitterAuthenticationSettings.Value.ConsumerKey,
                    ConsumerSecret = twitterAuthenticationSettings.Value.ConsumerSecret,
                    OAuthToken = twitterAuthenticationSettings.Value.OAuthToken,
                    OAuthTokenSecret = twitterAuthenticationSettings.Value.OAuthSecret,

                    UserID = ulong.Parse(userId),
                    ScreenName = screenName
                }
            };

            await authTwitter.AuthorizeAsync();

            var twitterCtx = new TwitterContext(authTwitter);

            //VERY important you explicitly keep the "== true" part of comparison. ReSharper will prompt you to remove this, and if it does, the query will not work
            var account = await (from acct in twitterCtx.Account
                                 where (acct.Type == AccountType.VerifyCredentials) && (acct.IncludeEmail == true)
                                 select acct).SingleOrDefaultAsync();

            return account;
        }
开发者ID:yi2369,项目名称:allReady,代码行数:27,代码来源:TwitterRepository.cs


示例17: DoFilterStreamAsync

        static async Task DoFilterStreamAsync(TwitterContext twitterCtx)
        {
            Console.WriteLine("\nStreamed Content: \n");
            int count = 0;
            var cancelTokenSrc = new CancellationTokenSource();

            try
            {
                await
                    (from strm in twitterCtx.Streaming
                                            .WithCancellation(cancelTokenSrc.Token)
                     where strm.Type == StreamingType.Filter &&
                           strm.Track == "twitter"
                     select strm)
                    .StartAsync(async strm =>
                    {
                        HandleStreamResponse(strm);

                        if (count++ >= 5)
                            cancelTokenSrc.Cancel();
                    });
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine("Stream cancelled.");
            }
        }
开发者ID:prog-moh,项目名称:LinqToTwitter,代码行数:27,代码来源:StreamDemos.cs


示例18: UpdateAccountBackgroundImageAndTileDemo

        /// <summary>
        /// Shows how to update the background image in an account and tiles the image
        /// </summary>
        /// <param name="twitterCtx">TwitterContext</param>
        private static void UpdateAccountBackgroundImageAndTileDemo(TwitterContext twitterCtx)
        {
            byte[] fileBytes = Utilities.GetFileBytes(@"C:\Users\jmayo\Documents\linq2twitter\linq2twitter\linq2twitter_v3_300x90.png");
            var user = twitterCtx.UpdateAccountBackgroundImage(fileBytes, "linq2twitter_v3_300x90.png", "png", true);

            Console.WriteLine("User Image: " + user.ProfileBackgroundImageUrl);
        }
开发者ID:giggio,项目名称:tweetercloud,代码行数:11,代码来源:AccountDemos.cs


示例19: Run

 /// <summary>
 /// Run all direct message related demos
 /// </summary>
 /// <param name="twitterCtx">TwitterContext</param>
 public static void Run(TwitterContext twitterCtx)
 {
     DirectMessageSentByQueryDemo(twitterCtx);
     //DirectMessageSentToQueryDemo(twitterCtx);
     //NewDirectMessageDemo(twitterCtx);
     //DestroyDirectMessageDemo(twitterCtx);
 }
开发者ID:giggio,项目名称:tweetercloud,代码行数:11,代码来源:DirectMessageDemos.cs


示例20: UpdateAccountBackgroundImageBytes

        /// <summary>
        /// Shows how to update the background image in an account
        /// </summary>
        /// <param name="twitterCtx">TwitterContext</param>
        private static void UpdateAccountBackgroundImageBytes(TwitterContext twitterCtx)
        {
            byte[] fileBytes = Utilities.GetFileBytes(@"C:\Users\jmayo\Documents\linq2twitter\linq2twitter\200xColor_2.png");
            var user = twitterCtx.UpdateAccountBackgroundImage(fileBytes, "200xColor_2.png", "png", false);

            Console.WriteLine("User Image: " + user.ProfileBackgroundImageUrl);
        }
开发者ID:giggio,项目名称:tweetercloud,代码行数:11,代码来源:AccountDemos.cs



注:本文中的LinqToTwitter.TwitterContext类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Projects.ProjectGateway类代码示例发布时间:2022-05-26
下一篇:
C# LinqToTwitter.List类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap