Get all followings using LINQ to Twitter - c#

I've just started a Windows Phone app, and I need to get all the user's followings.
I tried this :
SharedState.Authorizer = pinAuth;
ITwitterAuthorizer auth = SharedState.Authorizer;
TwitterContext twitterCtx = new TwitterContext(auth);
var friendList =
(from friend in twitterCtx.SocialGraph
where friend.Type == SocialGraphType.Friends && friend.ScreenName == "_TDK"
select friend)
.SingleOrDefault();
List<String> Followings;
foreach (var id in friendList.ScreenName)
{
Followings.Add(id.ToString());
}
But friendlist is always null and, obviously, the foreach does not like that and throws an exception.
Could someone help me ?
Thanks.

I think you need to iterate over the IDs collection, like this:
foreach (var id in friendList.IDs)
{
Followings.Add(id.ToString());
}
You need to make async calls with Silverlight-based apps, including Windows Phone. Here's an example of how you can refactor the query:
var twitterCtx = new TwitterContext(auth);
(from social in twitterCtx.SocialGraph
where social.Type == SocialGraphType.Followers &&
social.ScreenName == "JoeMayo"
select social)
.MaterializedAsyncCallback(asyncResponse =>
Dispatcher.BeginInvoke(() =>
{
if (asyncResponse.Status != TwitterErrorStatus.Success)
{
MessageBox.Show(
"Error during query: " +
asyncResponse.Exception.Message);
return;
}
SocialGraph social = asyncResponse.State.SingleOrDefault();
SocialListBox.ItemsSource = social.IDs;
}));
The MaterializedAsyncCallback manages the callback from Twitter. Notice how I use Dispatcher.BeginInvoke to marshal the call back onto the UI thread as the callback is on a worker thread. On the asyncResponse callback parameter, use Status to see if there is an error and use State to get the data if the query is successful.

I had the same problem, I solved this way (I know it's not the best way)
public void getProfile(MyProgressBar myprogressbar)
{
var auth = new SingleUserAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = GlobalVariables.ConsumerKey,
ConsumerSecret = GlobalVariables.ConsumerSecret,
AccessToken = GlobalVariables.AccessToken,
OAuthToken = GlobalVariables.AccessTokenSecret
}
};
using (var twitterCtx = new TwitterContext(auth, "https://api.twitter.com/1/", "https://search.twitter.com/"))
{
//Log
twitterCtx.Log = Console.Out;
var queryResponse = (from tweet in twitterCtx.Status
where tweet.Type == StatusType.User && tweet.ScreenName == GlobalVariables.ScreenName
select tweet);
queryResponse.AsyncCallback(tweets =>
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
var publicTweets = (from tweet in tweets
select tweet).FirstOrDefault();
s.TwitterName = publicTweets.User.Name.ToString();
s.TwitterScreenName = "#" + GlobalVariables.ScreenName;
s.TwitterDescription = publicTweets.User.Description.ToString();
s.TwitterStatus = publicTweets.User.StatusesCount.ToString() + " Tweets / " + publicTweets.User.FriendsCount.ToString() + " Following / " + publicTweets.User.FollowersCount.ToString() + " Followers";
s.TwitterImage = publicTweets.User.ProfileImageUrl.ToString();
myprogressbar.ShowProgressBar = false;
})).SingleOrDefault();
}
}

Related

Sign in with Apple in .Net MAUI

I am currently working on an dotnet maui app and I need to integrate Sign in With Apple. But when I click the sign in button, It shows "invalid_request invalid web redirect url"
Tried solutions
I tried the solutions available here, but it is not working.
Other than that I have also read the documentation, also got help from tutorials such as this, this and this
Code
Initializing request:
//Initiating apple sign in request
WebAuthenticatorResult result = null;
if (scheme.Equals(Constants.apple, StringComparison.Ordinal)
&& DeviceInfo.Platform == DevicePlatform.iOS
&& DeviceInfo.Version.Major >= 13)
{
// Make sure to enable Apple Sign In in both the
// entitlements and the provisioning profile.
var options = new AppleSignInAuthenticator.Options
{
IncludeEmailScope = true,
IncludeFullNameScope = true,
};
result = await AppleSignInAuthenticator.AuthenticateAsync(options);
}
else
{
var authUrl = new Uri(Constants.authenticationUrl + scheme);
var callbackUrl = new Uri(Constants.callbackUrl);
result = await WebAuthenticator.AuthenticateAsync(authUrl, callbackUrl);
}
AuthToken = string.Empty;
// Get Name and Email from callback url
//if (result.Properties.TryGetValue("name", out var name) && !string.IsNullOrEmpty(name))
// AuthToken += $"Name: {name}{Environment.NewLine}";
//if (result.Properties.TryGetValue("email", out var email) && !string.IsNullOrEmpty(email))
// AuthToken += $"Email: {email}{Environment.NewLine}";
AuthToken += result?.AccessToken ?? result?.IdToken;
AuthCredential credential = null;
Handling results:
// WebAuthenticator Endpoint - use for social login e.g. Google, Facebook, Apple etc.
const string callbackScheme = "socialloginauthenticator";
[HttpGet("{scheme}")]
public async Task Get([FromRoute] string scheme)
{
var auth = await Request.HttpContext.AuthenticateAsync(scheme);
if (!auth.Succeeded
|| auth?.Principal == null
|| !auth.Principal.Identities.Any(id => id.IsAuthenticated)
|| string.IsNullOrEmpty(auth.Properties.GetTokenValue("access_token")))
{
// Not authenticated, challenge
await Request.HttpContext.ChallengeAsync(scheme);
}
else
{
var claims = auth.Principal.Identities.FirstOrDefault()?.Claims;
var email = string.Empty;
email = claims?.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value;
// Get parameters to send back to the callback
var qs = new Dictionary<string, string>
{
{ "access_token", auth.Properties.GetTokenValue("access_token") },
{ "refresh_token", auth.Properties.GetTokenValue("refresh_token") ?? string.Empty },
{ "expires_in", (auth.Properties.ExpiresUtc?.ToUnixTimeSeconds() ?? -1).ToString() },
{ "email", email }
};
// Build the result url
var url = callbackScheme + "://#" + string.Join(
"&",
qs.Where(kvp => !string.IsNullOrEmpty(kvp.Value) && kvp.Value != "-1")
.Select(kvp => $"{WebUtility.UrlEncode(kvp.Key)}={WebUtility.UrlEncode(kvp.Value)}"));
// Redirect to final url
Request.HttpContext.Response.Redirect(url);
}
}
I have resolved the issue. The issue was with redirect uri in apple service I made.
The required uri was of format "www.example.com/signin-apple" while I was following "www.example.com/path/to/endpoints"

Check if AWS Lambda function completed the job

I am currently sending a file to be transcoded to my AWS lambda function. After I send the file, I send a notification to the SQS for some external aplication to start downloading the transcoded files.
The problem is, sometimes, the download of the files happen before the Lambda function completed.
How can I only send the notification to SQS after the Lambda completed.
I tried getting the Job.Status as follow, but not sure how to query it again if Status is not Complete.
Here is my code:
using (var eClient = new AmazonElasticTranscoderClient())
{
var response = await this.S3Client.GetObjectMetadataAsync(s3Event.Bucket.Name, s3Event.Object.Key);
var videoPresets = new List<Preset>();
var presetRequest = new ListPresetsRequest();
ListPresetsResponse presetResponse;
do
{
presetResponse = await eClient.ListPresetsAsync(presetRequest);
videoPresets.AddRange(presetResponse.Presets);
presetRequest.PageToken = presetResponse.NextPageToken;
} while (presetResponse.NextPageToken != null);
var pipelines = new List<Pipeline>();
var pipelineRequest = new ListPipelinesRequest();
ListPipelinesResponse pipelineResponse;
do
{
pipelineResponse = await eClient.ListPipelinesAsync(pipelineRequest);
pipelines.AddRange(pipelineResponse.Pipelines);
pipelineRequest.PageToken = pipelineResponse.NextPageToken;
} while (pipelineResponse.NextPageToken != null);
var pipeLine = s3Event.Bucket.Name.ToLower().Contains("test") ? pipelines.First(p => p.Name.ToLower().Contains("test")) : pipelines.First(p => !p.Name.ToLower().Contains("test"));
//HLS Stuff for Apple
var usablePreset = videoPresets.Where(p => p.Name.Contains("HLS") && !p.Name.Contains("HLS Video")).ToList();
var hlsPresets = new List<Preset>();
foreach (var preset in usablePreset)
{
var resolution = preset.Name.Replace("System preset: HLS ", "");
switch (resolution)
{
case "2M":
case "1M":
case "400k":
hlsPresets.Add(preset);
break;
}
}
var jobReq = new CreateJobRequest
{
PipelineId = pipeLine.Id,
Input = new JobInput() { Key = fileName, },
OutputKeyPrefix = outPutPrefix
//OutputKeyPrefix = "LambdaTest/" + playlistName + "/"
};
var outputs = new List<CreateJobOutput>();
var playlistHLS = new CreateJobPlaylist() { Name = "HLS_" + playlistName, Format = "HLSv3" };
foreach (var preset in hlsPresets)
{
var resolution = preset.Name.Replace("System preset: HLS ", "").Replace(".", "");
var newName = resolution + "_" + playlistName;
var output = new CreateJobOutput() { Key = newName, PresetId = preset.Id, SegmentDuration = "10" };
outputs.Add(output);
playlistHLS.OutputKeys.Add(newName);
}
jobReq.Playlists.Add(playlistHLS);
jobReq.Outputs = outputs;
//var temp = JsonConvert.SerializeObject(jobReq);
var reply = eClient.CreateJobAsync(jobReq);
var transcodingCompleted = reply.Result.Job.Status == "Complete" ? true : false;
do {
//somehow need to query status again
} while (!transcodingCompleted);
if (transcodingCompleted)
await SendAsync(jobReq.OutputKeyPrefix, pipeLine.OutputBucket);
}
The part I am interested in:
var reply = eClient.CreateJobAsync(jobReq);
var transcodingCompleted = reply.Result.Job.Status == "Complete" ? true : false;
do {
//somehow need to query status again
} while (!transcodingCompleted);
if (transcodingCompleted)
await SendAsync(jobReq.OutputKeyPrefix, pipeLine.OutputBucket);

Get Tweets by LinqToTwitter

I'm trying to get tweets from Twitter but it's not working with me, here is the code:
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore()
{
ConsumerKey = ConfigurationManager.AppSettings["***"],
ConsumerSecret = ConfigurationManager.AppSettings["***"],
AccessToken = ConfigurationManager.AppSettings["***"],
AccessTokenSecret = ConfigurationManager.AppSettings["***"]
}
};
var context = new TwitterContext(auth);
var tweets =
from tw in context.Status
where
tw.Type == StatusType.User &&
tw.ScreenName == "***"
select tw;
// handle exceptions, twitter service might be down
try
{
// map to list
tweets
.Take(3)
.Select(t =>
new Tweets
{
//Username = t.ScreenName,
//FullName = t.User.Name,
TweetText = t.Text,
//FormattedText = ParseTweet(t.Text)
})
.ToList();
}
catch (Exception) { }
every time it fail when I'm trying to read the tweets, the exception is
LinqToTwitter.TwitterQueryException: Bad Authentication data
But I'm sure that the credentials are correct.
and also is it possible to read the posts of another twitter account? like a company account or a celebrate account?
LINQ to Twitter is async, so you should change your query like this:
var tweets =
await
(from tw in context.Status
where
tw.Type == StatusType.User &&
tw.ScreenName == "***"
select tw)
.ToListAsync();
Also, hit a breakpoint after instantiating auth and inspect Credentials to make sure you've populated them correctly.

TweetInvi - Cannot Unfollow Users

I have the following code that is intended to find the users you are following, and the users that you have requested to follow. It then unfollows the one's that are not following you. However it never actually seem's to work, however the AuthenticatedUser_UnFollowUser returns true. Any ideas? Thanks.
private void AuthenticateUser()
{
CheckRateLimits();
Auth.SetUserCredentials(_consumerKey, _consumerSecret, _userAccessToken, _userAccessSecret);
authenticatedUser = User.GetAuthenticatedUser();
}
private void CheckRateLimits()
{
// Enable RateLimit Tracking
RateLimit.RateLimitTrackerMode = RateLimitTrackerMode.TrackAndAwait;
TweetinviEvents.QueryBeforeExecute += (sender, args) =>
{
var queryRateLimits = RateLimit.GetQueryRateLimit(args.QueryURL);
// Some methods are not RateLimited. Invoking such a method will result in the queryRateLimits to be null
if (queryRateLimits != null)
{
if (queryRateLimits.Remaining > 0)
{
AppendProgress("RateLimits Available : " + queryRateLimits.Remaining.ToString());
// We have enough resource to execute the query
return;
}
// Strategy #1 : Wait for RateLimits to be available
AppendProgress("Waiting for RateLimits until : " + queryRateLimits.ResetDateTime.ToLongTimeString() + "For " + queryRateLimits.ToString());
MessageBox.Show("Waiting for " + queryRateLimits.ResetDateTime.ToLongTimeString());
Thread.Sleep((int)queryRateLimits.ResetDateTimeInMilliseconds);
// Strategy #2 : Use different credentials
//var alternateCredentials = TwitterCredentials.CreateCredentials("", "", "", "");
//var twitterQuery = args.TwitterQuery;
//twitterQuery.OAuthCredentials = alternateCredentials;
// Strategy #3 : Cancel Query
//args.Cancel = true;
}
};
}
private void UnfollowUsersNotFollowingYou()
{
AuthenticateUser();
var toUnfollow = Examples.Friendship_GetUsersNotFollowingYou();
toUnfollow.ForEach(x =>
{
if (Examples.AuthenticatedUser_UnFollowUser(x.ScreenName))
{
AppendProgress("You have unfollowed " + x.ScreenName);
SaveUnfollowedUserIdToTextFile(x.ScreenName);
}
});
}
//From Examples Static Class
public static bool AuthenticatedUser_UnFollowUser(string userName)
{
var authenticatedUser = User.GetAuthenticatedUser();
var userToFollow = User.GetUserFromScreenName(userName);
bool unfollowed = authenticatedUser.UnFollowUser(userToFollow);
return unfollowed;
}
//Users Not Following You
public static IEnumerable<IUser> Friendship_GetUsersNotFollowingYou()
{
var currentuser = Examples.User_GetCurrentUserScreenname();
var followers = Examples.User_GetFriendIds(currentuser);
var following = Examples.Friendship_GetUsersYouRequestedToFollow();
var toUnfollow = following.Where(x => followers != x.FriendIds);
return toUnfollow;
}
I am the developer of Tweetinvi. I have just verified and unfollow like follow seems to work properly. Could you please verify that you are using the latest version of Tweetinvi (0.9.13.0)?
Also please note that Unfollow will return success even if the user was not followed. This is what Twitter is returning and there is nothing I can do about that.
EDIT :
The problem came from the fact that #david-beamont was not retrieving the users properly.
Here is the code to get the following users :
var authenticatedUser = User.GetAuthenticatedUser();
var friends = authenticatedUser.GetFriends();

Could someone provide a C# example using itemsearch from Amazon Web Services

I am trying to use Amazon Web Services to query Artist and title information and receive album art back. Using C# I cannot find any examples that come even close to this. All of the examples online are outdated and do not work with AWS' newer version.
There is an open Source project on CodePlex you might want to take a look at.... It's A .NET Library for Amazon's Web Services. S3, SQS, FPS, EC2, and DevPay
It could be as simple as this(as shown on codeplex):
S3Client s3 = new S3Client("myAWSKey", "MyAWSPassword");
bool success = s3.Connect();
S3Client s3 = new S3Client("key", "secret"):
var buckets = from b in s3.Buckets
where b.Name == "demo"
select b;
foreach(Bucket b in buckets)
{
Console.WriteLine(b.About());
}
Here you go for what it's worth. This is code within an Asp.Net control to display book information. You can probably adapt it for your purposes easily enough. Or at least give you a starting-point. If you really want, I'd be happy to bundle the control up and send it your way.
if (!(string.IsNullOrEmpty(ISBN) && string.IsNullOrEmpty(ASIN)))
{
AWSECommerceService service = new AWSECommerceService();
ItemLookup lookup = new ItemLookup();
ItemLookupRequest request = new ItemLookupRequest();
lookup.AssociateTag = ConfigurationManager.AppSettings["AssociatesTag"];
lookup.AWSAccessKeyId = ConfigurationManager.AppSettings["AWSAccessKey"];
if (string.IsNullOrEmpty(ASIN))
{
request.IdType = ItemLookupRequestIdType.ISBN;
request.ItemId = new string[] { ISBN.Replace("-", "") };
}
else
{
request.IdType = ItemLookupRequestIdType.ASIN;
request.ItemId = new string[] { ASIN };
}
request.ResponseGroup = ConfigurationManager.AppSettings["AWSResponseGroups"].Split(new char[] { ' ', ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
lookup.Request = new ItemLookupRequest[] { request };
ItemLookupResponse response = service.ItemLookup(lookup);
if (response.Items.Length > 0 && response.Items[0].Item.Length > 0)
{
Item item = response.Items[0].Item[0];
if (item.MediumImage == null)
{
bookImageHyperlink.Visible = false;
}
else
{
bookImageHyperlink.ImageUrl = item.MediumImage.URL;
}
bookImageHyperlink.NavigateUrl = item.DetailPageURL;
bookTitleHyperlink.Text = item.ItemAttributes.Title;
bookTitleHyperlink.NavigateUrl = item.DetailPageURL;
if (item.OfferSummary.LowestNewPrice == null)
{
if (item.OfferSummary.LowestUsedPrice == null)
{
priceHyperlink.Visible = false;
}
else
{
priceHyperlink.Text = string.Format("Buy used {0}", item.OfferSummary.LowestUsedPrice.FormattedPrice);
priceHyperlink.NavigateUrl = item.DetailPageURL;
}
}
else
{
priceHyperlink.Text = string.Format("Buy new {0}", item.OfferSummary.LowestNewPrice.FormattedPrice);
priceHyperlink.NavigateUrl = item.DetailPageURL;
}
if (item.ItemAttributes.Author != null)
{
authorLabel.Text = string.Format("By {0}", string.Join(", ", item.ItemAttributes.Author));
}
else
{
authorLabel.Text = string.Format("By {0}", string.Join(", ", item.ItemAttributes.Creator.Select(c => c.Value).ToArray()));
}
ItemLink link = item.ItemLinks.Where(i => i.Description.Contains("Wishlist")).FirstOrDefault();
if (link == null)
{
wishListHyperlink.Visible = false;
}
else
{
wishListHyperlink.NavigateUrl = link.URL;
}
}
}

Categories