"Response status code does not indicate success: 500 (Internal Server Error)" while creating Test Suite through TFS Rest API - tfs

While trying to create a Test Suite using TFS 2017 REST API, I am getting the error:
System.Net.Http.HttpRequestException - Response status code does not
indicate success: 500 (Internal Server Error)
Code I tried:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string base64StringPat = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", Configs.Pat)));
AuthenticationHeaderValue authHeader = new AuthenticationHeaderValue("Basic", base64StringPat);
client.DefaultRequestHeaders.Authorization = authHeader;
string url = "http://vmctp-tl-mtm:8080/tfs/DefaultCollection/SgkProject/_apis/test/Plans/7/Suites/8?api-version=1.0";
var content = new StringContent("{\"suiteType\":\"StaticTestSuite\",\"name\":\"Module1\"}", Encoding.UTF8, "application/json");
using (HttpResponseMessage response = client.PostAsync(url, content).Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
I have used this documentation from Microsoft to call the API: Create a test suite
Please guide me in fixing the issue.

HTTP code 500 means that this is an error on your server. The server threw an exception when trying to process this POST request.
So, this error has nothing to do with HttpClient. Just check your server first and see what causes the exception.
A possibility is that the specified content type is not expected by the server. POST a StringContent will set the content type to text/plain. You might find the server doesn't like that. In this case just try to find out what media type the server is expecting and set the Headers.ContentType of the StringContent instance.
Whatever, I can create the suite by below sample, you can have a try for that:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace CreateTestSuite
{
class Program
{
public static void Main()
{
Task t = CreateTestSuite();
Task.WaitAll(new Task[] { t });
}
private static async Task CreateTestSuite()
{
try
{
var username = "username";
var password = "password";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", username, password))));
string url = "http://server:8080/tfs/DefaultCollection/LCScrum/_apis/test/plans/212/suites/408?api-version=1.0";
var content = new StringContent("{\"suiteType\":\"StaticTestSuite\",\"name\":\"Module3\"}", Encoding.UTF8, "application/json");
using (HttpResponseMessage response = client.PostAsync(url, content).Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}

Related

How to authenticate with HttpRepl to test protected api's?

In order to test the Azure DevOp API,
POST https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/itemsbatch?api-version=6.0
we need to log in first.
HTTP/1.1 203 Non-Authoritative Information
What is the best way to handle authentication in this API testing?
Add tokens in the request headers?
After you get JWT you can use it in the command line like below:
set header Authorization "bearer <TOKEN VALUE>"
You can see this link https://learn.microsoft.com/en-us/aspnet/core/web-api/http-repl/?view=aspnetcore-6.0&tabs=windows#set-http-request-headers
To test the REST API, you need either Testing Tool to drive the API or writing down your own code.
Rest API can be tested with tools like:
Advanced Rest Client
Postman
To write your own code, you could refer to the following sample:
public static async void GetProjects()
{
try
{
var personalaccesstoken = "PAT_FROM_WEBSITE";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
using (HttpResponseMessage response = await client.GetAsync(
"https://dev.azure.com/{organization}/_apis/projects"))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

c# - TFS 2015 Service hook to post HTTP call to Slack

Have been working on creating a custom TFS Service Hook which 'll post (HTTP) notification to Slack.
My requirement is to POST a HTTP call to slack when a Bug workitem's status is changed to Inprogress . (I have Implemented the same with TFS Server side plugin .unfortunately , I had to go for Service Hook over Plugin)
I tried the below code with TFS 2017 onprem with PAT, unfortunately it was breaking. am I doing anything wrong ? I want my code to work in 2015.2 without PAT.
Can someone help please ?
public async static void CreateServiceHook(string collName, string projName, string projId, string AccessToken)
{
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
string url = "https://" + collName + ".visualstudio.com/DefaultCollection/_apis/projects/" + projName + "?includecapabilities=true&api-version=1.0";
HttpRequestMessage req = new HttpRequestMessage(new HttpMethod("GET"), url);
var response = client.SendAsync(req).Result;
string contents = await response.Content.ReadAsStringAsync();
}
//create service hook
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
var request = new
{
publisherId = "tfs",
eventType = "workitem.created",
consumerId = "webHooks",
consumerActionId = "httpRequest",
scope = "project",
publisherInputs = new {
// buildStatus = "",
projectId = projId
},
consumerInputs = new
{
url = "https://slack.api.com/services/XXXXXXXXXX
}
};
var response = client.PostAsync("https://" + collName + ".visualstudio.com/DefaultCollection/_apis/hooks/subscriptions/?api-version=1.0",
new StringContent(JsonConvert.SerializeObject(request).ToString(),
Encoding.UTF8, "application/json"))
.Result;
if (response.IsSuccessStatusCode)
{
dynamic content = JsonConvert.DeserializeObject(
response.Content.ReadAsStringAsync()
.Result);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
TFS has default slack service hook which can post a message to a channel. So instead of using web hooks consumer, you can use slack consumer. And you can only achieve is posting messages to Slack when a Bug workitem's status is updated.
The API looks like below:
POST http://tfsserver:8080/tfs/DefaultCollection/_apis/hooks/subscriptions?api-version=3.2
Content-Type: application/json
{
"consumerActionId":"postMessageToChannel",
"consumerId":"slack",
"consumerInputs":{
"url":"https://hooks.slack.com/services/xxxxxx"},
"eventType":"workitem.updated",
"publisherId":"tfs",
"publisherInputs":{
"areaPath":"",
"workItemType":"Bug",
"changedFields":"System.State",
"projectId":"77e3c775-dc30-4354-xxxx-xxxxxxxxxxxx"},
"scope":1
}

Xamarin - C# - HttpClient

I have a question regarding httpclient, i have a node.js rest api and Im trying to post (send) the user info to the service in order to insert to a database. the service is ok i tested manually and with postman.
But im using vs2017 xamarin and to consume the information im using the httpclient
I convert my user object to a json format
var json = JsonConvert.SerializeObject(user);
result: {"userName":"user","email":"user#hot.com","psw":"jok"}
then I create a content string type and pass the json:
var content = new StringContent(json, Encoding.UTF8, "application/json");
then I create the client
var client = new HttpClient();
and i test the following two codes
if i use this code the service work and the data is inserted in the data base but i think is because im like manually passing the parameters
HttpResponseMessage response = await client.PostAsync("http://localhost/ws/postUser/"+ e.userName + "/" + e.email + "/" + e.psw, content);
but what i was expecting is that this code works but in the server im getting the error that the url is not find. I think i need to map the parameters with the content
HttpResponseMessage response = await client.PostAsync("http://localhost/ws/postUser/", content);
The URL of the service is
http://localhost/ws/postUser/:userName/:email/:psw
this is the complete code:
I have a OnSignUpEventArgs class that inherit from EventArgs and where i declare the user object.
private async void SigUpDialog_mOnSigUpComplete(object sender, OnSignUpEventArgs e)
{
var json = JsonConvert.SerializeObject(e);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var client = new HttpClient();
HttpResponseMessage response = await client.PostAsync("http://localhost/ws/postGasUser/"+ e.userName + "/" + e.email + "/" + e.psw, content);
// HttpResponseMessage response = await client.PostAsync("http://localhost/ws/postGasUser/", content);
if (response.IsSuccessStatusCode)
{
Console.Write("Success");
}
else
{
Console.Write("Error");
}
}

Xamarin__HttpClient__HttpResponseMessage-Content --- Getting HTML instead of JSON

HttpClient myClient = new HttpClient();
myClient.BaseAddress = new Uri(URL);
Base address already specified on client it's URL.
var encodedObject = JsonConvert.SerializeObject(Obj);
myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await myClient.PostAsync("test.php/yourAPI",new StringContent(encodedObject, System.Text.Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
var responseContent = response.ToString();
var responsebody = response.Content.ToString();
Stream receiveStream = response.GetResponseStream();
string responseBodyAsText = response.Content.ReadAsStringAsync().Result;
}
Could be a content negotiation issue. Try clearing the Accept header before adding the json media type
myClient.DefaultRequestHeaders.Accept.Clear();
myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//...other code removed for brevity.
this code sets the Accept header to "application/json", which tells the server to send data in JSON format.
Reference source: Calling a Web API From a .NET Client in ASP.NET Web API 2
the Method PostAsync has as first argument the complete URI of The API. Therefore, it should be like follow :
HttpResponseMessage response = await myClient.PostAsync("http://bla-bla-bla/test.php/test",new StringContent(encodedObject, System.Text.Encoding.UTF8, "application/json"));
And there is no need to define the BaseAddress.

37signals DotNetOpenAuth ProcessUserAuthorization always returns bad request (400)

I try to get token from 37Signals using DotNetOpenAuth But geeting 400 (Bad Request) can you help me on this. below is code
[Route("basecamp1")]
public ActionResult Basecamp1()
{
var server = new DotNetOpenAuth.OAuth2.AuthorizationServerDescription();
server.AuthorizationEndpoint = new Uri("basecamp authorization URL");
server.TokenEndpoint = new Uri("basecamp Token URL");
var client = new DotNetOpenAuth.OAuth2.WebServerClient(
server, "clientid", "clientsecret");
client.RequestUserAuthorization(returnTo: new Uri("http://localhost:2263/company/settings/basecampauth"));
Response.End();
return null;
}
[Route("basecampauth")]
public void BasecampAuth(string code, string state)
{
var server = new DotNetOpenAuth.OAuth2.AuthorizationServerDescription();
server.AuthorizationEndpoint = new Uri("basecamp authorization URL");
server.TokenEndpoint = new new Uri("basecamp Token URL");
var client = new DotNetOpenAuth.OAuth2.WebServerClient(
server, "4179c03d1aea7c4d18234d3f70b4f6d4206b33e5", "f4b0b6e837bd67676f4a2432ec295be2031cecc1");
var data = client.ProcessUserAuthorization();
Response.Write(data.AccessToken);
Response.End();
}
Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request.

Resources