I am unable to create Work Item using Azure DevOps REST API as mentioned in Work Items - Create
Request:
https://dev.azure.com/{organization}/MyTestProject/_apis/wit/workitems/$Task?api-version=6.0-preview.3
Request Body:
[
{
"op": "add",
"path": "/fields/System.Title",
"value": "Task2"
}
]
Code to Get Response (Note this code works for all other POST Requests):
using (HttpResponseMessage response = client.SendAsync(requestMessage).Result)
{
response.EnsureSuccessStatusCode();
JsonResponse = await response.Content.ReadAsStringAsync();
}
Response: 400
Can someone please suggest?
It might be helpful to see your full example. However, here is a working example with Newtonsoft.Json (do not forget to create your PAT create personal access token):
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
string PAT = "<personal access token>"; //https://learn.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=azure-devops&tabs=preview-page
string requestUrl = "https://dev.azure.com/<my_org>/<my_project>/_apis/wit/workitems/$Task?api-version=5.0";
try
{
List<Object> flds = new List<Object>
{
new { op = "add", path = "/fields/System.Title", value = "Title" }
};
string json = JsonConvert.SerializeObject(flds);
HttpClientHandler _httpclienthndlr = new HttpClientHandler();
using (HttpClient client = new HttpClient(_httpclienthndlr))
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", PAT))));
var request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUrl)
{
Content = new StringContent(json, Encoding.UTF8, "application/json-patch+json")
};
HttpResponseMessage responseMessage = client.SendAsync(request).Result;
}
}
catch (Exception ex)
{
}
}
}
}
Additionally, you can consider to use .NET client libraries for Azure DevOps and TFS. Here is the example: Create a bug in Azure DevOps Services using .NET client libraries
application/json-patch+json is required.
Related
Can someone please help on this issue, i gets hang and no error is coming.
Seems like ends up with some unknow issue.
I am attaching my code before and after upgrading the restsharp library.
Code in Rest sharp version 106.12.00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
var client = new RestClient("https://shoonyatrade.finvasia.com/NorenWClientTP/QuickAuth");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "text/plain");
var body = #"jData={""apkversion"":""1.0.0"",""uid"":""123456""}";
request.AddParameter("text/plain", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
}
}
Code after upgrading to 108.0.1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
var client = new RestClient("https://shoonyatrade.finvasia.com/NorenWClientTP/QuickAuth");
client.Options.MaxTimeout = -1;
var request = new RestRequest("",Method.Post);
request.AddHeader("Content-Type", "text/plain");
var body = #"jData={""apkversion"":""1.0.0"",""uid"":""123456""}";
request.AddParameter("text/plain", body, ParameterType.RequestBody);
RestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
}
}
Expected Response
{"stat":"Not_Ok","emsg":"Invalid Input : uid or pwd or factor2 or imei or apkversion or vc or appkey or source is Missing."}
Postman Authorisation
Postman Headers
PostMan Results (Expected)
The docs clearly say that you should not use AddParameter with content-type as the parameter name. It won't work.
Use AddStringBody as described in the docs.
request.AddStringBody(body, "text/plain);
You would spend way less time figuring out what's wrong by sending requests to something like requestbin.com and analysing the actual content of it.
Adding this line solved my issue
System.Net.ServicePointManager.Expect100Continue = false;
I have used fiddler to understand what actual request is going on web.
using RestSharp;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp5
{
class Program
{
static async Task Main(string[] args)
{
System.Net.ServicePointManager.Expect100Continue = false;
var client = new RestClient("https://shoonyatrade.finvasia.com/NorenWClientTP/QuickAuth");
var request = new RestRequest("",Method.Post);
var body = #"jData={""apkversion"":""1.0.0"",""uid"":""123456""}";
request.AddParameter("text/plain", body, ParameterType.RequestBody);
RestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
}
}
I have a site on localhost created to learn how to send http requests, I send a post request to it, trying to simulate sending data via forms, as a response I expect that the data I sent will be added to the database, as it happens when sending via forms, but this does not happen. I assume that I am sending the post request incorrectly and something is missing in it
The site: localhost site
Post request: Pose request headers and data
My C# code:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace AirParsingScript
{
class Program
{
private static readonly HttpClient Client = new HttpClient();
static async Task Main()
{
var values = new Dictionary<string, string>
{
{ "Person.DocId_pre", "421" },
{ "Person.DocId", "ADGAGSA" },
{ "Person.Email", "4124421" },
{ "Person.TeleNumber", "4444" }
};
var content = new FormUrlEncodedContent(values);
var response = await Client.PostAsync("https://localhost:44391", content);
var responseString = await Client.GetStringAsync("https://localhost:44391");
// var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseString);
}
}
}
I'm following
https://towardsdatascience.com/creating-a-serverless-python-chatbot-api-in-microsoft-azure-from-scratch-in-9-easy-steps-2f1913fc9581
in creating a python chatbot, and my source code is as below, however when I try to run it, I'm getting an error. According to repositories that error is the adapter's on_error handler receives any exceptions thrown by bot's turn logic. If there is an exception thrown, the handler deletes the conversation state for the current conversation to prevent the bot from getting stuck in an error-loop caused by being in a bad state. any expert can help with this?
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Schema;
using System.Net;
using System;
using System.Net.Http;
using System.Text; // for class Encoding
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Microsoft.BotBuilderSamples.Bots
{
public class EchoBot : ActivityHandler
{
public class FlaskRequestModel
{
[JsonProperty("text")]
public string Text {get; set;}
}
protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
var replyText = $"{turnContext.Activity.Text}";
//if (!replyText.ToLower().Contains("Hey Bot")){ # Optional bit of code that only sends the sends the message to the back end if it contains a particular keyword
// return;
//}
var replyTextModel = new FlaskRequestModel()
{
Text = replyText
};
var jsonObject = JsonConvert.SerializeObject(replyTextModel);
var request = new HttpRequestMessage()
{
Content = new StringContent(jsonObject, Encoding.UTF8, "application/json"),
Method = HttpMethod.Post,
RequestUri = new Uri("yudao.azurewebsites.net"), // <- Replace the URL with the the URL for your function app
};
var httpClient = new HttpClient();
// httpClient.DefaultRequestHeaders.Add("API-Key","your API-key"); <- required if your HTTP trigger authorization was set to something other than Anonymous
var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead);
if (response.IsSuccessStatusCode)
{
var responseString = await response.Content.ReadAsStringAsync();
await turnContext.SendActivityAsync(MessageFactory.Text(responseString, responseString), cancellationToken);
}
else
{
await turnContext.SendActivityAsync(MessageFactory.Text("failure", "failure"), cancellationToken);
var responseString = await response.Content.ReadAsStringAsync();
await turnContext.SendActivityAsync(MessageFactory.Text(responseString, responseString), cancellationToken);
}
}
}
}
try this using regex:
A2 = "12 15|||Pform|||their|||REQUIRED|||-NONE-|||0"
intval=[val for val in A2.split('|||') if bool(re.search(pattern='\d+', string=val))]
Output:
['12 15', '0']
I have an existing and functioning API, which now have to be able to get data from another external API. How do i do that best?
I have tried with using HTTPClient, but i can't seem to get it to work. The error i get:
"No MediaTypeFormatter is available to read an object of type 'IList`1' from content with media type 'text/html'." -> I get this error on line 37. Can you spot it and/or tell me how I can do this differently, taking into account that all i want is the data (From the external API) and not to display it using a view, as this is an API?
Code below. I have also created a Pastebin: https://pastebin.com/MuKjEVys
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net;
namespace API.Controllers
{
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class ExternalApiController : Controller
{
private string ExternalApiLink = "https://blablabla.com/api";
private string ExternalApiLinkGet = "/module/1/";
[HttpGet("getdata")]
public ActionResult<ExternalApi> GetDataFromExternal()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ExternalApiLink);
var requestApi = client.GetAsync(ExternalApiLinkGet);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "XXXX");
requestApi.Wait();
var resultFromApi = requestApi.Result;
if (resultFromApi.IsSuccessStatusCode)
{
var readResponse = resultFromApi.Content.ReadAsAsync<IList<ExternalApi>>();
readResponse.Wait();
var data = readResponse.Result;
return Json(data);
}else
{
return NotFound();
}
}
}
}
}
Your response content seems to be json, while the content-type is text/html. If that is the case, the first thing to do would be to call the party that is exposing the service and have them fix it. In the meantime you could just read the content of the response as a string, and deserialize that string:
// Note that I made this method async.
public async Task<IActionResult> GetDataFromExternal()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ExternalApiLink);
// note that I moved this line above the GetAsync method.
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "XXXX");
// note that I'm disposing the response
using (var response = await client.GetAsync(ExternalApiLinkGet))
{
if (response.IsSuccessStatusCode)
{
// Since the response content is json, but the content-type
// is text/html, simply read the content as a string.
string content = await response.ReadAsStringAsync();
// You can return the actual received content like below,
// or you may deserialize the content before returning to make
// sure it is correct, using JsonConvert.DeserializeObject<List<ExternalApi>>()
// var data = JsonConvert.DeserializeObject<List<ExternalApi>>(content);
// return Json(data);
return Content(content, "application/json");
}
else
{
return NotFound();
}
}
}
}
I received access for an API and I have multiple files I want to send through to the API to be analysed. The responses are saved in json format on my hard drive and I would like them to be saved with different file names.
I would like to send a single file every 3 seconds, so that I don't crash their server. I know how to do it for a single file, but do not know how to automate this for many files.
I have uploaded audiofiles with the names: www.xyz.com/myaudiofile1, www.xyz.com/myaudiofile2,www.xyz.com/myaudiofile3.
I am using Visual Studio and my singular request is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.IO;
using RestSharp;
using RestSharp.Authenticators;
namespace TestAudio
{
class Program
{
static void Main(string[] args)
{ try
{
var ClientEndpoint = "https://website ";
var audiofile = "https://myaudiofile1 ";
var client = new RestClient(ClientEndpoint + audiofile);
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Login", "Login Key");
IRestResponse response = client.Execute(request);
System.IO.File.WriteAllText(#"C:\Users\myaudiofile1.json",response.Content);
Console.WriteLine(response.Content.ToString());
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
If you use Microsoft's Reactive Framework (aka Rx) then you can do this:
var files = new[] { "myaudiofile1", "myaudiofile2", "myaudiofile3" };
var query =
Observable
.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(3.0))
.Zip(files, (_, audiofile) => audiofile)
.Select(audiofile =>
{
var ClientEndpoint = "https://website ";
var client = new RestClient(ClientEndpoint + audiofile);
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Login", "Login Key");
IRestResponse response = client.Execute(request);
return (audiofile, response.Content);
});
var subscription =
query
.Subscribe(x => System.IO.File.WriteAllText($#"C:\Users\{x.audiofile}.json", x.Content));
It would be useful to know what objects are disposable as that would change the way I would write this code.
Just NuGet System.Reactive and add using System.Reactive.Linq; to get this to work.