Issue After upgrading Restsharp version - c#

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);
}
}
}

Related

Getting "application/octet-stream" for audio, document and video files that is uploaded?

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

Create Work Item using Azure DevOps Rest API using C#

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.

how to write an asynchronous get request for an api

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.

Get submitted data from formstack using C#?

I am using this code to get form's sumbitted data from formstack
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net; //webClient
using System.IO; // use for StreamReader
namespace Test_to_integrate_FormStack
{
class Program
{
static void Main(string[] args)
{
var uri = string.Format("https://www.formstack.com/api/v2/submission/:313004779.json");
try
{
using (var webClient = new WebClient())
{
webClient.Headers.Add("Accept", "application/json");
webClient.Headers.Add("Authorization", "apikey" + "4D6A94162B2");
string Response = string.Empty;
Response = webClient.DownloadString(uri);
}
}
catch (WebException we)
{
using (var sr = new StreamReader(we.Response.GetResponseStream()))
{
}
}
}
}
}
It is giving me error:The remote server returned an error: (400) Bad Request.
Where should I wrong? Please do let me know.
Thank You
I know its late in the game, but the authentication looks incorrect to me.
It should be "Bearer [API KEY]"
Your URL is incorrect.
You used: https://www.formstack.com/api/v2/submission/:313004779.json
but it should be: https://www.formstack.com/api/v2/submission/313004779.json
https://developers.formstack.com/reference#submission-id-get
The documentation shows /:id and that means it expects a variable.
https://www.formstack.com/api/v2/submission/id.json

c# sending data to php url

okay so I have a c# console source code I have created but it does not work how I want it to.
I need to post data to a URL the same as if I was going to input it an a browser.
url with data = localhost/test.php?DGURL=DGURL&DGUSER=DGUSER&DGPASS=DGPASS
Here is my c# script that does not do it the way I want to I want it to post the data as if I had typed it like above.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string URL = "http://localhost/test.php";
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData["DGURL"] = "DGURL";
formData["DGUSER"] = "DGUSER";
formData["DGPASS"] = "DGPASS";
byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
string responsefromserver = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(responsefromserver);
webClient.Dispose();
}
}
}
I have also triead another method in c# this does now work either
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string URI = "http://localhost/test.php";
string myParameters = "DGURL=value1&DGUSER=value2&DGPASS=value3";
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "text/html";
string HtmlResult = wc.UploadString(URI, myParameters);
System.Threading.Thread.Sleep(500000000);
}
}
}
}
I have been trying to figure a way to do this in my c# console for days now
Since what you seem to want is a GET-request with querystrings and not a POST you should do it like this instead.
static void Main(string[] args)
{
var dgurl = "DGURL", user="DGUSER", pass="DGPASS";
var url = string.Format("http://localhost/test.php?DGURL={0}&DGUSER={1}&DGPASS=DGPASS", dgurl, user, pass);
using(var webClient = new WebClient())
{
var response = webClient.DownloadString(url);
Console.WriteLine(response);
}
}
I also wrapped your WebClient in a using-statement so you don't have to worry about disposing it yourself even if it would throw an exception when downloading the string.
Another thing to think about is that you might want to url-encode the parameters in the querystring using WebUtility.UrlEncode to be sure that it doesn't contain invalid chars.
How to post data to a URL using WebClient in C#: https://stackoverflow.com/a/5401597/2832321
Also note that your parameters will not appear in the URL if you post them. See: https://stackoverflow.com/a/3477374/2832321

Categories

Resources