Get retweets of a tweet in C# oAuthTwitterWrapper - c#

My goal is to get all the retweet IDs of a specific tweet. I tried to use oAuthTwitterWrapper for C# twitter authentication and tried changing the code, but without any success. I am getting Forbidden message from twitter when I change the searchFormat to suit my requirement.
Someone please help!
oAuthTwitterWrapper Wrapper - https://github.com/andyhutch77/oAuthTwitterWrapper
Stack Exchange Link - Authenticate and request a user's timeline with Twitter API 1.1 oAuth
Thanks in advance..

Ok, I think this is how you would do this manually to begin with.
I have not tested it so there may be some typos, let me know and I will update it the answer accordingly.
This makes a call to the api specified here:
https://dev.twitter.com/docs/api/1.1/get/statuses/retweets/%3Aid
// You need to set your own keys and tweet id
var oAuthConsumerKey = "superSecretKey";
var oAuthConsumerSecret = "superSecretSecret";
var oAuthUrl = "https://api.twitter.com/oauth2/token";
var tweetId = "21947795900469248";
// Do the Authenticate
var authHeaderFormat = "Basic {0}";
var authHeader = string.Format(authHeaderFormat,
Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" +
Uri.EscapeDataString((oAuthConsumerSecret)))
));
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);
}
}
// Get the retweets by Id
var retweetFormat = "https://api.twitter.com/1.1/statuses/retweets/{0}.json";
var retweetsUrl = string.Format(retweetFormat, tweetId);
HttpWebRequest retweetRequest = (HttpWebRequest)WebRequest.Create(retweetsUrl);
var retweetHeaderFormat = "{0} {1}";
timeLineRequest.Headers.Add("Authorization", string.Format(retweetHeaderFormat, twitAuthResponse.token_type,
twitAuthResponse.access_token));
retweetRequest.Method = "Get";
WebResponse retweetResponse = timeLineRequest.GetResponse();
var retweetJson = string.Empty;
using (retweetResponse)
{
using (var reader = new StreamReader(retweetResponse.GetResponseStream()))
{
retweetJson = reader.ReadToEnd();
}
}
//parse the json from retweetJson to read the returned id's
public class TwitAuthenticateResponse {
public string token_type { get; set; }
public string access_token { get; set; }
}
If this works and you have time please submit a pull request via GitHub and I will include it in oauthtwitterwrapper.

Related

How to Return the HTTP Call Response in C#

I am trying to return the response of productRating in this HTTP call. I have tried several ways but haven't been successful. Any idea? The response is a json with an object that I want to get access to the streamInfo>avgRatings>_overall
public double GetRatings(string productId)
{
const string URL = "https://comments.au1.gigya.com/comments.getStreamInfo";
var apiKey = "3_rktwTlLYzPlqkzS62-OxNjRDx8jYs-kV40k822YlHfEx5VCu93fpUo8JtaKDm_i-";
var categoryId = "product-ratings";
var urlParams = "?apiKey=" + apiKey + "&categoryID=" + categoryId + "&streamID=" + productId + "";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = JsonConvert.DeserializeObject(client.GetAsync(urlParams).Result.Content.ReadAsStringAsync().Result);
var productrating = (response["streamInfo"]["avgRatings"]["_overall"]);
return;
}
GetRatings Erroe: not all code paths return a value.
Productrating Error:can not apply indexing with [] to an expression of type HttpResponseMessage
return Error: an object of a type convertable to double is required
ApiCall has to return something. Looking at the example below.
#functions {
public static string ApiCall()
{
return "Hello World!";
}
}
#{
var ratings = ApiCall();
}
#if (ratings != null)
{
<div class="gig-rating-stars" content=#ratings></div>
}
I am using this function for POST API Call and it returns response string and if you want to add security features you can send it in JObject because its the secure channel to send Jobject as a parameter on URL
## Code Start ##
protected string RemoteApiCallPOST(JObject elements, string url)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
// JObject jsonResult = new JObject();
string id;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(elements);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
id = (streamReader.ReadToEnd()).ToString();
return id;
}
}
catch (Exception EX)
{
return "";
}
}
Code End
The only change I needed to do is changing "var" to "dynamic" in :
dynamic response = JsonConvert.DeserializeObject(client.GetAsync(urlParams).Result.Content.ReadAsStringAsync().Result);

Google reCaptcha in Web API 2 c#

I have an ASP.NET Web API 2 Project. I am trying to read Google Captcha from the form.
I tried this Code:
public string Post(FoundingRequest model)
{
var response = Request["g-recaptcha-response"];
string secretKey = "my key";
var client = new WebClient();
var result = client.DownloadString(
$"https://www.google.com/recaptcha/api/siteverify?secret={secretKey}&response={response}");
var obj = JObject.Parse(result);
model.Captcha = (bool)obj.SelectToken("success");
....
}
but I am receiving an Error on the first line:
Cannot apply indexing with [] to an expression of type
'HttpRequestMessage'
why? and how to solve it? thank you
That method's body for me works fine:
const string secretKey = "YOUR KEY";
string responseFromServer = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + response);
using (WebResponse resp = req.GetResponse())
using (Stream dataStream = resp.GetResponseStream())
{
if (dataStream != null)
{
using (StreamReader reader = new StreamReader(dataStream))
{
// Read the content.
responseFromServer = reader.ReadToEnd();
}
}
}
dynamic jsonResponse = new JavaScriptSerializer().DeserializeObject(responseFromServer);
return jsonResponse == null || bool.Parse(jsonResponse["success"].ToString());
Update
Regarding the comment, it can be checked on the client side
var response = window.grecaptcha.getResponse()
And then pass this variable to Web API
This is part of my client script:
if (typeof window.grecaptcha != 'undefined') {
var capResponse = window.grecaptcha.getResponse();
if (!capResponse || capResponse.length === 0) {
user.isCaptchaPassed = false;
//alert("Captcha not Passed");
return false;
}
user.gReCaptcha = capResponse;
}
"user" is JS object created before, which passed through JS to server. (AJAX call)
Here's how I did it. I don't use the ChallangeTs so I didn't bother
trying to figure out why it wasn't converting to DateTime properly.
Maybe someone else has that solved.
public class ReCaptchaResponse
{
public bool Success;
public string ChallengeTs;
public string Hostname;
public object[] ErrorCodes;
}
[HttpPost]
[Route("captcha")]
public bool Captcha([FromBody] string token)
{
bool isHuman = true;
try
{
string secretKey = ConfigurationManager.AppSettings["reCaptchaPrivateKey"];
Uri uri = new Uri("https://www.google.com/recaptcha/api/siteverify" +
$"?secret={secretKey}&response={token}");
HttpWebRequest request = WebRequest.CreateHttp(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = 0;
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string result = streamReader.ReadToEnd();
ReCaptchaResponse reCaptchaResponse = JsonConvert.DeserializeObject<ReCaptchaResponse>(result);
isHuman = reCaptchaResponse.Success;
}
catch (Exception ex)
{
Trace.WriteLine("reCaptcha error: " + ex);
}
return isHuman;
}
I found the answer, I created a hidden input with a certain name and updated its value on Captcha call back. Code:
<input type="hidden" value="" id="recaptcha" name="recaptcha" />
<div class="g-recaptcha" data-callback="imNotARobot" data-sitekey="key"></div>
and the Javascript is:
<script type="text/javascript">
var imNotARobot = function () {
$("#recaptcha").val(grecaptcha.getResponse());
};
</script>
server side:
public string Recaptcha { get; set; }
and the model binder does all the work.
I assume this request is coming from a form, change this:
var response = Request["g-recaptcha-response"];
To this:
var response = Request.Form["g-Recaptcha-Response"];
Also Change this:
var result = client.DownloadString($"https://www.google.com/recaptcha/api/siteverify?secret={secretKey}&response={response}");
To this:
var result = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response));

How to access users calendar list and events from google api using access token and refresh token

I already have obtained users access token from google api using oAuth2. Now i want to use this token to get user events/calendars. I have tried following code but it is not working.
Can anyone here help me with this please.
Thanks
var urlBuilder = new System.Text.StringBuilder();
urlBuilder.Append("https://");
urlBuilder.Append("www.googleapis.com");
urlBuilder.Append("/calendar/v3/users/me/calendarList");
urlBuilder.Append("?minAccessRole=reader");
var httpWebRequest = HttpWebRequest.Create(urlBuilder.ToString()) as HttpWebRequest;
httpWebRequest.CookieContainer = new CookieContainer();
httpWebRequest.Headers["Authorization"] string.Format("Bearer {0}", data.access_token);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream eventResponseStream = response.GetResponseStream();
StreamReader eventResponseStreamReader = new StreamReader(responseStream);
string eventsStr = eventResponseStreamReader.ReadToEnd();
I have found solution using Google.Apis.Calendar.v3, i am posting it here so may help someone else. Following is the code to get the events list when you have refresh token of a user:
First get new access token using the refresh token:
string postString = "client_id=yourclientid";
postString += "&client_secret=youclientsecret&refresh_token=userrefreshtoken";
postString += "&grant_type=refresh_token";
string url = "https://www.googleapis.com/oauth2/v4/token";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(postString);
Stream os = null;
request.ContentLength = bytes.Length;
os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
GoogleToken token = new GoogleToken();
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
string result = responseStreamReader.ReadToEnd();
JavaScriptSerializer serializer = new JavaScriptSerializer();
token = serializer.Deserialize<GoogleToken>(result);
Then use the toke and refresh token to create credentials.
var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = yourclientid,
ClientSecret = yourclientsecret
},
Scopes = new[] { CalendarService.Scope.Calendar }
});
var credential = new UserCredential(flow, Environment.UserName, new TokenResponse
{
AccessToken = token.access_token,
RefreshToken = userrefreshtoke
});
CalendarService service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "application name",
});
var list = service.CalendarList.List().Execute().Items;
foreach (var c in list)
{
var events = service.Events.List(c.Id).Execute().Items.Where(i => i.Start.DateTime >= DateTime.Now).ToList();
foreach (var e in events)
{
}
}
GoogleToken class:
public class GoogleToken
{
public string access_token { get; set; }
public string token_type { get; set; }
public string expires_in { get; set; }
}
According to the .NET Quickstart sample provided by Google you'll be needing to download a client_secret.json which is part of the authentication process. Check the whole process in the link.
Here' a snippet for feching events in .NET:
// List events.
Events events = request.Execute();
Console.WriteLine("Upcoming events:");
if (events.Items != null && events.Items.Count > 0)
{
foreach (var eventItem in events.Items)
{
string when = eventItem.Start.DateTime.ToString();
if (String.IsNullOrEmpty(when))
{
when = eventItem.Start.Date;
}
Console.WriteLine("{0} ({1})", eventItem.Summary, when);
}
}
else
{
Console.WriteLine("No upcoming events found.");
}
Console.Read();
You can also read more of oAuth related guides in .NET here.
For more info on retrieving Calendar lists and events, read this guide.

Box API Create Shared link

I am trying to upload some documents to Box and create and retrieve a shared link for each of them.
This is the code I am using for it, but I always retrieve 403:access_denied_insufficient_permissions.
Any idea of why this is happening?
Hope you can help me! Thanks.
// CREATE THE FILE
BoxFileRequest req = new BoxFileRequest
{
Name = zipFile.Name,
Parent = new BoxRequestEntity { Id = newFolder.Id}
};
BoxFile uploadedFile = client.FilesManager.UploadAsync(req, stream).Result;
//REQUEST SHARED LINK
BoxSharedLinkRequest sharedLinkReq = new BoxSharedLinkRequest()
{
Access = BoxSharedLinkAccessType.open,
Permissions = new BoxPermissionsRequest
{
Download = BoxPermissionType.Open,
Preview = BoxPermissionType.Open,
}
};
BoxFile fileLink = fileManager.CreateSharedLinkAsync(uploadedFile.Id, sharedLinkReq).Result;
you need to give the access token and url. I have use the Following code and in JSON Format you will get the Response. For more reference check the box API document
HttpWebRequest httpWReq = HttpWebRequest)WebRequest.Create("https://api.box.com/2.0/folders/" + FolderID);
ASCIIEncoding encoding = new ASCIIEncoding();
string putData = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] data = encoding.GetBytes(putData);
httpWReq.Method = "PUT";
httpWReq.Headers.Add("Authorization", "Bearer ");
httpWReq.ContentType = "application/json";
httpWReq.ContentLength = data.Length;
Use the httpwebrequest PUT method after this.
Mark it as Answer if its helpful.
It looks as if you are using the 3rd party BoxSync V2 API object. If you would like to just code to the API directly I had a similar issue that you are having. If you view this post you will see the answer. Here is the code I use and it works.
string uri = String.Format(UriFiles, fileId);
string response = string.Empty;
string body = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] postArray = Encoding.ASCII.GetBytes(body);
try
{
using (var client = new WebClient())
{
client.Headers.Add("Authorization: Bearer " + token);
client.Headers.Add("Content-Type", "application/json");
response = client.UploadString(uri, "PUT", body);
}
}
catch (Exception ex)
{
return null;
}
return response;

Unable to get Refresh Token in Google Calendar Version 3

I am developing my for Google Integration in ASP.NET. I am tring to create a service using access token and refresh token. But i am unable to get the refresh token as i am just getting Access Token, Token Type and Expires in. Please check the below code for this.
private String ExchangeCodeWithAccessAndRefreshToken()
{
string Url = "https://accounts.google.com/o/oauth2/token";
string grant_type = "authorization_code";
string redirect_uri_encode = UrlEncodeForGoogle(Convert.ToString(Session["URL"]));
string data = "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}";
string Code = Request.QueryString["Code"];
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
String ClientID = ConfigurationManager.AppSettings["clientID"].ToString();
String ClientSecret = ConfigurationManager.AppSettings["clientSecret"].ToString();
string param = string.Format(data, Code, ClientID, ClientSecret, redirect_uri_encode, grant_type);
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
var jsonSerializer = new JavaScriptSerializer();
var tokenData = jsonSerializer.Deserialize<GoogleTokenModel>(result);
return tokenData.Access_Token;
}
Try setting access_type=offline in your URL:
string data = "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}&access_type=offline";

Categories

Resources