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.
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 upload different type of files to API with the following code
using RestSharp;
using System;
using System.Net;
using System.Net.Http;
namespace ConsoleApp2;
class Program
{
static void Main()
{
var client = new RestClient("http://localhost:7071/api/Function1");
var request = new RestRequest("http://localhost:7071/api/Function1", Method.Post);
request.AddFile("File", #"D:sample Files/doc0004.pdf");
RestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
}
The problem is the content type of all files consider as a "application/octet-stream", while they are different?!
Thanks for your answers
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.
I am looking at Slack’s documentation on conversations.create and I’m not sure how to integrate it in C#. Do I need to import their Slack API solution into my code to use it? Any help would be great!
To create a channel with C# all you need to do is make a POST request to the respective API method. channels.create will work, but I recommend the newer conversations.create API method.
There are many way how to you can make a POST request in C#. Here is an example using HttpClient, which is the preferred approach. Check out this post for alternatives.
Here is an example:
using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace SlackExamples
{
class CreateChannels
{
private static readonly HttpClient client = new HttpClient();
static async Task CreateChannel()
{
var values = new Dictionary<string, string>
{
{ "token", Environment.GetEnvironmentVariable("SLACK_TOKEN") },
{ "name", "cool-guys" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://slack.com/api/conversations.create", content);
var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseString);
}
static void Main(string[] args)
{
CreateChannel().Wait();
}
}
}
Note: The token you need it kept in an environment variable for security purposes, which is good practice.
you can use httpclient or restsharp (my personal favorite) to call slacks web api.
You'd be calling https://slack.com/api/conversations.create from your application, it's not like an sdk you download.
restsharp code:
var client = new RestClient("https://slack.com/api/chat.postMessage");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "7efd9a78-827d-4cbf-a80f-c7449b96d31f");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-type", "application/json");
request.AddHeader("Authorization", "Bearer xoxb-1234-56789abcdefghijklmnop");
request.AddParameter("undefined", "{\"channel\":\"C061EG9SL\",\"text\":\"I hope the tour went well, Mr. Wonka.\",\"attachments\": [{\"text\":\"Who wins the lifetime supply of chocolate?\",\"fallback\":\"You could be telling the computer exactly what it can do with a lifetime supply of chocolate.\",\"color\":\"#3AA3E3\",\"attachment_type\":\"default\",\"callback_id\":\"select_simple_1234\",\"actions\":[{\"name\":\"winners_list\",\"text\":\"Who should win?\",\"type\":\"select\",\"data_source\":\"users\"}]}]}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
I'm trying to check Microsoft Linguistic Analysis API, basic example, so I have subscribed and addad my Key 1 in Ocp-Apim-Subscription-Key and Key 2 into the subscription key here client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");.
Then I add Newtonsoft.Json with Manage NuGet Packages into the References of Application, even it is not listed in using of particular example using Newtonsoft.Json; using bNewtonsoft.Json.Serialization; not sure, I'm new with this tool.
I'm trying to check this example Linguistics API for C# to get some natural language processing results for text analysis mainly of Verb and Noun values according to this example results So I'm not sure if I'm on the right direction with this example, or possible I've missed something to install, maybe I need some additions. I found this Analyze Method not sure how and if I have to use it for this particular goal.
But seems like something is wrong with var queryString = HttpUtility.ParseQueryString(string.Empty); and HttpUtility does not exist.
using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;
namespace CSHttpClientSample
{
static class Program
{
static void Main()
{
MakeRequest();
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
static async void MakeRequest()
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");
var uri = "https://westus.api.cognitive.microsoft.com/linguistics/v1.0/analyze?" + queryString;
HttpResponseMessage response;
// Request body
byte[] byteData = Encoding.UTF8.GetBytes("{body}");
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("< your content type, i.e. application/json >");
response = await client.PostAsync(uri, content);
}
}
}
}
You can create a new writeable instance of HttpValueCollection by calling System.Web.HttpUtility.ParseQueryString(string.Empty), and then use it as any NameValueCollection, like this:
NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
Try adding a reference to System.Web, and possibly to System.Runtime.Serialization.