Using convertapi in Windows Store App - c#

Im trying out the Convertapi in a Windows store App project, and i want to send a .docx file and get a pdf file in return, im trying to do a post but im not sure how its done, this is what i have so far, but its not working.
private async Task GeneratePdfContract(string path) {
try {
var data = new List < KeyValuePair < string, string >> {
new KeyValuePair < string, string > ("Api", "5"),
new KeyValuePair < string, string > ("ApiKey", "419595049"),
new KeyValuePair < string, string > ("File", "" + stream2),
};
await PostKeyValueData(data);
} catch (Exception e) {
Debug.WriteLine(e.Message);
}
}
private async Task PostKeyValueData(List < KeyValuePair < string, string >> values) {
var httpClient = new HttpClient();
var response = await httpClient.PostAsync("http://do.convertapi.com/Word2Pdf", new FormUrlEncodedContent(values));
var responseString = await response.Content.ReadAsStringAsync();
}
How should i do my post to send a .docx file and get a .pdf file in return?
Edit:
private async Task GeneratePdfContract(string path)
{
try
{
using (var client = new System.Net.Http.HttpClient())
{
using (var multipartFormDataContent = new MultipartFormDataContent())
{
var values = new[]
{
new KeyValuePair<string, string>("ApiKey", "413595149")
};
foreach (var keyValuePair in values)
{
multipartFormDataContent.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key));
}
StorageFolder currentFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(Constants.DataDirectory);
StorageFile outputFile = await currentFolder.GetFileAsync("file.docx");
byte[] fileBytes = await outputFile.ToBytes();
//multipartFormDataContent.Add(new ByteArrayContent(FileIO.ReadBufferAsync(#"C:\test.docx")), '"' + "File" + '"', '"' + "test.docx" + '"');
multipartFormDataContent.Add(new ByteArrayContent(fileBytes));
const string requestUri = "http://do.convertapi.com/word2pdf";
var response = await client.PostAsync(requestUri, multipartFormDataContent);
if (response.IsSuccessStatusCode)
{
var responseHeaders = response.Headers;
var paths = responseHeaders.GetValues("OutputFileName").First();
var path2 = Path.Combine(#"C:\", paths);
StorageFile sampleFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(#"C:\Users\Thought\AppData\Local\Packages\xxxxx_apk0zz032bzya\LocalState\Data\");
await FileIO.WriteBytesAsync(sampleFile, await response.Content.ReadAsByteArrayAsync());
}
else
{
Debug.WriteLine("Status Code : {0}", response.StatusCode);
Debug.WriteLine("Status Description : {0}", response.ReasonPhrase);
}
}
}
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
}
#Tomas tried to adapt your answer a bit since there doesn't seem to be a "File.ReadAllBytes" on windows store apps, im getting this response tho :\

You can't pass file stream as string to HttpClient. Just use WebClient.UploadFile method which also support asynchronous uploads.
using (var client = new WebClient())
{
var fileToConvert = "c:\file-to-convert.docx";
var data = new NameValueCollection();
data.Add("ApiKey", "413595149");
try
{
client.QueryString.Add(data);
var response = client.UploadFile("http://do.convertapi.com/word2pdf", fileToConvert);
var responseHeaders = client.ResponseHeaders;
var path = Path.Combine(#"C:\", responseHeaders["OutputFileName"]);
File.WriteAllBytes(path, response);
Console.WriteLine("The conversion was successful! The word file {0} converted to PDF and saved at {1}", fileToConvert, path);
}
catch (WebException e)
{
Console.WriteLine("Exception Message :" + e.Message);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
}
}
}
The example using HttpClient()
using (var client = new System.Net.Http.HttpClient())
{
using (var multipartFormDataContent = new MultipartFormDataContent())
{
var values = new[]
{
new KeyValuePair<string, string>("ApiKey", "YourApiKey")
};
foreach (var keyValuePair in values)
{
multipartFormDataContent.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key));
}
multipartFormDataContent.Add(new ByteArrayContent(File.ReadAllBytes(#"C:\test.docx")), '"' + "File" + '"', '"' + "test.docx" + '"');
const string requestUri = "http://do.convertapi.com/word2pdf";
var response = await client.PostAsync(requestUri, multipartFormDataContent);
if (response.IsSuccessStatusCode)
{
var responseHeaders = response.Headers;
var paths = responseHeaders.GetValues("OutputFileName").First();
var path = Path.Combine(#"C:\", paths);
File.WriteAllBytes(path, await response.Content.ReadAsByteArrayAsync());
}
else
{
Console.WriteLine("Status Code : {0}", response.StatusCode);
Console.WriteLine("Status Description : {0}", response.ReasonPhrase);
}
}
}

Related

My translation of a given string doesn't work using AzureApi

I want to translate a given string to a specific language and print the translation to console , but my console prints nothing , I am also trying to catch some error , but my console still prints nothing, anyone know why ?
Here are my headers:
using Newtonsoft.Json;
using System.Net.Http;
using NPOI.SS.Formula.Functions;
I have defined the necessary key and region and url attribute inside class block , but it just won't work like this :
public const string subscriptionKey = "mykey";
public const string region = "myregion";
public const string endpoint="https://api.cognitive.microsofttranslator.com/";
mykey consists of my subscription key and myregion consists of my region
Here is my main:
TranslateString();
Here is my implementation of method TranslateString
public static async void TranslateString()
{
string route = "translate?api-version=3.0&from=en&to=fr&to=zu";
string xmlString = "Hello , welcome";
try
{
object[] body = new object[] { new { Text = xmlString } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
request.Headers.Add("Ocp-Apim-Subscription-Region", region);
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success , translated text:");
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
else
{
Console.WriteLine("Error: " + response.StatusCode + " " + response.ReasonPhrase);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.Message);
}
Here is your code with minimal changes to make it produce an output. The relevant change is for TranslateString() to return a Task, so that the main thread waits for the async call to complete. Another option would have been to make this a synchronous call.
This uses the .Net built-in Json serializer instead of Newtonsoft for simplicity.
This compiles as is using .Net7 with C#10, and your key and region filled in.
using System.Net;
using System.Text;
using System.Text.Json;
const string subscriptionKey = "mykey";
const string region = "myregion";
const string endpoint = "https://api.cognitive.microsofttranslator.com/";
Console.WriteLine("Program Start");
await TranslateString();
static async Task TranslateString()
{
string route = "translate?api-version=3.0&from=en&to=fr&to=zu";
string xmlString = "Hello , welcome";
try
{
object[] body = new object[] { new { Text = xmlString } };
var requestBody = JsonSerializer.Serialize(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
request.Headers.Add("Ocp-Apim-Subscription-Region", region);
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success , translated text:");
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
else
{
Console.WriteLine("Error: " + response.StatusCode + " " + response.ReasonPhrase);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.Message);
}
}
The output is:
Program Start
Success , translated text:
[{"translations":[{"text":"Bonjour , bienvenue","to":"fr"},{"text":"Sawu , wamukelekile","to":"zu"}]}]
You will need to add deserializing the output.

Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: h. Path '', line 0, position 0

I am trying to display the URL of the selected image to be uploaded. However, when I run the program it tells me Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: h. Path '', line 0, position 0. and that there is an issue with the parsing in the deserialization. However, I do not see any issues with the deserialization. Am I not seeing something that is causing this? The web api returns the AbsoluteUri for my file that has been uploaded which I made it into a string... so it returns var absoluteUrl = blob.Uri.AbsoluteUri.ToString();.
private async Task<HttpResponseMessage> UploadFileSelected()
{
// Create the content
var content = new MultipartFormDataContent();
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
content.Add(new StreamContent(fileStream, Convert.ToInt32(fileStream.Length)), "file", fileName);
string url = "https://localhost:5011";
var response = await _httpClient.PostAsync($"{url}/api/fileupload", content);
response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<HttpResponseMessage>(responseContent);
message = "Uploaded!!";
fileurl = responseContent;
Console.Write("result: " + result);
Console.WriteLine("url: " + fileurl);
return await Task.FromResult(result);
}
Endpoint:
[HttpPost]
public async Task<IActionResult> Upload()
{
try
{
var formCollection = await Request.ReadFormAsync();
var file = formCollection.Files.First();
if (file.Length > 0)
{
var container = new BlobContainerClient(_azureConnectionString, "container");
var createResponse = await container.CreateIfNotExistsAsync();
if (createResponse != null && createResponse.GetRawResponse().Status == 201)
await container.SetAccessPolicyAsync(PublicAccessType.Blob);
var blob = container.GetBlobClient(file.FileName);
await blob.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots);
using (var fileStream = file.OpenReadStream())
{
await blob.UploadAsync(fileStream, new BlobHttpHeaders { ContentType = file.ContentType });
}
var absoluteUrl = blob.Uri.AbsoluteUri.ToString();
Console.WriteLine(absoluteUrl);
return Ok(absoluteUrl);
}
return BadRequest();
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}

How to post Image from xamrine to webapi in asp.net mvc

Here is my webapi code that is correct i check that i post the
image using postman..how to send image to webapi image save is already work .but i need how to post image from xamrine to webapi request.
[HttpPost]
public ActionResult PostData([System.Web.Http.FromBody] string Name,HttpPostedFileBase Picture)
{
ResponseModel response = new ResponseModel();
try
{
//using (AndroidApiPostEntities db = new AndroidApiPostEntities())
//{
Dictionary<dynamic, dynamic> dic = new Dictionary<dynamic, dynamic>();
string img = "";
img = ImageUpload(Picture);
PostPicture p = new PostPicture();
p.Name = Name;
p.Picture = img;
//db.PostPictures.Add(p);
//db.SaveChanges();
response.error = false;
response.message = "data added successfully.";
dic.Add("Id", 0);
dic.Add("Name", p.Name);
dic.Add("Picture", p.Picture);
response.data = dic;
return Json(response, JsonRequestBehavior.AllowGet);
//}
}
catch (Exception ex)
{
response.error = true;
response.message = "inner exp: " + ex.InnerException.Message + " /second/: " + Convert.ToString(ex.InnerException);
return Json(response, JsonRequestBehavior.AllowGet);
}
}
private string ImageUpload(HttpPostedFileBase img)
{
string fileName;
string extension = System.IO.Path.GetExtension(img.FileName);
Random rnd = new Random();
fileName = "b" + rnd.Next(1000).ToString("000") + extension; //Create a new Name for the file due to security reasons.
// string fileName = Guid.NewGuid().ToString() + ImageName;
//var path = Path.Combine(Directory.GetCurrentDirectory(), "images", fileName);
//string fileName = Guid.NewGuid().ToString() + ImageName;
string physicalPath = Server.MapPath("/images/" + fileName);
//string physicalPath = "~/images/" + fileName;
// save image in folder
img.SaveAs(physicalPath);
return fileName;
}
Now here is my xamrine button click code how to post image or how to convert image to post it also hit the api here is code but i face image error i face null picture on webapi
private async void btnsubmit_Clicked(object sender, EventArgs e)
{
try
{
string picc = MyImage.Source.ToString();
PostUserAsync(txtName.Text, "");
}
catch (Exception ex)
{
await DisplayAlert("Error", ex.InnerException.ToString(), "OK");
}
}
static MediaFile files;
public async void PostUserAsync(string name, string pic)
{
string Host = "http://dxxx5.expxxxxxxxion.com/Home/PostData";
var client = new HttpClient();
var ss=MyImage.Source = ImageSource.FromStream(() =>
{
var stream = files.GetStream();
return stream;
});
byte[] file = File.ReadAllBytes(files.Path);
WebClient webClient = new WebClient();
var fileData = webClient.Encoding.GetString(file);
var fileName = System.IO.Path.GetFileNameWithoutExtension(files.Path);
var model = new PostPicture
{
Name = name,
Picture = file
};
var json = JsonConvert.SerializeObject(model);
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = client.PostAsync(Host, httpContent).Result;
string res = "";
using (HttpContent content = response.Content)
{
// ... Read the string.
Task<string> result = content.ReadAsStringAsync();
res = result.Result;
}
var jsoss = JsonConvert.DeserializeObject(res);
//var rootObj = JsonConvert.DeserializeObject<PostPicture>(File.ReadAllText(res));
string f = jsoss.ToString();
await DisplayAlert("Successfull", f, "OK");
}

sending the image as a bytes to the web service in Windows Application

I'm working on UWP apps, In that i need to upload the image for that i'm calling the web service to post the details. I'm using the below code to serialize the image.
byte[] fileBytes = null;
using (var stream = await file.OpenReadAsync())
{
fileBytes = new byte[stream.Size];
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(fileBytes);
}
}
docs.Document = fileBytes;
docs.DocumentName = file.Name;
docs.DocumentTypeOtherDescription = "ProfilePicture";
var docsAsJson = JsonConvert.SerializeObject(docs);
StringContent stringContent = new StringContent(docsAsJson, System.Text.Encoding.UTF8);
ByteArrayContent byteContent = new ByteArrayContent(fileBytes);
MultipartFormDataContent httpContent = new MultipartFormDataContent();
httpContent.Add(byteContent, file.Name);
httpContent.Add(stringContent);
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage {Method = HttpMethod.Post};
request.Headers.Add("authorization", App.TokenType + " " + App.AccessToken);
request.RequestUri = new Uri(App.BaseUrl + "api/User/UploadUserDocument");
request.Content = httpContent;
request.Content.Headers.Add(#"Content-Length", fileBytes.Length.ToString());
var response = httpClient.SendAsync(request).Result;
var data = response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
}
}
This is my side to serialize the image and in service side they deserialize the image and saved in database. But i'm getting StatusCode: 500, ReasonPhrase: 'Internal Server Error' this error, Any one please help me to solve this issue.
Here is my Service Code:
public IHttpActionResult UpdateUserWithProfilePic(FormData userviewmodel)
{
var error = string.Empty;
var userJson = new StringBuilder();
foreach (var items in userviewmodel.Fields)
{
if (items.Name == "}")
{
if (!userJson.ToString().EndsWith(",")) continue;
userJson.Remove(userJson.Length - 1, 1);
userJson.Append("}");
}
else
userJson.Append((items.Name.Replace("%22", "\"")) + ":" + items.Value);
}
var userView = JsonConvert.DeserializeObject<UserViewModel>(userJson.ToString());
var result = UpdateUser(userView, error);
if (result.ResultType != ResultType.Success) return daHttpActionResult(result.Result, result);
if (userviewmodel.Files != null && userviewmodel.Files.Count > 0)
{
userView.ProfileDocument = new UserDocument
{
DocumentName = userviewmodel.Files[0].Name,
Document = userviewmodel.Files[0].Value.Buffer,
UserID = UserId,
DocumentType = DocumentTypeEnum.ProfilePicture,
DocumentTypeOtherDescription = userviewmodel.Files[0].Value.MediaType,
};
}
return AdHttpActionResult(result.Result, result);
}
Thanks & Regards,
Cristina

Client code to upload file via ASP.NET MVC WebApi

I am trying to write code to upload file(s) by WinForm app to WebApi.
The WebApi code is like:
[HttpPost]
[Route("UploadEnvelope")]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
public Task<HttpResponseMessage> PostUploadEnvelope()
{
HttpRequestMessage request = this.Request;
if (!request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
var provider = new MultipartFormDataStreamProvider(root);
var task = request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(o =>
{
foreach (MultipartFileData fileData in provider.FileData)
{
if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
{
return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
}
string fileName = fileData.Headers.ContentDisposition.FileName;
if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
{
fileName = fileName.Trim('"');
}
if (fileName.Contains(#"/") || fileName.Contains(#"\"))
{
fileName = Path.GetFileName(fileName);
}
File.Move(fileData.LocalFileName, Path.Combine(root, fileName));
}
return new HttpResponseMessage()
{
Content = new StringContent("Files uploaded.")
};
}
);
return task;
}
But I am not sure how to call it and pass file in a client app.
static string UploadEnvelope(string filePath, string token, string url)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
// How to pass file here ???
var response = client.GetAsync(url + "/api/Envelope/UploadEnvelope").Result;
return response.Content.ReadAsStringAsync().Result;
}
}
Any help or suggestion is welcome. Thanks in advance!
First you are using Get method which is used for reading. You have to use Post instead.
Try the following:
public static string UploadEnvelope(string filePath,string token, string url)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
using (var content = new MultipartFormDataContent("Envelope" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
{
content.Add(new StreamContent(new MemoryStream(File.ReadAllBytes(filePath))), "filename", "filename.ext");
using (var message = await client.PostAsync(url + "/api/Envelope/UploadEnvelope", content))
{
var input = await message.Content.ReadAsStringAsync();
return "success";
}
}
}
}
Note: For a large file you have to change configuration on IIS web.config.

Categories