protected void SetContentResponder() { _contentResponder = new ContentResponder(GetCurrentConf(true), MainLogger); _contentResponder.FileUploading += (o, a) => FileUploading?.Invoke(o, a); _contentResponder.FileUploaded += (o, a) => FileUploaded?.Invoke(o, a); AddResponder(_contentResponder); }
private async void Upload(FileResult file) { try { using (Busy()) { using (var stream = await file.OpenReadAsync()) { using (var client = new HttpClient()) using (var formData = new MultipartFormDataContent()) { formData.Add(new StreamContent(stream), "file1", file.FileName); formData.Headers.TryAddWithoutValidation("session-handle", (await SessionHandler.Session.Ping()).Handle); var response = await client.PostAsync(new Uri(SessionHandler.Session.Configuration.Uri(), "/majaocr"), formData); response.EnsureSuccessStatusCode(); var id = await response.Content.ReadAsStringAsync(); await SessionHandler.ExecuteOpenbiCommand((s, t) => s.AnalyzeOcrDocument(id)); FileUploaded?.Invoke(this, new StringEventArgs(id)); } } } } catch (Exception ex) { DisplayException(ex); } }
public async Task <ActionResult> UploadToBlob() { IFormFile file = Request.Form.Files[0]; if (file == null) { return(BadRequest()); } var ext = System.IO.Path.GetExtension(file.FileName); var f = new FileUploaded() { FileNameOriginal = file.FileName, Extension = ext.Replace(".", ""), FileName = string.Format(@"{0}{1}", Guid.NewGuid(), ext) }; var result = await _blobService.UploadFileBlobAsync( "files", file.OpenReadStream(), file.ContentType, f.FileName); f.AbsoluteUri = result.AbsoluteUri; return(Ok(f)); }
public void Handle(FileUploaded msg) { using (var file = File.OpenRead(msg.Filename)) using (StreamReader reader = new StreamReader(file)) { int row = 0; string line; while ((line = reader.ReadLine()) != null) { var values = line.Split(new [] { ',' }); var report = new AbideReport { TradeId = values[0], ActionType = values[1], OtherStuff = values[2] }; Context.Parent.Tell(new NewAbideReport { Filename = msg.Filename, Row = row++, Report = report }); } } Context.Parent.Tell(new EndOfFile { Filename = msg.Filename }); }
public async Task <IActionResult> UploadFileToS3(IFormFile file) { var fileName = Path.GetFileName( ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName.Value.Trim('"')); string objectKey = S3KeyGen.GenerateObjectKey(fileName); using (var stream = file.OpenReadStream()) { UploadFileInfo info = FileProcesser.GetUploadFileInfo(stream, file.ContentType); FileUploaded model = await FileUploadService.UploadFile( S3Settings.OriginalBucketName, S3Settings.OriginalBucketUrl, objectKey, S3StorageClass.Standard, //Need to check with Ginu S3CannedACL.PublicRead, info); if (model.Exception != null) { //log the error: return(StatusCode((int)HttpStatusCode.InternalServerError)); } return(Created(model.ObjectLocation, model)); } }
private void InitializeAppResponders(AppConf[] configs) { string currentMode = ProcessMode.Current.Mode.ToString(); configs.Where(c => c.ProcessMode.Equals(currentMode)).Each(ac => { OnAppContentResponderInitializing(ac); Logger.RestartLoggingThread(); AppContentResponder responder = new AppContentResponder(this, ac) { Logger = Logger }; Subscribers.Each(logger => { logger.RestartLoggingThread(); responder.Subscribe(logger); }); string appName = ac.Name.ToLowerInvariant(); responder.Initialize(); responder.FileUploading += (o, a) => FileUploading?.Invoke(o, a); responder.FileUploaded += (o, a) => FileUploaded?.Invoke(o, a); responder.Responded += (r, context) => OnResponded(context); responder.NotResponded += (r, context) => OnNotResponded(context); AppContentResponders[appName] = responder; OnAppContentResponderInitialized(ac); }); }
public async Task <TResult> UploadFile <TResult>(string requestUri, FileUploaded file) { List <MemoryStream> memories = new List <MemoryStream>(); List <HttpContent> streamContents = new List <HttpContent>(); using (var requestContent = new MultipartFormDataContent()) { var ms = new MemoryStream(file.Content); memories.Add(ms); HttpContent stream = null; stream = CreateFileContent(ms, $"{ file.FileName }", file.MineType); requestContent.Add(stream); streamContents.Add(stream); using (var requestResponse = await this.HttpClient.PostAsync(requestUri, requestContent)) { foreach (var m in memories) { m.Dispose(); } foreach (var st in streamContents) { st.Dispose(); } return(await HandleResponse <TResult>(requestResponse)); } } }
public void UploadFile(ConversationMessageModel message, FileModel file) { try { IsBusy = true; _writer.Write(MessageDictionary.UploadFile); if (_reader.ReadByte() == MessageDictionary.OK) { _writer.Write(file.Name); _writer.Write(file.ContentType.MediaType); _writer.Write(file.DateAdded.ToString("dd-MM-yyyy")); SendFile(new MemoryStream(file.Data)); string fileId = _reader.ReadString(); file.Id = fileId; FileUploaded?.Invoke(this, new FileUploadedEventArgs() { Message = message, File = file }); } IsBusy = false; } catch (Exception ex) { MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace); ErrorHelper.LogError(ex); Logout(); } }
public async Task <FileCommon> UploadFile(FileCommon file) { var uploadedFile = await _httpService.Post <FileCommon, FileCommon>("api/file/upload", file); FileUploaded?.Invoke(uploadedFile); return(uploadedFile); }
public DialogResult ShowDialog() { FileUploadButton.SimulateClick(); FileUploadButton.Command = new ParameterizedCommand( parameter => FileUploaded?.Invoke(this, new OpenFileDialogEventArgs(parameter.Parameter as FileUploadEventArgs))); return(DialogResult.Unspecified); }
public async Task <ActionResult <string> > AddFile([FromForm] FileUploaded File, CancellationToken Cancel) { try { return(Ok(await FileService.AddFile(File, Environment.WebRootPath, Cancel))); } catch { return(BadRequest()); } }
public ActionResult Index(UploadFileModel productmodel, HttpPostedFileBase fileUpload) { if (ModelState.IsValid) { HttpPostedFileBase file = fileUpload; ViewBag.Branch = CommonHelper.ToSelectItemList(ch.GetBranch()); ViewBag.Filetype = CommonHelper.ToSelectItemList(ch.GetFileType()); FileUploaded fu = new FileUploaded(); fu.Dateofentery = DateTime.Today; fu.filuploaded = new FileToUploadedDetail { Id = uh.GetFileDetail(Convert.ToInt32(productmodel.Branch), Convert.ToInt32(productmodel.Department)) };; if (!string.IsNullOrEmpty(file.FileName)) { try { string path = Path.Combine(Server.MapPath("~/Images/"), Path.GetFileName(fileUpload.FileName)); if (System.IO.File.Exists(path)) { ViewBag.Message = "The File Already Exists in System"; } else { file.SaveAs(path); fu.Path = path; } } catch (Exception exception) { ViewBag.Message = "ERROR:" + exception.Message.ToString(); } } //else //{ // ViewBag.Message = "Specify the file"; //} //if (!string.IsNullOrEmpty(file.FileName)) //{ // //string url = "~/Images/" + file.FileName.Substring(file.FileName.LastIndexOf(".")); // //string path = Server.MapPath(url); //} fu.user = new User { Id = 1 }; ufh.AddNewFile(fu); } return(View()); }
public async Task <string> UploadFile(FileUploaded files) { try { var res = await base.UploadFile <string>(AppConstant.AppConstant.APIUploadImage, files); return(res); } catch (Exception ex) { return(""); } }
public bool AddNewFile(FileUploaded f) { DeadlineManagementContext context = new DeadlineManagementContext(); using (context) { using (context) { context.fileuploades.Add(f); context.SaveChanges(); return(true); } } }
/// <summary> /// Uploads the settings file. /// </summary> /// <returns></returns> public async Task <bool> UploadSettingsFileOnExitAsync() { if (!CloudStorageServiceSettings.Default.UploadAlways || !HasCredentialsStored) { return(true); } //var isValid = CheckAPIAuthIsValid(); // Quit if user is not authenticated if (!IsAuthenticated && !CheckAPIAuthIsValid()) { MessageBox.Show($"The {Name} API credentials could not be authenticated.", $"{Name} API Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } EveMonClient.Trace("Initiated"); // Ask for user action if uploading fails while (true) { SerializableAPIResult <CloudStorageServiceAPIFile> result = await UploadFileAsync().ConfigureAwait(false); FileUploaded?.ThreadSafeInvoke(this, new CloudStorageServiceProviderEventArgs(result.Error?.ErrorMessage)); if (!result.HasError) { EveMonClient.Trace("CloudStorageServiceProvider.UploadSettingsFileOnExitAsync - Completed", printMethod: false); return(true); } DialogResult dialogResult = MessageBox.Show(result.Error?.ErrorMessage, $"{Name} API Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error); switch (dialogResult) { case DialogResult.Abort: EveMonClient.Trace("Failed and Aborted"); return(false); case DialogResult.Retry: continue; } EveMonClient.Trace("Failed and Ignored"); return(true); } }
private async Task ProcessChannelMessageAsync(Message message) { if (message.Type != MessageType.Photo) { return; } var maxResolutionPhoto = message.Photo.First(x => x.FileSize == message.Photo.Max(x => x.FileSize)); var ms = new MemoryStream(); var stream = await _client.GetInfoAndDownloadFileAsync(maxResolutionPhoto.FileId, ms); await Task.Delay(5000); FileUploaded?.Invoke(ms, message.Caption); }
public async Task <FileUploaded> UploadFile( string bucketName, string bucketUrl, string objectKey, S3StorageClass storageClass, S3CannedACL permissions, UploadFileInfo file) { FileUploaded model = new FileUploaded(); try { PutObjectRequest request = new PutObjectRequest { BucketName = bucketName, Key = objectKey, StorageClass = storageClass, CannedACL = permissions, ContentType = file.MimeType }; request.InputStream = file.FileConent; //MD-HASH byte[] md5Hash = file.FileConent.Md5Hash(); request.MD5Digest = md5Hash.ToBase64String(); PutObjectResponse response = await S3Clinet.PutObjectAsync(request); string eTag = response.ETag.Trim('"').ToLowerInvariant(); string expectedETag = md5Hash.ToS3ETagString(); if (eTag != expectedETag) { throw new Exception("The eTag received from S3 doesn't match the eTag computed before uploading. This usually indicates that the file has been corrupted in transit."); } model.ObjectKey = objectKey; //model.ETag = eTag; model.ObjectLocation = bucketUrl + objectKey; } catch (Exception ex) { model.Exception = ex; } return(model); }
public async Task UploadAsync(Entities.RequestFile file) { var imageObject = await _client.UploadObjectAsync( bucket : file.Bucket, objectName : file.Name, contentType : file.ContentType, source : new MemoryStream(file.Data) ); var response = new ResponseFile { Name = file.Name, Uri = new Uri(imageObject.MediaLink) }; var args = new UploadFileEventArgs { Response = response, Request = file }; FileUploaded?.Invoke(this, args); }
/// <summary> /// Uploads the settings file asynchronously. /// </summary> public async Task UploadSettingsFileAsync() { if (m_queryPending) { return; } m_queryPending = true; EveMonClient.Trace("Initiated"); SerializableAPIResult <CloudStorageServiceAPIFile> result = await UploadFileAsync().ConfigureAwait(false); FileUploaded?.ThreadSafeInvoke(this, new CloudStorageServiceProviderEventArgs(result.Error?.ErrorMessage)); m_queryPending = false; string resultText = result.HasError ? "Failed" : "Completed"; EveMonClient.Trace($"CloudStorageServiceProvider.UploadSettingsFileAsync - {resultText}", printMethod: false); }
private void InitializeAppResponders(AppConf[] configs) { configs.Each(ac => { OnAppContentResponderInitializing(ac); Logger.RestartLoggingThread(); AppContentResponder responder = new AppContentResponder(this, ac); responder.Logger = Logger; Subscribers.Each(logger => { logger.RestartLoggingThread(); responder.Subscribe(logger); }); string appName = ac.Name.ToLowerInvariant(); responder.Initialize(); responder.FileUploading += (o, a) => FileUploading?.Invoke(o, a); responder.FileUploaded += (o, a) => FileUploaded?.Invoke(o, a); AppContentResponders[appName] = responder; OnAppContentResponderInitialized(ac); }); }
public async Task <Guid> AddFile(FileUploaded File, string PathToFolder, CancellationToken Cancel) { if (File?.Files.Length > 0) { if (!Directory.Exists(PathToFolder + "\\Upload\\")) { Directory.CreateDirectory(PathToFolder + "\\Upload\\"); } using (FileStream FileStream = System.IO.File.Create(PathToFolder + "\\Upload\\" + File.Files.FileName)) { File.Files.CopyTo(FileStream); FileStream.Flush(); return(await AddToDbTable("\\Upload\\" + File.Files.FileName, Cancel)); } } else { throw new ArgumentException(); } }
public Boolean Insert(FileUploaded Item, int UserId) { try { DbProvider.SetCommandText2("sp_FileUploaded_Insert", CommandType.StoredProcedure); DbProvider.AddParameter("InJson", Libs.SerializeObject(Item), SqlDbType.NVarChar); DbProvider.AddParameter("UserId", UserId, SqlDbType.Int); DbProvider.AddParameter("ErrorCode", DBNull.Value, SqlDbType.NVarChar, 100, ParameterDirection.Output); DbProvider.AddParameter("ReturnMsg", DBNull.Value, SqlDbType.NVarChar, 4000, ParameterDirection.Output); DbProvider.ExecuteNonQuery(); string errorCode = DbProvider.Command.Parameters["ErrorCode"].Value.ToString(); if (!errorCode.Equals(Constants.SUCCESS)) { return(false); } return(true); } catch (Exception) { return(false); } }
internal Task UploadFile <T>(object appConstant, FileUploaded files) { throw new NotImplementedException(); }
private void UploadEntry(FileTransferTask fileTransferTask) { fileTransferTask.State = FileProcessEntryState.Preparing; fileTransferTask.IsWorking = true; try { var fileInfo = new FileInfo(fileTransferTask.Path); if (!fileInfo.Exists) { fileTransferTask.State = FileProcessEntryState.FileNotFound; return; } using (var fileStream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read)) { fileTransferTask.Size = fileStream.Length; using (var md5Service = new MD5CryptoServiceProvider()) fileTransferTask.HashValue = md5Service.ComputeHash(fileStream); fileStream.Position = 0; fileTransferTask.State = FileProcessEntryState.Busy; var sessionGuid = _fileExplorerCommand.RequestFileUpload(fileTransferTask.TargetPath, fileTransferTask.HashValue, fileStream.Length); var packets = (int)Math.Ceiling(fileStream.Length / (double)BufferSize); var remainingLength = fileStream.Length; var lastSlowValuesUpdate = DateTime.UtcNow; var lastProgressUpdate = DateTime.UtcNow; int dataDownloadedSinceLastUpdate = 0; for (int i = 0; i < packets; i++) { int currentPacketLength; if (remainingLength > BufferSize) { currentPacketLength = BufferSize; remainingLength -= BufferSize; } else { currentPacketLength = (int)remainingLength; } var buffer = new byte[currentPacketLength]; fileStream.Read(buffer, 0, currentPacketLength); _fileExplorerCommand.SendUploadPackage(sessionGuid, buffer); dataDownloadedSinceLastUpdate += currentPacketLength; var slowUpdateTimeDifference = DateTime.UtcNow - lastSlowValuesUpdate; if (slowUpdateTimeDifference > TimeSpan.FromMilliseconds(400)) { fileTransferTask.Speed = dataDownloadedSinceLastUpdate / slowUpdateTimeDifference.TotalSeconds; fileTransferTask.EstimatedTime = TimeSpan.FromSeconds(remainingLength / fileTransferTask.Speed); lastSlowValuesUpdate = DateTime.UtcNow; dataDownloadedSinceLastUpdate = 0; } if (DateTime.UtcNow - lastProgressUpdate > TimeSpan.FromMilliseconds(50)) { fileTransferTask.Progress = fileTransferTask.ProcessedSize / (double)fileStream.Length; fileTransferTask.ProcessedSize = fileStream.Length - remainingLength; UpdateProgress(); lastProgressUpdate = DateTime.UtcNow; } if (fileTransferTask.IsCanceled) { fileTransferTask.State = FileProcessEntryState.Canceled; fileTransferTask.EstimatedTime = TimeSpan.Zero; fileTransferTask.Speed = 0; _fileExplorerCommand.CancelFileUpload(sessionGuid); return; } fileTransferTask.UpdateProgress(); } fileTransferTask.Progress = 1; fileTransferTask.ProcessedSize = fileStream.Length; fileTransferTask.EstimatedTime = TimeSpan.Zero; UpdateProgress(); fileTransferTask.UpdateProgress(); var finished = _fileExplorerCommand.FinishFileUpload(sessionGuid); switch (finished) { case UploadResult.Succeed: fileTransferTask.State = FileProcessEntryState.Succeed; FileUploaded?.Invoke(this, new FileEntry { CreationTime = fileInfo.CreationTime, LastAccess = fileInfo.LastAccessTime, Name = fileInfo.Name, Path = fileTransferTask.TargetPath, Size = fileInfo.Length }); break; case UploadResult.HashValuesDoNotMatch: fileTransferTask.State = FileProcessEntryState.HashValuesNotMatch; break; case UploadResult.InvalidFileLength: fileTransferTask.State = FileProcessEntryState.InvalidFileLength; break; default: fileTransferTask.State = FileProcessEntryState.Failed; break; } fileTransferTask.Progress = 1; fileTransferTask.EstimatedTime = TimeSpan.Zero; fileTransferTask.Speed = 0; } } catch (Exception exception) { fileTransferTask.State = FileProcessEntryState.Failed; LogManager.GetCurrentClassLogger().Error(exception, "Upload failed"); } finally { fileTransferTask.IsWorking = false; fileTransferTask.IsFinished = true; } }
protected virtual void OnFileUploaded(FileUploadedEventArgs e) { FileUploaded?.Invoke(this, e); }
public async Task Handle(FileUploaded message) { await _dataProcessingApplicationService.ProcessFile(message.FilePath); _fileManagementApplicationService.MoveFileToProcessedFolder(message.FilePath); }