Beispiel #1
0
        public ActionResult Create(ImportProfileModel model)
        {
            if (PathHelper.HasInvalidFileNameChars(model.TempFileName))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Invalid file name."));
            }

            var importFile = Path.Combine(FileSystemHelper.TempDirTenant(), model.TempFileName.EmptyNull());

            if (System.IO.File.Exists(importFile))
            {
                var profile = _importProfileService.InsertImportProfile(model.TempFileName, model.Name, model.EntityType);

                if (profile != null && profile.Id != 0)
                {
                    var importFileDestination = Path.Combine(profile.GetImportFolder(true, true), model.TempFileName);

                    FileSystemHelper.CopyFile(importFile, importFileDestination, true, true);

                    return(RedirectToAction("Edit", new { id = profile.Id }));
                }
            }
            else
            {
                NotifyError(T("Admin.DataExchange.Import.MissingImportFile"));
            }

            return(RedirectToAction("List"));
        }
Beispiel #2
0
        public ActionResult Create(ImportProfileModel model)
        {
            if (!Services.Permissions.Authorize(StandardPermissionProvider.ManageImports))
            {
                return(AccessDeniedView());
            }

            var importFile = Path.Combine(FileSystemHelper.TempDirTenant(), model.TempFileName.EmptyNull());

            if (System.IO.File.Exists(importFile))
            {
                var profile = _importProfileService.InsertImportProfile(model.TempFileName, model.Name, model.EntityType);

                if (profile != null && profile.Id != 0)
                {
                    var importFileDestination = Path.Combine(profile.GetImportFolder(true, true), model.TempFileName);

                    FileSystemHelper.CopyFile(importFile, importFileDestination, true, true);

                    return(RedirectToAction("Edit", new { id = profile.Id }));
                }
            }
            else
            {
                NotifyError(T("Admin.DataExchange.Import.MissingImportFile"));
            }

            return(RedirectToAction("List"));
        }
Beispiel #3
0
        private async Task ProcessFileImpl(IWebFile file, BundleOptions bundleOptions, BundleContext bundleContext)
        {
            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }

            var extension = Path.GetExtension(file.FilePath);

            var fileWatchEnabled = bundleOptions?.FileWatchOptions.Enabled ?? false;

            Lazy <IFileInfo> fileInfo;
            var cacheBuster = bundleOptions != null
                ? _cacheBusterResolver.GetCacheBuster(bundleOptions.GetCacheBusterType())
                : _cacheBusterResolver.GetCacheBuster(_bundleManager.GetDefaultBundleOptions(false).GetCacheBusterType()); //the default for any dynamically (non bundle) file is the default bundle options in production

            var cacheFile = _fileSystemHelper.GetCacheFilePath(file, fileWatchEnabled, extension, cacheBuster, out fileInfo);

            var exists = File.Exists(cacheFile);

            //check if it's in cache
            if (exists)
            {
                _logger.LogDebug($"File already in cache '{file.FilePath}', type: {file.DependencyType}, cacheFile: {cacheFile}, watching? {fileWatchEnabled}");
            }
            else
            {
                if (file.Pipeline.Processors.Count > 0)
                {
                    _logger.LogDebug($"Processing file '{file.FilePath}', type: {file.DependencyType}, cacheFile: {cacheFile}, watching? {fileWatchEnabled} ...");
                    var contents = await _fileSystemHelper.ReadContentsAsync(fileInfo.Value);

                    var watch = new Stopwatch();
                    watch.Start();
                    //process the file
                    var processed = await file.Pipeline.ProcessAsync(new FileProcessContext(contents, file, bundleContext));

                    watch.Stop();
                    _logger.LogDebug($"Processed file '{file.FilePath}' in {watch.ElapsedMilliseconds}ms");
                    //save it to the cache path
                    await _fileSystemHelper.WriteContentsAsync(cacheFile, processed);
                }
                else
                {
                    // we can just copy the the file as-is to the cache file
                    _fileSystemHelper.CopyFile(fileInfo.Value.PhysicalPath, cacheFile);
                }
            }

            //If file watching is enabled, then watch it - this is regardless of whether the cache file exists or not
            // since after app restart if there's already a cache file, we still want to watch the file set
            if (fileWatchEnabled)
            {
                // watch this file for changes, if the file is already watched this will do nothing
                _fileSystemHelper.Watch(file, fileInfo.Value, bundleOptions, FileModified);
            }
        }
Beispiel #4
0
        public void CopyFileFromAtoB()
        {
            string source      = @"C:\temp\a.txt";
            string destination = @"cheapcopy.txt";

            //   FileAssert.DoesNotExist(destination);
            Assert.IsTrue(FileSystemHelper.CopyFile(source, destination));
            FileAssert.Exists(destination);
        }
Beispiel #5
0
        public async Task <IQueryable <UploadImportFile> > ImportFiles()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw this.ExceptionUnsupportedMediaType();
            }

            ImportProfile profile    = null;
            string        identifier = null;
            var           tempDir    = FileSystemHelper.TempDirTenant(Guid.NewGuid().ToString());
            var           provider   = new MultipartFormDataStreamProvider(tempDir);

            try
            {
                await Request.Content.ReadAsMultipartAsync(provider);
            }
            catch (Exception ex)
            {
                FileSystemHelper.ClearDirectory(tempDir, true);
                throw this.ExceptionInternalServerError(ex);
            }

            // Find import profile.
            if (provider.FormData.AllKeys.Contains("Id"))
            {
                identifier = provider.FormData.GetValues("Id").FirstOrDefault();
                profile    = _importProfileService.Value.GetImportProfileById(identifier.ToInt());
            }
            else if (provider.FormData.AllKeys.Contains("Name"))
            {
                identifier = provider.FormData.GetValues("Name").FirstOrDefault();
                profile    = _importProfileService.Value.GetImportProfileByName(identifier);
            }

            if (profile == null)
            {
                FileSystemHelper.ClearDirectory(tempDir, true);
                throw this.ExceptionNotFound(WebApiGlobal.Error.EntityNotFound.FormatInvariant(identifier.NaIfEmpty()));
            }

            var startImport    = false;
            var deleteExisting = false;
            var result         = new List <UploadImportFile>();
            var unzippedFiles  = new List <MultipartFileData>();
            var importFolder   = profile.GetImportFolder(true, true);
            var csvTypes       = new string[] { ".csv", ".txt", ".tab" };

            if (provider.FormData.AllKeys.Contains("deleteExisting"))
            {
                var strDeleteExisting = provider.FormData.GetValues("deleteExisting").FirstOrDefault();
                deleteExisting = strDeleteExisting.HasValue() && strDeleteExisting.ToBool();
            }

            if (provider.FormData.AllKeys.Contains("startImport"))
            {
                var strStartImport = provider.FormData.GetValues("startImport").FirstOrDefault();
                startImport = strStartImport.HasValue() && strStartImport.ToBool();
            }

            // Unzip files.
            foreach (var file in provider.FileData)
            {
                var import = new UploadImportFile(file.Headers);

                if (import.FileExtension.IsCaseInsensitiveEqual(".zip"))
                {
                    var subDir = Path.Combine(tempDir, Guid.NewGuid().ToString());
                    ZipFile.ExtractToDirectory(file.LocalFileName, subDir);
                    FileSystemHelper.DeleteFile(file.LocalFileName);

                    foreach (var unzippedFile in Directory.GetFiles(subDir, "*.*"))
                    {
                        var content = CloneHeaderContent(unzippedFile, file);
                        unzippedFiles.Add(new MultipartFileData(content.Headers, unzippedFile));
                    }
                }
                else
                {
                    unzippedFiles.Add(new MultipartFileData(file.Headers, file.LocalFileName));
                }
            }

            // Copy files to import folder.
            if (unzippedFiles.Any())
            {
                using (_rwLock.GetWriteLock())
                {
                    if (deleteExisting)
                    {
                        FileSystemHelper.ClearDirectory(importFolder, false);
                    }

                    foreach (var file in unzippedFiles)
                    {
                        var import   = new UploadImportFile(file.Headers);
                        var destPath = Path.Combine(importFolder, import.FileName);

                        import.Exists = File.Exists(destPath);

                        switch (profile.FileType)
                        {
                        case ImportFileType.XLSX:
                            import.IsSupportedByProfile = import.FileExtension.IsCaseInsensitiveEqual(".xlsx");
                            break;

                        case ImportFileType.CSV:
                            import.IsSupportedByProfile = csvTypes.Contains(import.FileExtension, StringComparer.OrdinalIgnoreCase);
                            break;
                        }

                        import.Inserted = FileSystemHelper.CopyFile(file.LocalFileName, destPath);

                        result.Add(import);
                    }
                }
            }

            FileSystemHelper.ClearDirectory(tempDir, true);

            if (startImport)
            {
                var customer = _workContext.Value.CurrentCustomer;

                if (_permissionService.Value.Authorize(Permissions.System.ScheduleTask.Execute, customer))
                {
                    _taskScheduler.Value.RunSingleTask(profile.SchedulingTaskId, new Dictionary <string, string>
                    {
                        { TaskExecutor.CurrentCustomerIdParamName, customer.Id.ToString() },
                        { TaskExecutor.CurrentStoreIdParamName, _storeContext.Value.CurrentStore.Id.ToString() }
                    });
                }
            }

            return(result.AsQueryable());
        }
Beispiel #6
0
        private static bool WriteThumbToFolder(string testPath)
        {
            string imageResource = Path.Combine(Directory.GetCurrentDirectory(), "images\\thumb.png");

            return(FileSystemHelper.CopyFile(imageResource, Path.Combine(testPath, "thumb.png")));
        }