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.0/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);
}
But here i can not get the user information. Please help me to get the user information.
Thanks in advance.
Now i try like this:
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,
Version = "1.1",
};
var restClient = new RestClient
{
Authority = "https://api.twitter.com",
HasElevatedPermissions = true
};
var restRequest = new RestRequest
{
Credentials = credentials,
Path = string.Format("/1.1/users/show.json?screen_name={0}",///1.1/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);
});
}
But I am getting this error:
{"errors":[{"message":"Bad Authentication data","code":215}]}
Please help me how to resolve my problem?

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.Cloud.Dialogflow.V2 Detect Intent not working

I am running this code below but get no answer from the API at the DetectIntent() line. I also tested the DetectIntentsAsync() method instead, but have the same problem.
I also call the bot from nodejs fulfillment and all responses were OK.
Code is below:
private void Button_Click(object sender, RoutedEventArgs e)
{
messageList.Items.Add("User: " + messageText.Text);
try
{
var query = new QueryInput
{
Text = new TextInput
{
Text = messageText.Text,
LanguageCode = "en-us"
}
};
var sessionId = Guid.NewGuid().ToString();
var agent = "...";
var parameters = new JsonCredentialParameters
{
Type = JsonCredentialParameters.ServiceAccountCredentialType,
ClientEmail = "...",
PrivateKey = "..."
};
string json = JsonConvert.SerializeObject(parameters);
var creds = GoogleCredential.FromJson(json);
var channel = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host, creds.ToChannelCredentials());
var client = SessionsClient.Create(channel);
var sessionName = new SessionName(agent, sessionId);
var dialogFlow = client.DetectIntent(
sessionName,
query
);
channel.ShutdownAsync();
messageList.Items.Add("Bot: " + dialogFlow);
}
catch (Exception ex)
{
messageList.Items.Add("error: " + ex.Message);
}
}

How to use cursors to iterate through the result set of GET followers/list in Twitter API using c#?

I have been trying a way to get the data in the next page of the result set of GET followers/list API call. I can get the default data set with the data of first 20 followers and not the others. To get the data of other followers i have to access the next page using the next_cursor but it's not working. I tried using the pseudo-code mentioned in this link. https://dev.twitter.com/docs/misc/cursoring
Is it a must to use this(this is mentioned in the dev. site):
var api-path = "https://api.twitter.com/1.1/endpoint.json?screen_name=targetUser"
Because I have been using the resource URL as,
var resource_url = "https://api.twitter.com/1.1/followers/list.json";
and I tried appending the next_cursor to the same resource URL.
var url_with_cursor = resource_url + "&cursor=" + 1463101490306580067;
and then created the request.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url_with_cursor);
but I'm getting an exception in this line when getting the response.
WebResponse response = request.GetResponse();
The error I'm getting is
The Remote Server returned an Error 401 Unauthorized
Can someone tell the exact way to do cursor-ing, or the exact way to include the cursor in the request. I'm using a asp.net C# web application.
Here's my code, The oauth_token, oauth_token_secret, oauth_consumer_key, oauth_consumer_secret, oauth_version and oauth_signature_method are defined in my application
var resource_url = "https://api.twitter.com/1.1/followers/list.json";
var cursor = "-1";
do
{
var url_with_cursor = resource_url + "&cursor=" + cursor;
// unique request details
var oauth_nonce = Convert.ToBase64String(
new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var timeSpan = DateTime.UtcNow
- new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
// create oauth signature
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}";
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version
//,Uri.EscapeDataString(status)
);
baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));
var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
"&", Uri.EscapeDataString(oauth_token_secret));
string oauth_signature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
{
oauth_signature = Convert.ToBase64String(
hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}
// create the request header
var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
"oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
"oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
"oauth_version=\"{6}\"";
var authHeader = string.Format(headerFormat,
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_consumer_key),
Uri.EscapeDataString(oauth_token),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_version)
);
// make the request
ServicePointManager.Expect100Continue = false;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url_with_cursor);
request.Headers.Add("Authorization", authHeader);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
WebResponse response = request.GetResponse();
string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
JObject j = JObject.Parse(result);
JArray data = (JArray)j["users"];
cursor = (String)j["next_cursor_str"];
} while (!cursor.Equals("0"));
Thanks.
Tweetinvi would make it somewhat easier for you.
Please visit https://github.com/linvi/tweetinvi/wiki/Get-All-Followers-Code to have an idea on how to do it including RateLimit handling.
Without considering the RateLimits, you could simply use the following code.
long nextCursor = -1;
do
{
var query = string.Format("https://api.twitter.com/1.1/followers/ids.json?screen_name={0}", username);
var results = TwitterAccessor.ExecuteCursorGETCursorQueryResult<IIdsCursorQueryResultDTO>(query, cursor: cursor).ToArray();
if (results.Any())
{
nextCursor = results.Last().NextCursor;
}
else
{
nextCursor = -1;
}
}
while (nextCursor != -1 && nextCursor != 0);
you should make a different call to authenticate, by an authorization request. Once that has been granted, you can call the webresponse with the cursor. See my sample code below (Take special note to the StartCreateCall method, where the authentication is done. The data from Twitter is then retrieved by the CallData method):
public partial class twitter_followers : System.Web.UI.Page
{
public string strTwiterFollowers { get; set; }
private List<TwiterFollowers> listFollowers = new List<TwiterFollowers>();
private string screen_name = string.Empty;
// oauth application keys
private string oauth_consumer_key = string.Empty;
private string oauth_consumer_secret = string.Empty;
// oauth implementation details
private string resource_urlFormat = "https://api.twitter.com/1.1/followers/list.json?screen_name={0}&cursor={1}";
// unique request details
private string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
protected void Page_Load(object sender, EventArgs e)
{
//just get your request parameters from the config file.
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings[GetVariableName(() => screen_name)])) {
screen_name = ConfigurationManager.AppSettings[GetVariableName(() => screen_name)];
}
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings[GetVariableName(() => oauth_consumer_key)]))
{
oauth_consumer_key = ConfigurationManager.AppSettings[GetVariableName(() => oauth_consumer_key)];
}
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings[GetVariableName(() => oauth_consumer_secret)]))
{
oauth_consumer_secret = ConfigurationManager.AppSettings[GetVariableName(() => oauth_consumer_secret)];
}
StartCreateCall();
}
// Do the authenticate by an authorization request
private void StartCreateCall() {
// You need to set your own keys and screen name
var oAuthUrl = "https://api.twitter.com/oauth2/token";
// Do the Authenticate
var authHeaderFormat = "Basic {0}";
var authHeader = string.Format(authHeaderFormat,
Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oauth_consumer_key) + ":" +
Uri.EscapeDataString((oauth_consumer_secret)))
));
var postBody = "grant_type=client_credentials";
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(oAuthUrl);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (Stream stream = authRequest.GetRequestStream())
{
byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
stream.Write(content, 0, content.Length);
}
authRequest.Headers.Add("Accept-Encoding", "gzip");
WebResponse authResponse = authRequest.GetResponse();
// deserialize into an object
TwitAuthenticateResponse twitAuthResponse;
using (authResponse)
{
using (var reader = new StreamReader(authResponse.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objectText = reader.ReadToEnd();
twitAuthResponse = JsonConvert.DeserializeObject<TwitAuthenticateResponse>(objectText);
}
}
//now we have been granted access and got a token type with authorization token from Twitter
//in the form of a TwitAuthenticateResponse object, we can retrieve the data recursively with a cursor
CallData(twitAuthResponse, authHeader, cursor);
int totalFollowers = listFollowers.Count;
lblTotalFollowers.Text = screen_name + " has " + listFollowers.Count + " Followers";
Random objRnd = new Random();
List<TwiterFollowers> randomFollowers = listFollowers.OrderBy(item => objRnd.Next()).ToList<TwiterFollowers>();
foreach (TwiterFollowers tw in randomFollowers)
{
strTwiterFollowers = strTwiterFollowers + "<li><a target='_blank' title='" + tw.ScreenName + "' href=https://twitter.com/" + tw.ScreenName + "><img src='" + tw.ProfileImage + "'/><span>" + tw.ScreenName + "</span></a></li>";
}
}
//Retrieve the data from Twitter recursively with a cursor
private void CallData(TwitAuthenticateResponse twitAuthResponse, string authHeader, string cursor)
{
try {
JObject j = GetJSonObject(twitAuthResponse, authHeader, cursor);
JArray data = (JArray)j["users"];
if (data != null)
{
foreach (var item in data)
{
TwiterFollowers objTwiterFollowers = new TwiterFollowers();
objTwiterFollowers.ScreenName = item["screen_name"].ToString().Replace("\"", "");
objTwiterFollowers.ProfileImage = item["profile_image_url"].ToString().Replace("\"", "");
objTwiterFollowers.UserId = item["id"].ToString().Replace("\"", "");
listFollowers.Add(objTwiterFollowers);
}
JValue next_cursor = (JValue)j["next_cursor"];
if (long.Parse(next_cursor.Value.ToString()) > 0)
{
//Get the following data from Twitter with the next cursor
CallData(twitAuthResponse, authHeader, next_cursor.Value.ToString());
}
}
} catch (Exception ex)
{
//do nothing
}
}
private JObject GetJSonObject(TwitAuthenticateResponse twitAuthResponse, string authHeader, string cursor)
{
string resource_url = string.Format(resource_urlFormat, screen_name, cursor);
if (string.IsNullOrEmpty(cursor))
{
resource_url = resource_url.Substring(0, resource_url.IndexOf("&cursor"));
}
HttpWebRequest fRequest = (HttpWebRequest)WebRequest.Create(resource_url);
var timelineHeaderFormat = "{0} {1}";
fRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, twitAuthResponse.token_type, twitAuthResponse.access_token));
fRequest.Method = "Get";
WebResponse response = fRequest.GetResponse();
string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
return JObject.Parse(result);
}
private string GetVariableName<T>(Expression<Func<T>> expr)
{
var body = (MemberExpression)expr.Body;
return body.Member.Name;
}
private class TwitAuthenticateResponse
{
public string token_type { get; set; }
public string access_token { get; set; }
}
private class TwiterFollowers
{
public string ScreenName { get; set; }
public string ProfileImage { get; set; }
public string UserId { get; set; }
}
}
You are getting "401 Unauthorized"
Did you check you are setting everything right?
Credentials? Check both queries on fiddler.

Get request after a put or a post shows previous data instead of modified data?

The problem is that I do a GET request in the constructor(I call upon the method so every time that you enter the page the data is newly get from the database) and it gets the data from the database in a proper way. But after I modify the data and go back to page the data is still unmodified. The data changes in the database so the modify works but the GET request seems to get old data that is no longer in the database. How is this happening and how can I fix this? Thanks in advance!
public void getUserData()
{
RestClient client = new RestClient("http://localhost:8080/GigShare/webresources");
var request = new RestRequest("/user/{username}", Method.GET);
request.AddUrlSegment("username", "" + user.userName);
client.ExecuteAsync(request, response =>
{
getYourCarpools();
System.Diagnostics.Debug.WriteLine(modifyName.Text);
userget = (User) JsonConvert.DeserializeObject<User>(response.Content);
System.Diagnostics.Debug.WriteLine("GET");
System.Diagnostics.Debug.WriteLine(userget.name);
modifyName.Text = userget.Name;
modifySurname.Text = userget.surName;
modifyUsername.Text = userget.userName;
modifyTown.Text = userget.town;
modifyStreetName.Text = userget.streetName;
modifyHomenumber.Text = userget.homeNumber;
modifyProvince.Text = userget.province;
modifyEmail.Text = userget.email;
modifyCarBrand.Text = userget.car.brand;
modifyFuelType.Text = userget.car.fuelType;
modifySeats.Text = "" + userget.car.seats;
modifyavarageConsumption.Text = "" + userget.car.averageConsumption;
getCarData();
});
}
private void btnModifyCreateAccount_Click(object sender, RoutedEventArgs e)
{
User outputUser = dataFromUser();
var client = new RestClient()
{
BaseUrl = "http://localhost:8080/GigShare/webresources",
Authenticator = new HttpBasicAuthenticator("" + user.userId, user.password)
};
var request = new RestRequest("/user/id/{id}", Method.PUT);
request.AddUrlSegment("id", "" + user.userId);
request.RequestFormat = DataFormat.Json;
request.AddBody(outputUser);
client.ExecuteAsync(request, response =>
{
if (response.StatusCode == HttpStatusCode.NoContent)
{
// getUserData();
// NavigationService.Navigate(new Uri("/Views/NewlyAdded.xaml", UriKind.Relative));
System.Diagnostics.Debug.WriteLine("PUT");
}
else
{
System.Diagnostics.Debug.WriteLine("failmode");
}
});
}

Facebook C# SDK get user accessToken

I having problems with getting the accessToken from the results of my login to facebook.
In the Page_load, my url doesn't get parsed correctly.
GenerateLoginUrl method is working without errors and i can see the accessToken in the QueryString.
I have tried get it from the but that it's not working either.
protected void Page_Load(object sender, EventArgs e)
{
var fb = new FacebookClient();
FacebookOAuthResult result;
if (fb.TryParseOAuthCallbackUrl(Request.Url, out result))
{
if (result.IsSuccess)
{
// result clicked authorized
var accessToken = result.AccessToken;
Label1.Text = accessToken.ToString();
}
else
{
// user clicked cancelled and didn't authorize the app
var error = result.ErrorDescription;
Label1.Text = error;
}
}
else
{
//This is were it always goes
Label1.Text = "not valid facebook url";
}
}
private Uri GenerateLoginUrl(string appId, string extendedPermissions)
{
try
{
dynamic parameters = new ExpandoObject();
parameters.client_id = appId;
parameters.redirect_uri = "local iis ip";
// The requested response: an access token (token), an authorization code (code), or both (code token).
parameters.response_type = "token";
// list of additional display modes can be found at http://developers.facebook.com/docs/reference/dialogs/#display
parameters.display = "popup";
// add the 'scope' parameter only if we have extendedPermissions.
if (!string.IsNullOrWhiteSpace(extendedPermissions))
parameters.scope = extendedPermissions;
// generate the login url
var fb = new FacebookClient();
var url = fb.GetLoginUrl(parameters);
return url;
}
catch (FacebookOAuthException fbex)
{
Label1.Text = fbex.Message;
return null;
}
catch (Exception ex)
{
Label1.Text = ex.Message;
return null;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string AppId = ConfigurationManager.AppSettings["apiKey"];
string ExtendedPermissions = ConfigurationManager.AppSettings["ExtendedPermissions"];
var url = GenerateLoginUrl(AppId, ExtendedPermissions);
Response.Redirect(url.AbsoluteUri, false);
}
Thanks for your help.
Update:
In the Request.Url the url always is:
http://localhost:23560/Appname/default.aspx
but i can se the real url in the browser and it is:
http://localhost:23560/Appname/#access_token=0000000000&expires_in=3821
So way can't asp.net read the url correctly?
I found the answare and it is:
You have to get the code not token, the code is gonna show in querystring accesstoken gets stripped.
parameters.response_type = "token";
exchange
parameters.response_type = "code";
And then exchange to code to token
dynamic token = fb.Get("oauth/access_token", new
{
client_id = "appid",
client_secret = "appsecret",
redirect_uri = url,
code = Request.QueryString["code"]
});
var accessToken = token.access_token;

Text doesn't get posted on Twitter

I am trying to implement a functionality to post tweets on twitter in asp.Net and C#. I have got access token, consumer key, callback url etc. I have two buttons "autheticate" and "Send" to authenticate and send tweets respectively.
I am using Twitterizer2 dll for all this. Authenticate and Send buttons' click do not give any error but also do not post anything on twitter. Is there anything I need to add or change? Kindly help.
protected void btnSendTwitterMsg_Click(object sender, EventArgs e)
{
OAuthTokens accessToken = new OAuthTokens();
accessToken.ConsumerKey = "XXXXXXXXXXXXXXXXXXXXXXXX";
accessToken.ConsumerSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXX";
accessToken.AccessToken = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
accessToken.AccessTokenSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
TwitterStatus.Update(accessToken, "Hello World!!");
}
protected void btnAuthenticate_Click(object sender, EventArgs e)
{
var consumerKey = "XXXXXXXXXXXXXXXXXXXX";
var consumerSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXX";
var callBackUrl = "my call back url";
if (Request.QueryString["oauth_token"] == null)
{
OAuthTokenResponse RequestToken = OAuthUtility.GetRequestToken(consumerKey, consumerSecret, callBackUrl);
Response.Redirect("http://twitter.com/oauth/authorize?oauth_token=" + RequestToken.Token);
}
else
{
OAuthTokenResponse RequestToken = OAuthUtility.GetRequestToken(consumerKey, consumerSecret, callBackUrl);
string oathToken = Request.QueryString["oauth_token"].ToString();
var accessToken = OAuthUtility.GetAccessToken(consumerKey, consumerSecret, RequestToken.Token, RequestToken.VerificationString);
this.lblScreenName.Text = "Hello " + accessToken.ScreenName;
}
}
Thanks
Rakesh
Try Spring.net Twitter, there is an ASP.NET example that does exactly what you want:
http://springframework.net/social-twitter/

Categories