本文整理汇总了C#中LinqToTwitter.TwitterContext类的典型用法代码示例。如果您正苦于以下问题:C# TwitterContext类的具体用法?C# TwitterContext怎么用?C# TwitterContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
TwitterContext类属于LinqToTwitter命名空间,在下文中一共展示了TwitterContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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;
}
示例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);
}
示例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();
}
示例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;
}
示例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;
}
示例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');
}
示例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");
});
}
示例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);
}
}
示例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');
}
示例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();
}
示例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);
}
示例12: UpdateStatus
public static void UpdateStatus(string tweet, IOAuthCredentials credentials) {
var singleUserAuthorizer = new SingleUserAuthorizer {
Credentials = credentials
};
var twitterCtx = new TwitterContext(singleUserAuthorizer);
twitterCtx.UpdateStatus(tweet);
}
示例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();
}
}
示例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/");
}
示例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 );
}
} );
}