FluidSurvey API - CSV filter - c#

I'm working with the fluidsurveys API.
I have a survey and now I'm going to get survey data in .csv format.
Here is the documentation
My requirement is I need to save this response as .csv file. Would it be possible to do this?
Here is a code snippet I use:
public void Read(String urlParameters)
{
String _clientURL = _url + urlParameters;
_client = new RestClient(_clientURL);
var req = new RestRequest(Method.GET);
req.AddParameter("Content-Type", "text/csv", ParameterType.HttpHeader);
req.AddParameter("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(_apikey+':'+_passWord)), ParameterType.HttpHeader);
var response = _client.Execute(req);
}

If you're just looking to modify your method to save the csv string to a file you can do as follows:
public void Read(string urlParameters, string path)
{
string _clientURL = _url + urlParameters;
_client = new RestClient(_clientURL);
var req = new RestRequest(Method.GET);
req.AddParameter("Content-Type", "text/csv", ParameterType.HttpHeader);
req.AddParameter("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(_apikey+':'+_passWord)), ParameterType.HttpHeader);
var response = _client.Execute(req);
File.WriteAllText(path, response.Content);
}

Related

Empty attachement through post WS

I'am trying to send attachement to atlassain Jira, but my files are empty.
string postUrl = url + "/rest/api/2/issue/" + issuekey + "/attachments";
MultipartFormDataContent content = new MultipartFormDataContent();
client.DefaultRequestHeaders.Add("X-Atlassian-Token", "nocheck");
HttpContent fileContent1 = new ByteArrayContent(Convert.FromBase64String(docbody));
content.Add(fileContent1, "file", filename);
var response2 = client.PostAsync(postUrl, content).Result;
if (response2.IsSuccessStatusCode)
{
Console.WriteLine("OK");
}

AzureDevops Api: Get item API with download true return a json

I'm trying to download a Git File using C#. I use the following code:
Stream response = await client.GetStreamAsync(url);
var splitpath = path.Split("/");
Stream file = File.OpenWrite(splitpath[splitpath.Length - 1]);
response.CopyToAsync(file);
response.Close();
file.Close();
Following this documentation, I use the following url:
string url = mainurl + name + "/_apis/git/repositories/" + rep + "/items?path=" + path + "&download=true&api-version=6.0";
but the file saved contains a json containing different links and information about the git file.
To check if all was working well, I tried to download it in a zip format, using the following url:
string url = mainurl + name + "/_apis/git/repositories/" + rep + "/items?path=" + path + "&$format=zip";
And it works fine, the file downloaded is a zip file containing the original file with its content...
Can someone help me? Thanks
P.S. I know that I can set IncludeContent to True, and get the content in the json, but I need the original file.
Since you are using C#, I will give you a C# sample to get the original files:
using RestSharp;
using System;
using System.IO;
using System.IO.Compression;
namespace xxx
{
class Program
{
static void Main(string[] args)
{
string OrganizationName = "xxx";
string ProjectName = "xxx";
string RepositoryName = "xxx";
string Personal_Access_Token = "xxx";
string archive_path = "./"+RepositoryName+".zip";
string extract_path = "./"+RepositoryName+"";
string url = "https://dev.azure.com/"+OrganizationName+"/"+ProjectName+"/_apis/git/repositories/"+RepositoryName+"/items?$format=zip&api-version=6.0";
var client = new RestClient(url);
//client.Timeout = -1;
var request = new RestRequest(url, Method.Get);
request.AddHeader("Authorization", "Basic "+Personal_Access_Token);
var response = client.Execute(request);
//save the zip file
File.WriteAllBytes("./PushBack.zip", response.RawBytes);
//unzip the file
if (Directory.Exists(extract_path))
{
Directory.Delete(extract_path, true);
ZipFile.ExtractToDirectory(archive_path, extract_path);
}
else
{
ZipFile.ExtractToDirectory(archive_path, extract_path);
}
}
}
}
Successfully on my side:
Let me know whether this works on your side.
var personalaccesstoken = "xyz....";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("*/*")); //this did the magic for me
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
using (Stream stream = await client.GetStreamAsync(
"https://dev.azure.com/fabrikam/myproj/_apis/git/repositories/myrepoid/items?path=%2Fsrc%2Ffolder%2Ffile.txt&api-version=7.0")) //no download arg
{
StreamReader sr = new StreamReader(stream);
var text = sr.ReadToEnd();
return text; // text has the content of the source file
}
}
no need for download parameter in the url
request headers should not be json

Posting a file with a raw XML using RestClient

I've been using similar XML Posts with success....just that this one calls for ProofPDF which is a byte array.
How can I populate this XML Tag properly... I'm getting an invalid request at the moment.
public async void Post(List<IFormFile> files)
{
MemoryStream s = new MemoryStream();
files[0].CopyTo(s);
var client = new RestClient("https://api.2312312312dsa.com/default.asmx");
var request = new RestRequest();
request.AddHeader("SOAPAction", "http://api.giuhuiu.com/v20/LifelineStatus_Update");
request.AddHeader("Content-Type", " text/xml; charset=utf-8");
request.AddBody("<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body> <EP_Update xmlns=\"http://api.dddd23432.com\"><Request><Credentials><Username>dddd</Username><Password>dddd</Password><Client>test</Client></Credentials><CustomerID>1234454</CustomerID><Status>APPROVED</Status>"
+ "<ProofPDF>"+ s.ToArray()+"</ProofPDF>" //Here is the concerning code
+ "<Program>Apples</Program>"
+ "</Request></EP_Update></soap:Body></soap:Envelope>", "txt/xml");
var response = client.PostAsync(request);
var m = response.Result;
return;
}
Don't set the content type, read the docs, and use AddStringBody
request.AddStringBody(xmlString, "application/xml");
var response = await client.PostAsync(request);

Translate single document using azure translator

I want to translate single document from one language to another please guide me how to do that i have done translating all the files in azure blob storage but not able to find to translate single file.
please find below code and let me know the changes.
string _FileName = Path.GetFileName(file.FileName);
fileName = _FileName;
string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);
file.SaveAs(_path);
string route = "/batches";
string endpoint = "https://translator.cognitiveservices.azure.com/translator/text/batch/v1.0";
string filePath = UploadToAzureStorageAccount.UploadDocument(_path, "uploadeddocs");
string subscriptionKey = "key";
string json = ("" +
"{\"inputs\": " +
"[{\"storageType\": \"File\","+"\"source\": " +
"{\"sourceUrl\": \"https://cdposticketsstorage.blob.core.windows.net/uploadeddocs/test.docx?sp=r&st=2022-03-08T08:13:18Z&se=2022-03-08T16:13:18Z&spr=https&sv=2020-08-04&sr=b&sig=Pt68ogFCj6WSgEBUWI95YJ4GudOcyhEW1cgVXmFCing%3D\"," +
"\"storageSource\": \"AzureBlob\"" +
"}," +
"\"targets\": " +
"[{\"targetUrl\": \"https://cdposticketsstorage.blob.core.windows.net/translateddocs/translate.docx?sp=rcw&st=2022-03-08T11:15:45Z&se=2022-03-08T19:15:45Z&spr=https&sv=2020-08-04&sr=b&sig=QM2FhLxOIE%2FLjeLLfYyR2PmfkNb3nm70wZdCveSJC0M%3D\"," +
"\"storageSource\": \"AzureBlob\"," +
"\"language\": \"fr\"}]}]}");
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
string result = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Status code: {response.StatusCode}");
Console.WriteLine();
Console.WriteLine($"Response Headers:");
Console.WriteLine(response.Headers);
}
else
Console.Write("Error");
}
// TextTranslatorAPI client = new TextTranslatorAPI();
//string res = await client.DocumentTranslator(fileName);
//return res;
}
ViewBag.Message = "File Uploaded Successfully!!";
}
catch(Exception e)
{
ViewBag.Message = "File upload failed!!";
}

How to download file from API using Post Method

I have an API using POST Method.From this API I can download the file via Postmen tool.But I would like to know how to download file from C# Code.I have tried below code but POST Method is not allowed to download the file.
Code:-
using (var client = new WebClient())
{
client.Headers.Add("X-Cleartax-Auth-Token", ConfigurationManager.AppSettings["auth-token"]);
client.Headers[HttpRequestHeader.ContentType] = "application/json";
string url = ConfigurationManager.AppSettings["host"] + ConfigurationManager.AppSettings["taxable_entities"] + "/ewaybill/download?print_type=detailed";
TransId Id = new TransId()
{
id = TblHeader.Rows[0]["id"].ToString()
};
List<string> ids = new List<string>();
ids.Add(TblHeader.Rows[0]["id"].ToString());
string DATA = JsonConvert.SerializeObject(ids, Newtonsoft.Json.Formatting.Indented);
string res = client.UploadString(url, "POST",DATA);
client.DownloadFile(url, ConfigurationManager.AppSettings["InvoicePath"].ToString() + CboGatePassNo.EditValue.ToString().Replace("/", "-") + ".pdf");
}
Postmen Tool:-
URL : https://ewbbackend-preprodpub-http.internal.cleartax.co/gst/v0.1/taxable_entities/1c74ddd2-6383-4f4b-a7a5-007ddd08f9ea/ewaybill/download?print_type=detailed
Header :-
Content-Type : application/json
X-Cleartax-Auth-Token :b1f57327-96db-4829-97cf-2f3a59a3a548
Body :-
[
"GLD24449"
]
using (WebClient client = new WebClient())
{
client.Headers.Add("X-Cleartax-Auth-Token", ConfigurationManager.AppSettings["auth-token"]);
client.Headers[HttpRequestHeader.ContentType] = "application/json";
string url = ConfigurationManager.AppSettings["host"] + ConfigurationManager.AppSettings["taxable_entities"] + "/ewaybill/download?print_type=detailed";
client.Encoding = Encoding.UTF8;
//var data = "[\"GLD24449\"]";
var data = UTF8Encoding.UTF8.GetBytes(TblHeader.Rows[0]["id"].ToString());
byte[] r = client.UploadData(url, data);
using (var stream = System.IO.File.Create("FilePath"))
{
stream.Write(r,0,r.length);
}
}
Try this. Remember to change the filepath. Since the data you posted is not valid
json. So, I decide to post data this way.
I think it's straight forward, but instead of using WebClient, you can use HttpClient, it's better.
here is the answer HTTP client for downloading -> Download file with WebClient or HttpClient?
comparison between the HTTP client and web client-> Deciding between HttpClient and WebClient
Example Using WebClient
public static void Main(string[] args)
{
string path = #"download.pdf";
// Delete the file if it exists.
if (File.Exists(path))
{
File.Delete(path);
}
var uri = new Uri("https://ewbbackend-preprodpub-http.internal.cleartax.co/gst/v0.1/taxable_entities/1c74ddd2-6383-4f4b-a7a5-007ddd08f9ea/ewaybill/download?print_type=detailed");
WebClient client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers.Add("X-Cleartax-Auth-Token", "b1f57327-96db-4829-97cf-2f3a59a3a548");
client.Encoding = Encoding.UTF8;
var data = UTF8Encoding.UTF8.GetBytes("[\"GLD24449\"]");
byte[] r = client.UploadData(uri, data);
using (var stream = System.IO.File.Create(path))
{
stream.Write(r, 0, r.Length);
}
}
Here is the sample code, don't forget to change the path.
public class Program
{
public static async Task Main(string[] args)
{
string path = #"download.pdf";
// Delete the file if it exists.
if (File.Exists(path))
{
File.Delete(path);
}
var uri = new Uri("https://ewbbackend-preprodpub-http.internal.cleartax.co/gst/v0.1/taxable_entities/1c74ddd2-6383-4f4b-a7a5-007ddd08f9ea/ewaybill/download?print_type=detailed");
HttpClient client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, uri)
{
Content = new StringContent("[\"GLD24449\"]", Encoding.UTF8, "application/json")
};
request.Headers.Add("X-Cleartax-Auth-Token", "b1f57327-96db-4829-97cf-2f3a59a3a548");
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
using (FileStream fs = File.Create(path))
{
await response.Content.CopyToAsync(fs);
}
}
else
{
}
}

Categories