Пример #1
0
        public ActionResult SaveFile(IEnumerable <HttpPostedFileBase> Files)
        {
            var fh = new FileUploadHandler(Server, Session, false, "~/SimpleCMS/Data/Images");

            if (fh.Save(Files))
            {
                byte[]   data     = null;
                FileInfo fileInfo = null;
                foreach (var item in Files)
                {
                    ReadFileData(new FileUploadInfo()
                    {
                        FileName = Path.GetFileName(item.FileName), Extension = Path.GetExtension(item.FileName), UID = null
                    }, out data, out fileInfo);
                    if (data != null && fileInfo != null)
                    {
                        var file = new SimpleCMS.Models.File()
                        {
                            Name        = fileInfo.Name,
                            ContentType = MimeMapping.GetMimeMapping(fileInfo.FullName),
                            Length      = fileInfo.Length,
                            Data        = data,
                            ChangeEvent = CreateChangeEvent()
                        };
                        db.Files.Add(file);
                    }
                }
                db.SaveChanges();
                return(Content(""));
            }
            return(Content("Error"));
        }
Пример #2
0
        public async Task <ActionResult> FileHandler()
        {
            FileUploadHandler handler = new FileUploadHandler(Request, this);

            handler.IncomingRequestStarted += handler_IncomingRequestStarted;

            handler.AuthorizeRequestStarted  += handler_AuthorizeRequestStarted;
            handler.AuthorizeRequestFinished += handler_AuthorizeRequestFinished;

            handler.GetFilesRequestStarted   += handler_GetFilesRequestStarted;
            handler.GetFilesRequestFinished  += handler_GetFilesRequestFinished;
            handler.GetFilesRequestException += handler_GetFilesRequestException;

            handler.StoreFileRequestStartedAsync += handler_StoreFileRequestStartedAsync; // async event handler
            handler.StoreFileRequestFinished     += handler_StoreFileRequestFinished;
            handler.StoreFileRequestException    += handler_StoreFileRequestException;

            handler.DeleteFilesRequestStarted       += handler_DeleteFilesRequestStarted;
            handler.DeleteFilesRequestFinishedAsync += handler_DeleteFilesRequestFinishedAsync; // async event handler
            handler.DeleteFilesRequestException     += handler_DeleteFilesRequestException;

            handler.OutgoingResponseCreated += handler_OutgoingResponseCreated;

            handler.ProcessPipelineExceptionOccured += handler_ProcessPipelineExceptionOccured;


            ActionResult result = await handler.HandleRequestAsync();

            return(result);
        }
Пример #3
0
        public FileUploadForm()
        {
            try
            {
                InitializeComponent();
                MaximizeBox = false;

                reportBox.ReadOnly               = true;
                fileUploadDialog.Filter          = "Image Files(*.bmp;*.jpg;*.jpeg;*.gif;*.png)|*.bmp;*.jpg;*.jpeg;*.gif;*.png|All files (*.*)|*.*";
                fileUploadDialog.Multiselect     = true;
                fileUploadDialog.FileOk         += FileUploadDialog_FilesOk;
                uploadWorker.ProgressChanged    += UploadWorker_ProgressChanged;
                uploadWorker.RunWorkerCompleted += UploadWorker_Completed;
                uploadHandler = new FileUploadHandler();
            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show($"{ex.StackTrace}.", "Falha ao carregar arquivos de configuracoes");
                System.Environment.Exit(500);
            }
            catch (MissingCredentialsException ex)
            {
                MessageBox.Show($"{ex.Message}", "Falha ao carregar credenciais do Imgur");
                System.Environment.Exit(500);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " - " + ex.StackTrace, "Erro Fatal");
                System.Environment.Exit(500);
            }
        }
Пример #4
0
        public async Task<ActionResult> FileHandler()
        {
            FileUploadHandler handler = new FileUploadHandler(Request, this);
            handler.IncomingRequestStarted += handler_IncomingRequestStarted;

            handler.AuthorizeRequestStarted += handler_AuthorizeRequestStarted;
            handler.AuthorizeRequestFinished += handler_AuthorizeRequestFinished;

            handler.GetFilesRequestStarted += handler_GetFilesRequestStarted;
            handler.GetFilesRequestFinished += handler_GetFilesRequestFinished;
            handler.GetFilesRequestException += handler_GetFilesRequestException;

           handler.StoreFileRequestStartedAsync += handler_StoreFileRequestStartedAsync; // async event handler 
            handler.StoreFileRequestFinished += handler_StoreFileRequestFinished;
            handler.StoreFileRequestException += handler_StoreFileRequestException;

            handler.DeleteFilesRequestStarted += handler_DeleteFilesRequestStarted;
            handler.DeleteFilesRequestFinishedAsync += handler_DeleteFilesRequestFinishedAsync; // async event handler 
            handler.DeleteFilesRequestException += handler_DeleteFilesRequestException;

            handler.OutgoingResponseCreated += handler_OutgoingResponseCreated;

            handler.ProcessPipelineExceptionOccured += handler_ProcessPipelineExceptionOccured;


            ActionResult result = await handler.HandleRequestAsync();
            return result;
        }
Пример #5
0
        public void SaveChunkData()
        {
            // arrange
            var handler = new FileUploadHandler();
            int savedButes;

            Mock.Arrange(() => handler.IsFinalFileRequest()).Returns(false);

            // act
            var result = handler.SaveChunkData(@"D:\1.txt", 1, new byte[0], 10, out savedButes);

            // assert
            Assert.IsFalse(result);

            // arrange
            Mock.Arrange(() => handler.IsFinalFileRequest()).Returns(true);
            Mock.Arrange(() => handler.GetQueryParameter((Constants.ReplaceReportConnectionStrings))).Returns("bla-bla-bla (not bool value)");

            // act
            result = handler.SaveChunkData(@"D:\1.txt", 1, new byte[0], 10, out savedButes);

            // assert
            Assert.IsFalse(result);

            // arrange
            Mock.Arrange(() => handler.GetQueryParameter((Constants.ReplaceReportConnectionStrings))).Returns("false");

            // act
            result = handler.SaveChunkData(@"D:\1.txt", 1, new byte[0], 10, out savedButes);

            // assert
            Assert.IsFalse(result);
        }
Пример #6
0
 private static bool Upload(UploadCmdArgs args, ILogger logger)
 {
     using (var handler = new FileUploadHandler(args.Owner, logger, TimeSpan.FromSeconds(args.Timeout)))
     {
         handler.Handle(args.Path);
         return(handler.IsHandled);
     }
 }
Пример #7
0
        public JsonResult UploadHandler()
        {
            FileUploadHandler handler = new FileUploadHandler(Request);
            handler.FileUploadedStarted += FileUploadedStarted;
            JsonResult result = handler.HandleRequest();

            return result;
        }
Пример #8
0
        public async Task<ActionResult> FileHandler()
        {
            FileUploadHandler handler = new FileUploadHandler(Request, this);
            handler.IncomingRequestStarted += handler_IncomingRequestStarted;

            ActionResult result = await handler.HandleRequestAsync();
            return result;
        }
        public void OwnerNotFound()
        {
            var handler = new FileUploadHandler("Non-existent window title", _logger, TimeSpan.Zero);

            Assert.That(handler.CanHandle, Is.False);
            _logger.Received(1).LogInfo(FileUploadHandler.OwnerCannotBeFoundErrMsg);
            // Means there were no calls to the dialog.
            _logger.DidNotReceive().LogInfo(handler.DialogIsNotVisibleErrMsg);
        }
 public void ClassSetup()
 {
     _handler = new FileUploadHandler(_dialog, _logger, TimeSpan.Zero);
     // Dialog is always open and can be handled.
     _dialog.IsVisible.Returns(true);
     // Make the logger invoke passing method.
     _logger.When(e => e.LogExec(Arg.Any <Expression <Func <bool> > >()))
     .Do(e => e.ArgAt <Expression <Func <bool> > >(0).Compile().Invoke());
 }
Пример #11
0
        public JsonResult UploadHandler()
        {
            FileUploadHandler handler = new FileUploadHandler(Request);

            handler.FileUploadedStarted += FileUploadedStarted;
            JsonResult result = handler.HandleRequest();

            return(result);
        }
Пример #12
0
        protected virtual async Task OnFileSelectedAsync(ChangeEventArgs args)
        {
            EditContext.NotifyPropertyBusy(Property);

            UploadCompletion = 0.01;

            var files = await FileReaderService.CreateReference(_fileInput).EnumerateFilesAsync();

            if (files.Count() > 1)
            {
                EditContext.AddValidationMessage(Property, "This editor only supports single files for now.");
            }

            var file = files.FirstOrDefault();

            if (file == null)
            {
                return;
            }

            var fileInfo = await file.ReadFileInfoAsync();

            var validationMessages = FileUploadHandler.ValidateFile(fileInfo);

            if (validationMessages.Any())
            {
                foreach (var message in validationMessages)
                {
                    EditContext.AddValidationMessage(Property, message);
                }

                EditContext.NotifyPropertyFinished(Property);

                StateHasChanged();
                return;
            }

            using var uploadedFile = await UploadFileToTempFileAsync(file, 8192, fileInfo.Size, (completion) =>
            {
                if (completion - UploadCompletion > 1)
                {
                    UploadCompletion = completion;
                    StateHasChanged();
                }
            });

            UploadCompletion = 0.0;
            StateHasChanged();

            var value = await FileUploadHandler.SaveFileAsync(fileInfo, uploadedFile);

            SetValueFromObject(value);

            EditContext.NotifyPropertyFinished(Property);
            EditContext.NotifyPropertyChanged(Property);
        }
Пример #13
0
        internal List <ImageInfo> SaveImages(IEnumerable <HttpPostedFileBase> Files)
        {
            var fh = new FileUploadHandler(Server, Session, false, GetImagesPath());

            if (fh.Save(Files))
            {
                return(SaveImages());
            }
            return(null);
        }
Пример #14
0
        public async Task <ActionResult> FileHandler()
        {
            FileUploadHandler handler = new FileUploadHandler(Request, this);

            handler.IncomingRequestStarted += handler_IncomingRequestStarted;

            ActionResult result = await handler.HandleRequestAsync();

            return(result);
        }
Пример #15
0
        public ActionResult RemoveFile(string[] fileNames)
        {
            var fh = new FileUploadHandler(Server, Session, false, "~/SimpleCMS/Data/Images");

            if (fh.Remove(fileNames))
            {
                return(Content(""));
            }
            return(Content("Error"));
        }
Пример #16
0
        public ActionResult SaveFile(IEnumerable <HttpPostedFileBase> Files)
        {
            var fh = new FileUploadHandler(Server, Session, false, "~/Views/Shared/BlogViewTemplates");

            if (fh.Save(Files))
            {
                return(Content(""));
            }
            return(Content("Error"));
        }
Пример #17
0
        public async Task<ActionResult> FileHandler()
        {
            FileUploadHandler handler = new FileUploadHandler(Request, this);
            handler.FileUploadedStarted += FileUploadedStarted;
            handler.FileUploadedFinished += handler_FileUploadedFinished;
            handler.FileUploadException +=handler_FileUploadException;
            ActionResult result = await handler.HandleRequestAsync();

            return result;
        }
        public async Task<ActionResult> FileHandler()
        {
            Debug.WriteLine("HAF HAF HAF");
            FileUploadHandler handler = new FileUploadHandler(Request, this);
            handler.StoreFileRequestFinished += handler_StoreFileRequestFinished;
            handler.IncomingRequestStarted += handler_IncomingRequestStarted;

            ActionResult result = await handler.HandleRequestAsync();  
            return result;
        }
Пример #19
0
        public ActionResult SaveFile(IEnumerable <HttpPostedFileBase> Files)
        {
            var fh = new FileUploadHandler(Server, Session, false, "~/SimpleCMS/Data/Plugins");

            if (fh.Save(Files))
            {
                return(Content(""));
            }
            return(Content("Error"));
        }
Пример #20
0
        public ActionResult RemoveFile(string[] fileNames)
        {
            var fh = new FileUploadHandler(Server, Session, false, "~/Views/Shared/BlogViewTemplates");

            if (fh.Remove(fileNames))
            {
                return(Content(""));
            }
            return(Content("Error"));
        }
        public IDisposable RegisterFileUploadHandler(string id, FileUploadHandlerDelegate handler)
        {
            FileUploadHandler fileUploadHandler =
                new FileUploadHandler(handler, () => _registeredInputFiles.TryRemove(id, out _));

            if (!_registeredInputFiles.TryAdd(id, fileUploadHandler))
            {
                throw new InvalidOperationException($"Id '{id}' is already registered");
            }

            return(fileUploadHandler);
        }
Пример #22
0
        public async Task <IActionResult> AddUserDocumentsById([FromRoute] long userid, IList <IFormFile> models)
        {
            User usr = _repo.Find(userid);

            if (usr == null)
            {
                return(BadRequest("Invalid User"));
            }

            IList <string>       filepaths = new List <string>();
            IList <UserDocument> docs      = new List <UserDocument>();

            foreach (IFormFile f in models)
            {
                string storePath = userid.ToString() + "_" + f.Name;
                string docFolder = Path.Combine("UserDocuments", storePath);

                try
                {
                    if (f == null || f.Length == 0)
                    {
                        return(Content("File not selected"));
                    }

                    string path = FileUploadHandler.GetFilePathForUpload(docFolder, f.FileName);

                    using (FileStream stream = new FileStream(path, FileMode.Create))
                    {
                        await f.CopyToAsync(stream);
                    }
                }
                catch (Exception e)
                {
                    return(Json(new { result = "Upload Failed", error = e.Message }));
                }

                string filePath = FileUploadHandler.FileReturnPath(docFolder, f.FileName);

                UserDocument doc = new UserDocument
                {
                    UserId       = userid,
                    FilePath     = filePath,
                    DocumentName = f.FileName
                };

                docs.Add(doc);
                filepaths.Add(filePath);
            }

            doc_repo.AddRange(docs);

            return(Json(new { FilePaths = filepaths, UserID = userid }));
        }
        public void NonExistingFileName()
        {
            const string fileName = "Some.file";

            _handler.Handle(fileName);

            // Call to Upload.
            _logger.Received(1).LogExec(Arg.Any <Expression <Func <bool> > >());
            // Error logging.
            _logger.Received(1).LogInfo(FileUploadHandler.FileCannotBeFoundErrMsg(fileName));
            Assert.That(_handler.IsHandled, Is.False);
        }
Пример #24
0
        private void ReadFileData(SimpleCMS.Models.FileUploadInfo o, out byte[] File, out FileInfo FileInfo)
        {
            var fh = new FileUploadHandler(Server, Session, false, "~/SimpleCMS/Data/Images");

            File     = null;
            FileInfo = null;
            if (o != null && o.FileName != null)
            {
                var FilePath = fh.GetFilePhysicalPath(o.FileName);
                FileInfo = new FileInfo(FilePath);
                File     = System.IO.File.ReadAllBytes(FilePath);
            }
        }
Пример #25
0
        private void ReadFileData(FileUploadInfo o, out byte[] file, out FileInfo fileInfo)
        {
            var fh = new FileUploadHandler(Server, Session, false, "~/Views/Shared/BlogViewTemplates");

            file     = null;
            fileInfo = null;
            if (o != null && o.FileName != null)
            {
                var filePath = fh.GetFilePhysicalPath(o.FileName);
                fileInfo = new FileInfo(filePath);
                file     = System.IO.File.ReadAllBytes(filePath);
            }
        }
Пример #26
0
        public async Task <ActionResult> FileHandler()
        {
            FileUploadHandler handler = new FileUploadHandler(Request, this);

            handler.StoreFileRequestStarted         += handler_StoreFileRequestStarted;
            handler.StoreFileRequestFinished        += handler_StoreFileRequestFinished;
            handler.StoreFileRequestException       += handler_StoreFileRequestException;
            handler.OutgoingResponseCreated         += handler_OutgoingResponseCreated;
            handler.ProcessPipelineExceptionOccured += handler_ProcessPipelineExceptionOccured;

            ActionResult result = await handler.HandleRequestAsync();

            return(result);
        }
        private async Task HandleFileDispositionSection(
            FileUploadHandler fileUploadHandler,
            MultipartSection section,
            ContentDispositionHeaderValue contentDisposition)
        {
            if (section == null)
            {
                await fileUploadHandler.Handler(null);

                return;
            }

            await fileUploadHandler.Handler(section.Body);
        }
Пример #28
0
        private async Task<JQueryFileUpload> HandleRequest()
        {
            var request = new HttpRequestWrapper(HttpContext.Current.Request);
            FileUploadHandler handler = new FileUploadHandler(request, null);       // Get an instance of the handler class
            handler.IncomingRequestStarted += handler_IncomingRequestStarted;       // Register event handler for demo purposes

            var task = handler.HandleRequestAsync();                                // Call the asyncronous handler method
            // Do other stuff here
            var jsonResult = (JsonResult)await task;                                // Awaits the result, but does not block the thread
            //var jsonResult = (JsonResult)await handler.HandleRequestAsync();      // Both methods above can be combined 

            return (JQueryFileUpload)jsonResult.Data;                               // JsonResult.Data is of type object and must be casted 
            // to your plugins handler class
        }
Пример #29
0
        public ActionResult SaveFile(IEnumerable <HttpPostedFileBase> Files)
        {
            var fh = new FileUploadHandler(Server, Session, false, "~/SimpleCMS/Data/Images");

            if (fh.Save(Files))
            {
                //var files = AddFiles(vmObj.Files);
                foreach (var fileInfo in FileUploadHandler.UploadedFiles)
                {
                    var file = new SimpleCMS.Models.File()
                    {
                        Name        = fileInfo.Name,
                        Length      = fileInfo.Length,
                        ContentType = MimeMapping.GetMimeMapping(fileInfo.FullName),
                        Data        = System.IO.File.ReadAllBytes(Server.MapPath(Path.Combine("~/SimpleCMS/Data/Images", fileInfo.Name))),
                        ChangeEvent = CreateChangeEvent()
                    };
                    var dbObj = new ImageInfo()
                    {
                        Width       = -1,
                        Height      = -1,
                        Description = string.Empty,
                        File        = file,
                        ChangeEvent = CreateChangeEvent()
                    };
                    using (FileStream fs = new FileStream(Server.MapPath(Path.Combine("~/SimpleCMS/Data/Images", file.Name)), FileMode.Open, FileAccess.Read))
                    {
                        using (Image img = Image.FromStream(stream: fs,
                                                            useEmbeddedColorManagement: false,
                                                            validateImageData: false))
                        {
                            float width  = img.PhysicalDimension.Width;
                            float height = img.PhysicalDimension.Height;
                            //float hresolution = img.HorizontalResolution;
                            //float vresolution = img.VerticalResolution;
                            dbObj.Width  = (int)width;
                            dbObj.Height = (int)height;
                        }
                        fs.Close();
                    }
                    db.Files.Add(file);
                    db.Images.Add(dbObj);
                    db.SaveChanges();
                }
                return(Content(""));
            }
            return(Content("Error"));
        }
Пример #30
0
        public void ProcessRequest(HttpContext context)
        {
            HttpRequestBase request = new HttpRequestWrapper(context.Request);      // Wrap the request into a HttpRequestBase type
            context.Response.ContentType = "application/json; charset=utf-8";

            // Important note: we reference the .NET 4.0 assembly here, 
            // not the .NET 4.5 version! If you use the NuGet package, make sure
            // to set the correct reference
            FileUploadHandler handler = new FileUploadHandler(request, null);       // Get an instance of the handler class
            handler.IncomingRequestStarted += handler_IncomingRequestStarted;       // Register event handler for demo purposes

            var jsonResult = (JsonResult)handler.HandleRequest();                   // Call the handler method
            JQueryFileUpload result = (JQueryFileUpload)jsonResult.Data;            // JsonResult.Data is of type object and must be casted 

            context.Response.Write(JsonConvert.SerializeObject(result));            // Serialize the JQueryFileUpload object to a Json string
        }
Пример #31
0
        private async Task <JQueryFileUpload> HandleRequest()
        {
            var request = new HttpRequestWrapper(HttpContext.Current.Request);
            FileUploadHandler handler = new FileUploadHandler(request, null);       // Get an instance of the handler class

            handler.IncomingRequestStarted += handler_IncomingRequestStarted;       // Register event handler for demo purposes

            var task = handler.HandleRequestAsync();                                // Call the asyncronous handler method
            // Do other stuff here
            var jsonResult = (JsonResult)await task;                                // Awaits the result, but does not block the thread

            //var jsonResult = (JsonResult)await handler.HandleRequestAsync();      // Both methods above can be combined

            return((JQueryFileUpload)jsonResult.Data);                               // JsonResult.Data is of type object and must be casted
            // to your plugins handler class
        }
Пример #32
0
        public void ProcessRequest(HttpContext context)
        {
            HttpRequestBase request = new HttpRequestWrapper(context.Request);      // Wrap the request into a HttpRequestBase type

            context.Response.ContentType = "application/json; charset=utf-8";

            // Important note: we reference the .NET 4.0 assembly here,
            // not the .NET 4.5 version! If you use the NuGet package, make sure
            // to set the correct reference
            FileUploadHandler handler = new FileUploadHandler(request, null);       // Get an instance of the handler class

            handler.IncomingRequestStarted += handler_IncomingRequestStarted;       // Register event handler for demo purposes

            var jsonResult          = (JsonResult)handler.HandleRequest();          // Call the handler method
            JQueryFileUpload result = (JQueryFileUpload)jsonResult.Data;            // JsonResult.Data is of type object and must be casted

            context.Response.Write(JsonConvert.SerializeObject(result));            // Serialize the JQueryFileUpload object to a Json string
        }
Пример #33
0
        public async Task <IActionResult> AddPatientDocuments([FromRoute] long patientid, List <IFormFile> models)
        {
            IList <string>          filepaths = new List <string>();
            IList <PatientDocument> docs      = new List <PatientDocument>();

            foreach (IFormFile f in models)
            {
                string storePath = patientid.ToString() + "_" + f.Name;
                string docFolder = Path.Combine("PatientDocuments", storePath);

                try
                {
                    if (f == null || f.Length == 0)
                    {
                        return(Content("File not selected"));
                    }

                    string path = FileUploadHandler.GetFilePathForUpload(docFolder, f.FileName);

                    using (FileStream stream = new FileStream(path, FileMode.Create))
                    {
                        await f.CopyToAsync(stream);
                    }
                }
                catch (Exception e)
                {
                    return(Json(new { result = "Upload Failed", error = e.Message }));
                }

                string filePath = FileUploadHandler.FileReturnPath(docFolder, f.FileName);

                PatientDocument doc = new PatientDocument
                {
                    PatientId    = patientid,
                    FilePath     = filePath,
                    DocumentName = f.FileName
                };
                docs.Add(doc);
                filepaths.Add(filePath);
            }

            doc_repo.AddRange(docs);
            return(Json(new { FilePaths = filepaths, PatientID = patientid }));
        }
Пример #34
0
        public IActionResult AddUserPhotoById([FromRoute] long userid, IFormFile file)
        {
            User mod = _repo.Find(userid);

            if (mod == null)
            {
                return(NotFound("Incorrect UserId"));
            }

            string userPath  = userid.ToString() + "_Photo_" + file.FileName;
            string docFolder = Path.Combine("EmployeesImages", userPath);

            try
            {
                if (file == null || file.Length == 0)
                {
                    return(Content("File Not Selected"));
                }

                string path = FileUploadHandler.GetFilePathForUpload(docFolder, file.FileName);

                using (FileStream stream = new FileStream(path, FileMode.Create))
                {
                    file.CopyTo(stream);
                }
            }
            catch (Exception e)
            {
                return(Json(new { result = "upload Failed", error = e.Message }));
            }

            string filePath = FileUploadHandler.FileReturnPath(docFolder, file.FileName);


            mod.UserPhoto = new UserPhoto {
                FilePath = filePath, UserId = userid
            };
            _repo.Update(mod);

            return(new OkObjectResult(new { UserPhotoID = mod.UserPhotoId }));
        }
Пример #35
0
        public void TargetPhysicalFolder()
        {
            // arrange
            var handler = new FileUploadHandler
                {
                    TargetPhysicalFolder = @"D:\temp\"
                };

            Mock.Arrange(() => Directory.Exists(@"D:\temp\")).Returns(false);

            var called = false;
            Mock.Arrange(() => Directory.CreateDirectory(@"D:\temp\")).DoInstead(() => called = true);

            // act
            var result = handler.TargetPhysicalFolder;

            // assert
            Assert.AreEqual(@"D:\temp\", result);
            Assert.IsTrue(called);

            // arrange
            called = false;
            handler.TargetPhysicalFolder = " ";

            // act
            result = handler.TargetPhysicalFolder;

            // assert
            Assert.IsFalse(called);

            // arrange
            Mock.Arrange(() => Directory.Exists(@"D:\temp\")).Returns(true);
            handler.TargetPhysicalFolder = @"D:\temp\";

            // act
            result = handler.TargetPhysicalFolder;

            // assert
            Assert.IsFalse(called);
        }
Пример #36
0
        public async Task <ActionResult> UploadStockImage(IFormFile file, long OutletStockId)
        {
            // full path to file in temp location
            var stockObj = Repo.GetStockItemById(OutletStockId);

            if (stockObj == null)
            {
                return(new NotFoundResult());
            }

            var    filePath  = "";
            string storePath = "Store_" + stockObj.StoreVisit.StoreId;
            string docFolder = Path.Combine("StoreImages", storePath, "Stock");

            try
            {
                if (file == null || file.Length == 0)
                {
                    return(Content("file not selected"));
                }

                var path = FileUploadHandler.GetFilePathForUpload(docFolder, file.FileName);

                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
            }
            catch (Exception e)
            {
                return(Json(new { result = "upload Failed", error = e.Message }));
            }

            filePath = FileUploadHandler.FileReturnPath(docFolder, file.FileName);

            stockObj.ImageUrl = filePath;
            Repo.UpdateStock(stockObj);

            return(Json(new { filepath = filePath, OutletStockId = OutletStockId }));
        }
Пример #37
0
        private BulkFileUploadModel SetupBulkUpload(out FileUploadResult fileUploadResult)
        {
            const string filename = "test.xml";

            var file = new Mock <IFormFile>();

            file.Setup(x => x.Length).Returns(200);
            file.Setup(x => x.FileName).Returns("test.xml");

            var model = new BulkFileUploadModel
            {
                BulkFileType = InterchangeFileType.AssessmentMetadata.Value,
                BulkFiles    = new List <IFormFile>
                {
                    file.Object
                }
            };

            fileUploadResult = new FileUploadResult
            {
                Directory = "directoryPath",
                FileNames = new[] { filename }
            };

            InstanceContext.Id   = OdsInstanceContext.Id;
            InstanceContext.Name = OdsInstanceContext.Name;

            FileUploadHandler.Setup(x =>
                                    x.SaveFilesToUploadDirectory(It.IsAny <IFormFile[]>(), It.IsAny <Func <string, string> >(), WebHostingEnvironment.Object))
            .Returns(fileUploadResult);

            ApiConnectionInformationProvider
            .Setup(x => x.GetConnectionInformationForEnvironment())
            .ReturnsAsync(_connectionInformation);

            OdsSecretConfigurationProvider.Setup(x => x.GetSecretConfiguration(It.IsAny <int>()))
            .Returns(Task.FromResult(OdsSecretConfig));
            return(model);
        }
        private OdsInstanceSettingsModel SetupBulkUpload(out FileUploadResult fileUploadResult)
        {
            const string filename = "test.xml";
            var          file     = new Mock <HttpPostedFileBase>();

            file.Setup(x => x.ContentLength).Returns(200);
            file.Setup(x => x.FileName).Returns("test.xml");
            var model = new OdsInstanceSettingsModel
            {
                BulkFileUploadModel = new BulkFileUploadModel
                {
                    BulkFiles = new List <HttpPostedFileBase>
                    {
                        file.Object
                    }
                }
            };

            fileUploadResult = new FileUploadResult
            {
                Directory = "directoryPath",
                FileNames = new[] { filename }
            };

            InstanceContext.Id   = OdsInstanceContext.Id;
            InstanceContext.Name = OdsInstanceContext.Name;

            FileUploadHandler.Setup(x =>
                                    x.SaveFilesToUploadDirectory(It.IsAny <HttpPostedFileBase[]>(), It.IsAny <Func <string, string> >()))
            .Returns(fileUploadResult);

            ApiConnectionInformationProvider
            .Setup(x => x.GetConnectionInformationForEnvironment(CloudOdsEnvironment.Production))
            .ReturnsAsync(_connectionInformation);

            OdsSecretConfigurationProvider.Setup(x => x.GetSecretConfiguration(It.IsAny <int>()))
            .Returns(Task.FromResult(OdsSecretConfig));
            return(model);
        }
Пример #39
0
        public async Task <ActionResult> UploadUserImage(IFormFile file, long id)
        {
            // full path to file in temp location
            var    filePath  = "";
            string storePath = "User_" + id.ToString();
            string docFolder = Path.Combine("ProfileImages", storePath);

            try
            {
                if (file == null || file.Length == 0)
                {
                    return(Content("file not selected"));
                }

                var path = FileUploadHandler.GetFilePathForUpload(docFolder, file.FileName);

                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
            }
            catch (Exception e)
            {
                return(Json(new { result = "upload Failed", error = e.Message }));
            }


            filePath = FileUploadHandler.FileReturnPath(docFolder, file.FileName);

            var user = _repo.Find(id);

            if (user != null)
            {
                user.PhotoFilePath = filePath;
                _repo.Update(user);
            }
            return(Json(new { filepath = filePath, userid = id }));
        }
Пример #40
0
        public void SaveChunkDataTest()
        {
            // arrange
            var handler = new FileUploadHandler();

            int x;
            Mock.Arrange(() => new RadUploadHandler().SaveChunkData(string.Empty, 0, Arg.IsAny<byte[]>(), 0, out x)).IgnoreInstance().DoInstead(() =>
                {
                    Mock.Arrange(() => handler.IsFinalFileRequest()).Returns(true);
                    Mock.Arrange(() => handler.GetQueryParameter((Constants.ReplaceReportConnectionStrings))).Returns("true");
                }).Returns(true);

            var called = false;
            Mock.Arrange(() => ReportUploadHelper.ReplaceReportConnectionStrings(Arg.AnyString)).DoInstead(() => called = true);

            // act
            var result = handler.SaveChunkData(string.Empty, 0, new byte[0], 0, out x);

            // assert
            Assert.IsTrue(result);
            Assert.IsTrue(called);
        }