Upload image directly to twitter - c#

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

Related

C# Response = "WaitingForActivation"

I have an asp.net website which sends a tweet on a button click event.
I am using the TwitterApi for this and have an authenticated developer account.
This function was working from September 2018 until last month, but all of a sudden it won't send the tweets on request.
The response I get now is - "Id = 1, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}""
After searching around, this doesn't seem like a twitter error, but an async error of some kind. I have made some minor alterations to my website in this time, but I cant see anything I have changed that would cause this issue.
The code is below.
Can any one see why this error would occur?
protected void Publish_Click(object sender, EventArgs e)
{
DataAccess.Publish();
SendEmails();
SendTweet();
Response.Redirect("OtherPage.aspx");
}
public static void SendTweet()
{
string text = DataAccess.GetText();
var twitter = new TwitterApi();
var response = twitter.Tweet(text);
}
public TwitterApi()
{
this.consumerKey = "XXX";
this.consumerKeySecret = "XXX";
this.accessToken = "XXX";
this.accessTokenSecret = "XXX";
sigHasher = new HMACSHA1(new ASCIIEncoding().GetBytes(string.Format("{0}&{1}", consumerKeySecret, accessTokenSecret)));
}
public Task<string> Tweet(string text)
{
var data = new Dictionary<string, string> {
{ "status", text },
{ "trim_user", "1" }
};
return SendRequest("statuses/update.json", data);
}
Task<string> SendRequest(string url, Dictionary<string, string> data)
{
var fullUrl = TwitterApiBaseUrl + url;
// Timestamps are in seconds since 1/1/1970.
var timestamp = (int)((DateTime.UtcNow - epochUtc).TotalSeconds);
// Add all the OAuth headers we'll need to use when constructing the hash.
data.Add("oauth_consumer_key", consumerKey);
data.Add("oauth_signature_method", "HMAC-SHA1");
data.Add("oauth_timestamp", timestamp.ToString());
data.Add("oauth_nonce", "a"); // Required, but Twitter doesn't appear to use it, so "a" will do.
data.Add("oauth_token", accessToken);
data.Add("oauth_version", "1.0");
// Generate the OAuth signature and add it to our payload.
data.Add("oauth_signature", GenerateSignature(fullUrl, data));
// Build the OAuth HTTP Header from the data.
string oAuthHeader = GenerateOAuthHeader(data);
// Build the form data (exclude OAuth stuff that's already in the header).
var formData = new FormUrlEncodedContent(data.Where(kvp => !kvp.Key.StartsWith("oauth_")));
return SendRequest(fullUrl, oAuthHeader, formData);
}
async Task<string> SendRequest(string fullUrl, string oAuthHeader, FormUrlEncodedContent formData)
{
using (var http = new HttpClient())
{
http.DefaultRequestHeaders.Add("Authorization", oAuthHeader);
var httpResp = await http.PostAsync(fullUrl, formData);
var respBody = httpResp.ToString();
return respBody;
}
}

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 Integration In windows Phone 7

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..!!

Unable Post tweet From C# Aaplication

i'm using oauth and twitterizer in my C# apps, and after trying for several times. and it won't get any exception, error. but it's doesn't want to post it to twitter.
here is my code
protected void Page_Load(object sender, EventArgs e)
{
BLTgUser objBLTgUser = new BLTgUser();
if (!objBLTgUser.IsLogin) objBLTgUser.GoToLoginPage(HttpContext.Current.Request.Url.AbsoluteUri);
m_strIdGods = objBLTgUser.IdGods;
BLGodsProfile objGods = new BLGodsProfile();
tbmgodsprofile objGodsProfile = objGods.GetGodsByIdGods(m_strIdGods);
string reqToken = Request.QueryString["oauth_token"].ToString();
string pin = Request.QueryString["oauth_verifier"].ToString();
var oauth_consumerKey = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerKey"];
var oauth_consumerSecret = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerSecret"];
var tokens = OAuthUtility.GetAccessToken(
oauth_consumerKey,
oauth_consumerSecret,
reqToken,
pin);
string accessToken = tokens.Token;
string accessTokenSecret = tokens.TokenSecret;
objGodsProfile.twittertoken = accessToken;
objGodsProfile.twitterpin = accessTokenSecret;
objGodsProfile.twitterstatus = "1";
objGods.UpdateGodsProfile(objGodsProfile);
}
i'm trying store the token and tokensecret to Database, it's for the next uses.
string v_str = "";
BLEnumHelper m_BLEnumHelper = new BLEnumHelper();
BLGodsProfile userprofile = new BLGodsProfile();
tbmgodsprofile godsAccessToken = userprofile.GetGodsByIdGods(m_strIdGods);
string reqToken = godsAccessToken.twittertoken;
string reqTokenAccess = godsAccessToken.twitterpin;
var oauth_consumerKey = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerKey"];
var oauth_consumerSecret = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerSecret"];
OAuthTokens accesstoken = new OAuthTokens()
{
AccessToken = reqToken,
AccessTokenSecret = reqTokenAccess ,
ConsumerKey = oauth_consumerKey,
ConsumerSecret = oauth_consumerSecret
};
TwitterResponse<TwitterStatus> response = TwitterStatus.Update(accesstoken,p_strMessage);
if (response.Result == RequestResult.Success)
{
Response.Write("we did it!");
}
else
{
Response.Write("it's all bad.");
}
and after the 2nd code be called, it wont' post to twitter.
Twitterizer is no longer maintained.
https://github.com/Twitterizer/Twitterizer/blob/develop/README.mediawiki
Twitterizer not supporting Twitter's new API version 1.1, you can't use it for development.
As an alternative, I recommend CoreTweet for you.

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();
}
}

Categories

Resources