Translate single document using azure translator - c#

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!!";
}

Related

Azure Storage Queue via REST API c# using Shared Key Authentication

I am trying to call Azure Storage queue using REST API, but I am getting an error
The MAC signature found in the HTTP request
'UCiypkoySXueF4scXt+EqQESf5VXmAVLJUA93+3W10M=' is not the same as any
computed signature. The server used following string to sign: 'POST
text/plain
My C# Code is
var Client = new HttpClient();
var RequestDateString = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
if (Client.DefaultRequestHeaders.Contains("x-ms-date"))
Client.DefaultRequestHeaders.Remove("x-ms-date");
Client.DefaultRequestHeaders.Add("x-ms-date", RequestDateString);
var StorageAccountName = "storaxxxxxxxsnd";
var StorageKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==";
String urlPath = String.Format("{0}/messages", "splitator");
Uri uri = new Uri(string.Format("https://{0}.queue.core.windows.net/", StorageAccountName) + urlPath);
if (Client.DefaultRequestHeaders.Contains("Authorization"))
Client.DefaultRequestHeaders.Remove("Authorization");
var canonicalizedStringToBuild = string.Format("{0}\n{1}", RequestDateString, $"/{StorageAccountName}/{uri.AbsolutePath.TrimStart('/')}");
string signature;
using (var hmac = new HMACSHA256(Convert.FromBase64String(StorageKey)))
{
byte[] dataToHmac = Encoding.UTF8.GetBytes(canonicalizedStringToBuild);
signature = Convert.ToBase64String(hmac.ComputeHash(dataToHmac));
}
string authorizationHeader = string.Format($"{StorageAccountName}:" + signature);
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedKey", authorizationHeader);
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
if (Client.DefaultRequestHeaders.Contains("x-ms-version"))
Client.DefaultRequestHeaders.Remove("x-ms-version");
Client.DefaultRequestHeaders.Add("x-ms-version", "2015-12-11");
// if (httpMethod == HttpMethod.Delete || httpMethod == HttpMethod.Put)
// {
// if (Client.DefaultRequestHeaders.Contains("If-Match"))
// Client.DefaultRequestHeaders.Remove("If-Match");
// Currently I'm not using optimistic concurrency :-(
try
{
//Client.DefaultRequestHeaders.Add("If-Match", "*");
var stringContent = new StringContent("TESTAUTH", Encoding.UTF8, "text/plain");
var response= Client.PostAsync(uri, stringContent);
var resu=response.Result;
}
catch(Exception ex)
{
}
I am not sure what I am missing. I tried various combination but its failing.
I tried Microsoft recommended stringToSign formula too
I tried using canonical headers too
string signature;
var stringTosign = "POST\n" + "\n" + "\n" + "1024" + "\n" + "\n" + "text/plain\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + dateInRfc1123Format + "/xxxxxx/splitator/messages";
var hmac = new HMACSHA256(Convert.FromBase64String(accountKey));
var headerval= accountName + ":" + Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringTosign)));
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedKey", headerval);
Client.DefaultRequestHeaders.Accept.Clear();
I fixed the issue in your code, and now it's working. Please give it a try:
namespace ConsoleApp25
{
class Program
{
static void Main(string[] args)
{
var Client = new HttpClient();
var StorageAccountName = "yy1";
var StorageKey = "xxxx";
var apiversion = "2020-02-10";
var queue_name = "myqueue2";
String urlPath = String.Format("{0}/messages", queue_name);
Uri uri = new Uri(string.Format("https://{0}.queue.core.windows.net/{1}", StorageAccountName, urlPath));
//define a message to send
string raw_message = "TESTAUTH is ok";
//to send the message to the queue storage, the raw message must be formatted as below
string queue_message = $"<QueueMessage><MessageText>{raw_message}</MessageText></QueueMessage>";
//define the content type
string content_type = "text/plain; charset=utf-8";
//define date
var RequestDateString = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
string StringToSign = String.Format("POST\n"
+ "\n" // content encoding
+ "\n" // content language
+ queue_message.Length + "\n" // content length
+ "\n" // content md5
+ content_type +"\n" // content type
+ "\n" // date
+ "\n" // if modified since
+ "\n" // if match
+ "\n" // if none match
+ "\n" // if unmodified since
+ "\n" // range
+ "x-ms-date:" + RequestDateString + "\nx-ms-version:" + apiversion + "\n" // headers
+ "/{0}/{1}/{2}", StorageAccountName, queue_name, "messages"); //url
string auth = SignThis(StringToSign, StorageKey, StorageAccountName);
//define authorization header
if (Client.DefaultRequestHeaders.Contains("Authorization"))
Client.DefaultRequestHeaders.Remove("Authorization");
Client.DefaultRequestHeaders.Add("Authorization", auth);
Client.DefaultRequestHeaders.Accept.Clear();
//define x-ms-version header
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
if (Client.DefaultRequestHeaders.Contains("x-ms-version"))
Client.DefaultRequestHeaders.Remove("x-ms-version");
Client.DefaultRequestHeaders.Add("x-ms-version", apiversion);
//define the x-ms-date header
if (Client.DefaultRequestHeaders.Contains("x-ms-date"))
Client.DefaultRequestHeaders.Remove("x-ms-date");
Client.DefaultRequestHeaders.Add("x-ms-date", RequestDateString);
try
{
var stringContent = new StringContent(queue_message, Encoding.UTF8, "text/plain");
var response = Client.PostAsync(uri, stringContent);
var resu = response.Result;
}
catch (Exception ex)
{
}
Console.WriteLine("**completed**");
Console.ReadLine();
}
private static String SignThis(String StringToSign, string Key, string Account)
{
String signature = string.Empty;
byte[] unicodeKey = Convert.FromBase64String(Key);
using (HMACSHA256 hmacSha256 = new HMACSHA256(unicodeKey))
{
Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(StringToSign);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
String authorizationHeader = String.Format(
CultureInfo.InvariantCulture,
"{0} {1}:{2}",
"SharedKey",
Account,
signature);
return authorizationHeader;
}
}
}
And if you don't want to generate the shared key since it's not easy, you can use sas token for authentication in the rest api.

Post C# MultipartFormContent application/octet-stream Winform HttpClient

I am trying to post one or more files from my local machine to an API with HttpClient, MultipartFormContent and ContentType: "application/octet-stream" but when i do postSync and call an API from a local Winform application, the result of the task (var response = task.Result;) says that it is "Unsopported Type File" StatusCode: 415. I tried with ByteArrayContent but was still unsuccessful.
This is my code:
bool Upload(string url, string path, string localFilename, string fileName, string projectId, string folderId)
{
Boolean isFileUploaded = false;
string xapiKey = "-----";
try
{
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(url);
httpClient.DefaultRequestHeaders.Add("x-api-key", xapiKey);
var fileInfo = new FileInfo(localFilename);
FileUpload uploadResult = null;
bool _fileUploaded = false;
//Extract content file
FileStream fileStream = File.OpenRead(path);
var streamContent = new StreamContent(fileStream);
streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
streamContent.Headers.ContentDisposition.FileName = "\"" + Path.GetFileName(path) + "\"";
streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octetstream");
string boundary = Guid.NewGuid().ToString();
MultipartFormDataContent content = new MultipartFormDataContent(boundary);
content.Headers.Remove("Content-Type");
content.Headers.TryAddWithoutValidation("Content-Type", "mulitpart/form-data; boundary=" + boundary);
content.Add(streamContent);
//content.Add(new StreamContent(fileStream), "\"file\"", string.Format("\"{0}\"", fileName + fileInfo.Extension));
Task taskUpload = httpClient.PostAsync(url, content).ContinueWith(task =>
{
if (task.Status == TaskStatus.RanToCompletion)
{
var response = task.Result;
if (response.IsSuccessStatusCode)
{
uploadResult = response.Content.ReadAsAsync<FileUpload>().Result;
if (uploadResult != null)
_fileUploaded = true;
}
}
fileStream.Dispose();
});
taskUpload.Wait();
if (_fileUploaded)
isFileUploaded = true;
httpClient.Dispose();
}
catch (Exception ex)
{
isFileUploaded = false;
throw new Exception(ex.Message);
}
return isFileUploaded;
}

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

FluidSurvey API - CSV filter

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

Categories