How to mimic this using RESTSHARP C# restclient instead of using httpclient? - c#

I am using httpclient to invoke a endpoint , this is working fine for me. But i need to invoke the endpoint using the restsharp restclient object. How can i do that? Here is the code that works for me using the http client postasync.
//Input Parameters and request headers
string userID = "testuser";
string memberId = "001";
string baseURL = "https://www.test.com";
string urlParameters ="TestServices/GetAll/{0}/{1}/{2}/{3}/{4}/{5}";
string contentType = "application/json";
string role = "USER";
string Caller = "PREVIEW";
string ticks = DateTime.Now.Ticks.ToString();
string systemId = "613e70b3-e3ec-4205-bcd6-094d6a9f7a41";
string encryptedToken = “XXXXXXXXXXXXXXXXXXXX”
string sessionID = "8303d34a-5c8a-4984-9bf9-4ba39be21352";
//data to be send as stringcontent
string postData = "{\"TheContentAreas\":[{\"ControlTypeID\":\"230c5669-aa0d-41bc-9069-559b5e7d0ece\",\"PlaceholderID\":\"a16a471e-9416-43fc-8ceb-fddb97509e0c\"}]}";
string response = string.Empty;
//call the end point
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseURL);
client.DefaultRequestHeaders.Add("Authorization", "XXXXXXXXXXXXXXXXXXXXXXX");
client.DefaultRequestHeaders.Add("Session", sessionID);
client.DefaultRequestHeaders.Add("EncryptedKey", encryptedToken);
try
{
HttpResponseMessage resp = client
.PostAsync(string.Format(urlParameters, role, systemId, Caller, ticks, userID, memberId),
new StringContent(postData, System.Text.Encoding.UTF8, "application/json")).Result;
if (resp.IsSuccessStatusCode)
{
response = resp.Content.ReadAsStringAsync().Result;
}
}

I spent some time working on it, here is my solution.
I created a generic service invoker class and called it from my main class.
//Main class calling the service invoker
try
{
var _restMethodInvoker = new RestEndPointInvoker();
var headers = new Dictionary<string, string>
{
{ "Authorization", "xxx" },
{ "Session", "xxx" } ,
{ "EncryptedKey", "xxx"}
};
var inputParameters = new Dictionary<string, string>
{
{ "Role", "MEMBER" },
{ "SystemID", "xxx" } ,
{ "Caller", "PREVIEW" } ,
{ "Ticks", "1234" } ,
{ "UserID", "TestUser" } ,
{ "MemberId", "TestMEmber" }
var request1 = new RestClientRequest
{
_apiMethod = "TestServices/GetAll/{Role}/{SystemID}/{Caller}/{Ticks}/{UserID}/{MemberId}",
_environmentType = "xx",
_inputParameters = inputParameters,
_requestHeaders = headers
};
var result1 = _restMethodInvoker.GetAsync<List<ReturnType>>(request1);
var result = result1.Result;
}
catch (Exception ex)
{
throw ex;
}
Rest Invoker class using restsharp
namespace RestServiceInvoker
{
public class RestEndPointInvoker : IRestEndPointInvoker
{
public RestEndPointInvoker()
{
_httpClient = new RestClient();
}
private void BuildRestClient(RestClientRequest request)
{
//Set the headers
foreach (var header in request._requestHeaders)
{
_httpClient.AddDefaultHeader(header.Key, header.Value);
}
}
public async Task<IRestResponse<T>> GetAsync<T>(RestClientRequest request) where T: new()
{
//Build the client object
BuildRestClient(request);
//Build request object
var restRequest = BuildRestReqestObject(request);
//var response11 = _httpClient.Execute<T>(restRequest);
var taskSource = new TaskCompletionSource<IRestResponse<T>>();
//Execute the request
_httpClient.ExecuteAsync<T>(restRequest, response =>
{
if (response.ErrorException != null)
taskSource.TrySetException(response.ErrorException);
else
taskSource.TrySetResult(response);
});
return await taskSource.Task;
}
private RestRequest BuildRestReqestObject(RestClientRequest requestObj)
{
var request = new RestRequest {Resource = requestObj._apiMethod};
if (requestObj._inputParameters == null || requestObj._inputParameters.Count <= 0) return request;
foreach (var inputParam in requestObj._inputParameters)
{
request.AddParameter(inputParam.Key, inputParam.Value, ParameterType.UrlSegment);
}
request.Method = Method.POST; //This could be parameterized from the client. For now we are only supporting get calls
//This would be sent as input parameter. Just was lazy to hardcode it here
string jsonToSend = #"xxxxxxxxxxx";
request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
return request;
}
}
}

Related

c# Background Task only runs 1 time?

Hi so i wane do a background task with my code but the code only runs 1 time when i startup my application. i have put a break point already in my infinity loop but that doesn't get triggerd. So i was wondering what can be the issue. my task is doing a test if my data is coming in my google calendar. Its a check. I hope somebody can help me out.
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
string DbConnectionString = _configuration.GetValue<string>("Site:ConnectionString");
using (IDbConnection conn = OpenConnection(DbConnectionString))
{
List<GoogleAccess> googleCredentials = conn.Query<Domain.GoogleAccess>("Select g.Id, g.CalendarId, g.RefreshToken, convert(nvarchar(36), g.CompanyUserId) as CompanyUserId from [dbo].[googleAccess] g", null, commandType: CommandType.Text).ToList();
// list with all users
foreach (var credential in googleCredentials.Where(e => e.RefreshToken is not null).ToList())
{
var accessToken = RefreshToken(credential.RefreshToken);
// search all events Where that contain CompanyUserTreatmentId From that user
var allReservations = await TurnUp.Admin.Infrastructure.RestAPI.Reservation.GetAll(new Models.RestAPI.Reservation.PostModel.GetAllReservationPostModel() { });
var covertedList = new List<EventModel>();
foreach (var reservation in allReservations.result.items.Where(e => e.isCancelled == false).ToList())
{
covertedList.Add(new EventModel
{
Id = reservation.id.ToString(),
Description = reservation.description,
Start = new EventDateTime { DateTime = DateTime.Parse(reservation.startTime.ToString()).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"), TimeZone = "Europe/Zurich" },
End = new EventDateTime { DateTime = DateTime.Parse(reservation.endTime.ToString()).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"), TimeZone = "Europe/Zurich" },
Summary = reservation.description
});
}
//Retrieving all Google Events from google api
var allGoogleEvents = new List<EventModel>();
RestClient restClient = new RestClient(new Uri("https://www.googleapis.com/calendar/v3/calendars/primary/events"));
RestRequest restRequest = new RestRequest();
//Send parameters with the request
restRequest.AddQueryParameter("key", $"{ApiKeys}");
restRequest.AddParameter("maxResults", 2500);
restRequest.AddParameter("OrderBy", "startTime");
restRequest.AddParameter("showDeleted", "false");
restRequest.AddParameter("timeMin", DateTime.UtcNow.AddMonths(-1).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"));
restRequest.AddParameter("timeMax", DateTime.UtcNow.AddMonths(6).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"));
restRequest.AddHeader("Authorization", "Bearer " + accessToken);
restRequest.AddHeader("Accept", "application/json");
try
{
//Get request to server
var response = restClient.Get(restRequest);
//check if response is ok
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
//change response to an class that can be used
JObject calendarEvents = JObject.Parse(response.Content);
var test = calendarEvents["nextSyncToken"].ToString();
allGoogleEvents = calendarEvents["items"].ToObject<List<EventModel>>();
}
}
catch (Exception ex)
{
throw new Exception("Coulden't connect to google agenda.");
}
//list with reservations that arn't in google
var newList = covertedList.Except(allGoogleEvents).Concat(allGoogleEvents.Except(covertedList));
//var newList = googleEventList.Except(covertedList).Concat(covertedList.Except(googleEventList));
foreach (var ev in newList)
{
var restClientForAddingEvents = new RestClient();
var restRequestForAddingEvents = new RestRequest();
restClientForAddingEvents.BaseUrl = new System.Uri($"https://www.googleapis.com/calendar/v3/calendars/{credential.CalendarId}/events");
EventModel newEvent = new EventModel();
newEvent.Start.DateTime = DateTime.Parse(ev.Start.DateTime).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK");
newEvent.End.DateTime = DateTime.Parse(ev.End.DateTime).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK");
newEvent.Description = ev.Description;
newEvent.Id = Guid.NewGuid().ToString().Replace("-", "");
var model = JsonConvert.SerializeObject(newEvent, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
//Send parameters with the request
restRequest.AddQueryParameter("key", $"{ApiKeys}");
restRequest.AddHeader("Authorization", "Bearer " + accessToken);
restRequest.AddHeader("Accept", "application/json");
restRequest.AddHeader("Content-Type", "application/json; charset=utf-8");
restRequest.AddParameter("application/json", model, ParameterType.RequestBody);
//RestClient restClient = new RestClient(new Uri($"https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events/" + ev.Id.ToString().Replace("-", "")));
//RestRequest restRequest = new RestRequest();
////Send parameters with the request
//restRequest.AddQueryParameter("key", $"{ApiKeys}");
//restRequest.AddHeader("Authorization", "Bearer " + accestoken);
//restRequest.AddHeader("Accept", "application/json");
try
{
//Post request to server
var restResponse = restClient.Post(restRequest);
//check if response is ok
if (restResponse.StatusCode == System.Net.HttpStatusCode.OK)
{
}
}
catch (Exception ex)
{
throw new Exception("Coulden't Create an event in google agenda.");
}
}
}
}
await Task.Delay(5000, stoppingToken);
}
}

Sending Multiple Files in a single Request to API

I am fairly new to API's. I am writing a "simple" API that will convert .docx files to .pdf files and return the pdf's back to the client for saving. I have the code working for a single file but I wanted to code the API to handle multiple files in a single request. Now the API is not receiving the request. I can provide the working code with a single file if requested.
I am sure I am missing something simple. Please see below and see if anyone see's something that I could be doing better or why the API is not receiving the POST request.
Client:
List<string> documents = new List<string>();
private async void btnConvert_Click(object sender, EventArgs e)
{
using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
{
client.BaseAddress = new Uri(BaseApiUrl);
//client.DefaultRequestHeaders.Add("Accept", "application/json");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, BaseApiUrl + ApiUrl);
foreach (string s in docPaths)
{
byte[] bte;
bte = File.ReadAllBytes(docPath);
string data = JsonConvert.SerializeObject(Convert.ToBase64String(bte));
documents.Add(data);
}
using (var formData = new MultipartFormDataContent())
{
foreach (string s in documents)
{
//add content to form data
formData.Add(new StringContent(s, Encoding.UTF8, "application/json"));
}
// List of Http Reponse Messages
var conversions = documents.Select(doc => client.PostAsync(BaseApiUrl + ApiUrl, formData)).ToList();
//Wait for all the requests to finish
await Task.WhenAll(conversions);
//Get the responses
var responses = conversions.Select
(
task => task.Result
);
foreach (var r in responses)
{
// Extract the message body
var s = await r.Content.ReadAsStringAsync();
SimpleResponse res = JsonConvert.DeserializeObject<SimpleResponse>(s);
if (res.Success)
{
byte[] pdf = Convert.FromBase64String(res.Result.ToString());
// Save the PDF here
}
else
{
// Log issue
}
}
}
}
API: This is not getting the request so this function is not complete. I need to figure out why it not being hit.
[HttpPost]
public async Task<List<SimpleResponse>> Post([FromBody]string request)
{
var response = new List<SimpleResponse>();
Converter convert = new Converter();
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var requestContents in provider.Contents)
{
try
{
//var result = convert.CovertDocToPDF(requestContents, WebConfigurationManager.AppSettings["tempDocPath"], WebConfigurationManager.AppSettings["tempPdfPath"]);
//response.Add(new SimpleResponse() { Result = result, Success = true });
}
catch (Exception ex)
{
response.Add(new SimpleResponse() { Success = false, Exception = ex, Errors = new List<string>() { string.Format("{0}, {1}", ex.Message, ex.InnerException?.Message ?? "") } });
}
}
return response;
}
SimpleResponse Model:
public class SimpleResponse
{
public object Result { get; set; }
public bool Success { get; set; }
public Exception Exception { get; set; }
public List<string> Errors { get; set; }
}
UPDATE
Did suggestions made by #jdweng and I am getting a null response on the API POST
Client:
public async void btnConvert_Click(object sender, EventArgs e)
{
using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
{
client.BaseAddress = new Uri(BaseApiUrl);
client.DefaultRequestHeaders.Add("Accept", "application/json");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//application/json
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, BaseApiUrl + ApiUrl);
List<string> requests = new List<string>();
byte[] bte;
// New Code per the suggestion
foreach (string s in docPaths)
{
bte = File.ReadAllBytes(s);
requests.Add(Convert.ToBase64String(bte));
}
// End new code
string data = JsonConvert.SerializeObject(requests);
request.Content = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response1 = client.PostAsync(BaseApiUrl + ApiUrl, request.Content).Result;
Task<string> json = response1.Content.ReadAsStringAsync();
SimpleResponse response = JsonConvert.DeserializeObject<SimpleResponse>(json.Result);
//result = JsonConvert.DeserializeObject(result).ToString();
if (response.Success)
{
bte = Convert.FromBase64String(response.Result.ToString());
if (File.Exists(tempPdfPath))
{
File.Delete(tempPdfPath);
}
System.IO.File.WriteAllBytes(tempPdfPath, bte);
}
else
{
}
}
}
Server:
[HttpPost]
public async Task<List<SimpleResponse>> Post([FromBody]string request)
{
// The request in NULL....
List<SimpleResponse> responses = new List<SimpleResponse>();
List<string> resp = JsonConvert.DeserializeObject(request) as List<string>;
try
{
Converter convert = new Converter();
foreach (string s in resp)
{
var result = convert.CovertDocToPDF(request, WebConfigurationManager.AppSettings["tempDocPath"], WebConfigurationManager.AppSettings["tempPdfPath"]);
responses.Add(new SimpleResponse()
{
Result = result,
Success = true
});
}
}
catch (Exception ex)
{
responses.Add(new SimpleResponse()
{
Result = null,
Success = true,
Exception = ex,
Errors = new List<string>() { string.Format("{0}, {1}", ex.Message, ex.InnerException?.Message ?? "") }
});
}
return responses;
}
I have finally solved the issues and can now successfully send multiple .docx files to the API and get the .pdf files back from the API. Now I want to figure out how to send each files on it's own thread instead of all together.
Client:
public async void btnConvert_Click(object sender, EventArgs e)
{
using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
{
client.BaseAddress = new Uri(BaseApiUrl);
client.DefaultRequestHeaders.Add("Accept", "application/json");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, BaseApiUrl + ApiUrl);
List<string> requests = new List<string>();
byte[] bte;
foreach (string s in docPaths)
{
bte = File.ReadAllBytes(s);
requests.Add(Convert.ToBase64String(bte));
}
var data = JsonConvert.SerializeObject(requests);
request.Content = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response1 = await client.PostAsync(BaseApiUrl + ApiUrl, request.Content);
Task<string> json = response1.Content.ReadAsStringAsync();
var response = JsonConvert.DeserializeObject<List<SimpleResponse>>(json.Result);
foreach (SimpleResponse sr in response)
{
if (sr.Success)
{
bte = Convert.FromBase64String(sr.Result.ToString());
string rs = RandomString(16, true);
string pdfFileName = tempPdfPath + rs + ".pdf";
if (File.Exists(pdfFileName))
{
File.Delete(pdfFileName);
}
System.IO.File.WriteAllBytes(pdfFileName, bte);
}
else
{
}
}
}
}
API:
[HttpPost]
public async Task<List<SimpleResponse>> Post([FromBody] List<string> request)
{
List<SimpleResponse> responses = new List<SimpleResponse>();
try
{
Converter convert = new Converter();
foreach (string s in request)
{
var result = convert.CovertDocToPDF(s, WebConfigurationManager.AppSettings["tempDocPath"], WebConfigurationManager.AppSettings["tempPdfPath"]);
responses.Add(new SimpleResponse()
{
Result = result,
Success = true
});
}
}
catch (Exception ex)
{
responses.Add(new SimpleResponse()
{
Result = null,
Success = true,
Exception = ex,
Errors = new List<string>() { string.Format("{0}, {1}", ex.Message, ex.InnerException?.Message ?? "") }
});
}
return responses;
}

Xamarin Sending POST Data

I am attempting to send POST data to my server and get back a response. For some reason, no POST data is actually getting sent. A request is being sent to my server but the POST array is empty.
Here is my code for sending the request:
public class GlobalMethods
{
public async Task<string> callAjax(string mthd,NameValueCollection parameters)
{
var client = new HttpClient();
var content = JsonConvert.SerializeObject(parameters);
var result = await client.PostAsync("http://dev.adex-intl.com/adex/mvc/receiving/"+mthd, new StringContent(content)).ConfigureAwait(false);
var tokenJson = "";
if (result.IsSuccessStatusCode)
{
tokenJson = await result.Content.ReadAsStringAsync();
}
return tokenJson;
}
}
And here is my code that calls the above method:
public void loginPressed(object sender, EventArgs e)
{
if(String.IsNullOrEmpty(badge.Text)) {
DisplayAlert("Error", "Enter your badge number", "Ok");
} else {
IsBusy = true;
NameValueCollection parameters = new NameValueCollection();
parameters["badgetNumber"] = badge.Text;
GlobalMethods globalMethods = new GlobalMethods();
var results = globalMethods.callAjax("login", parameters);
}
}
I'm not sure what I'm doing wrong. Also, I'm a newbie to Xamarin and C# so I'm not even sure if the way I am attempting to do things is the best way.
You haven't specify the type of content that you want to send, in your case it's 'application/json', you can set it like that:
"var client = new HttpClient();
var content = new StringContent(JsonConvert.SerializeObject(parameters));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");". Also, I would suggest you to write code like that:
var uri = new Uri(url);
using (var body = new StringContent(JsonConvert.SerializeObject(data)))
{
body.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var request = new HttpRequestMessage
{
Version = new Version(1, 0),
Content = body,
Method = HttpMethod.Post,
RequestUri = uri
};
try
{
using (var response = await _client.SendAsync(request,cancellationToken))
{
if (response.IsSuccessStatusCode)
{
//Deal with success response
}
else
{
//Deal with non-success response
}
}
}
catch(Exception ex)
{
//Deal with exception.
}
}
You can use PostAsync for async sending data to server. your code should be something like this:
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "p1", "data1" },
{ "p2", "data2" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/index.php", content);
var responseString = await response.Content.ReadAsStringAsync();

Using HttpClient to GET

So, because HttpClient is "better," I need to convert WebClient to HttpClient, but it just doesn't work as expected. The following function uses WebClient and works like a charm.
private static void Authenticate()
{
Console.WriteLine("Authenticating . . .");
var clientId = ConfigurationManager.AppSettings["AuthNClientId"];
var uri = ConfigurationManager.AppSettings["AuthNUri"];
var userName = ConfigurationManager.AppSettings["AuthNUserName"];
var password = ConfigurationManager.AppSettings["AuthNPassword"];
var client = new WebClient();
string formData = $"client_id={clientId}&grant_type=password&username={userName}&password={password}";
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var response = client.UploadString($"{uri}", formData);
dynamic authResult = JsonConvert.DeserializeObject(response);
_accessToken = authResult.access_token;
if (_accessToken == null)
{
throw new ApplicationException("Unable to authenticate. Check your configuration file <appSettings>.");
}
Console.WriteLine("Authenticated.");
}
This code, on the other hand, returns a BadRequest response code.
static async Task<string> GetAuthenticationToken()
{
string token = string.Empty;
var clientId = ConfigurationManager.AppSettings["AuthNClientId"];
var uri = ConfigurationManager.AppSettings["AuthNUri"];
var userName = ConfigurationManager.AppSettings["AuthNUserName"];
var password = ConfigurationManager.AppSettings["AuthNPassword"];
client.BaseAddress = new Uri("https://myurl.com/oauth2/token");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded");
var path = $"client_id={clientId}&grant_type=password&username={userName}&password={password}";
HttpResponseMessage response = await client.GetAsync($"https://myurl.com/oauth2/token?{path}");
if (response.IsSuccessStatusCode)
{
Console.WriteLine("success");
token = await response.Content.ReadAsStringAsync();
}
else { Console.WriteLine($"failure: {response.StatusCode}"); }
return token;
}
You can see that I've tried it a couple of ways, including setting the client BaseAddress as well as just try to pass the url into the GetAsync method.
Anyone see what I'm doing wrong here?
UploadString is a POST method in the first example. In the second example a GET method is being done.
static async Task<string> GetAuthenticationTokenAsync() {
string token = string.Empty;
var clientId = ConfigurationManager.AppSettings["AuthNClientId"];
var uri = ConfigurationManager.AppSettings["AuthNUri"];
var userName = ConfigurationManager.AppSettings["AuthNUserName"];
var password = ConfigurationManager.AppSettings["AuthNPassword"];
var client = new HttpClient();
client.BaseAddress = new Uri(uri);
client.DefaultRequestHeaders.Accept.Clear();
var nameValueCollection = new Distionary<string, string>() {
{ "client_id", clientId },
{ "grant_type", "password" },
{ "username", userName },
{ "password", password },
};
var content = new FormUrlEncodedContent(nameValueCollection);
var response = await client.PostAsync("", content);
if (response.IsSuccessStatusCode) {
Console.WriteLine("success");
var json = await response.Content.ReadAsStringAsync();
dynamic authResult = JsonConvert.DeserializeObject(json);
token = authResult.access_token;
}
else { Console.WriteLine($"failure: {response.StatusCode}"); }
return token;
}

Twitter API invalid or expired token

I'm trying to use the below code but for some reason I'm getting an invalid or expired token it seemed to work once but never again.
Any ideas? (consumerKey and consumerSecret are constants generated in the class.)
public ActionResult Index()
{
string twitterAccount = System.Configuration.ConfigurationManager.AppSettings["twitterAccount"];
JsonDeserializer jsonDeserializer = new JsonDeserializer();
var model = new TwitterVM.LandingModel();
var qs = GetToken();
string oauthToken = qs["oauth_token"];
string oauthTokenSecret = qs["oauth_token_secret"];
RestClient client = new RestClient("https://api.twitter.com/1.1")
{
Authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey, consumerSecret, oauthToken, oauthTokenSecret)
};
RestRequest request = new RestRequest("statuses/user_timeline", Method.GET);
request.Parameters.Add(new Parameter()
{
Name = "screen_name",
Value = twitterAccount,
Type = ParameterType.GetOrPost
});
request.Parameters.Add(new Parameter()
{
Name = "count",
Value = 10,
Type = ParameterType.GetOrPost
});
request.Parameters.Add(new Parameter()
{
Name = "include_rts",
Value = true,
Type = ParameterType.GetOrPost
});
request.Parameters.Add(new Parameter()
{
Name = "include_entities",
Value = true,
Type = ParameterType.GetOrPost
});
IRestResponse response = client.Execute(request);
model.Tweets =
jsonDeserializer.Deserialize<List<TwitterVM.Tweet>>(response);
return View(model);
}
private NameValueCollection GetToken()
{
RestClient client = new RestClient("https://api.twitter.com") { Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret) };
//Do the auth shit...
RestRequest request = new RestRequest("oauth/request_token", Method.POST);
IRestResponse response = client.Execute(request);
return HttpUtility.ParseQueryString(response.Content);
}
Using Twitter's OAuth2 API (https://api.twitter.com/oauth2/token)
See https://dev.twitter.com/oauth/application-only for details....
var client = await CreateHttpClient("....", "....");
//don't dispose this client and use for subsequent API calls
var screenName = "....";
var count = 10;
var include_rts = true;
var url = $"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={screenName}&include_rts={include_rts}&count={count}";
var json = await client.GetStringAsync(url);
public static async Task<HttpClient> CreateHttpClient(string consumerKey, string consumerSecret)
{
var bearerToken = Convert.ToBase64String(Encoding.UTF8.GetBytes(consumerKey + ":" + consumerSecret));
string url = "https://api.twitter.com/oauth2/token";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Basic " + bearerToken);
var resp = await client.PostAsync(url, new StringContent("grant_type=client_credentials", Encoding.UTF8, "application/x-www-form-urlencoded")).ConfigureAwait(false);
resp.EnsureSuccessStatusCode();
var result = await resp.Content.ReadAsStringAsync().ConfigureAwait(false);
var jObj = new JavaScriptSerializer().Deserialize<Dictionary<string,string>>(result);
if (jObj["token_type"] != "bearer") throw new Exception("Invalid Response From Twitter/OAuth");
client.DefaultRequestHeaders.Remove("Authorization");
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + jObj["access_token"]);
return client;
}

Categories

Resources