public ActionResult GetResourceImage(string id) { using (var emkService = ServiceFactory.GetServiceWrapper <IEmkService>()) { IList <EmkResource> emkResources = emkService.Instance.GetAllResources(); EmkResource resource = emkResources.FirstOrDefault(x => x.Id == id); if (resource == null) { return(null); } using (FileTransferServiceClient client = new FileTransferServiceClient()) { try { Stream content = client.GetFileFromPath(resource.IconFileName); if (content != null) { return(File(content, GetMimeType(resource.IconFileName))); } } catch (IOException ex) { // This exception is totally OK. No image will be displayed. } catch (AssertionFailedException) { // This exception is totally OK. No image will be displayed. } } } return(null); }
private void LoadIconAsync() { ThreadPool.QueueUserWorkItem(w => { using (FileTransferServiceClient client = new FileTransferServiceClient()) { try { Stream content = client.GetFileFromPath(EmkResourceItem.IconFileName); if (content != null) { ImageSource icon = BitmapFrame.Create(content); Application.Current.Dispatcher.Invoke((Action)(() => { Icon = icon; OnPropertyChanged("Icon"); })); } } catch (AssertionFailedException) { // Occurs if the path is empty. } catch (IOException) { // This exception is totally OK. No image will be displayed. } catch (Exception ex) { Logger.Instance.LogException(this, ex); } } }); }
static void uploadFile() { try { Console.WriteLine("Выберите файл"); string pathDirectory = getUploadFileDirectory(); if (!checkDerectory(pathDirectory)) { createDirectory(pathDirectory); } string[] files = getUploadFilesName(pathDirectory); showUploadFiles(files); int index = int.Parse(Console.ReadLine()); string pathFile = getFile(index, files); using (FileStream fstream = File.OpenRead(pathFile)) { using (var client = new FileTransferServiceClient()) { client.UploadFile(getFileName(pathFile), fstream.Length, fstream); } } } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(ex.Message); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
static void showListFilesServer() { using (var client = new FileTransferServiceClient()) { showFiles(client.ListFiles()); } }
public override void TransferFile(FileTransferBase f, Platform platform) { try { String sourcepath = TemporarySanitizePath(f.Path); String sourcefilepath = Path.Combine(sourcepath, f.Filename); String destinationfilepath = ""; if (!platform.KeepFileStructure) { destinationfilepath = Path.Combine(CurrentPlatform.WCF.PhysicalPath, f.Filename); } else { String dirguid = f.Path.Split(Path.VolumeSeparatorChar)[0]; String structure = f.Path.Substring(Path.GetPathRoot(f.Path).Length) + "\\"; destinationfilepath = Path.Combine(CurrentPlatform.WCF.PhysicalPath, dirguid, structure, f.Filename); } if (File.Exists(sourcefilepath)) { FileInfo fi = new FileInfo(sourcefilepath); FileTransferServiceClient stc = new FileTransferServiceClient(); //stc.Endpoint.Address = new System.ServiceModel.EndpointAddress("net.tcp://#IP_SCORM_SERVER#:9999/"); using (FileStream fs = new FileStream(sourcefilepath, FileMode.Open, FileAccess.Read, FileShare.Read)) { //Console.WriteLine(DateTime.Now.ToLongTimeString()); //FileTransferServiceClient proxy = new FileTransferServiceClient(); stc.Upload(destinationfilepath, platform.Name, fs); stc.Close(); } f.Status = f.Decompress ? TransferStatus.ReadyToUnzip : TransferStatus.Completed; //return f; } else { f.Status = TransferStatus.UploadFileNotFound; // return f; } } catch (Exception ex) { f.Status = TransferStatus.Error; //return f; //throw ex; } }
public override void DirFile(string[] files, Platform platform) { FileTransferServiceClient stc = new FileTransferServiceClient(); stc.Endpoint.Address = new System.ServiceModel.EndpointAddress("net.tcp://#IP_SCORM_SERVER#:9999/"); stc.Dir(files); }
private async void RemoveFileButton_OnClick(object sender, RoutedEventArgs e) { ProgressDialogController controller = await this.ShowProgressAsync("Удаление файла", "Подождите идет удаление файла на сервере..."); controller.SetIndeterminate(); FileInfoEx fileInfoEx = FilesDataGrid.SelectedItem as FileInfoEx; if (fileInfoEx != null) { try { using (FileTransferServiceClient client = new FileTransferServiceClient()) { await client.RemoveAsync(fileInfoEx); } await this.ShowMessageAsync("Удаление файла", "Файл был успешно удален!"); GetFilesList(); } catch (Exception exception) { await this.ShowMessageAsync("Ошибка", exception.Message); } } await controller.CloseAsync(); }
private async void DownloadFileButton_OnClick(object sender, RoutedEventArgs e) { FileInfoEx fileInfoEx = FilesDataGrid.SelectedItem as FileInfoEx; if (fileInfoEx != null) { ProgressDialogController controller = await this.ShowProgressAsync("Загрузка файла", "Подождите идет загрузка файла на компьютер..."); controller.SetIndeterminate(); try { string directoryPath = ConfigurationSettings.AppSettings["DownloadFilesFolder"]; DirectoryInfo directoryInfo; if (!Directory.Exists(directoryPath)) { directoryInfo = Directory.CreateDirectory(directoryPath); } else { directoryInfo = new DirectoryInfo(directoryPath); } string filePath = Path.Combine(directoryInfo.FullName, fileInfoEx.OriginalFileName); using (FileTransferServiceClient client = new FileTransferServiceClient()) using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None)) { FileDataDownload download; do { download = await client.DownloadAsync(fileInfoEx); if (download.Data != null) { stream.Write(download.Data, 0, download.Data.Length); } } while (!download.IsLastPart); } await this.ShowMessageAsync("Загрузка файла", "Файл был успешно загружен на компьютер!"); } catch (Exception exception) { await this.ShowMessageAsync("Ошибка", exception.Message); } await controller.CloseAsync(); } }
static void downloadFile() { try { Console.WriteLine("Выберите файл"); string pathDirectory = getFileDirectory(); if (!checkDerectory(pathDirectory)) { createDirectory(pathDirectory); } using (var client = new FileTransferServiceClient()) { var files = client.ListFiles(); showFiles(files); int index = int.Parse(Console.ReadLine()); string fileName = getFile(index, files); using (FileStream fstream = new FileStream(Path.Combine(pathDirectory, fileName), FileMode.OpenOrCreate)) { client.DownloadFile(ref fileName, out Stream stream); int byteLenght = 2048; int readByte = 0; byte[] array = new byte[byteLenght]; while (true) { readByte = stream.Read(array, 0, byteLenght); if (readByte < 1) { break; } fstream.Write(array, 0, readByte); } } } } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(ex.Message); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private void UploadButton_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; try { // get some info about the input file System.IO.FileInfo fileInfo = new System.IO.FileInfo(FileTextBox.Text); // show start message LogText("Starting uploading " + fileInfo.Name); LogText("Size : " + fileInfo.Length); // open input stream using (System.IO.FileStream stream = new System.IO.FileStream(FileTextBox.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { using (StreamWithProgress uploadStreamWithProgress = new StreamWithProgress(stream)) { uploadStreamWithProgress.ProgressChanged += uploadStreamWithProgress_ProgressChanged; // start service client FileTransferServiceClient client = new FileTransferServiceClient(); // upload file ResoureMetadataMessage res = client.SaveFile(fileInfo.Name, fileInfo.Length, uploadStreamWithProgress); LogText("Done!"); // close service client //client.Close(); } } } catch (Exception ex) { LogText("Exception : " + ex.Message); if (ex.InnerException != null) LogText("Inner Exception : " + ex.InnerException.Message); } finally { Cursor = Cursors.Default; } }
public string ImportaSingoloCondominio(string inputPathFileName, string codiceCondominio, string prefixConto, bool importaContiStudio, TipoSaldi tipoSaldi, string password, SoftwareInput importType) { string message; string fullPathFileName = compressFile(inputPathFileName, importType == SoftwareInput.Excel || importType == SoftwareInput.Summa); // get some info about the input file var fileInfo = new FileInfo(fullPathFileName); // open input stream using (var stream = new FileStream(fullPathFileName, FileMode.Open, FileAccess.Read)) { var key = Guid.NewGuid(); using (var uploadStreamWithProgress = new StreamWithProgress(stream)) { //uploadStreamWithProgress.ProgressChanged += uploadStreamWithProgress_ProgressChanged; // start service client var client = new FileTransferServiceClient(); // upload file client.UploadFile(key.ToString(), fileInfo.Length, uploadStreamWithProgress); // close service client //client.Close(); } message = GetServiceClient().ImportazioneSingoloCondominio(key.ToString(), codiceCondominio, prefixConto, importaContiStudio, tipoSaldi, password, importType, GetUserInfo()); // Aggiorno le lista di condomini, unità immobiliari e persone _cacheService.LoadPersone(); _cacheService.LoadCondomini(); _cacheService.LoadUI(); _cacheService.LoadEsercizi(); CloseService(); } return message; }
/// <summary> /// Transfiere un archivo desde el servidor al dispositivo. /// </summary> /// <param name="fileName"> /// El nombre del archivo a transferrir /// </param> public static void TransferFile(string fileName) { if (String.IsNullOrEmpty(fileName)) { throw new ArgumentException( global::PresentationLayer.GeneralResources.FileNameNullArgument); } LastSyncDataAccess syncDataAccess = new LastSyncDataAccess(); // Crear el servicio de transferencia FileTransferServiceClient fileTransfer = new FileTransferServiceClient(BaseForm.ServerBinding, new EndpointAddress(UtnEmall.Client.SmartClientLayer.Connection.ServerUri + "FileTransferService")); // Cargar la información de sincronización Collection <LastSyncEntity> results = syncDataAccess.LoadWhere("entityName", fileName.Substring(fileName.LastIndexOf(@"\", StringComparison.Ordinal) + 1), false, OperatorType.Equal); DownloadRequest request = new DownloadRequest(); request.FileName = Path.GetFileName(fileName); if (results.Count > 0) { request.FileDateTime = results[0].LastTimestamp.Ticks.ToString(CultureInfo.InvariantCulture); } else { request.FileDateTime = DateTime.MinValue.Ticks.ToString(CultureInfo.InvariantCulture); } if (!File.Exists(Path.Combine(Utilities.AppPath, fileName))) { request.FileDateTime = DateTime.MinValue.Ticks.ToString(CultureInfo.InvariantCulture); } // Realizar la transferencia RemoteFileInfo returnInfo = null; try { returnInfo = fileTransfer.DownloadFile(request, UtnEmall.Client.SmartClientLayer.Connection.Session); } catch (TargetInvocationException) { BaseForm.ShowErrorMessage( global::PresentationLayer.GeneralResources.TargetInvocationExceptionMessage, global::PresentationLayer.GeneralResources.ErrorTitle); return; } catch (CommunicationException) { BaseForm.ShowErrorMessage( global::PresentationLayer.GeneralResources.CommunicationException, global::PresentationLayer.GeneralResources.ErrorTitle); return; } FileStream writer = null; if (returnInfo != null) { fileName = Path.Combine(Utilities.AppPath, fileName); // Guardar el archivo a disco try { writer = new FileStream(fileName, FileMode.Create, FileAccess.Write); writer.Write(returnInfo.FileByteStream, 0, returnInfo.FileByteStream.Length); // Guardar la información para futuras sincronizaciones LastSyncEntity fileSync = new LastSyncEntity(); fileSync.EntityName = returnInfo.FileName; fileSync.LastTimestamp = new DateTime(Convert.ToInt64(returnInfo.FileDateTime, CultureInfo.InvariantCulture)); if (File.Exists(fileName) && results.Count > 0) { fileSync.Id = results[0].Id; fileSync.IsNew = false; fileSync.Changed = true; } syncDataAccess.Save(fileSync); } finally { if (writer != null) { writer.Close(); } } } }
public CondominiImportabili GetCondomini(string inputPathFileName, string password, SoftwareInput importType) { try { var fullPathFileName = compressFile(inputPathFileName, importType == SoftwareInput.Excel || importType == SoftwareInput.Summa); // get some info about the input file var fileInfo = new FileInfo(fullPathFileName); // open input stream using (var stream = new FileStream(fullPathFileName, FileMode.Open, FileAccess.Read)) { var key = Guid.NewGuid(); using (var uploadStreamWithProgress = new StreamWithProgress(stream)) { //uploadStreamWithProgress.ProgressChanged += uploadStreamWithProgress_ProgressChanged; // start service client var client = new FileTransferServiceClient(); // upload file client.UploadFile(key.ToString(), fileInfo.Length, uploadStreamWithProgress); // close service client //client.Close(); } var result = GetServiceClient().GetCondominiDaImportare(key.ToString(), password, importType, GetUserInfo()); CloseService(); return result; } } catch (CommunicationObjectAbortedException ex) { _log.DebugFormat("Errore nella chiamata al servizio - {0} - azienda:{1}", ex, Utility.GetMethodDescription(), Login.Instance.CurrentLogin().Azienda); } catch (CommunicationObjectFaultedException ex) { _log.DebugFormat("Errore nella chiamata al servizio - {0} - azienda:{1}", ex, Utility.GetMethodDescription(), Login.Instance.CurrentLogin().Azienda); } catch (CommunicationException ex) { _log.DebugFormat("Errore nella chiamata al servizio - {0} - azienda:{1}", ex, Utility.GetMethodDescription(), Login.Instance.CurrentLogin().Azienda); } catch (IOException ex) { _log.ErrorFormat("Errore nella lettura del file da importare - {0} - file:{1} - password:{2} - importType:{3} - azienda:{4}", ex, Utility.GetMethodDescription(), inputPathFileName, password, importType, Login.Instance.CurrentLogin().Azienda); var message = $"Non è possibile accedere al file: {inputPathFileName}"; return new CondominiImportabili { Message = message, Condomini = null}; } catch (Exception ex) { _log.ErrorFormat("Errore nella lettura del file da importare - {0} - file:{1} - password:{2} - importType:{3} - azienda:{4}", ex, Utility.GetMethodDescription(), inputPathFileName, password, importType, Login.Instance.CurrentLogin().Azienda); var message = $"Errore inaspettato nell'importazione del file: {inputPathFileName}{Environment.NewLine}Si prega di riprovare."; return new CondominiImportabili { Message = message, Condomini = null }; } return new CondominiImportabili { Message = "Errore nella chiamata al servizio", Condomini = null }; }
public IList<BollettaMessaggioDTO> GetBolletteDaImportare(string inputPathFileName) { IList<BollettaMessaggioDTO> result; var fullPathFileName = inputPathFileName + ".zip"; using (var zipFile = new ZipFile()) { zipFile.AddFile(inputPathFileName); zipFile.Save(fullPathFileName); } // get some info about the input file var fileInfo = new FileInfo(fullPathFileName); // open input stream using (var stream = new FileStream(fullPathFileName, FileMode.Open, FileAccess.Read)) { var key = Guid.NewGuid(); using (var uploadStreamWithProgress = new StreamWithProgress(stream)) { //uploadStreamWithProgress.ProgressChanged += uploadStreamWithProgress_ProgressChanged; // start service client var client = new FileTransferServiceClient(); // upload file client.UploadFile(key.ToString(), fileInfo.Length, uploadStreamWithProgress); } result = GetServiceClient().GetBolletteDaImportare(key.ToString(), GetUserInfo()); CloseService(); } return result; }
private async void UploadButton_OnClick(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(FileNameTextBox.Text) || string.IsNullOrWhiteSpace(FileNameTextBox.Text)) { await this.ShowMessageAsync("Предупреждение", "Пожалуйста укажите имя файла!"); return; } if (string.IsNullOrEmpty(AuthorTextBox.Text) || string.IsNullOrWhiteSpace(AuthorTextBox.Text)) { await this.ShowMessageAsync("Предупреждение", "Пожалуйста укажите автора!"); return; } if (string.IsNullOrEmpty(DescriptionTextBox.Text) || string.IsNullOrWhiteSpace(DescriptionTextBox.Text)) { await this.ShowMessageAsync("Предупреждение", "Пожалуйста укажите автора!"); return; } if (string.IsNullOrEmpty(FileNameTextBox.Tag.ToString()) || string.IsNullOrWhiteSpace(FileNameTextBox.Tag.ToString())) { await this.ShowMessageAsync("Предупреждение", "Пожалуйста укажите файл!"); return; } ProgressDialogController controller = await this.ShowProgressAsync("Загрузка файла", "Подождите идет загрузка файла на сервер..."); controller.SetIndeterminate(); try { FileTransferServiceClient client = new FileTransferServiceClient(); using (FileStream stream = new FileStream(FileNameTextBox.Tag.ToString(), FileMode.Open, FileAccess.Read, FileShare.None)) { byte[] buffer = new byte[bufferSize]; int readBytes; string fileName = Path.GetFileNameWithoutExtension(FileNameTextBox.Tag.ToString()); string fileGuid = $"{Guid.NewGuid()}_#{_random.Next(0, 100_000)}"; string serverFileName = $"{fileName}_{fileGuid}_{Path.GetExtension(FileNameTextBox.Tag.ToString())}"; do { readBytes = stream.Read(buffer, 0, buffer.Length); if (readBytes > 0) { byte[] data = new byte[readBytes]; Array.Copy(buffer, data, readBytes); FileDataUpload dataUpload = new FileDataUpload { FileId = serverFileName, FileName = FileNameTextBox.Text, Author = AuthorTextBox.Text, DateUpload = DateTime.Now, Description = DescriptionTextBox.Text, Data = data, IsLastPart = false }; await client.UploadAsync(dataUpload); } else { FileDataUpload dataUpload = new FileDataUpload { FileId = serverFileName, FileName = FileNameTextBox.Text, Author = AuthorTextBox.Text, DateUpload = DateTime.Now, Description = DescriptionTextBox.Text, Data = null, IsLastPart = true }; await client.UploadAsync(dataUpload); } } while (readBytes > 0); } await this.ShowMessageAsync("Загрузка файла", "Файл был успешно загружен на сервер!"); GetFilesList(); } catch (Exception exception) { await this.ShowMessageAsync("Ошибка", exception.Message); } await controller.CloseAsync(); }
private void DownloadButton_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; try { // start service client FileTransferServiceClient client = new FileTransferServiceClient(); LogText("Start"); // kill target file, if already exists string filePath = System.IO.Path.Combine("Download", textBox1.Text); if (System.IO.File.Exists(filePath)) System.IO.File.Delete(filePath); // get stream from server System.IO.Stream inputStream; string fileName = textBox1.Text; long length = client.DownloadFile(ref fileName, out inputStream); // write server stream to disk using (System.IO.FileStream writeStream = new System.IO.FileStream(filePath, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write)) { int chunkSize = 2048; byte[] buffer = new byte[chunkSize]; do { // read bytes from input stream int bytesRead = inputStream.Read(buffer, 0, chunkSize); if (bytesRead == 0) break; // write bytes to output stream writeStream.Write(buffer, 0, bytesRead); // report progress from time to time progressBar1.Value = (int)(writeStream.Position * 100 / length); } while (true); // report end of progress LogText("Done!"); writeStream.Close(); } // close service client inputStream.Dispose(); //client.Close(); } catch (Exception ex) { LogText("Exception : " + ex.Message); if (ex.InnerException != null) LogText("Inner Exception : " + ex.InnerException.Message); } finally { Cursor = Cursors.Default; } }
private async void GetFilesList() { ProgressDialogController controller = await this.ShowProgressAsync("Загрузка списка файлов", "Подождите идет загрузка списка файлов..."); controller.SetIndeterminate(); try { FileListType type; Enum.TryParse(FileListTypeComboBox.SelectedValue.ToString(), out type); FileTransferServiceClient client = new FileTransferServiceClient(); FileInfoEx[] files = null; switch (type) { case FileListType.AllFiles: files = await client.GetListFilesAsync(FileListType.AllFiles, ""); break; case FileListType.ByAuthor: if (string.IsNullOrEmpty(ValueTextBox.Text) || string.IsNullOrWhiteSpace(ValueTextBox.Text)) { await this.ShowMessageAsync("Предупреждение", "Пожалуйста укажите автора!"); return; } files = await client.GetListFilesAsync(FileListType.ByAuthor, ValueTextBox.Text); break; case FileListType.ByFileName: if (string.IsNullOrEmpty(ValueTextBox.Text) || string.IsNullOrWhiteSpace(ValueTextBox.Text)) { await this.ShowMessageAsync("Предупреждение", "Пожалуйста укажите имя файла!"); return; } files = await client.GetListFilesAsync(FileListType.ByFileName, ValueTextBox.Text); break; case FileListType.ByDateUpload: if (DateUploadDatePicker.SelectedDate == null) { await this.ShowMessageAsync("Предупреждение", "Пожалуйста укажите дату загрузки файла!"); return; } string date = DateUploadDatePicker.SelectedDate.Value.Date.ToShortDateString(); files = await client.GetListFilesAsync(FileListType.ByDateUpload, date); break; } if (files != null) { FilesDataGrid.ItemsSource = files; if (files.Length <= 0) { if (type != FileListType.AllFiles) { await this.ShowMessageAsync("Результат поиска", "К сожалению по указанным критериям ничего не было найдено!"); } } } } catch (Exception exception) { await this.ShowMessageAsync("Ошибка", exception.Message); } await controller.CloseAsync(); }