Receiving data from WebClient.UploadString - c#

I am trying to send/receive byte array of image from server to server.
I think i managed to send it but am unable to receive it.
Here is code for sending:
[HttpPost]
[Route("/ARGallery/AUploadImage/{appid}")]
public IActionResult AUploadImage(IFormFile file, int appid)
{
try
{
// Korisnik prosledjuje fajl kroz browser
// Taj fajl ima svoje ime
// Bezbednosti radi proveravam ime fajla i prilagodjavam ga
string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
filename = this.EnsureCorrectFilename(filename);
//===============
// Uzimam app model iz buffera
ApplicationsModel am = Buffer.GetApplication(appid);
// Proveravam da li je uspesno uzet model, ako nije uzimam direktno iz faljova
if (am == null)
am = ApplicationsModel.List().Where(a => a.ID == appid).FirstOrDefault();
// Ako je posle svega neuspesno vracam gresku
if (am == null)
return View("Error", "Error loading application info!");
byte[] imageInBytes = null;
System.Drawing.Image img = System.Drawing.Image.FromStream(file.OpenReadStream());
using (var ms = new MemoryStream())
{
img.Save(ms, img.RawFormat);
imageInBytes = ms.ToArray();
}
using(var client = new WebClient())
{
return Json(client.UploadString("http://" + am.Name + "/ARGallery/AUploadImage/" + file.FileName, System.Text.Encoding.UTF8.GetString(imageInBytes)));
}
}
catch (Exception ex)
{
return Json(ex.ToString());
}
}
and here is receiving code
[HttpPost]
[Route("/ARGallery/AUploadImage/{filename}")]
public IActionResult AUploadImage(string bufferedImage, string filename)
{
try
{
MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(bufferedImage));
System.Drawing.Image myimg = Image.FromStream(ms);
while(System.IO.File.Exists(GetPathAndFilename(filename)))
{
string extension = "";
int br = filename.ToString().IndexOf('.');
string ex = filename.ToString().Substring(br);
if (ex == "jpeg")
extension = filename.Substring(filename.Length - 5, 5);
else
extension = filename.Substring(filename.Length - 4, 4);
// Dodajem na ostatak fajl name-a bez extensiona random karaktere i vracam extension nazad
filename = filename.Substring(0, filename.Length - 4) + AR.Security.HashPW(Program.rnd.Next(1000).ToString()).Substring(0, 2) + extension;
}
//Cuvam original format slike u temp folder
myimg.Save(GetPathAndFilename(filename));
// Cuvam osiromaseni format slike u temp folder
LowerQuality((Bitmap)myimg).Save(GetPathAndFilenameLQ(filename));
// Vracam nazad link do slike na remote serveru (serveru aplikacije)
return Json(filename);
}
catch (Exception ex)
{
return Json(ex.ToString());
}
}
I get "null" exception on line MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(bufferedImage));
EDIT:
Also what i have tried on sending app side is this but still same problem:
[HttpPost]
[Route("/ARGallery/AUploadImage/{appid}")]
public async Task<IActionResult> AUploadImage(IFormFile file, int appid)
{
try
{
// Korisnik prosledjuje fajl kroz browser
// Taj fajl ima svoje ime
// Bezbednosti radi proveravam ime fajla i prilagodjavam ga
string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
filename = this.EnsureCorrectFilename(filename);
//===============
// Uzimam app model iz buffera
ApplicationsModel am = Buffer.GetApplication(appid);
// Proveravam da li je uspesno uzet model, ako nije uzimam direktno iz faljova
if (am == null)
am = ApplicationsModel.List().Where(a => a.ID == appid).FirstOrDefault();
// Ako je posle svega neuspesno vracam gresku
if (am == null)
return View("Error", "Error loading application info!");
byte[] imageInBytes = null;
System.Drawing.Image img = System.Drawing.Image.FromStream(file.OpenReadStream());
using (var ms = new MemoryStream())
{
img.Save(ms, img.RawFormat);
imageInBytes = ms.ToArray();
}
using(var client = new HttpClient())
{
var options = new
{
bufferedImage = System.Text.Encoding.UTF8.GetString(imageInBytes),
filename = file.FileName
};
HttpResponseMessage message = await client.PostAsync("http://" + am.Name + "/ARGallery/AUploadImage", new StringContent(JsonConvert.SerializeObject(options), Encoding.UTF8, "application/json"));
return Json(await message.Content.ReadAsStringAsync());
}
}
catch (Exception ex)
{
return Json(ex.ToString());
}
}

Related

How do I get digital persona fmd or fid from byte array in C#?

I have an application in Xamarin forms that uses digital persona which I adapted successfully from this code of Android Java https://github.com/shodgson/uareu/blob/master/app/src/main/java/asia/kanopi/fingerreader/ScanActivity.java
The problem is that this app returns only a byte[] array of a fingerprint, so I consume a web service which takes in a byte array, but I cannot successfully convert byte[] to fmd or fid to compare fingerprints.
I'm trying to use the method FeatureExtraction.CreateFmdFromRaw but not successfully
public ActionResult validateLogin(ImageSend fimage,DataTable figerUsers) {
ActionResult r = new ActionResult() {
Success = false, ResultCode = ResultCode.GeneralError
};
try
{
// RawImage x = new RawImage(fimage.IMAGE_WIDTH, fimage.IMAGE_HEIGHT,75,10,fimage.data);
byte[] x = Convert.FromBase64String(fimage.data);
// Fmd fmd = new Fmd(x, 1, "1.0");
// byte[] x = fimage.data;
//duda cantidad de dpi
//Fid.Fiv fiv = new Fid.Fiv(x);
// DPCtlUruNet.IdentificationControl.FinishIdentification
DataResult<Fmd> resultConversion = FeatureExtraction.CreateFmdFromRaw(x, 1,0,fimage.IMAGE_WIDTH,fimage.IMAGE_HEIGHT, 75, Constants.Formats.Fmd.ANSI); ;
if (resultConversion.ResultCode == Constants.ResultCode.DP_SUCCESS)
{
Fmd fmd1 = resultConversion.Data;
//Fmd fmd1 = fmd;
Fmd fmd2 = null;
CompareResult compareResult;
foreach (DataRow row in figerUsers.Rows)
{
fmd2 = Fmd.DeserializeXml(row["FINGER"].ToString());
compareResult = Comparison.Compare(fmd1, 0, fmd2, 0);
if (compareResult.Score < (PROBABILITY_ONE / (double)100000))
{
r.Success = true;
r.Message = "Login Correcto";
r.ResultCode = ResultCode.Success;
return r;
}
}
}
else {
r.Success = false;
r.ResultCode = ResultCode.GeneralError;
r.Message = $"Error generando objeto de comparacion de huellas\n{x.Length} result: {resultConversion.ResultCode.ToString()}";
//r.Message = $"Error generando objeto de comparacion de huellas\n{x.Length} result: {fmd.ToString()}";
}
}
catch (Exception ex) {
r.Success = false;
r.ResultCode = ResultCode.GeneralError;
r.Message = ex.Message+ex.StackTrace;
}
return r;
}
public class ImageSend
{
public string name;
public string data;
public int IMAGE_HEIGHT = 290;
public int IMAGE_WIDTH;
}
it returns DP_INVALID_FID

create a file and upload the chunks to the in team drive from C#

I Have to Upload the file to my teamdrive, the file has been created to team drive but I can not upload the file chunks to it. So, please help to solve it.
On Writing a Chunk I am facing the Error of "The remote server returned an error: (404) Not Found."
I am getting the Teamdrive ID and the File ID which has been created.
/*** Creation of a File to Team Drive ***/
f_ObjFile.TeamDriveId = "/*TeamDrive ID*/";
try
{
f_ObjNewFile.Parents = f_ObjFile.Parents; // f_ObjFile = <Team Driv ID>
f_ObjNewFile.Name = f_ObjFile.Name;
f_ObjNewFile.MimeType = f_ObjFile.MimeType;
f_ObjNewFile.TeamDriveId = f_ObjFile.TeamDriveId;
f_CreateRequest = GoogleHelper.InvokeApiCall(() => { return this.DriveServiceObj.Files.Create(f_ObjNewFile); }, this);
if (f_CreateRequest != null)
{
f_CreateRequest.SupportsTeamDrives = true;
f_CreateRequest.Fields = "*";
f_ObjNewFile = GoogleHelper.InvokeApiCall(() => { return f_CreateRequest.Execute(); }, this);
}
f_ObjDocumentItem = new DocumentItem(UserEmailID, f_ObjNewFile);
f_ObjDocumentItem.ItemID = f_ObjNewFile.Id;
string f_Url = GoogleHelper.CreateChunkURL("https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable", f_ObjNewFile.Id);
f_ObjDocumentItem.ChunkUploadURL = InitiateResumeRequest(f_Url, f_ObjNewFile.Id);
}
catch(Exception ex) { }
finally
{
f_ObjNewFile = null;
f_CreateRequest = null;
}
/* Writing the chunks to the file in TeamDrive */
try
{
httpRequest = GoogleHelper.CreateHttpWebRequestObj(f_ObjChunkData.ChunkUploadURL,true);
httpRequest.Method = GoogleConstant.PATCH;
httpRequest.ContentLength = f_ObjChunkData.FileData.Length;
httpRequest.SendChunked = true;
httpRequest.Headers["Content-Range"] = "bytes " + f_ObjChunkData.StartOffset +
"-" +
f_ObjChunkData.EndOffset + "/" +
f_ObjChunkData.FileSize.ToString();
using (System.IO.Stream f_ObjHttpStream = GoogleHelper.InvokeApiCall(() => { return httpRequest.GetRequestStream(); }, this))
{
if (f_ObjHttpStream != null)
{
System.IO.MemoryStream f_ChunkStream = null;
f_ChunkStream = new System.IO.MemoryStream(f_ObjChunkData.FileData);
f_ChunkStream.CopyTo(f_ObjHttpStream);
f_ObjHttpStream.Flush();
f_ObjHttpStream.Close();
f_ChunkStream.Close();
f_ChunkStream = null;
}
}
using (HttpWebResponse httpResponse = GoogleHelper.InvokeApiCall(() => { return (HttpWebResponse)(httpRequest.GetResponse()); }, this))
{
if (httpResponse != null)
{
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
httpResponse.Close();
}
}
}
}
catch (Exception ex) { }
In Followin Line :
string f_Url = GoogleHelper.CreateChunkURL("https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable", f_ObjNewFile.Id);
Insted Of
"https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable"
Use following URL :
https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable&supportsTeamDrives=true
and its Done...
Now you can upload the chunks...

Incorrect behavior when trying to simultaneously download multiple PDFs

I have a list of reports page. I have a download button for each report. If I click 4-5 reports download button I only get the last one downloaded. Below you can see my code
public async Task<ActionResult> Download(ReportPage currentPage, string id)
{
var token = RystadIdentity.Current.AuthenticatedUser.Token;
try
{
DocumentRequestInput documentRequestInput = new DocumentRequestInput(int.Parse(id), 2);
documentRequestInput.Add(token);
}
catch
{ }
Report report = await RystadGlobal.api.GetReport(token, int.Parse(id));
string ext = Path.GetExtension(report.fileName);
byte[] byteArray = await RystadGlobal.api.DownloadReport(token, report.Id);
if (ext.ToLower() == ".pdf")
{
var name = RystadIdentity.Current.AuthenticatedUser.UserInfo.name;
var company = RystadIdentity.Current.AuthenticatedUser.UserInfo.company;
try
{
byteArray = PdfWatermarker.Watermark(byteArray, name, company);
}
catch (Exception ex)
{
//Ignore if failed and give the user the pdf anyway
}
}
return File(byteArray, System.Net.Mime.MediaTypeNames.Application.Octet, report.fileName);
}
public async Task<byte[]> DownloadReport(Token token, int reportId)
{
clientForDownloading.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.token_type, token.access_token);
var result = await clientForDownloading.GetAsync("api/" + ApiVersion + "/LibraryDocument/" + reportId + "/download");
if (!result.IsSuccessStatusCode)
throw new ApiException("Could not download the report");
var contentBytes = await result.Content.ReadAsByteArrayAsync();
return SevenZipHelper.Decompress(contentBytes);
}
public async Task<Report> GetReport(Token token, int reportId)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.token_type, token.access_token);
var result = await client.GetAsync("api/" + ApiVersion + "/LibraryDocument/" + reportId);
if (!result.IsSuccessStatusCode)
throw new ApiException("Could not get report");
Report report = await result.Content.ReadAsAsync<Report>();
return report;
}
Does anyone see the issue which I am missing?
You can try to do it Synchronously like so:
public ActionResult Download(ReportPage currentPage, string id)
{
var token = RystadIdentity.Current.AuthenticatedUser.Token;
try
{
DocumentRequestInput documentRequestInput = new DocumentRequestInput(int.Parse(id), 2);
documentRequestInput.Add(token);
}
catch
{ }
Report report = RystadGlobal.api.GetReport(token, int.Parse(id)).Result;
string ext = Path.GetExtension(report.fileName);
byte[] byteArray = RystadGlobal.api.DownloadReport(token, report.Id).Result;
if (ext.ToLower() == ".pdf")
{
var name = RystadIdentity.Current.AuthenticatedUser.UserInfo.name;
var company = RystadIdentity.Current.AuthenticatedUser.UserInfo.company;
try
{
byteArray = PdfWatermarker.Watermark(byteArray, name, company);
}
catch (Exception ex)
{
//Ignore if failed and give the user the pdf anyway
}
}
return File(byteArray, System.Net.Mime.MediaTypeNames.Application.Octet, report.fileName);
}
The other problem might be in this method:
RystadGlobal.api.GetReport(token, int.Parse(id))
I do not know that this method looks like inside
EDIT
Try creating new instances of your clients in the methods you added in your question:
public async Task<byte[]> DownloadReport(Token token, int reportId)
{
using(var clientForDL = new System.Net.Http.HttpClient())
{
clientForDL.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.token_type, token.access_token);
var result = await clientForDL.GetAsync("api/" + ApiVersion + "/LibraryDocument/" + reportId + "/download");
if (!result.IsSuccessStatusCode)
throw new ApiException("Could not download the report");
var contentBytes = await result.Content.ReadAsByteArrayAsync();
return SevenZipHelper.Decompress(contentBytes);
}
}
public async Task<Report> GetReport(Token token, int reportId)
{
using(var clientForGet = new System.Net.Http.HttpClient())
{
clientForGet.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.token_type, token.access_token);
var result = await clientForGet.GetAsync("api/" + ApiVersion + "/LibraryDocument/" + reportId);
if (!result.IsSuccessStatusCode)
throw new ApiException("Could not get report");
Report report = await result.Content.ReadAsAsync<Report>();
return report;
}
}

Pass the value to database in asp.net web api

Am trying to save the images to the database using the asp.net webapi. In this controller am saving the image into my /Content/Banner/ Folder.
[HttpPost]
[Route("PostBanner")]
[AllowAnonymous]
public HttpResponseMessage PostBannerImage()
{
Dictionary<string, object> dict = new Dictionary<string, object>();
try
{
var httpRequest = HttpContext.Current.Request;
foreach (string file in httpRequest.Files)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
var postedFile = httpRequest.Files[file];
if (postedFile != null && postedFile.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB
IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png" };
var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
var extension = ext.ToLower();
if (!AllowedFileExtensions.Contains(extension))
{
var message = string.Format("Please Upload image of type .jpg,.gif,.png.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else if (postedFile.ContentLength > MaxContentLength)
{
var message = string.Format("Please Upload a file upto 1 mb.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else
{
var filePath = HttpContext.Current.Server.MapPath("~/Content/Banner/" + postedFile.FileName + extension);
postedFile.SaveAs(filePath);
}
}
var message1 = string.Format("Image Updated Successfully.");
return Request.CreateErrorResponse(HttpStatusCode.Created, message1); ;
}
var res = string.Format("Please Upload a image.");
dict.Add("error", res);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}
catch (Exception ex)
{
var res = string.Format("some Message");
dict.Add("error", res);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}
}
Now what i need to send this filePath to database. I know i just need to pass this file path to the following service controller. But i dont know how to pass it. could anyone help me to solve this problem.
This Is my services.cs
public async Task<int?> Addbanner(DisplayBannersDto dto)
{
try
{
var d = _dbContext.Banners
.FirstOrDefault();
d.Banner_Description = dto.Description;
d.Banner_Location = dto.Location;
//mark entry as modifed
_dbContext.Entry(d).State = EntityState.Modified;
await _dbContext.SaveChangesAsync();
return d.Banner_Id;
}
catch (Exception ex)
{
throw ex;
}
}
This is my controller
[HttpPost]
[Route("AddBanner")]
public async Task<IHttpActionResult> AddBanner(DisplayBannersDto dto)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
int? result = await _service.Addbanner(dto);
return Ok();
}
Change your else condition like below:
else
{
var filePath = HttpContext.Current.Server.MapPath("~/Content/Banner/" + postedFile.FileName + extension);
postedFile.SaveAs(filePath);
return new HttpResponseMessage()
{
StatusCode = HttpStatusCode.Created,
Content = new StringContent(filePath, Encoding.UTF8, "application/json")
};
}
Now, you have the filepath in the content of the API response.
and use that response like :
var displayBannersDto = new DisplayBannersDto();
displayBannersDto.Banner_Location = response.Content.ToString();
then call your AddBanner() API with displayBannersDto as the dto.

File used by another process ; PDF.JS ; iText

I'm using PDF.JS to display document that I upload to the server in canvas element using PDF.JS that's working perfectely. That time i'm using iTextSharp to digitally sign the document. When i try to sign the document an Exception is throwed (Exception.IO.Exception) The file is already used by another process. here is my Code for uploding the file :)
[HttpPost]
public async Task<JsonResult> Upload()
{
string fileName = null;
try
{
foreach (string item in Request.Files)
{
var fileContent = Request.Files[item];
if(fileContent != null && fileContent.ContentLength > 0)
{
var inputStream = fileContent.InputStream;
fileName = fileContent.FileName;
string path = Path.Combine(Server.MapPath("~/UploadFolder"), fileName);
using (fileContent.InputStream)
{
using (var stream = new FileStream(path, FileMode.Create))
{
await inputStream.CopyToAsync(stream);
}
}
}
}
}
catch (Exception e)
{
return Json("Upload failed");
}
return Json(fileName);
}
There's how i display PDF in canvas
$(document).ready(function () {
$("#btn2").click(function () {
var url = document.getElementById("document-to-sign").getAttribute("required-document");
if (url != "" && url != null) {
var pdfDoc = null,
pageNum = 1,
pageRendering = false,
pageNumPending = null,
scale = 1.5,
canvas = document.getElementById('document-to-sign'),
ctx = canvas.getContext('2d');
function renderPage(num) {
pageRendering = true;
pdfDoc.getPage(num).then(function (page) {
var viewport = page.getViewport(scale);
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
var renderTask = page.render(renderContext);
renderTask.promise.then(function () {
pageRendering = false;
if (pageNumPending !== null) {
renderPage(pageNumPending);
pageNumPending = null;
}
});
});
document.getElementById('page_num').textContent = pageNum;
}
function queueRenderPage(num) {
if (pageRendering) {
pageNumPending = num;
} else {
renderPage(num);
}
}
function onPrevPage() {
if (pageNum <= 1) {
return;
}
pageNum--;
queueRenderPage(pageNum);
}
document.getElementById('prev').addEventListener('click', onPrevPage);
function onNextPage() {
if (pageNum >= pdfDoc.numPages) {
return;
}
pageNum++;
queueRenderPage(pageNum);
}
document.getElementById('next').addEventListener('click', onNextPage);
PDFJS.getDocument(url).then(function (pdfDoc_) {
pdfDoc = pdfDoc_;
document.getElementById('page_count').textContent = pdfDoc.numPages;
renderPage(pageNum);
});
PDFJS.disableStream = true;
$("#document-to-sign").removeAttr("required-document");
}
});
I finally that's how i'm signing the document (Adding the empty field to sign)
public static void AddField(string src,
Double x1X, Double x1Y, Double x2X, Double x2Y, int page,
string User)
{
try
{
PdfReader reader = new PdfReader(src);
using (PdfStamper s = new PdfStamper(reader, new FileStream(src, FileMode.Open)))
{
PdfFormField field = PdfFormField.CreateSignature(s.Writer);
field.FieldName = "Signature de " + User;
field.SetWidget(new Rectangle(Convert.ToSingle(x1X), Convert.ToSingle(x1Y), Convert.ToSingle(x2X), Convert.ToSingle(x2Y)), PdfAnnotation.HIGHLIGHT_PUSH);
field.Flags = PdfAnnotation.FLAGS_PRINT;
s.AddAnnotation(field, page);
}
}
catch (Exception e)
{
logger.Fatal(e.ToString());
throw e;
}
}
I'm stacked in this line
using (PdfStamper s = new PdfStamper(reader, new FileStream(src, FileMode.Open)))
EDIT:
I'm just adding the siging field in this step. Signing the document will be the next task, in console application i'm singing the document with a self-certificate.
Upload the document, and adding the signing field and signing it will be further :)
Sorry for the confussion.
Thanks a lot. :)
I just found what i'm missing in reading the file
refer to this
Cannot access the file because it is being used by another process
i was passing the url of the file instead of reading the all bytes from stream
PdfReader reader = new PdfReader(src);
PdfReader reader = new PdfReader(System.IO.File.ReadAllBytes(filePath))

Categories