Twitter Integration In windows Phone 7 - c#

I want to get the user information from the twitter and show in windows phone 7. I found some examples for twitter integration.
Link 1
Link 2
But in this examples i can only login to the twitter. I can not post or can not get the user information. Can any one provide a sample application or links for windows phone 7 twitter integration.
After getting login i try like this:
private void btntest_Click(object sender, RoutedEventArgs e)
{
string newURL = string.Format("https://api.twitter.com/1.1/users/show.json?screen_name={0}", userScreenName);
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webBrowser_Navigated);
webClient.DownloadStringAsync(new Uri(newURL));
}
void webBrowser_Navigated(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
Console.WriteLine("Error ");
return;
}
Console.WriteLine("Result==> " + e.Result);
//List<Tweet> tweets = JsonConvert.DeserializeObject<List<Tweet>>(e.Result);
//this.lbTweets.ItemsSource = tweets;
}
But here i can not get the user information. Please help me to get the user infoemation.
Thanks in advance.

Did you try using the Tweetinvi API from Codeplex, where you could grab the user details as well you could post tweets.
Tweetinvi a friendly Twitter C# API
Have a look at this one too:
Windows Phone 8 - Twitter API

Finally i found the Solution..!!! :-)
public void GetTwitterDetail(string _userScreenName)
{
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = AppSettings.consumerKey,
ConsumerSecret = AppSettings.consumerKeySecret,
Token = this.accessToken,
TokenSecret = this.accessTokenSecret,
};
var restClient = new RestClient
{
Authority = "https://api.twitter.com/1.1",
HasElevatedPermissions = true
};
var restRequest = new RestRequest
{
Credentials = credentials,
Path = string.Format("/users/show.json?screen_name={0}&include_entities=true", _userScreenName),
Method = WebMethod.Get
};
restClient.BeginRequest(restRequest, new RestCallback(test));
}
private void test(RestRequest request, RestResponse response, object obj)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
Console.WriteLine("Content==> " + response.Content.ToString());
Console.WriteLine("StatusCode==> " + response.StatusCode);
});
}
Now i got the User's In formations..!!! 5 days struggling comes to end..!! Thanks to all..!!

Related

Google integation in windows phone 8.1[RT] application

I am working with windows phone 8.1 application and I want to login with Google Plus , for that I have create Client id and Client secret from Google
string uri = string.Format("{0}?response_type=code&client_id={1}&redirect_uri={2}&scope={3}&approval_prompt=force",
authEndpoint,
clientId,
"urn:ietf:wg:oauth:2.0:oob",
scope);
webBrowser.Navigate(new Uri(uri, UriKind.Absolute));
and I Got string something like 4/BGIl1Na3TQJlAD8SQ7blvHyONJ_Jyav8COHa7tIrAdo
I want User Email and Name from account for signup or login
Please help me for that.
Thank you
Implement the interafce IWebAuthenticationContinuable to your class and then under ContinueWebAuthentication() Method use this code :
var authData = GetGoogleSuccessCode(args.WebAuthenticationResult.ResponseData);
var userData = await GetTokenAndUserInfo(authData);
private string GetGoogleSuccessCode(string data)
{
if (string.IsNullOrEmpty(data)) return null;
var parts = data.Split('&')[0].Split('=');
for (int i = 0; i < parts.Length; ++i)
{
if (parts[i] == "Success code")
{
return parts[i + 1];
}
}
return null;
}
public async Task<string> GetTokenAndUserInfo(string code)
{
var client = new HttpClient();
var auth = await client.PostAsync("https://accounts.google.com/o/oauth2/token", new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("code", code),
new KeyValuePair<string, string>("client_id",Constants.GoogleAppId),
new KeyValuePair<string, string>("client_secret",Constants.GoogleAppSecret),
new KeyValuePair<string, string>("grant_type","authorization_code"),
new KeyValuePair<string, string>("redirect_uri","urn:ietf:wg:oauth:2.0:oob"),
}));
var data = await auth.Content.ReadAsStringAsync();
var j = JToken.Parse(data);
var token = j.SelectToken("access_token");
var searchUrl = "https://www.googleapis.com/oauth2/v2/userinfo";
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token.ToString());
HttpResponseMessage res = await client.GetAsync(searchUrl);
string content = await res.Content.ReadAsStringAsync();
return content;
}
And add following code in App.xaml.cs file:
public static ContinuationManager ContinuationManager { get; private set; }
public App()
{
ContinuationManager = new ContinuationManager();
}
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
#if WINDOWS_PHONE_APP
ContinuationManager.MarkAsStale();
#endif
// TODO: Save application state and stop any background activity
deferral.Complete();
}
protected override void OnActivated(IActivatedEventArgs args)
{
#if WINDOWS_PHONE_APP
if (args.Kind == ActivationKind.WebAuthenticationBrokerContinuation)
{
var continuationEventArgs = args as IContinuationActivatedEventArgs;
if (continuationEventArgs != null)
{
ContinuationManager.Continue(continuationEventArgs);
ContinuationManager.MarkAsStale();
}
}
#endif
}
Don't forget to include Continuation Manager class file in your project.
You will get the user info.
I'm not an expert.
It looks like you need to request the email scope:
https://developers.google.com/+/web/api/rest/oauth#login-scopes
as well as (probably) the profile scope (same page).
If this isn't helpful, please edit your question and show more of your code (obscuring your secret API key, etc.).
I have also searched for sign in using facebook and google in WIN RT Apps and finally found solution from this link :
Web authentication broker sample
Maybe it will help you also.

Twitter with 1 hashtag in wp7 (read only integration)

Found myself a solution: Found an own solution. If you want 2 know, contact me.
Don't know to integrate twitter in windows phone app.
What do I have or need:
A Hashtag ("zesdaagsegent"), so who tweets to this hashtags, this will be shown in de windows phone app.
Only for read, you will not reply in de windows phone app, etc. just read.
I need user name of the tweeter, image avatar of the tweeter and his message of course.
This is my try code:
WebClient twitter = new WebClient();
twitter.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitter_DownloadStringCompleted);
twitter.DownloadStringAsync(new Uri("http://search.twitter.com/search.xml?q=23zesdaagsegent"));
public void twitter_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
return;
XElement xmlTweets = XElement.Parse(e.Result);
lstTwitter.ItemsSource = from tweet in xmlTweets.Descendants("status")
select new Tweet
{
ImageSource = tweet.Element("user").Element("profile_image_url").Value,
Message = tweet.Element("text").Value,
UserName = tweet.Element("user").Element("screen_name").Value
};
}
EDIT: I don't get any errors.
public void FireHashSearch()
{
//string searchQuery = string.Format(TWITTER_URL, "%23zesdaagsegent", _MaxSearchResultsCount);
Uri searchQueryUri = new Uri(URI, UriKind.Absolute);
searchTwitter = new WebClient();
searchTwitter.DownloadStringCompleted += new DownloadStringCompletedEventHandler(searchTwitter_DownloadStringCompleted);
searchTwitter.DownloadStringAsync(searchQueryUri);
}
public void searchTwitter_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
// Grab response.
string results = e.Result;
JObject o = JObject.Parse(results);
// String naam = o.GetValue("text").ToString();
JToken token = o["results"];
JArray array =(JArray)(o["results"]);
for (int i = 0; i < array.Count; i++)
{
lstTwitter.ItemsSource = ItemsTwitter;
JToken test = JObject.Parse(array[i].ToString());
// for(int i = 0; i<token.
// DataBind.
this.ItemsTwitter.Add(new Tweet()
{
Avatar = "",
Msg = (string)test.SelectToken("text"),
User = (string)test.SelectToken("from_user")
});
}
}

getting security warning in facebook authentication

I am getting security warning while using authentication in facebook app.My code is as shown with screenShot with security warning
private void imageFacebook_Tap(object sender, GestureEventArgs e)
{
FaceBookBlocker.Visibility = Visibility.Visible;
pop_up.IsOpen = true;
//Get this from the facebook
string appId = "My Facebook App Id";
var parameters = new Dictionary<string, object>();
parameters["client_id"] = appId;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
string extendedPermissions = "user_about_me,read_stream,publish_stream";
// add the 'scope' only if we have extendedPermissions.
if (!string.IsNullOrEmpty(extendedPermissions))
{
// A comma-delimited list of permissions
parameters["scope"] = extendedPermissions;
}
var oauth = new FacebookOAuthClient();
//Create the login url
var loginUrl = oauth.GetLoginUrl(parameters);
////Open the facebook login page into the browser
_webBrowser.Navigate(loginUrl);
}
I do have resolved.Check my answer here. Escape from Facebook security Warning
Also replace http: with https: in the Facebook GraphAPI.
There is going to be your code,where you connect to Facebook.Best guess would be Facebook has rolled out a security change to their API and the code being used by you has not been updated to work with the new API
Alternatively
You need to delete this bit of code
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "// connect . facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
Looks like it is in your footer?
I just hide BrowserControl if navigating to the success page
private void BrowserControl_Navigating(object sender, NavigatingEventArgs e)
{
if (e.Uri.AbsolutePath.ToString() == "/connect/login_success.html")
{
BrowserControl.Visibility = Visibility.Collapsed;
}
if (NavigatingCallback != null)
{
NavigatingCallback();
}
}

Upload image directly to twitter

I need help in uploading images directly to twitter in Windows Phone 7.
I am done with oauth flow of twitter and can also could update tweets but I have not been able to upload image to twitter using wp7?
I have worked out a solution for this, by using the Hammock.WindowsPhone.Mango library.
(TweetSharp internally uses Hammock library for oAuth and other functionalities, but I have never used TweetSharp or Twitterizer)
I have installed the latest version of Hammock from Nuget
And then the following code is used for photo upload to Twitter:
public void uploadPhoto(Stream photoStream, string photoName)
{
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = TwitterSettings.consumerKey,
ConsumerSecret = TwitterSettings.consumerKeySecret,
Token = TwitterSettings.accessToken,
TokenSecret = TwitterSettings.accessTokenSecret,
Version = "1.0a"
};
RestClient restClient = new RestClient
{
Authority = "https://upload.twitter.com",
HasElevatedPermissions = true,
Credentials = credentials,
Method = WebMethod.Post
};
RestRequest restRequest = new RestRequest
{
Path = "1/statuses/update_with_media.json"
};
restRequest.AddParameter("status", tbxNewTweet.Text);
restRequest.AddFile("media[]", photoName, photoStream, "image/jpg");
}
restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));
}
private void PostTweetRequestCallback(RestRequest request, Hammock.RestResponse response, object obj)
{
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
//Success code
}
}
Here,
photoName is the name of the image selected ( "e.OriginalFileName")
photoStream is the "e.ChosenPhoto" from the PhotoChooserTask
and the 4th parameter for .AddFile() should be taken care (I have not considered other formats while doing this sample, you have to take care in your apps)
I hope this helps!!
LINQ to Twitter supports WP7 and has a TweetWithMedia method that works like this:
private void PostButton_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(TweetTextBox.Text))
MessageBox.Show("Please enter text to tweet.");
ITwitterAuthorizer auth = SharedState.Authorizer;
if (auth == null || !auth.IsAuthorized)
{
NavigationService.Navigate(new Uri("/OAuth.xaml", UriKind.Relative));
}
else
{
var twitterCtx = new TwitterContext(auth);
var media = GetMedia();
twitterCtx.TweetWithMedia(
TweetTextBox.Text, false, StatusExtensions.NoCoordinate, StatusExtensions.NoCoordinate, null, false,
media,
updateResp => Dispatcher.BeginInvoke(() =>
{
HandleResponse(updateResp);
}));
}
}
Joe

how to update twitter status from my asp.net web page

I have created an asp.net web page and I am using twitterizer.framework.dll.
Below is my c# code.
protected void btnTwitt_Click(object sender, EventArgs e)
{
//OAuthTokens tokens = new OAuthTokens();
//tokens.AccessToken = "--REDACTED--";
//tokens.AccessTokenSecret = "--REDACTED--";
//tokens.ConsumerKey = "--REDACTED--";
//tokens.ConsumerSecret = "--REDACTED--";
/////
//TwitterResponse<TwitterUser> showUserResponse = TwitterUser.Show(tokens, "twit_er_izer");
string TwitterUserName = "My twitter username";
string TwitterPassword = "my password";
// string TwitterMessage = txtShout.Text;
if (TwitterUserName != string.Empty && TwitterPassword != string.Empty)
{
try
{
//Twitter
// TwitterAccount twitter = new TwitterAccount(TwitterUserName, TwitterPassword);
//Twitter tw
Twitter twitter = new Twitter(TwitterUserName, TwitterPassword);
string TwitterMsg = txtShout.Text;
if (txtShout.Text.Length > 120)
{
TwitterMsg = TwitterMsg.Substring(0, 130) + "... For more update logon to DailyFreeCode.com";
}
else
{
TwitterMsg = TwitterMsg + "... For more update logon to DailyFreeCode.com";
}
twitter.Status.Update(TwitterMsg);
//Twitterizer.TwitterStatus.Update(tokens,TwitterMsg);
lblTwitMsg.Text = "Your have shout successfully on http://twitter.com/" + TwitterUserName;
}
catch (Exception ex)
{
Response.Write("<b>" + ex.Message + "</b><br>" + ex.StackTrace);
}
}
}
Now, I am getting error authorization failed.
On this line
twitter.Status.Update(TwitterMsg);
Plz help me, thanks!
It appears as though you're using Twitterizer version 1.x, but trying to copy code examples from Twitterizer version 2.x. Twitter twitter = new Twitter(TwitterUserName, TwitterPassword); is a dead giveaway. 2.x no longer uses that syntax.
Twitter no longer allows access to the API by supplying username and password. The tokens ARE your username and password, in a manner of speaking.
If you use the twitterizer framework you shouldn't be passing the username/password. You need to fill:
OAuthTokens tokens = new OAuthTokens();
tokens.AccessToken = "XXX";
tokens.AccessTokenSecret = "XXX";
tokens.ConsumerKey = "XXX";
tokens.ConsumerSecret = "XXX";
you can do this by using the following three methods from the framework:
1:
public static Uri BuildAuthorizationUri(
string requestToken
)
2:
public static OAuthTokenResponse GetRequestToken(
string consumerKey,
string consumerSecret,
string callbackAddress
)
3:
OAuthTokenResponse accessToken = OAuthUtility.GetAccessToken(consumerKey, consumerSecret, requestToken, verifier);
look it up here

Categories

Resources