JFROG Repository Creation with Api - c#

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;

Related

Calling Get Request with Json Body using httpclient

I came with an issue this morning where the Api which I am calling is a Get Method but to get Get the Data from it I had to send the json body this is working good when I am testing it in the post man but I am not able to implement it in my project where I am calling this using HttpClient
here is the screenshot of post
It also have a bearer token which I pass in Authorization
Now when I am try to implement this at client side here is my code
var stringPayload = JsonConvert.SerializeObject(json);
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://myapiendpoint/serviceability/"),
Content = new StringContent(stringPayload, Encoding.UTF8, "application/json"),
};
var response = await client.SendAsync(request).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
when I call this method using this code I get
System.Net.HttpStatusCode.MethodNotAllowed - Status code 405
I also tried changing this line
Method = HttpMethod.Get to Method = HttpMethod.Post
but still getting same error
I know this is bad implementation at API Side the request ideally should be POST but changing this is not in my hand and hence need to find the solution
almost search all over and trying all the variant of using GET Method finally the solution which worked for me in this case was this
var client = new HttpClient();
client.BaseAddress = new Uri("https://baseApi/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", token));
var query = new Dictionary<string, string>
{
["pickup_postcode"] = 400703,
["delivery_postcode"] = 421204,
["cod"] = "0",
["weight"] = 2,
};
var url = "methodurl";
var response = await client.GetAsync(QueryHelpers.AddQueryString(url, query));
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return JsonConvert.DeserializeObject<MyModel>(responseBody);
Got QueryHelpers from Microsoft.AspNetCore.WebUtilities package

.net core console app calling PHP rest API with basic authentication

I am not able to get the data from a php rest api from the .net core console app(the call works fine from POSTMAN). I use below code for basic authentication and looks like it redirects to https://www.thesite.org/login for HttpClient.
Not sure what I am missing.
static async Task<RootObject> GetOrderDataAsync()
{
HttpClient client = new HttpClient();
RootObject result = null;
var byteArray = Encoding.ASCII.GetBytes("username:password");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
client.BaseAddress = new Uri("https://www.thesite.org/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("orders/processing");
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsAsync<RootObject>();
}
return result;
}
I think when you use AuthenticationHeaderValue you don't need to explicitly convert to a Base64 string. Have you tried:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "username:password");

Error Calling a Odata service in C#

I am trying to call a Odata service from the C# application. I have called the rest services before and consumed the responses in the C#, and trying Odata for the first time. Below is the Code I am using
using (var client = new HttpClient())
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
Uri uri = new Uri(BaseURL);
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var response = client.GetAsync(uri).Result;
var responsedata = await response.Content.ReadAsStringAsync();
I am using the same URL and the credentials in PostMan and it returns the response. But throws error i the code, is there something different we need to follow calling a Odata services.Please help with this
It is recommended to use a library to access OData. There are at least a couple of libraries that you can choose from, such as:
https://www.nuget.org/packages/Microsoft.OData.Client/ (OData v4)
https://www.nuget.org/packages/Microsoft.Data.OData/ (OData v1..3)

Proper way to send Raw XML to Tableau Rest API in 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;

How to create new NoteBook with OneNote API

I'm getting a "Bad Request" error 400 when I try to create a new Notebook. Below is my code, I think it is the PagesEndPoint Uri but I have tried all combinations. I can use the apigee console app, but cannot detemine how to make a C# Windows app Post message.
async public Task<StandardResponse> CreateNewNotebook(string newNotebookName)
{
Uri PagesEndPoint = new Uri("https://www.onenote.com/api/v1.0/notebooks?notebookName="+newNotebookName.ToString());
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (IsAuthenticated)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authClient.Session.AccessToken);
}
string date = GetDate();
string simpleHtml = "<html>"+"<head>"+"<title>A simple page created with an image1 on it</title>" +"<meta name=\"created\" content=\"" + date + "\" />" +
"</head>" +"<body>" +"<h1>This is a page with an image on it</h1>" +"</body>" +"</html>";
HttpResponseMessage response;
HttpRequestMessage createMessage = new HttpRequestMessage(HttpMethod.Post, PagesEndPoint)
{
Content = new StringContent(simpleHtml, System.Text.Encoding.UTF8, "text/html")
};
response = await client.SendAsync(createMessage);
tbResponse.Text = response.ToString();
return await TranslateResponse(response);
}
I've tried with this new code, but still not working. The links to the documentation show the elements to use, but not how to use them to make C# method.
Here is my latest code.
async public Task<StandardResponse> CreateJsonNotebook(string newNotebookName)
{
string postData = "{name: \"NewNotebookName\"}";
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (IsAuthenticated)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authClient.Session.AccessToken);
}
StreamWriter requestWriter;
var webRequest = System.Net.WebRequest.Create("https://www.onenote.com/api/v1.0/notebooks") as HttpWebRequest;
HttpResponseMessage response;
response = await client.SendAsync(postData);
tbResponse.Text = response.ToString();
return await TranslateResponse(response);
}
there are a few things incorrect with your latest code pasted above.
Here's the modified version that I got working :
public async Task<StandardResponse> CreateJsonNotebook(string newNotebookName)
{
var client = new HttpClient();
string postData = "{name: \"" + newNotebookName + "\"}";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (IsAuthenticated)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
_authClient.Session.AccessToken);
}
StreamWriter requestWriter;
var webRequest = new HttpRequestMessage(HttpMethod.Post, "https://www.onenote.com/api/v1.0/notebooks")
{
Content = new StringContent(postData, Encoding.UTF8, "application/json")
};
HttpResponseMessage response;
response = await client.SendAsync(webRequest);
return await TranslateResponse(response);
}
Notice that:
I didn't combine usage of HttpClient and HttpWebRequest.
When creating the HttpWebRequest.Content, I set the mediaType to "application/json"
Also client.SendAsync() used the HttpRequestMessage and not the postData string.
You're right - the URL isn't quite right. You can't actually create a page and a notebook at the same time - they require two different calls.
To create a notebook, the URL you should post to is:
https://www.onenote.com/api/v1.0/notebooks
The notebook is created with the content of the body, which should be JSON. (Make sure you include CONTENT-TYPE: application/json in the header).
The body should look like:
{
name: "New Notebook Name"
}
You can then create a section in the notebook with the ID in the response. Once you get the ID of a new section, you can then post a page to that section.
More information can be found here: http://msdn.microsoft.com/en-us/library/office/dn790583(v=office.15).aspx
The way you are calling the API is incorrect. You shouldn't be putting a notebookName query parameter in the endpoint. Instead, you should just post to https://www.onenote.com/api/v1.0/notebooks with a JSON body. The JSON body should be
{ name: "New notebook name" }
You can see this blog post for an example.
-- James

Categories

Resources