IRestResponse could not be found - c#

I have restsharp 107.1.2 loaded via nuget target framework is .net 6.0. The following code claims that IRestResponse reference is missing, though I feel like I'm following pretty close to the RestSharp documentation. What am I missing?
using RestSharp;
using RestSharp.Authenticators;
using System.Text;
static void Main()
{
String url = "https://www.invoicecloud.com/api/v1/biller/status/";
//Set up the RestClient
var client = new RestClient(url);
//Store the generated API from the biller portal
String GeneratedAPIKey = "SomeKey=";
//Convert genrated API key to Base64
String encodedAPIKey = encoding(GeneratedAPIKey);
//HTTPBasicAuthentication will take a username and a password
//Here we use your API key as the username and leave the password with ""
client.Authenticator = new HttpBasicAuthenticator(encodedAPIKey, "");
//Get the request
var request = new RestRequest("resource", Method.Get);
//Get the response
// var response = client.ExecuteGetAsync(request);
IRestResponse reponse = client.Execute(request);

As per the documentation (https://restsharp.dev/v107/#restsharp-v107) ...
The IRestResponse interface is deprecated. You get an instance of RestResponse or RestResponse<T> in return.
https://restsharp.dev/v107/#deprecated-interfaces
Again, according to the documentation ...
var client = new RestClient("https://api.myorg.com");
var request = new RestRequest()
.AddQueryParameter("foo", "bar")
.AddJsonBody(someObject);
var response = await client.PostAsync<MyResponse>(request, cancellationToken);
... as an example.

Related

How to add bearertoken to post/get restsharp automation testing

maybe anyone could help me with RestSharp api automation testing.
I'll try to be as clear as possible.
Basically the scheme is:
I'm sending my username/password credentials & I get BearerToken in return.
I parse the bearer token into a json file.
After I get the bearer token I need to "Authenticate" in order to get the information that I need.
For example i need full company credit report which I get after I input companyName ="Whatever"; companyCode = "Whatever";
{
var client = new RestClient("https://www.myapitesting.com/api/Auth/Authenticate");
var request = new RestRequest(Method.GET);
var body = new AuthenticatePostCredentials { Username = "myUserName", Password = "myPassword" };
request.AddJsonBody(body);
var response = client.Post(request);
HttpStatusCode statusCode = response.StatusCode;
int numericStatusCode = (int)statusCode;
request.AddHeader("content-type", "application/json");
var queryResult = client.Execute<object>(request).Data;
string jsonToken = JsonConvert.SerializeObject(queryResult);
var JSON1 = JToken.Parse(jsonToken);
var pureToken = JSON1.Value<string>("token");
File.WriteAllText(#"C:\Users\....\TestAPI\TestAPI\token.json", pureToken);
Console.WriteLine(pureToken);
Console.WriteLine(numericStatusCode)
The output I get is: token, status code 200 (correct credentials to get the bearertoken)
//////////At this point I get the token and it is writed into my json file/////////////// (the token works)
Now im trying to authenticate with my token and get the company information that I need
var client = new RestClient("https://www.myapitesting.com/api/GetCompanyReport");
var myRequest = new RestRequest(Method.POST);
myRequest.AddHeader("Accept", "application/json");
myRequest.AddHeader("Authorization", $"Bearer{pureToken}");
myRequest.AddHeader("content-type", "application/json");
var companyInfoInput = new AuthenticatePostCredentials { companyName = "MyCompanyName", companyCode = "MyCompanyCode" };
requestas.AddJsonBody(companyInfoInput);
var response = myRequest.Execute(request);
Console.WriteLine(response.Content);
The output I get is error code that says I havent authenticated, even though I pass the bearer token with my addHeader command.
{"ErrorId":401,"ErrorName":"Unauthorized","ErrorDescription":"User is not logged in"}
What am I doing wrong? Any kind of help would be greatly appreciated!
In this case, you could load the "Authenticator" you want to use, in the case of JWT you may instantiate something like this:
var authenticator = new JwtAuthenticator(pureToken);
and then set your client authenticator like this:
client.Authenticator = authenticator;
Mainly, you should not need to set headers by hand for the most commons ones using Restsharp.
You can for example fix this statement:
var myRequest = new RestRequest(url, DataFormat.Json);
var response = client.Post(request);
I also made this gist for you to check an example
If you want to see something more complete I also have this another gist

I cannot use RestSharp In my WixSharp installer, is it possible to accomplish this with HttpClient or WebClient?

private async Task<AuthenticationToken> GetToken()
{
string username = loginDialog.username;
string password = loginDialog.password;
string requestString = $"Service/Login";
RestRequest request = new RestRequest(requestString, Method.POST);
request.AddParameter("username", username);
request.AddParameter("password", password);
IRestResponse<AuthenticationToken> response = await _client.ExecuteAsync<AuthenticationToken>(request);
return response.Data;
}
I am using RestSharp in a few projects within my solution. I can not use it within the installer, WixSharp isn't working well with RestSharp. I need to use WebClient or HttpClient to achieve the same response as I get with this Method using the RestSharp library. Is anyone able to help?
In the case of requirement some external assembly for Wixsharm runtime just add it like below:
var proj = ManagedProject()
proj.DefaultRefAssemblies.Add("Restsharp.dll")
And it will be avaliable for load in runtime and accessable for use.
P.S. Dont forget to check assembly existence in your builder executable file output location.
Sure, try this
var httpClient = new HttpClient();
var headers = httpClient.DefaultRequestHeaders;
headers.Add("Content-Tpye", "application/form-url-encoded");
string requestParams = string.Format("grant_type=password&username={0}&password={1}", username, password);
HttpContent content = new StringContent(requestParams);
var response = httpClient.PostAsync(requestString, content);
var responseContent = await response.Result.Content.ReadAsStringAsync();
Then you can use JSON deserializer on responseContent using NewtonSoft or any JSON library.

Problem calling the prediction endpoint uploading an image using rest sharp for the Microsoft custom vision API cognitive service

I am trying to upload an image to the Microsoft custom vision API prediction endpoint using Restsharp, I am trying to use the AddFile method but I am getting a BadRequest as the result, here is the code I am using
public IRestResponse<PredictionResponse> Predict(string imageFileName)
{
var file = new FileInfo(imageFileName);
var serviceUrl = ConfigurationManager.AppSettings["api.custom-vision.prediction.url.file"];
var serviceKey = ConfigurationManager.AppSettings["api.custom-vision.key"];
var client = new RestClient(serviceUrl);
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/octet-stream");
request.AddHeader("Prediction-Key", serviceKey);
request.AddFile(file.Name, file.FullName);
var response = client.Execute<PredictionResponse>(request);
return response;
}
When I execute the method I am getting the following response back from the service
{
"code": "BadRequestImageFormat",
"message": "Bad Request Image Format, Uri: 1062fe0480714281abe2daf17beb3ac5"
}
After looking for ways in the restsharp documentation to properly upload a file, I came to the solution that it needs to be passed as parameter with an array of bytes with the parameter type of ParameterType.RequestBody
Here is the example of the method that actually works
public IRestResponse<PredictionResponse> Predict(string imageFileName)
{
var file = new FileInfo(imageFileName);
var serviceUrl = ConfigurationManager.AppSettings["api.custom-vision.prediction.url.file"];
var serviceKey = ConfigurationManager.AppSettings["api.custom-vision.key"];
var client = new RestClient(serviceUrl);
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/octet-stream");
request.AddHeader("Prediction-Key", serviceKey);
request.AddParameter("content", File.ReadAllBytes(file.FullName), ParameterType.RequestBody);
var response = client.Execute<PredictionResponse>(request);
return response;
}

#Encoding special characters in HTTP requests

I'm trying to develop a console application to generate access token from Salesforce REST API using rest sharper library in C#. One of the request parameters is username which is of type user#username.com. I have tried to encode it. C# detects it the proper way after encoding it. But fiddler data is showing %20 instead of # for username.
Appreciate your input.
namespace Restsharper
{
class Program
{
static void Main(string[] args)
{
var client = new RestClient("https://xx--zz.mm.my.salesforce.com/services/oauth2/token");
RestRequest request = new RestRequest() { Method = Method.POST };
request.AddHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-16");
request.Parameters.Clear();
request.AddParameter("grant_type","password");
var pwd = Uri.EscapeUriString("Password#");
var userName = Uri.EscapeUriString("user#username.com");
request.AddParameter("password", pwd);
request.AddParameter("username", userName);
request.AddParameter("client_id","456fdas4fsdfsd4fds65uiryewiuryiuy43246FSDFSdasfcdasfasfFDF45_$rewrw#$$fFFFF");
request.AddParameter("client_secret","77554698412");
// request.RequestFormat("","");
var response = client.Execute(request);
}
}
}

Cannot set MIME type using RestSharp and GoCardless

Using C#, .Net 4,5, RestSharp v4.0.3
Attempting to create an api_key in GoCardless
I create a RestClient like this:
var client = new RestClient();
client.BaseUrl = SandboxBaseUrl;
client.Authenticator = new HttpBasicAuthenticator(apiKeyId, apiKey);
client.AddDefaultHeader("GoCardless-Version", Properties.Settings.Default.GoCardlessVersion);
client.AddDefaultHeader("Accept", "application/json");
client.AddDefaultHeader("content-type", "application/json");
request.AddHeader("content-type", "application/json");
When I post to GoCardless I get the error
{"error":{"message":"'Content-Type' header must be application/json or application/vnd.api+json ......
After a lot of fruitless searching I gave up and used the solutions in older StackOverflow postings. Such as
// Create the Json for the new object
StringBuilder requestJson = new StringBuilder();
var requestObject = new { api_keys = new { name = name, links = new { role = role } } };
(new JavaScriptSerializer()).Serialize(requestObject, requestJson);
...
// Set up the RestSharp request
request.Parameters.Clear();
request.AddParameter("application/json", requestJson, ParameterType.RequestBody);
I can see why this works - and even perhaps the intention of RestSharp doing it this way.

Categories

Resources