Proper way to send Raw XML to Tableau Rest API in C# - c#

I simply want to send a rest request to Tableau's REST API but for some reason .NET isn't sending the raw XML (although tested and it works using Postman in chrome)
var admin = "\hardcoded_admin_user"\"";
var pass = "\hardcoded_pass"\"";
var tableau_signin = String.Format("<tsRequest> <credentials name={0} password={1}> </credentials> <site contentUrl=\"\"/> </tsRequest>", admin, pass);
//if user is validated make a REST call to Tableau Server
string endPoint = #"http://server/api/2.0/auth/signin";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
var post = client.PostAsync(endPoint,
new StringContent(tableau_signin)).Result;
}
Any help would be appreciated.

Provide Encoding and Content Type in the StringContent.
var post = client.PostAsync(endPoint,
new StringContent(tableau_signin, Encoding.UTF8, "application/xml")).Result;

var user = FormatTextBodyForUserSignIn(userName, password);
var httpContent = new StringContent(user, Encoding.UTF8, "application/xml");
var response = client.PostAsync($"api/{TableauAPIVersion}/auth/signin", httpContent).Result;

Related

How to POST to a specific URL using the Microsoft Graph Client

I'm trying to send a POST request to the following URL using the MS Graph Client.
https://graph.microsoft.com/v1.0/sites/{SiteID}/lists/Documents/contentTypes/addCopyFromContentTypeHub
I looked at the various Request Builders and didn't see anything for "addCopyFromContentTypehub". There's a "ContentTypeAddCopyRequestBuilder", but that's a different action.
I tried getting access to the graph client's HttpProvider, but I can't figure out how to send the authentication with the request.
var requestUrl = graphServiceClient.Sites[siteId].Lists["Documents"].ContentTypes.AppendSegmentToRequestUrl("addCopyFromContentTypeHub");
var contentTypeId = "<ID>";
var body = $"{{\"contentTypeId\": \"{contentTypeId}\"}}";
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUrl))
{
httpRequestMessage.Content = new StringContent(requestUrl, Encoding.UTF8, "application/json");
//Errors here
var result = await graphServiceClient.HttpProvider.SendAsync(httpRequestMessage);
};
There error I get is:
"MsalUiRequiredException: No account or login hint was passed to the AcquireTokenSilent call."
My graph client uses an Azure AD App Registration to make all the calls so I need to include ".WithAppOnly()" on all my requests, but I don't see a way to do that using graphServiceClient.HttpProvider
Any help would be appreciated. Thanks!
You can authenticate HttpRequestMessage through Graph client
await graphServiceClient.AuthenticationProvider.AuthenticateRequestAsync(httpRequestMessage);
Code:
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUrl))
{
httpRequestMessage.Content = new StringContent(requestUrl, Encoding.UTF8, "application/json");
await graphServiceClient.AuthenticationProvider.AuthenticateRequestAsync(httpRequestMessage);
var result = await graphServiceClient.HttpProvider.SendAsync(httpRequestMessage);
};

Send POST request from webapi c# to onesignal url

I'm very new on this and I need some help. I'm trying to send a notification from my webapi to my app. To do this a need just send a post to the url("https://onesignal.com/api/v1/notifications") with some informations (Header from authorization and content-type). But when I send the post it takes a long and and I just get The operation timeout has been reached, no message errors that could help me. I tryed the code from onesignal's documentation from asp.net solutions but isn't worked for me. Anyone can help? Or just help how can I trace the error with my requisiton? After try the code from onesignal's documentation I decided use the following code(both codes had the same behavior):
using (var client = new HttpClient())
{
var url = new Uri("https://onesignal.com/api/v1/notifications");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "Rest ID");
var obj = new
{
app_id = "APP ID",
contents = new { en = "English Message" },
included_segments = new string[] { "All" }
};
var json = JsonConvert.SerializeObject(obj);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
}
For some reason is taking a long time to send a notification and return some response for me. So I increase the timeout to wait the response and don't get a task cancelled. Hope help someone.

JFROG Repository Creation with Api

Hi I want to create Repository with Artifactory JFROG Api,But I got 406 error code with api
I can run this json request over postman with selected application/json mime type
But I cant run over my c# code.What should I do in my .net code to use jfrog artifactory api?
{"key":"ArtifactRepoGroup3","rclass":"virtual","packageType":"nuget","description":"This repo created by"}
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(BaseAddress);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
............
HttpResponseMessage response = client.PutAsJsonAsync(puturi,
value).Result; }
I cant run PutAsJsonAsync method with standart application/json but I can do it use StringContent and embedded jfrog specific mime type into my content
VirtualRepository repository = new VirtualRepository();
repository.key = "ArtifactRepoGroup1";
repository.packageType = "nuget";
repository.rclass = "virtual";
repository.description = "This repo created by ";
var content = JsonConvert.SerializeObject(repository);
var conent = new StringContent(content, Encoding.UTF8,
"application/vnd.org.jfrog.artifactory.repositories.VirtualRepositoryConfiguration+json");
....
var response = client.PutAsync(uri, conent).Result;
string b = response.Content.ReadAsStringAsync().Result;

REST JSON GET - 400 Bad Request

I am working with the Basecamp API which is a REST (JSON) API using basic HTTP authentication over HTTPS.
This should be a GET request but when I run my code using GET I am receiving:
Cannot send a content-body with this verb-type
When I run it as a POST, I receive:
{"status":"400","error":"Bad Request"}
Does anyone know why this may be occurring?
using (var httpClient = new HttpClient()) {
string userName = "someone#someone.com";
string password = "somepassword";
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", userName, password)));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://correctUrlHere);
requestMessage.Headers.Add("User-Agent", "TheProject (someone#someone.com)");
requestMessage.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(requestMessage);
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
In this code I obviously swapped out the username, password, project name, and URL but in the actual code they are all correct.
GET requests must pass their parameters as url query and not as request body.
http://example.com?p1=1&p2=helloworld
If you don't have any content, as your example suggests, omit setting it on the request.
The BadRequest result indicates some error with your payload (again: content seems to be empty).

Https client with authorization in C#

I'm trying to create a https client in C#.
I had HTTP client which worked fine and I changed it to work with HTTPS. But unfortunately there is something wrong with the authorization (the server uses OAuth 2).
My program sends a request to a server and gets the token. But it can't get or send any data from the server.
The server works fine with other clients, so it's not its fault.
This is a piece of code which causes the problem. I know that, because when I comment authorization on the server, the data is send (everything is fine).
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("Authorization: {0}", token))));
This is the whole function, which should send data:
WebRequestHandler handler = new WebRequestHandler();
X509Certificate certificate = GetMyX509Certificate();
handler.ClientCertificates.Add(certificate);
var client = new HttpClient(handler);
string uri = "https://192.168.0.10:8443/data";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("Authorization: {0}", token))));
client.BaseAddress = new Uri(uri);
var parameters = new Dictionary<string, string>();
parameters["name"] = name;
parameters["surname"] = surname;
JavaScriptSerializer serializer = new JavaScriptSerializer();
var json = serializer.Serialize(parameters);
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
var response = client.PostAsync(uri, new StringContent(json, System.Text.Encoding.UTF8, "application/json")).Result;
Console.WriteLine((response.StatusCode.ToString()));
string resultContent = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(resultContent);
I guess I'm missing something in the header but can't find any information in the documentation about that.
It's a difficult issue so any advice will be very appreciated.
You shouldn't be including the HTTP header name ("Authorization: ") in the parameter of the AuthenticationHeaderValue. Setting the Authorization property will add the header to the request.
Additionally for OAuth 2, you probably want to be using "Bearer" as the scheme and not encoding token with base64.
Something like this should therefore work:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

Categories

Resources