protected async void Page_Load(object sender, EventArgs e)
        {
            _arquivoRepository = ArquivoRepositoryFactory.Create();

            Response.Clear();

            long   idDiretorio = Convert.ToInt64(Request.Params["parentFolderId"]);
            string token       = Request.Params["token"];
            string fileName    = Request.Params["fileName"];
            string mimeType    = Request.Params["mimeType"];

            Arquivo arquivoReferencia = await ArquivoRules.AddAsync(fileName, false, idDiretorio);

            IFileManager fileManager = FileManagerFactory.Create();

            long fileSize = await fileManager.MergeChunksAsync(arquivoReferencia.Url, token);

            arquivoReferencia.Tamanho  = fileSize;
            arquivoReferencia.MimeType = mimeType;

            await _arquivoRepository.UpdateAsync(arquivoReferencia);

            Response.Write(fileSize);
            Response.End();
        }
        private async Task <long> HandleFileUploadAsync()
        {
            HttpPostedFile httpPostedFile = Request.Files["file"];

            string urlArquivo = await CriarReferenciaArquivoAsync(httpPostedFile);

            IFileManager fileManager = FileManagerFactory.Create();

            return(await fileManager.UploadAsync(httpPostedFile.InputStream, urlArquivo));
        }
        protected async void Page_Load(object sender, EventArgs e)
        {
            Response.Clear();

            string         token          = Request.Params["token"];
            HttpPostedFile httpPostedFile = Request.Files["chunk"];

            IFileManager fileManager = FileManagerFactory.Create();

            long fileSize = await fileManager.UploadChunkAsync(httpPostedFile.InputStream, token);

            Response.Write(fileSize);
            Response.End();
        }
Example #4
0
        private string DealUploadedFile(string shortFileName, string fullFileName, Dictionary <string, string> customParams)
        {
            int    systemID     = customParams["SystemID"].ToInt32();
            string moduleCode   = customParams["ModuleCode"];
            string categoryCode = customParams["CategoryCode"];
            string masterID     = customParams["MasterID"];

            string fileName = shortFileName;
            string fileType = Path.GetExtension(shortFileName);

            byte[] fileContent = null;
            using (FileStream fs = File.Open(fullFileName, FileMode.Open))
            {
                using (BinaryReader reader = new BinaryReader(fs))
                {
                    fs.Seek(0L, SeekOrigin.Begin);
                    fileContent = reader.ReadBytes((int)fs.Length);
                }
            }

            ConnectionStringSettings connstr = ConfigurationManager.ConnectionStrings["SparkServiceDesk_FileManagerConnectionString"];
            DBOperator db = DBOperatorFactory.GetDBOperator(connstr);

            IFileManager fileManager = FileManagerFactory.CreateFileManager("DEFAULT");

            fileManager.DB = db;

            //add by qianbin
            bool overWrite = false;

            if (customParams.ContainsKey("OverWrite"))
            {
                overWrite = customParams["OverWrite"].ToBoolean(false);
            }
            if (overWrite)
            {
                List <SimpleFileModel> list = fileManager.GetSimpleFileModel(systemID, moduleCode, categoryCode, masterID);
                foreach (SimpleFileModel innerSfm in list)
                {
                    fileManager.DeleteFile(innerSfm.FileID);
                }
            }
            //end add

            SimpleFileModel sfm = fileManager.AddFile(systemID, moduleCode, categoryCode, masterID, fileName, fileType, fileContent, FileState.Saved);

            return(sfm.FileID.ToString());
        }
        protected async void ExcluirDiretorioAsync_Click(object sender, EventArgs e)
        {
            long idArquivo = PegarIdArquivoSelecionado();

            if ((await _arquivoRepository.FindWhereParentEqualsAsync(idArquivo)).Any())
            {
                ExibirMensagemErro("Diretório não pode ser excluído pois possui dependentes");
            }
            else
            {
                IFileManager fileManager = FileManagerFactory.Create();
                await fileManager.DeleteAsync(await _arquivoRepository.FindByIdAsync(idArquivo));

                await _arquivoRepository.DeleteAsync(idArquivo);
            }
        }
Example #6
0
        private void addButton_Click(object sender, EventArgs e)
        {
            AbstractFileFactory fFactory = new FileManagerFactory();
            var alumnoRepository         = new AlumnoRepository(fFactory, comboBox1.SelectedIndex, origin.SelectedIndex);

            log.Debug(Resource.addBtn);

            // recoge datos alumno
            Alumno alumno = new Alumno(nameBox.Text, surnameBox.Text, dniBox.Text);

            var alumnoSaved = alumnoRepository.Add(alumno);

            if (alumnoSaved.Equals(alumno))
            {
                MessageBox.Show(Resource.saveAlum);
            }
            else
            {
                MessageBox.Show(Resource.err3);
            }
            nameBox.Clear(); surnameBox.Clear(); dniBox.Clear();
        }
Example #7
0
        protected override void ConfigureContainer()
        {
            base.ConfigureContainer();
            LightSplitterHelper helper = new LightSplitterHelper();

            helper.Load();
            var documentParser = new DocumentParser(helper, new DevExpressParserFactory(20));
            var factory        = new FileManagerFactory(documentParser);

            Container.ComposeExportedValue <IFileManagerFactory>(factory);
            FileMonitorFactory monitorFactory = new FileMonitorFactory(documentParser);

            Container.ComposeExportedValue <IFileMonitorFactory>(monitorFactory);

            var documentHandler = new DocumentSetHandler(System.IO.Path.Combine(".", "documents.dat"));

            Container.ComposeExportedValue <IDataHandler <DocumentSet> >(documentHandler);

            var trainingResultLoader = new TrainingResultsHandler("Learning");

            Container.ComposeExportedValue <IDataHandler <TrainingResults> >(trainingResultLoader);
        }
        protected async void Page_Load(object sender, EventArgs e)
        {
            _arquivoRepository = ArquivoRepositoryFactory.Create();

            if (!IsPostBack)
            {
                Response.Clear();

                Arquivo arquivo = await PegarArquivoRequestAsync();

                IFileManager fileManager = FileManagerFactory.Create();

                using (Stream fileStream = await fileManager.GetStream(arquivo))
                {
                    Response.BufferOutput = false;
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + arquivo.Nome);
                    Response.AddHeader("Content-Length", fileStream.Length.ToString());
                    Response.ContentType = String.IsNullOrWhiteSpace(arquivo.MimeType) ? "application/octet-stream" : arquivo.MimeType;
                    fileStream.CopyTo(Response.OutputStream);
                    Response.End();
                }
            }
        }
Example #9
0
 public void Setup()
 {
     parser   = new Mock <IDocumentParser>();
     instance = new FileManagerFactory(parser.Object);
 }
Example #10
0
        public override bool Execute()
        {
            _generatedFile = downloadFileFromFtp();

            // there should be an error if the downloaded file path is null and let's continue
            if (_generatedFile == null)
            {
                Logger.LogWarning(LogEntryType.FileInventoryTaskService, string.Format("The vendor product file for vendor ID {0} was not successfully downloaded! No file found at {1}!", _task.VendorId, _task.FtpFileFullPath));
                return(false);
            }

            try
            {
                // get the vendor info first
                var vendor = _service.GetVendorById(_task.VendorId);

                // let's create file manager
                var fileManager = FileManagerFactory.CreateFileManager(new FileInfo(_generatedFile), _task, FileType.Csv);
                fileManager.ReadFile(_task.HasHeader ? 1 : 0);

                // read the first vendor product record from the file
                var vendorProduct = fileManager.GetNextVendorProduct();
                var totalRecords  = fileManager.TotalRecords;

                while (vendorProduct != null)
                {
                    var percentage = (((double)fileManager.CurrentRowIndex) / totalRecords) * 100.00;
                    Console.WriteLine("{0:#0.00}% Processing vendor product \'{1}\' - {2}", percentage, _task.VendorId, vendorProduct.SupplierSKU);

                    // get first the vendor product SKU
                    var eisSupplierSKU = _service.GetVendorProductSKU(vendorProduct);
                    vendorProduct.EisSupplierSKU = eisSupplierSKU;

                    // continue if it is not to create new item and its eisSupplierSKU is NULL or it has invalid data
                    if ((!_task.IsAddNewItem && string.IsNullOrEmpty(eisSupplierSKU)) || vendorProduct.HasInvalidData)
                    {
                        Console.WriteLine(string.Format("{1:#0.00}% No vendor product updated!", vendorProduct.EisSupplierSKU, percentage));

                        // read and parsed the next product from the file
                        vendorProduct = fileManager.GetNextVendorProduct();
                        continue;
                    }

                    var isToUpdate = true;
                    if (string.IsNullOrEmpty(eisSupplierSKU))
                    {
                        // get the start SKU code for this vendor
                        var startSkuCode = _service.GetVendorStartSku(vendorProduct.VendorId);
                        vendorProduct.EisSupplierSKU = string.Format("{0}{1}", startSkuCode, vendorProduct.SupplierSKU.Trim());
                        isToUpdate = false;
                    }

                    // let's override its quantity if its vendor is configured as IsAlwasyInStock
                    if (vendor.IsAlwaysInStock && vendorProduct.IsQuantitySet)
                    {
                        vendorProduct.Quantity = vendor.AlwaysQuantity ?? 0;
                    }

                    // do insert or update vendor product
                    vendorProduct.IsAutoLinkToEisSKU    = _task.IsCreateEisSKUAndLink || _task.IsLinkEisSKU;
                    vendorProduct.IsAutoLinkToEisSKUSet = _task.IsCreateEisSKUAndLink || _task.IsLinkEisSKU;
                    _service.DoUpadateOrInsertVendorProduct(vendorProduct, isToUpdate, Constants.APP_NAME);
                    _updatedEisSupplierSKUs.Add(vendorProduct.EisSupplierSKU);

                    // check first if we want to auto-link and create new EIS product if it doesn't exist
                    if (_task.IsCreateEisSKUAndLink && !string.IsNullOrEmpty(vendorProduct.UPC))
                    {
                        _service.AddLinkAndCreateEisProductIfNoMatchWithUPC(vendorProduct);
                    }

                    // check if there's a need to auto-link this vendor product with EIS product
                    if (_task.IsLinkEisSKU && !_task.IsCreateEisSKUAndLink && !string.IsNullOrEmpty(vendorProduct.UPC))
                    {
                        _service.UpdateEisProductLinks(vendorProduct.EisSupplierSKU, vendorProduct.UPC, vendorProduct.MinPack);
                    }

                    // read and parsed the next product from the file
                    vendorProduct = fileManager.GetNextVendorProduct();
                }

                Logger.LogInfo(LogEntryType.FileInventoryTaskService, "Successfully parsed the vendor product inventory file. Total records: " + fileManager.TotalRecords);
                return(true);
            }
            catch (Exception ex)
            {
                Logger.LogError(LogEntryType.FileInventoryTaskService,
                                "Error in parsing the downloaded vendor product inventory file! Message: " + EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                return(false);
            }
        }
Example #11
0
        public void ReadAndParsedFile()
        {
            // use the System's date
            var systemDateTime      = DateTime.Now;
            var productFileSettings = _settingRepository.GetProductFileSettings(systemDateTime);

            foreach (var fileSetting in productFileSettings)
            {
                try
                {
                    // continue; if it's not reading time yet
                    if (!fileSetting.IsRunNow && !isWithInReadingTime(systemDateTime, fileSetting.ReadTime.TimeOfDay))
                    {
                        continue;
                    }

                    if (isFileSettingAlreadyExecuted(fileSetting.LastExecutedOn))
                    {
                        continue;
                    }

                    // let's update file setting execution
                    _settingRepository.UpdateFileSettingLastExecution(fileSetting.VendorId);

                    // download the file from the FTP and get the downloaded file path
                    var ftpWebRequestor    = new FtpWebRequestor(fileSetting);
                    var downloadedFilePath = ftpWebRequestor.DownloadFtpFile();

                    // there should be an error if the downloaded file path is null and let's continue
                    if (downloadedFilePath == null)
                    {
                        Logger.LogWarn(this.GetType().Name, string.Format("The file for vendor ID {0} was not successfully downloaded, set for the next day reading!", fileSetting.VendorId));
                        _settingRepository.SetProductNextUploadDate(fileSetting.VendorId, systemDateTime.AddDays(1));
                        continue;
                    }

                    // delete the file from FTP server first
                    ftpWebRequestor.DeleteFileFromFtpAsync();

                    // let's create file manager
                    fileSetting.ResultDate = DateTime.UtcNow.Date;
                    var fileManager = FileManagerFactory.CreateFileManager(new FileInfo(downloadedFilePath), fileSetting, fileSetting.FileType);

                    // create the task for managing file for this file setting and start the parsing file
                    var task = Task.Factory.StartNew(() =>
                    {
                        var dataService = new FileDataService(fileManager, fileSetting, _connectionString);
                        dataService.DeleteVendorProducts();
                        return(dataService.ParsedDataFile());
                    }).ContinueWith(t =>
                    {
                        // set the next read date for the product file
                        _settingRepository.SetProductNextUploadDate(t.Result.OwnerId, systemDateTime.AddDays(1));

                        // if it has no error update the main products table with the parsed product data file
                        if (!t.Result.HasError)
                        {
                            var productService = new ProductDataService(t.Result, _connectionString);
                            productService.UpdateProducts();
                        }
                    });
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(string.Format("Error in parsing product file for vendor ID: {0} Error message: {1}", fileSetting.VendorId, ex.Message));
                    Logger.LogError(this.GetType().Name, string.Format("Error in parsing product file for vendor ID: {0} Error message: {1}", fileSetting.VendorId, ex.Message), ex.StackTrace);
                }
            }
        }