/// <summary> /// Sends a response to a request to download a file to a host device. /// Will attempt to send the entire download in a single block. /// </summary> /// <param name="response">The response to the download request</param> /// <param name="fileIndex">The file index to download</param> /// <param name="downloadData">File to download. The entire file most be provided, even if the host requested an offset.</param> public void SendDownloadResponse(DownloadResponse response, ushort fileIndex, byte[] downloadData) { if (!bInitialized) throw new ObjectDisposedException("ANTFSClient object has been disposed"); SendDownloadResponse(response, fileIndex, 0, downloadData); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, [StorageAccount("StorageConnectionString")] CloudStorageAccount storageAccount, TraceWriter log ) { try { var client = storageAccount.CreateCloudTableClient(); string userKey = await Authenticator.Authenticate(client, req); if (string.IsNullOrEmpty(userKey)) { return(new UnauthorizedResult()); } var subPartition = req.Query["partition"]; if (string.IsNullOrWhiteSpace(subPartition)) { return(new BadRequestObjectResult("The query parameter \"partition\" empty or missing")); } log.Info($"User {userKey} has requested an item download for sub partition {subPartition}"); var itemTable = client.GetTableReference(ItemV1.TableName); var query = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, userKey + subPartition); var exQuery = new TableQuery <ItemV1>().Where(query); var unfilteredItems = await QueryHelper.ListAll(itemTable, exQuery); var filteredItems = unfilteredItems.Where(m => m.IsActive).ToList(); log.Info($"A total of {filteredItems.Count} items were returned"); var deleted = await GetDeletedItems(userKey + subPartition, client); log.Info($"A total of {deleted.Count} items were marked for deletion"); if (filteredItems.Count > 80) { log.Info($"Disabling partition {subPartition} for {userKey} (may already be disabled)"); var table = client.GetTableReference(PartitionV1.TableName); await table.CreateIfNotExistsAsync(); DisablePartition(userKey, subPartition, table); } var result = new DownloadResponse { Items = filteredItems.Select(m => Map(userKey, m)).ToList(), Removed = deleted }; return(new OkObjectResult(result)); } catch (Exception ex) { log.Error(ex.Message, ex); return(new ExceptionResult(ex, false)); } }
public DownloadResponse DownloadFormDetails(string Instance, string SessionId, string Version, DepartureFormFilterDetails FormFilterDetails) { const string FUNCTION_NAME = "DownloadFormDetails"; DownloadResponse DownloadResponse = new DownloadResponse(); SICTLogger.WriteInfo(CLASS_NAME, FUNCTION_NAME, "Start"); try { UserDetailsBusiness ObjSessionValidation = new FactoryBusiness().GetUserDetailsBusiness(BusinessConstants.VERSION_BASE); if (ObjSessionValidation.IsSessionIdValid(SessionId)) { DownloadBusiness ObjDownloadBusiness = new FactoryBusiness().GetDownloadBusiness(Version); DownloadResponse = ObjDownloadBusiness.FormExcelExport(Instance, SessionId, FormFilterDetails); } else { DownloadResponse.ReturnCode = 0; DownloadResponse.ReturnMessage = "Invalid session"; SICTLogger.WriteWarning(CLASS_NAME, FUNCTION_NAME, "Invalid session "); } } catch (Exception ex) { DownloadResponse.ReturnCode = -1; DownloadResponse.ReturnMessage = "Error in API Execution"; SICTLogger.WriteException(CLASS_NAME, FUNCTION_NAME, ex); } SICTLogger.WriteInfo(CLASS_NAME, FUNCTION_NAME, "End"); return(DownloadResponse); }
public async Task <IActionResult> Get() { var responseObject = new DownloadResponse(); const string cacheKey = "downloaded-gist-response"; var responseData = _cache.Get <string>(cacheKey); if (string.IsNullOrEmpty(responseData)) { responseObject.Log = "Making a call to the actual resource."; var httpClient = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, "https://gist.githubusercontent.com/nikneem/66060dad016cabd426166f282a946f80/raw/581fe051d1b84c6799eecbdca5496b69c474292c/4DotNet-WebCasts-Caching.json"); var response = await httpClient.SendAsync(request); responseData = await response.Content.ReadAsStringAsync(); _cache.Set(cacheKey, responseData); } else { responseObject.Log = "Got the value from cache."; } responseObject.ResponseData = responseData; return(Ok(responseData)); }
public HttpResponseMessage DownloadFile([FromBody] DownloadResponse request) { try { DownloadFactory _downloadfactory = new DownloadFactory(); var fStream = _downloadfactory.DownloadFile(request.file); HttpResponseMessage response; if (fStream == null) { response = Request.CreateResponse(HttpStatusCode.Gone); return(response); } else { response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StreamContent(fStream) }; //set content header of reponse as file attached in reponse response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = Path.GetFileName(fStream.Name) }; //set the content header content type as application/octet-stream as it returning file as reponse response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return(response); } } catch (Exception ex) { return(null); } }
public DownloadResponse DownloadObject(Uri uri) { CheckUri(uri); try { var timeoutMs = timeout.TotalMilliseconds <= Int32.MaxValue ? Convert.ToInt32(timeout.TotalMilliseconds) : Int32.MaxValue; var request = (HttpWebRequest)WebRequest.Create(uri); request.Timeout = timeoutMs; request.ReadWriteTimeout = timeoutMs; var response = request.GetResponse(); var downloadResponse = new DownloadResponse(); downloadResponse.Uri = uri; using (var responseStream = response.GetResponseStream()) { downloadResponse.ResponseStream = new MemoryStream(); if (responseStream != null) { responseStream.CopyTo(downloadResponse.ResponseStream); } } return(downloadResponse); } catch (Exception e) { throw new StorageException(string.Format("Failed to download object from {0}.", uri), e); } }
private void DownloadStarted(IAsyncResult theResult) { //get our wrapper back out DownloadRequest theRequest = theResult.AsyncState as DownloadRequest; //notify anyone that might be listening that we have commence our download if (OnDownloadProgress != null) { OnDownloadProgress(this, new DownloadProgressEventArgs(0, theRequest.Version.FileSize)); } //get the response WebResponse theResponse = theRequest.Request.EndGetResponse(theResult); //grab the stream Stream theStream = theResponse.GetResponseStream(); //wrap it up so we can pass it along DownloadResponse TheResponse = new DownloadResponse { TheStream = theStream, Version = theRequest.Version }; //now to start reading from it theStream.BeginRead(arFileBytes, 0, 100, new AsyncCallback(ReadingStream), TheResponse); }
public async Task <DownloadResponse> FetchDownload(string id) { var downloadResponse = new DownloadResponse(); var audioEntity = await _tableDbContext.GetEntityAsync("Uploads", id); // use try/parse instead? if (audioEntity.ProcessStatusEnum == ProcessStatusEnum.Failed.EnumValue()) { downloadResponse.GeneralStatusEnum = GeneralStatusEnum.Fail; return(downloadResponse); } //signalr to update status. var assemblyResponse = await GetTranscription(id); if (assemblyResponse.Status == "completed") { _ = await _dataRepository.UpdateTable(id, ProcessStatusEnum.Completed, null); downloadResponse.GeneralStatusEnum = GeneralStatusEnum.Ok; downloadResponse.AudioEntity = await _tableDbContext.GetEntityAsync("Uploads", id); downloadResponse.TranscriptionResponse = assemblyResponse; return(downloadResponse); } return(downloadResponse); }
public DownloadResponse DownloadObject(Uri uri) { CheckUri(uri); try { var request = (HttpWebRequest)WebRequest.Create(uri); var response = request.GetResponse(); var downloadResponse = new DownloadResponse(); downloadResponse.Uri = uri; using (var responseStream = response.GetResponseStream()) { downloadResponse.ResponseStream = new MemoryStream(); if (responseStream != null) { responseStream.CopyTo(downloadResponse.ResponseStream); } } return(downloadResponse); } catch (Exception e) { throw new StorageException(string.Format("Failed to download object from {0}.", uri), e); } }
public Stream Download() { DownloadResponse response = new DownloadResponse() { FileName = SysConfig.FileName, Stream = new MemoryStream() }; try { // open DB client and get DB reference var client = new MongoClient(SysConfig.DBconn); var database = client.GetDatabase("da_pp_db"); // download file as stream var bucket = new GridFSBucket(database); bucket.DownloadToStreamByName(response.FileName, response.Stream); // return the stream //response.Errored = false; //response.Message = "Stream initiated"; return(response.Stream); } catch (Exception ex) { return(null); } }
public override async Task DownloadFiles(DownloadRequest request, IServerStreamWriter <DownloadResponse> responseStream, ServerCallContext context) { foreach (var i in request.FileNames) { var result = new DownloadResponse(); Stream?stream = null; try { stream = await seaweed.DownloadAsync(i); } catch { // ignored } var succeeded = true; if (stream != null) { stream.Seek(0, SeekOrigin.Begin); } else { succeeded = false; } result.Result.Add(new DownloadResult { Content = succeeded ? await ByteString.FromStreamAsync(stream) : ByteString.Empty, FileName = i, Succeeded = succeeded }); await responseStream.WriteAsync(result); stream?.Dispose(); } }
public override async Task <DownloadResponse> DownloadHeadlines(DownloadRequest request, ServerCallContext context) { int articlesFromYear = request.Year; var currentMonth = DateTime.Now.Month.ToString(); var webRequest = await httpClient.GetAsync($"https://api.nytimes.com/svc/archive/v1/{articlesFromYear}/{currentMonth}.json?api-key={Startup.NytApiKey}"); var content = webRequest.Content; var response = new DownloadResponse(); var headlines = new List <TodayEventData.Models.Headline>(); try { var jsonContent = JsonConvert.DeserializeObject <NYTDocs>(await content.ReadAsStringAsync()); foreach (var headline in jsonContent.Response.Docs.Select(doc => doc.Headline)) { headlines.Add(headline); } } catch (JsonSerializationException ex) { Console.WriteLine(ex); } response.Headlines.AddRange(headlines.Select(Protos.Headline.FromRepositoryModel)); return(response); }
public DownloadResponse FormExcelExport(string Instance, string SessionId, DepartureFormFilterDetails DepartureFormFilterDetails) { DownloadResponse DownloadResponse = new DownloadResponse(); BusinessUtil ObjBusinessUtil = new BusinessUtil(); SICTLogger.WriteInfo(DownloadBusiness.CLASS_NAME, "FormExcelExport", "Start "); try { string FilePath = string.Empty; string FileLink = string.Empty; string FileName = string.Empty; ObjBusinessUtil.GetFormsExcelExportFilePath(Instance, ref FilePath, ref FileLink, ref FileName); DownloadResponse.ReturnCode = 1; DownloadResponse.ReturnMessage = "Downloaded Started"; DownloadResponse.FileLink = FileLink; DownloadResponse.FileName = FileName; Task.Factory.StartNew(delegate { this.DownloadDataInBackground(SessionId, DepartureFormFilterDetails, FilePath); }); } catch (System.Exception Ex) { DownloadResponse.ReturnCode = -1; DownloadResponse.ReturnMessage = "Error in Function "; SICTLogger.WriteException(DownloadBusiness.CLASS_NAME, "FormExcelExport", Ex); } SICTLogger.WriteInfo(DownloadBusiness.CLASS_NAME, "FormExcelExport", "FormExcelExportEnd"); return(DownloadResponse); }
private void ProcessFax() { // Check Fax var faxApi = new FaxApi(); var faxes = faxApi.GetDocuments(); foreach (FaxDocument fax in faxes.Entities.Where(x => !(x.Read ?? false))) { DateTime faxDate = fax.DateCreated != null ? ((DateTime)fax.DateCreated).ToLocalTime() : DateTime.Now; string fromNumber = fax.CallerAddress.Replace("tel:+", ""); string toNumber = fax.ReceiverAddress.Replace("tel:+", ""); Log("FAX from " + fax.CallerAddress + " at " + faxDate); // Try to look up the email for this fax # in Settings. If it's not found, just move on with the default string groupEmail = DefaultRecipientEmail; try { groupEmail = Properties.Settings.Default["n" + toNumber].ToString(); } catch { } // Download the fax file string fileName; DownloadResponse faxFile = faxApi.GetDocumentsDocumentIdContent(fax.Id); using (var client = new WebClient()) { // Replace any characters not allowed in a file name string fromNumberSafeString = fromNumber .Replace(@"\", "") .Replace(@"/", "") .Replace(@":", "") .Replace(@"*", "") .Replace(@"?", "") .Replace(@"""", "") .Replace(@"<", "") .Replace(@">", "") .Replace(@"|", "") .Replace(@" ", ""); fileName = Path.GetTempPath() + "PureCloud_FAX_" + fromNumberSafeString + "_" + faxDate.ToString("yyyyMMdd-HHmmss") + ".pdf"; client.DownloadFile(faxFile.ContentLocationUri, fileName); } // Email to the proper group string subject = "Fax from " + fromNumber; string body = ComposeFaxEmail(faxDate, fromNumber, toNumber); SendEmail(groupEmail, EmailFromAddress, body, subject, fileName); Log(" Sent to " + toNumber + ": " + groupEmail); // Mark the fax as read so it won't get sent again next time fax.Read = true; faxApi.PutDocumentsDocumentId(fax.Id, fax); } }
/// <summary> /// Sends a response to a request to download a file to a host device. /// Will attempt to send the entire download in a single block. /// </summary> /// <param name="response">The response to the download request</param> /// <param name="fileIndex">The file index to download</param> /// <param name="downloadData">File to download. The entire file most be provided, even if the host requested an offset.</param> public void SendDownloadResponse(DownloadResponse response, ushort fileIndex, byte[] downloadData) { if (!bInitialized) { throw new ObjectDisposedException("ANTFSClient object has been disposed"); } SendDownloadResponse(response, fileIndex, 0, downloadData); }
public async Task <HttpResponseMessage> PostUpload([FromBody] DownloadResponse request) { UploadFactory uploadFactory = new UploadFactory(); var retValue = await uploadFactory.PostData(request).ConfigureAwait(false); HttpResponseMessage response; response = Request.CreateResponse(HttpStatusCode.OK, retValue); return(response); }
/// <summary> /// Sends a response to a request to download a file to a host device /// </summary> /// <param name="response">The response to the download request</param> /// <param name="fileIndex">The file index to download</param> /// <param name="blockSize">The maximum number of bytes to send in a single block</param> /// <param name="downloadData">File to download. The entire file most be provided, even if the host requested an offset.</param> public void SendDownloadResponse(DownloadResponse response, ushort fileIndex, uint blockSize, byte[] downloadData) { if (!bInitialized) { throw new ObjectDisposedException("ANTFSClient object has been disposed"); } IntPtr pvData = IntPtr.Zero; uint dataLength = 0; ANTFS_DownloadParameters responseParameters; releaseDownloadBuffer(); // If we had not freed the handle from a previous download, do it now responseParameters.FileIndex = fileIndex; responseParameters.MaxBlockSize = blockSize; if (response == DownloadResponse.Ok) { if (downloadData == null) { throw new ANT_Exception("Download request accepted, but no data provided"); } ghDownloadData = GCHandle.Alloc(downloadData, GCHandleType.Pinned); // Pin managed buffer pvData = ghDownloadData.Value.AddrOfPinnedObject(); // Get address of managed buffer if (pvData == IntPtr.Zero) { throw new ANTFS_Exception("Download request failed: Unable to pin managed buffer for download"); } dataLength = (uint)downloadData.Length; if (blockSize == 0 || dataLength < blockSize) { responseParameters.MaxBlockSize = dataLength; } } ReturnCode theReturn = (ReturnCode)ANTFSClient_SendDownloadResponse(unmanagedClientPtr, (byte)response, ref responseParameters, dataLength, pvData); if (theReturn == ReturnCode.Pass) { usCurrentTransfer = responseParameters.FileIndex; // Track current transfer } else { // If the request was not successful, we should free the handle here // Otherwise, buffer needs to remain pinned while download completes (pass/fail/etc...) // GCHandle will be freed when we receive an ANT-FS response, or the application is terminated releaseDownloadBuffer(); throw new ANTFS_RequestFailed_Exception("SendDownloadResponse", theReturn); } }
public override async Task <DownloadResponse> DownloadFile(DownloadRequest request, ServerCallContext context) { var doc = await _db.Docs.FindAsync(request.PostId); var response = new DownloadResponse { Content = ByteString.CopyFrom(doc.Content), ContentType = doc.ContentType, Name = doc.FileName }; return(response); }
private void DownloadDataInBackground(string SessionId, DepartureFormFilterDetails DepartureFormFilterDetails, string FilePath) { DownloadResponse DownloadResponse = new DownloadResponse(); SICTLogger.WriteInfo(DownloadBusiness.CLASS_NAME, "DownloadDataInBackground", "Start "); try { DepartureFormBusiness ObjDepartureFormBusiness = new DepartureFormBusiness(); DataAccessLayer.DataAccessLayer DBLayer = new DataAccessLayer.DataAccessLayer(); System.Collections.Generic.List <DepartureFormDetails> DepartureFormDetails = new System.Collections.Generic.List <DepartureFormDetails>(); string OrderByCondition = string.Empty; string WhereCondition = string.Empty; Workbook Wb = new Workbook(); Worksheet DataSheet = null; this.AddDataSheetToWorkBook(ref Wb, ref DataSheet, "Forms"); this.InsertFormFilterstoWorkBook(ref DataSheet, DepartureFormFilterDetails); ObjDepartureFormBusiness.BuildOrderByandWhereConditions(DepartureFormFilterDetails, ref OrderByCondition, ref WhereCondition); int RecordsPerLoop = System.Convert.ToInt32(ConfigurationManager.AppSettings[BusinessConstants.UPLOAD_ROWS_CNT].ToString()); int StartIndex = 0; int Count = 0; bool IsFirstRecord = true; int DataRow = 1; do { DataSet DSCardDetails = new DataSet(); DSCardDetails = DBLayer.GetGlobalDepartureFormDetailst(SessionId, StartIndex, RecordsPerLoop, OrderByCondition, WhereCondition, DepartureFormFilterDetails.AirportId, DepartureFormFilterDetails.IsDepartureForm, false, 0L, 0L); if (DSCardDetails.Tables.Count == 2) { if (IsFirstRecord) { Count = System.Convert.ToInt32(DSCardDetails.Tables[0].Rows[0][BusinessConstants.FORM_TOTALRECORDS].ToString()); IsFirstRecord = false; } this.InsertFormDataToWorksheet(DSCardDetails.Tables[1], ref DataSheet, ref DataRow); StartIndex += RecordsPerLoop; if (StartIndex < Count && StartIndex + RecordsPerLoop > Count) { RecordsPerLoop = Count - StartIndex; } } }while (StartIndex < Count); Wb.Save(FilePath, new OoxmlSaveOptions(SaveFormat.Xlsx)); } catch (System.Exception Ex) { DownloadResponse.ReturnCode = -1; DownloadResponse.ReturnMessage = "Error in Function "; SICTLogger.WriteException(DownloadBusiness.CLASS_NAME, "DownloadDataInBackground", Ex); } }
public async Task <DownloadResponse> FetchDownload(string id) { var downloadResponse = new DownloadResponse(); var imageEntity = await _tableDbContext.GetEntityAsync("Uploads", id); // use try/parse instead? if (imageEntity.ProcessStatusEnum != ProcessStatusEnum.Completed.EnumValue()) { downloadResponse.GeneralStatusEnum = GeneralStatusEnum.Processing; downloadResponse.ImageEntity = null; } else { downloadResponse.GeneralStatusEnum = GeneralStatusEnum.Ok; downloadResponse.ImageEntity = imageEntity; } return(downloadResponse); }
private void DownloadFile(TCPProtocol protocol, DownloadRequest request) { var response = new DownloadResponse(); try { byte[] archivo = null; response.Result = ServerData.Instance.FileExists(request.FileName) ? TransferResponseEnum.OK : TransferResponseEnum.FileDoesntExist; if (response.Result == TransferResponseEnum.OK) { archivo = FileHelper.ReadFile(string.Format("{0}\\{1}", ServerData.Instance.FileRepository, request.FileName)); response.FileLength = archivo.LongLength; } protocol.SendMessage(response); if (response.Result == TransferResponseEnum.OK) { request = (DownloadRequest)protocol.RecieveMessage(); byte[] archivoAEnviar = new byte[archivo.LongLength - request.Rest]; Array.Copy(archivo, request.Rest, archivoAEnviar, 0, archivoAEnviar.LongLength); protocol.SendFile(archivoAEnviar); } else { throw new Exception("Error enviando archivo"); } } catch (Exception ex) { response.Result = TransferResponseEnum.ConnectionError; protocol.SendMessage(response); } }
public async Task <bool> PostData(DownloadResponse request) { List <DownloadResponse> memberList = new List <DownloadResponse>(); var codeBase = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase) + "\\ResourceFile\\DownloadJsonFile.json"; UriBuilder uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); // File.WriteAllText(@"C:\HRBGTCINDIA\HRB.TR.WEBSERVICE\HRB.TR.WEBSERVICE\ResourceFile\registered.json", JsonConvert.SerializeObject(request)); memberList = JsonConvert.DeserializeObject <List <DownloadResponse> >(System.IO.File.ReadAllText(path)); request.Id = memberList.Count + 1; memberList.Add(request); File.WriteAllText(path, JsonConvert.SerializeObject(memberList)); // serialize JSON directly to a file //using (StreamWriter file = File.CreateText(path)) //{ // JsonSerializer serializer = new JsonSerializer(); // serializer.Serialize(file, request); // retValue = true; //} return(true); }
public async Task <DownloadResponse> DownloadFiles(string objectKey) { DownloadResponse result = null; try { var minio = new MinioClient(this.endpoint, accessKey, accessSecret); await minio.GetObjectAsync(this.bucket, objectKey, (stream) => { result = new DownloadResponse(); result.HasSucceed = false; result.FileObject = ReadStream(stream); }); } catch (MinioException e) { Console.WriteLine("Error occurred: " + e); } return(result); }
private void ReadingStream(IAsyncResult theResult) { //get out wrapper out again DownloadResponse theResponse = theResult.AsyncState as DownloadResponse; //how many bytes read? nBytesRead += theResponse.TheStream.EndRead(theResult); //notify our users if (OnDownloadProgress != null) { OnDownloadProgress(this, new DownloadProgressEventArgs(nBytesRead, theResponse.Version.FileSize)); } if (nBytesRead == theResponse.Version.FileSize) { //completed //close the stream theResponse.TheStream.Flush(); theResponse.TheStream.Close(); DownloadComplete(theResponse.Version, arFileBytes); } else { if (theResponse.Version.FileSize - nBytesRead >= 100) { //read the next chunk theResponse.TheStream.BeginRead(arFileBytes, (int)nBytesRead, 100, new AsyncCallback(ReadingStream), theResponse); } else { //read the last chunk theResponse.TheStream.BeginRead(arFileBytes, (int)nBytesRead, (int)(theResponse.Version.FileSize - nBytesRead), new AsyncCallback(ReadingStream), theResponse); } } }
public ResponseReceivedEventArgs(DownloadRequest request, DownloadResponse response) { Request = request; Response = response; }
public void Init() { instance = new DownloadResponse(); }
public string Upload() { int iUploadedCnt = 0; // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES. string sPath = "C:/"; sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/locker/"); string body = System.Web.HttpContext.Current.Request.Form["body"]; DownloadResponse request = JsonConvert.DeserializeObject <DownloadResponse>(body); List <DownloadResponse> memberList = new List <DownloadResponse>(); var codeBase = System.Web.Hosting.HostingEnvironment.MapPath("~/ResourceFile/DownloadJsonFile.json"); //var codeBase = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase) + "\\ResourceFile\\DownloadJsonFile.json"; UriBuilder uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); memberList = JsonConvert.DeserializeObject <List <DownloadResponse> >(System.IO.File.ReadAllText(path)); //request.Id = memberList.Count + 1; System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files; // CHECK THE FILE COUNT. for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++) { System.Web.HttpPostedFile hpf = hfc[iCnt]; string fileName = new String(Path.GetFileNameWithoutExtension(hpf.FileName).Take(10).ToArray()).Replace(" ", "-"); fileName = fileName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(hpf.FileName); request.file = fileName; if (hpf.ContentLength > 0) { // CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE) if (!File.Exists(sPath + Path.GetFileName(fileName))) { // SAVE THE FILES IN THE FOLDER. hpf.SaveAs(sPath + Path.GetFileName(fileName)); iUploadedCnt = iUploadedCnt + 1; } } } if (request.Id == 0) { request.Id = memberList.Count + 1; memberList.Add(request); } else { var value = memberList.Where(x => x.Id == request.Id).ToList(); foreach (var prop in value) { prop.link = request.link; prop.ToolDescription = request.ToolDescription; prop.ToolName = request.ToolName; prop.file = hfc.Count > 0?request.file: prop.file; prop.ContactTo = request.ContactTo; } } File.WriteAllText(path, JsonConvert.SerializeObject(memberList)); // RETURN A MESSAGE. if (iUploadedCnt > 0) { return(iUploadedCnt + " Files Uploaded Successfully"); } else { return("Upload Failed"); } }
public Dictionary <string, string> Download(string documentType, string documentNumber, string documentPrefix, string resourceType) { #region Variables de trabajo string step = "ConfigWS"; string methodName = "Download"; DownloadResponse wsResp = null; DownloadRequest wsReq = new DownloadRequest(); Dictionary <string, string> dictResult = this.FaultDictionary(); #endregion try { #region Diccionario de respuesta dictResult.Add("methodName", methodName); dictResult.Add("downloadData", ""); dictResult.Add("status", ""); #endregion #region Inicializacion WS this.Initialize(); wsReq.documentType = documentType; wsReq.documentNumber = documentNumber; wsReq.documentPrefix = documentPrefix; wsReq.resourceType = resourceType; wsReq.companyId = this.m_Company; wsReq.accountId = this.m_Account; #endregion #region Llamado al WS try { step = "BeforeWS"; wsResp = this.m_Proxy.Download(wsReq); step = "AfterWS"; if (wsResp == null) { this.SetException(dictResult, "DownloadResponse nulo", "Se realizó correctamente el llamado al metodo Download y devolvio respuesta null"); } else { step = "BeforeDict"; dictResult["downloadData"] = wsResp.downloadData; dictResult["status"] = wsResp.status; step = "AfterDict"; } } catch (FaultException <InvoiceServiceFault> faultException) { var detail = faultException.Detail; this.SetException(dictResult, detail.errorMessage, detail.statusCode, detail.reasonPhrase); } catch (ProtocolException protocolExc) { this.SetException(dictResult, protocolExc.Message, protocolExc.StackTrace); } #endregion } catch (Exception excepcion) { string tipo = excepcion.GetType().ToString(); this.SetException(dictResult, excepcion.Message, excepcion.StackTrace); } finally { dictResult["Step"] = step; } return(dictResult); }
/// <summary> /// Sends a response to a request to download a file to a host device /// </summary> /// <param name="response">The response to the download request</param> /// <param name="fileIndex">The file index to download</param> /// <param name="blockSize">The maximum number of bytes to send in a single block</param> /// <param name="downloadData">File to download. The entire file most be provided, even if the host requested an offset.</param> public void SendDownloadResponse(DownloadResponse response, ushort fileIndex, uint blockSize, byte[] downloadData) { if (!bInitialized) throw new ObjectDisposedException("ANTFSClient object has been disposed"); IntPtr pvData = IntPtr.Zero; uint dataLength = 0; ANTFS_DownloadParameters responseParameters; releaseDownloadBuffer(); // If we had not freed the handle from a previous download, do it now responseParameters.FileIndex = fileIndex; responseParameters.MaxBlockSize = blockSize; if (response == DownloadResponse.Ok) { if (downloadData == null) throw new ANT_Exception("Download request accepted, but no data provided"); ghDownloadData = GCHandle.Alloc(downloadData, GCHandleType.Pinned); // Pin managed buffer pvData = ghDownloadData.Value.AddrOfPinnedObject(); // Get address of managed buffer if (pvData == IntPtr.Zero) throw new ANTFS_Exception("Download request failed: Unable to pin managed buffer for download"); dataLength = (uint) downloadData.Length; if(blockSize == 0 || dataLength < blockSize) responseParameters.MaxBlockSize = dataLength; } ReturnCode theReturn = (ReturnCode)ANTFSClient_SendDownloadResponse(unmanagedClientPtr, (byte)response, ref responseParameters, dataLength, pvData); if (theReturn == ReturnCode.Pass) { usCurrentTransfer = responseParameters.FileIndex; // Track current transfer } else { // If the request was not successful, we should free the handle here // Otherwise, buffer needs to remain pinned while download completes (pass/fail/etc...) // GCHandle will be freed when we receive an ANT-FS response, or the application is terminated releaseDownloadBuffer(); throw new ANTFS_RequestFailed_Exception("SendDownloadResponse", theReturn); } }
/// <summary> /// Resizes and crops the image. /// </summary> /// <param name="mediaImage">The image.</param> /// <param name="request">The request.</param> private MemoryStream ResizeAndCropImage(MediaImage mediaImage, ImageViewModel request) { int?x1 = request.CropCoordX1; int?x2 = request.CropCoordX2; int?y1 = request.CropCoordY1; int?y2 = request.CropCoordY2; var cropped = true; if ((x1 <= 0 && y1 <= 0 && ((x2 >= mediaImage.OriginalWidth && y2 >= mediaImage.OriginalHeight) || (x2 <= 0 && y2 <= 0)))) { x1 = y1 = 0; x2 = mediaImage.OriginalWidth; y2 = mediaImage.OriginalHeight; cropped = false; } var newWidth = request.ImageWidth; var newHeight = request.ImageHeight; var resized = (newWidth != mediaImage.OriginalWidth || newHeight != mediaImage.OriginalHeight); MemoryStream memoryStream = null; var hasChanges = (mediaImage.Width != newWidth || mediaImage.Height != newHeight || x1 != mediaImage.CropCoordX1 || x2 != mediaImage.CropCoordX2 || y1 != mediaImage.CropCoordY1 || y2 != mediaImage.CropCoordY2); if (hasChanges) { DownloadResponse downloadResponse = StorageService.DownloadObject(mediaImage.OriginalUri); var dimensionsCalculator = new ImageDimensionsCalculator(newWidth, newHeight, mediaImage.OriginalWidth, mediaImage.OriginalHeight, x1, x2, y1, y2); using (var image = Image.FromStream(downloadResponse.ResponseStream)) { var destination = image; var codec = ImageHelper.GetImageCodec(destination); if (resized) { destination = ImageHelper.Resize(destination, new Size { Width = newWidth, Height = newHeight }); } if (cropped) { var width = dimensionsCalculator.ResizedCroppedWidth; var heigth = dimensionsCalculator.ResizedCroppedHeight; var cropX12 = dimensionsCalculator.ResizedCropCoordX1.Value; var cropY12 = dimensionsCalculator.ResizedCropCoordY1.Value; Rectangle rec = new Rectangle(cropX12, cropY12, width, heigth); destination = ImageHelper.Crop(destination, rec); } memoryStream = new MemoryStream(); destination.Save(memoryStream, codec, null); mediaImage.Size = memoryStream.Length; } mediaImage.CropCoordX1 = x1; mediaImage.CropCoordY1 = y1; mediaImage.CropCoordX2 = x2; mediaImage.CropCoordY2 = y2; mediaImage.Width = newWidth; mediaImage.Height = newHeight; } return(memoryStream); }
public async Task <IActionResult> GetOrderDetails([FromHeader(Name = "Grid-Authorization-Token")] string token, [FromRoute] int orderID) { try { if (string.IsNullOrEmpty(token)) { return(Ok(new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = true, Message = EnumExtensions.GetDescription(CommonErrors.TokenEmpty) })); } AdminUsersDataAccess _adminUsersDataAccess = new AdminUsersDataAccess(_iconfiguration); DatabaseResponse tokenAuthResponse = await _adminUsersDataAccess.AuthenticateAdminUserToken(token); if (tokenAuthResponse.ResponseCode == (int)DbReturnValue.AuthSuccess) { if (!((AuthTokenResponse)tokenAuthResponse.Results).IsExpired) { if (!ModelState.IsValid) { return(StatusCode((int)HttpStatusCode.OK, new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = true, Message = string.Join("; ", ModelState.Values .SelectMany(x => x.Errors) .Select(x => x.ErrorMessage)) })); } CommonDataAccess commonData = new CommonDataAccess(_iconfiguration); var orderList = await commonData.GetOrderDetails(orderID); if (orderList == null || orderList.OrderID == 0) { return(Ok(new ServerResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.NotExists) })); } else { // DownloadFile DatabaseResponse awsConfigResponse = await commonData.GetConfiguration(ConfiType.AWS.ToString()); if (awsConfigResponse != null && awsConfigResponse.ResponseCode == (int)DbReturnValue.RecordExists) { MiscHelper configHelper = new MiscHelper(); GridAWSS3Config awsConfig = configHelper.GetGridAwsConfig((List <Dictionary <string, string> >)awsConfigResponse.Results); AmazonS3 s3Helper = new AmazonS3(awsConfig); DownloadResponse FrontImageDownloadResponse = new DownloadResponse(); DownloadResponse BackImageDownloadResponse = new DownloadResponse(); if (!string.IsNullOrEmpty(orderList.DocumentURL)) { FrontImageDownloadResponse = await s3Helper.DownloadFile(orderList.DocumentURL.Remove(0, awsConfig.AWSEndPoint.Length)); if (FrontImageDownloadResponse.HasSucceed) { orderList.FrontImage = FrontImageDownloadResponse.FileObject != null?configHelper.GetBase64StringFromByteArray(FrontImageDownloadResponse.FileObject, orderList.DocumentURL.Remove(0, awsConfig.AWSEndPoint.Length)) : null; orderList.DocumentURL = ""; } else { orderList.DocumentURL = ""; orderList.FrontImage = ""; } } if (!string.IsNullOrEmpty(orderList.DocumentBackURL)) { BackImageDownloadResponse = await s3Helper.DownloadFile(orderList.DocumentBackURL.Remove(0, awsConfig.AWSEndPoint.Length)); if (BackImageDownloadResponse.HasSucceed) { orderList.BackImage = BackImageDownloadResponse.FileObject != null?configHelper.GetBase64StringFromByteArray(BackImageDownloadResponse.FileObject, orderList.DocumentBackURL.Remove(0, awsConfig.AWSEndPoint.Length)) : null; orderList.DocumentBackURL = ""; } else { orderList.DocumentBackURL = ""; orderList.BackImage = ""; } } return(Ok(new ServerResponse { HasSucceeded = true, Message = StatusMessages.SuccessMessage, Result = orderList })); } else { // unable to get aws config LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.FailedToGetConfiguration)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(CommonErrors.FailedToGetConfiguration) })); } } } else { //Token expired LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.ExpiredToken)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenExpired), IsDomainValidationErrors = true })); } } else { // token auth failure LogInfo.Warning(EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed), IsDomainValidationErrors = false })); } } catch (Exception ex) { LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); return(Ok(new OperationResponse { HasSucceeded = false, Message = StatusMessages.ServerError, IsDomainValidationErrors = false })); } }
private void DownloadFile(TCPProtocol protocol, DownloadRequest request) { var response = new DownloadResponse(); try { //Le comunico al servidor de conciliacion que un usuario pidio descargar un archivo. var remotingRequest = new ClientDownloadRequest() { ClientName = request.ClientName, FileName = request.FileName }; _remotingService.SendMessage(remotingRequest); byte[] archivo = null; response.Result = ServerData.Instance.FileExists(request.FileName) ? TransferResponseEnum.OK : TransferResponseEnum.FileDoesntExist; if (response.Result == TransferResponseEnum.OK) { archivo = FileHelper.ReadFile(string.Format("{0}\\{1}", ServerData.Instance.FileRepository, request.FileName)); response.FileLength = archivo.LongLength; } protocol.SendMessage(response); if (response.Result == TransferResponseEnum.OK) { request = (DownloadRequest)protocol.RecieveMessage(); byte[] archivoAEnviar = new byte[archivo.LongLength - request.Rest]; Array.Copy(archivo, request.Rest, archivoAEnviar, 0, archivoAEnviar.LongLength); protocol.SendFile(archivoAEnviar); } else { throw new Exception("Error enviando archivo"); } } catch (System.IO.FileNotFoundException e) { response.Result = TransferResponseEnum.FileDoesntExist; //Actualizo mi lista, por las dudas. ServerData.Instance.FileList = new List <string>(); foreach (string pathArchivo in FileHelper.SearchFilesInLocation(ServerData.Instance.FileRepository)) { ServerData.Instance.FileList.Add(Path.GetFileName(pathArchivo)); } //Envio respuesta. protocol.SendMessage(response); } catch (Exception ex) { response.Result = TransferResponseEnum.ConnectionError; protocol.SendMessage(response); } }