private void btnSelecionarCsv_Click(object sender, EventArgs e) { try { using (OpenFileDialog caminhoDialogo = new OpenFileDialog() { Filter = "CSV|*.csv", ValidateNames = true, Multiselect = true }) { if (caminhoDialogo.ShowDialog() == DialogResult.OK) { foreach (String arquivo in caminhoDialogo.FileNames) { DataTable original = ConversionService.csv2datatable(arquivo); CSV csv = CSVService.gerarcsv(original, arquivo); string caminho = CAMINHO_SALVAR + verificarNome(csv.nomeEmpresa) + ".xlsx"; ConversionService.datatable2xls(csv.csvFinal, caminho); ExcelFunctionalService.criarModelo(caminho, csv); } MessageBox.Show("Processo finalizado com sucesso!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
static void Main(string[] args) { DateTime inicio = DateTime.Now; Venda venda = new Venda(); CSVService a = new CSVService(); string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string folderPath = Path.Combine(desktop, "testeCSV/"); string filePath = ""; VendaTask vendaTask = new VendaTask(); //a.GerarMassaDados(folderPath, 30); for (int i = 0; i < 3000; i++) { filePath = Path.Combine(desktop, "testeCSV/Venda" + i + ".csv"); var s = a.LeiturasDeDados(filePath); foreach (var item in s) { Debug.Write(item.Id); } vendaTask.TaskLeitura(filePath); } DateTime fim = DateTime.Now; TimeSpan x = fim - inicio; Console.WriteLine(x); Console.ReadKey(); }
public static void ExportListToCSV(string listTitle, string outputFilePath, string siteUrl, string[] fields) { using (var spoClient = new SharePointOnlineClient(siteUrl, Credentials.UserName, Credentials.Password)) { var listItems = spoClient.GetListItemsByTitle(listTitle); var outputLines = new List <List <string> >(); // build and write header var headerValues = new List <string> { "ID", "DisplayName" }; // add default headerValues.AddRange(fields); // add non-default outputLines.Add(headerValues); // build and write outputLines foreach (var listItem in listItems) { var fieldValues = new List <string> { listItem[SharePointInternalFields.ID].ToString(), listItem.DisplayName }; // add default foreach (var field in fields) { fieldValues.Add(listItem[field]?.ToString()); // add non-default } outputLines.Add(fieldValues); } // create the file CSVService.WriteCSV(headerValues, outputLines, outputFilePath); } }
private async void UploadCSVFile(object sender, RoutedEventArgs e) { Button uploadFileBtn = sender as Button; uploadFileBtn.IsEnabled = false; try { Process.SetInitialStatus("Открытие файла"); CSVService.UpdateFilePath(filePathTextBox.Text); IFileService <TunnelExit> csvService = CSVService.CSVServiceObject; Process.UpdateStatus("Чтение данных"); var tunnelsList = await csvService.ReadAsync(); Process.UpdateStatus("Отображение данных"); await Task.Run(() => MainPageModel.PageModel.CreateNewTunnelData(tunnelsList)); await MainPageModel.UploadDelegate(); int damagedRecNum = MainPageModel.PageModel.NumberOfDamagedRecords; Process.SetFinalStatus($"Файл загружен\n" + ((damagedRecNum == 0) ? string.Empty : $"Кол-во повреждений: {damagedRecNum}"), true); } catch (Exception ex) { Process.SetFinalStatus("Файл не загружен", false); ExceptionHandler.Handler.HandleExceptionWithMessageBox(ex, "Ошибка при загрузке файла"); } finally { uploadFileBtn.IsEnabled = true; } }
public void GetFilePathTest() { string TableName = "FilterSetting"; // 取得完整檔名 string FilePath = CSVService.GetFilePath(TableName); // 切出檔案名稱 string Fname = FilePath.Split("\\")[^ 1];
public void TaskLeitura(string caminho, string nomeDoArquivo) { this.NomeDoArquivo = nomeDoArquivo; _CSVService = new CSVService(); CaminhoDoArquivoSendoAnalizado = caminho; var leitura = Task.Run(() => LerArquivo(caminho)); leitura.Wait(); Console.WriteLine(nomeDoArquivo); }
static string GetCSVString(FilterTransactionReport filter) { if (!string.Equals(filter.subtotalBy, "None", StringComparison.InvariantCultureIgnoreCase)) { filter.subtotalBy = "None"; } var result = service.FilterTransactionReport(filter); return(CSVService.GetCsvString(filter, result)); }
public void Initialize() { _csvService = new CSVService(); _resultadoConcursoRepository = new Mock <IResultadoConcursoRepository>(); _apostaRepository = new Mock <IApostaRepository>(); _faturamentoLotericaRepository = new Mock <IFaturamentoLotericaRepository>(); randomMoq = new Mock <Random>(); _resultadoConcurso = new ResultadoConcursoService(_resultadoConcursoRepository.Object, _apostaRepository.Object, _faturamentoLotericaRepository.Object); File.Delete(file); }
public ShippingController(UserManager <AppUser> userManager, IShippingRepository shippingRepository, IVenderRepository venderRepository, CSVService csvHandler, IMapper mapper, IERPRepository eRPRepository) { _mapper = mapper; _shippingRepository = shippingRepository; _userManager = userManager; _venderRepository = venderRepository; _csvHandler = csvHandler; _erpRepository = eRPRepository; }
public void InfraCSV_GerarMassaDeDados_DeveGerar_UmArquivoCsvComUmaVendaValida() { _csvServiceTeste = new CSVService(); int quantidadeDeArquivos = 1; _csvServiceTeste.GerarMassaDados(caminhoCsvTeste, quantidadeDeArquivos); caminhoCsvTeste = Path.Combine(caminhoCsvTeste, "Venda0.csv"); File.Exists(caminhoCsvTeste).Should().BeTrue(); File.Delete(caminhoCsvTeste); }
public void ApplService_VendaTask_Inicializador() { CaminhoPastaDeVendas = ConfigurationManager.AppSettings["CaminhoPastaVendas"]; CaminhoPastaDeVendasValidas = ConfigurationManager.AppSettings["CaminhoPastaVendasValidas"]; CaminhoPastaDeVendasInvalidas = ConfigurationManager.AppSettings["CaminhoPastaVendasInvalidas"]; _vendaService = new Mock <IVendaService>(); _vendaRepositorio = new Mock <IVendaRepository>(); _vendaTask = new VendaTask(_vendaService.Object); _csvService = new CSVService(); _venda = new Mock <Venda>(); }
public BinController(IMapper mapper, IBinRepository binRepository, IUserRepository userRepository, IBinTypeRepository binTypeRepository, IWarehouseLocationRepository warehouseLocationRepository, CSVService csvHandler, DataContext context) { _csvHandler = csvHandler; _context = context; _mapper = mapper; _binRepository = binRepository; _userRepository = userRepository; _binTypeRepository = binTypeRepository; _warehouseLocationRepository = warehouseLocationRepository; }
public void InfraCSV_LeiturasDeDados_DeveRetornarUmaListaComPeloMenosUmaVenda() { _csvServiceTeste = new CSVService(); int quantidadeDeArquivos = 1; _csvServiceTeste.GerarMassaDados(caminhoCsvTeste, quantidadeDeArquivos); caminhoCsvTeste = Path.Combine(caminhoCsvTeste, "Venda0.csv"); var s = _csvServiceTeste.LeiturasDeDados(caminhoCsvTeste); s.Should().NotBeEmpty(); File.Delete(caminhoCsvTeste); }
static void Main(string[] args) { ParseMain parseMain = new ParseMain(); string html = parseMain.GetPage(Constants.mainUrl); List <PlayerModel> players = parseMain.GetPlayers(html); CSVService cSVService = new CSVService(); cSVService.CreateCSV(players); Console.WriteLine("done, path to file: " + Constants.pathToCSV); }
public BinItemController(IMapper mapper, IBinItemRepository binItemRepository, CSVService csvHandler, IBinRepository binRepository, IItemRepository itemRepository, IShippingRepository shippingRepository, IReceivingRepository receivingRepository, IReceivingItemRepository receivingItemRepository) { _csvHandler = csvHandler; _itemRepository = itemRepository; _binRepository = binRepository; _mapper = mapper; _binItemRepository = binItemRepository; _shippingRepository = shippingRepository; _receivingRepository = receivingRepository; _receivingItemRepository = receivingItemRepository; }
public IActionResult ImportUser() { try { // 調用 CSVService 提供的函數來匯入用戶資料 CSVService.ImportUser(_context); return(RedirectToRoute(new { controller = "User", action = "Index" })); } catch (Exception ex) { _logger.LogError(ex.ToString()); ViewBag.Error = "匯入用戶時發生錯誤,請查看LOG!"; return(View("~/Views/Shared/ErrorPage.cshtml")); } }
public IActionResult ExportFilterSetting() { try { // 調用 CSVService 提供的函數來匯出設定檔 CSVService.ExportFilterSetting(_context); return(RedirectToRoute(new { controller = "Setting", action = "Index" })); } catch (Exception ex) { _logger.LogError(ex.ToString()); ViewBag.Error = "匯出設定時發生錯誤,請查看LOG!"; return(View("~/Views/Shared/ErrorPage.cshtml")); } }
public void CheckWriteCSVWithSuccess() { bool output = true; ICSVService _csvService = new CSVService(); string path = FileHelper.CreateFile("csv"); _csvService.CreateCSV(path); if (!File.Exists(path)) { output = false; } Assert.True(output); }
private ProductTask[] _readTasks(string path) { TextReader reader = new StreamReader(path, Encoding.Default); var table = CSVService.ReadTable(reader, _parseInt, true); ProductTask[] productTasks = new ProductTask[table.Length]; for (int i = 0; i < table.Length; i++) { var row = table[i]; var times = row.Skip(1).ToArray(); var number = row[0]; productTasks[i] = new ProductTask(number, times); } return(productTasks); }
public async Task OpenFile() { var dialog = new OpenFileDialog(); dialog.Filters.Add(new FileDialogFilter() { Name = "Comma Separated Value", Extensions = { "csv" } }); var result = await dialog.ShowAsync(new Window()); if (result.Any()) { var filePath = result.First(); var fileContents = File.ReadAllText(filePath); var service = new CSVService(); var csv = service.GetCSVFileFromFileContents(fileContents); } }
/// <summary> /// Saves the changes in CSV file in a mode which was selected by user /// (Rewrite, append w/o header string, append w header string) /// </summary> private async void SaveFile(object sender, EventArgs e) { string filePath = filePathTextBox.Text; try { Close(); Process.SetInitialStatus("Открываем файл"); CSVService.UpdateFilePath(filePathTextBox.Text); IFileService <TunnelExit> csvService = CSVService.CSVServiceObject; Process.UpdateStatus("Записываем в файл"); if (rewriteFileRadioBtn.IsChecked == true) { await csvService.RewriteAsync(TunnelExits); } else { await csvService.AppendAsync(TunnelExits, false); } Process.SetFinalStatus("Файл перезаписан", true); } catch (UnauthorizedAccessException ex) { HandleSaveFileException(ex); } catch (IOException ex) { HandleSaveFileException(ex); } catch (Exception ex) { HandleSaveFileException(ex); } }
/// <summary> /// convert data from an input file to a new format and output to a new file /// this function could be broken down into smaller functions /// i.e. getData, convertData, writeData functions /// </summary> /// <param name="inputFile"></param> /// <param name="outputFile"></param> /// <param name="convertTo"></param> static void ConvertData(string inputFile, string outputFile, string convertTo) { // initialise variables CSVService inputService = null; IService <string, string, string> outputService = null; IBuilder builder = null; Converter converter = null; // get data inputService = new CSVService(inputFile); var lines = inputService.GetAllData(); // create builder and output services dependent on new format required switch (convertTo.ToLower()) { case "xml": builder = new XMLBuilder("root", "entity"); outputService = new XMLService(outputFile); break; case "json": builder = new JSONBuilder(); outputService = new JSONService(outputFile); break; default: throw new ArgumentNullException("Invalid file format to convert to"); } // do the conversion converter = new Converter(builder); var data = converter.ConvertCSV(lines.headings, lines.data); // write the new file outputService.WriteData(data); WriteLine($"Created {convertTo} file: {outputFile}"); }
void DoWork() { try { Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyyHH:mm:ss")} Сервис запущен"); DownloadService service = new DownloadService(); Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Идёт скачивание файла GeoLite2-City-CSV.zip "); if (string.IsNullOrEmpty(ConfigurationService.DownloadFileHref)) { throw new Exception("Настройте ключ DownloadFileHref в конфиг файле App.config"); } string filePath = service.DownloadFile(ConfigurationService.DownloadFileHref); // обновляем только в среду, так как данные на сайте обновляются только во вторник или указана AlwaysUpdate=true в конфиге if (DateTime.Now.DayOfWeek == DayOfWeek.Wednesday || ConfigurationService.AlwaysUpdate) { CSVService csvServ = new CSVService(); GeoRepository repository = new GeoRepository(); string filePathLocations = string.Format($"{filePath}\\{fileNameLocations}"); if (!File.Exists(filePathLocations)) { throw new Exception($"Загруженный файл {fileNameLocations} не был найден"); } Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Идёт считывание файла GeoLite2-City-Locations-ru.csv, подождите... "); var itemsLocations = csvServ.GetDataTabletFromCSVFile(filePathLocations); // загружаем файл Locations Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Запись в базу файла GeoLite2-City-Locations-ru.csv, подождите..."); repository.DeleteData("Stp_ClearCityLocationRu"); repository.InsertDataUsingSQLBulkCopy(itemsLocations, "CityLocationsRu"); string filePathCity = string.Format($"{filePath}\\{fileNameCity}"); if (!File.Exists(filePathCity)) { throw new Exception($"Загруженный файл {fileNameCity} не был найден"); } Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Идёт считывание файла GeoLite2-City-Blocks-IPv4.csv, подождите... "); var itemsCity = csvServ.GetDataTabletFromCSVFile(filePathCity); // загружаем файл City Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Запись в базу файла GeoLite2-City-Blocks-IPv4.csv, подождите..."); repository.DeleteData("Stp_ClearCityBlocksIPv4"); repository.InsertDataUsingSQLBulkCopy(itemsCity, "CityBlocksIPv4"); Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Данные в базе были обновлены"); } else { Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Данные не требуют обновления"); } Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Работа сервиса завершена успешно "); Thread.Sleep(new TimeSpan(ConfigurationService.AfterDaysToRunApp, 0, 0, 0)); // настраиваем через какое время запускаться, ключ вынесен в конфиг DoWork(); } catch (Exception ex) { Console.WriteLine($"{ex?.Message} {ex?.InnerException}"); Console.ReadLine(); } }
public PeopleController(PersonContext context, CSVService service) { this._context = context; this.service = service; }
public void SetUp() { _csvServiceTeste = new CSVService(); caminhoCsvTeste = Path.GetTempPath(); }
public ItemController(IMapper mapper, IItemRepository itemRepository, CSVService csvHandler) { _csvHandler = csvHandler; _mapper = mapper; _itemRepository = itemRepository; }
public VenderController(IVenderRepository venderRepository, CSVService csvHandler, IMapper mapper) { _mapper = mapper; _venderRepository = venderRepository; _csvHandler = csvHandler; }
public ERPController(CSVService csvHandler) { _csvHandler = csvHandler; }
public void Default_Constructor_ToString_Returns_Headers() { var csv = new CSVService <string>(); }
public BinTypeController(IMapper mapper, IBinTypeRepository binTypeRepository, CSVService csvHandler) { _csvHandler = csvHandler; _mapper = mapper; _binTypeRepository = binTypeRepository; }