Setting dynamic baseUrl for Get Request RestClient - c#

I am wanting to dynamically change my baseUrl for my RestClient depending on what token is being run.
This is for the deputy roster systems attempting to get Roster data out but cannot figure out how to get a custom baseUrl for each token
public List<DeputyRosterData> RosterData(string url, int? actual, int? roster)
{
BaseUrl = "e1f5c520093734.au.deputy.com"; //Error on this line but to show you what I need
var request = Request("/api/v1/resource/Roster");
var result = _client.Execute<List<DeputyRosterData>>(request);
return result.Data;
}

I think, It's useful for u
var client = new RestClient();
string baseURL = "http://northwind.servicestack.net";
string apiURL = baseURL + "/" + "customers?format=json";
client = new RestClient(apiURL); // 1 URL
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
baseURL = "https://jsonplaceholder.typicode.com";
apiURL = baseURL + "/posts/1";
client = new RestClient(apiURL);//2 URL
request = new RestRequest(Method.GET);
response = client.Execute(request);

Related

Including Authentication in the Header of a POST Request using ASP.NET Core

I'm trying to make a request to receive a session Id to integrate with a payment gateway.
var m = System.Text.Encoding.Unicode.GetBytes("merchant." + merchant_Id + ":" + merchant_pass);
var b64Val = Convert.ToBase64String(m);
var SerSession = JsonConvert.SerializeObject(sessionRequest);
var client = new HttpClient();
string _ContentType = "application/json";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType));
client.DefaultRequestHeaders.Add("Authorization", String.Format("Basic {0}", b64Val));
var _UserAgent = "d-fens HttpClient";
client.DefaultRequestHeaders.Add("User-Agent", _UserAgent);
HttpContent _Body = new StringContent(SerSession);
]_Body.Headers.ContentType = new MediaTypeHeaderValue(_ContentType);
HttpResponseMessage response;
response = await client.PostAsync(api_URL, _Body);
var content = response.Content.ReadAsStringAsync().Result;
return Ok(content);
I am getting (Invalid credentials) and I am sure the credentials I am using are correct. I have tested them in Python and PHP.
try this
var authenticationString = $"{merchant_Id}:{merchant_pass}";
var base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(authenticationString));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64EncodedAuthenticationString);

Sending JSON data from Logic App to Function App to Eloqua with RestSharp

I'm trying to make a Function App that takes JSON data from a Logic App and then sends it to Eloqua API.
I've been using the Eloqua documentation in order to set it up.
However, I am getting in to problems.
I seem to not get any data from my Logic App or be able to parse the URL you get from the first OAuth2 url you send.
I'm wondering if anyone knows what mistakes I've made as I'm kind of a junior on this and not entirely sure what I did wrong.
This is the code that I am using for my Function App:
Main function
/*
* Sets up the needed variables for sending to Eloqua
*/
string clientSecreat = "xxxxx";
var authentication = System.Text.Encoding.UTF8.GetBytes(clientSecreat);
string getJson = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "Body", true) == 0)
.Value;
/*
* Starts by calling to get token for Oauth2
*/
var client = new RestClient("https://login.eloqua.com/auth/oauth2/authorize?");
var request = new RestRequest(Method.GET);
var queryResult = client.Execute<Token>(request);
//log.Info(queryResult.ToString());
client = new RestClient("https://login.eloqua.com/auth/oauth2/token");
request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Authorization", "Basic " + authentication);
request.AddJsonBody("grant_type: ", "authorization_code");
request.AddJsonBody("code: " + queryResult);
request.AddJsonBody("redirect_uri: ", "redirect_url");
var response = await client.ExecuteAsync<AccessToken>(request);
log.Info(response.ToString());
/*
* Posts the Logic App parsed JSON data
*/
client = new RestClient("https://secure.p06.eloqua.com/API/Bulk/2.0/customObjects/377/imports/1904470/data");
request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Content_Type: ", "application/json");
request.AddHeader("Authorization: ", "Basic " + response);
request.AddJsonBody(getJson);
var execute = await client.ExecuteAsync(request);
return req.CreateResponse("Success");
Token.cs:
public class Token
{
[JsonProperty("code")]
public string code { get; set; }
}
AccessToken.cs:
public class AccessToken
{
[JsonProperty("access_token")]
public string access_token { get; set; }
}
Thank you in advance.
If you want to use resource owner password credentials grant flow, please refer to the following rest API
POST https://login.eloqua.com/auth/oauth2/token
Authorization: Basic <base64 encode string client_id:client_secret>
{
"grant_type":"password",
"scope":"full",
"username":"testsite\\testuser",
"password":"user123"
}
code
var authentication = Convert.ToBase64String(Encoding.UTF8.GetBytes("client_id:client_secret"));
client = new RestClient("https://login.eloqua.com/auth/oauth2/token");
request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Authorization", "Basic " + authentication);
....body
var response = await client.ExecuteAsync<AccessToken>(request);
log.Info(response.ToString());

Make a post Request with azure new rest api (ressource manager)

I want to start my VM using the post Uri as described here https://msdn.microsoft.com/en-us/library/azure/mt163628.aspx
Since i don't have body in my request i get 403 frobidden. I can make a get Request without problem. Here is my code
public void StartVM()
{
string subscriptionid = ConfigurationManager.AppSettings["SubscriptionID"];
string resssourcegroup = ConfigurationManager.AppSettings["ressourgroupename"];
string vmname = ConfigurationManager.AppSettings["VMName"];
string apiversion = ConfigurationManager.AppSettings["apiversion"];
var reqstring = string.Format(ConfigurationManager.AppSettings["apirestcall"] + "subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}/start?api-version={3}", subscriptionid, resssourcegroup, vmname, apiversion);
string result = PostRequest(reqstring);
}
public string PostRequest(string url)
{
string content = null;
using (HttpClient client = new HttpClient())
{
StringContent stringcontent = new StringContent(string.Empty);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string token = GetAccessToken();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = client.PostAsync(url, stringcontent).Result;
if (response.IsSuccessStatusCode)
{
content = response.Content.ReadAsStringAsync().Result;
}
}
return content;
}
i've also tried this in the PostRequest
var values = new Dictionary<string, string>
{
{ "api-version", ConfigurationManager.AppSettings["apiversion"] }
};
var posteddata = new FormUrlEncodedContent(values);
HttpResponseMessage response = client.PostAsync(url, posteddata).Result;
with url=string.Format(ConfigurationManager.AppSettings["apirestcall"] + "subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}/start", subscriptionid, resssourcegroup, vmname);
I Get 400 Bad request
I found the solution. Needed to add role in Azure to allow starting/stopping the VM. That is why i received 4.3 forbidden.
Thank you

Creating a folder on box using C# and RESTSharp

I'm trying to use RESTSharp to create a simple folder on Box, but I'm having a hard time. I keep getting this error:
{"type":"error","status":400,"code":"bad_request","help_url":"http://developers.box.com/docs/#errors","message":"Could
not parse JSON","request_id":"1474540366505ba7a11bdcd"}
This is my code:
static string box(string resourceURL, string APIKey, string authToken)
{
RestClient client = new RestClient();
client.BaseUrl = "https://api.box.com/2.0";
var request = new RestRequest(Method.POST);
request.Resource = resourceURL;
string Headers = string.Format("Authorization: BoxAuth api_key={0}&auth_token={1}", APIKey, authToken);
request.AddHeader("Authorization", Headers);
request.AddParameter("name", "TestFolder");
// request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
return response.Content;
}
What am I missing? Thanks in advance for your help.
You may also want to take a look at a recently created github repo, where some folks are collaborating on a C# Box SDK. https://github.com/jhoerr/box-csharp-sdk-v2
I see two issues:
The URL needs to point to /folder/{folder_id} (0 is the id of the root folder)
The folder name needs to be in the json body of the request, not a query parameter
I'm not that familiar with C# or RESTSharp, but I believe this code should address the two problems.
static string box(string APIKey, string authToken)
{
RestClient client = new RestClient();
client.BaseUrl = "https://api.box.com/2.0";
var request = new RestRequest(Method.POST);
request.Resource = "/folders/0";
string Headers = string.Format("BoxAuth api_key={0}&auth_token={1}", APIKey, authToken);
request.AddHeader("Authorization", Headers);
request.AddParameter("text/json", "{\"name\" : \"TestFolderName\"}", ParameterType.RequestBody);
//request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
return response.Content;
}
Thanks for your help, this is the exact code that finally worked.
static string box(string APIKey, string authToken)
{
RestClient client = new RestClient();
client.BaseUrl = "https://api.box.com/2.0";
var request = new RestRequest(Method.POST);
request.Resource = "/folders/0";
string Headers = string.Format("BoxAuth api_key={0}&auth_token={1}", APIKey, authToken);
request.AddHeader("Authorization", Headers);
request.AddParameter("text/json", "{\"name\" : \"TestFolderName\"}", ParameterType.RequestBody);
//request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
return response.Content;
}
static string folderCreation(string APIKey, string authToken)
{
RestClient client = new RestClient();
client.BaseUrl = "https://api.box.com/2.0/folders";
var request = new RestRequest(Method.POST);
string Headers = string.Format("Bearer {0}", authToken);
request.AddHeader("Authorization", Headers);
request.AddParameter("application/json", "{\"name\":\"Youka\",\"parent\":{\"id\":\"0\"}}", ParameterType.RequestBody);
var response = client.Execute(request);
return response.Content;
}

RestSharp requests on momentapp's restful api

So Im trying to set up RestSharp to use Moment Task scheduling according to the docs
http://momentapp.com/docs
here is my code.
public class MomentApi : ITaskScheduler
{
const string BaseUrl = "https://momentapp.com";
private RestResponse Execute(RestRequest request)
{
var client = new RestClient();
client.BaseUrl = BaseUrl;
request.AddParameter("apikey", "MYAPIKEYHERE", ParameterType.UrlSegment); // used on every request
var response = client.Execute(request);
return response;
}
public HttpStatusCode ScheduleTask(DateTime date, Uri url, string httpMethod, Uri callback = null)
{
var request = new RestRequest(Method.POST);
request.Resource = "jobs.json";
request.AddParameter("job[uri]", "http://develop.myapp.com/Something");
request.AddParameter("job[at]", "2012-06-31T18:36:21");
request.AddParameter("job[method]", "GET");
var response = Execute(request);
return response.StatusCode;
}
The problem is that it is always returnig HTTP 422
please help.
So this is what I ended up with.
found a sample here
http://johnsheehan.me/blog/building-nugetlatest-in-two-hours-3/
public HttpStatusCode ScheduleTask(DateTime date, Uri url, string httpMethod, Uri callback = null)
{
var request = new RestRequest("jobs.json?apikey={apikey}&job[uri]={uri}&job[at]={at}&job[method]={method}", Method.POST);
request.AddUrlSegment("uri", "http://develop.myapp.com/Something");
request.AddUrlSegment("at", "2012-03-31T18:36:21");
request.AddUrlSegment("method", "GET");
var response = Execute(request);
return response.StatusCode;
}
Im not completely sure on when I should use AddParameter and when I should use AddUrlSegment
but anyways it works now

Categories