コード例 #1
0
        public FileUploadResult ProcessUpload(HttpContext context)
        {
            if (!WebItemSecurity.IsAvailableForUser(ProductEntryPoint.ID.ToString(), SecurityContext.CurrentAccount.ID))
                throw CRMSecurity.CreateSecurityException();

            var fileUploadResult = new FileUploadResult();

            if (!FileToUpload.HasFilesToUpload(context)) return fileUploadResult;

            var file = new FileToUpload(context);

            String assignedPath;

            Global.GetStore().SaveTemp("temp", out assignedPath, file.InputStream);

            file.InputStream.Position = 0;

            var jObject = ImportFromCSV.GetInfo(file.InputStream, context.Request["importSettings"]);

            jObject.Add("assignedPath", assignedPath);

            fileUploadResult.Success = true;
            fileUploadResult.Data = Global.EncodeTo64(jObject.ToString());

            return fileUploadResult;
        }
コード例 #2
0
        public HttpResponseMessage AddImage([FromBody] FileToUpload img)
        {
            HttpResponseMessage response;

            response = employeeService.AddImage(img);
            return(response);
        }
コード例 #3
0
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            // Object Container: Use objectContainer.Get<T>() to retrieve objects from the scope
            var objectContainer = context.GetFromContext <IObjectContainer>(BitbucketAPIScope.ParentContainerPropertyTag);
            var client          = objectContainer.Get <FluentClient>();

            // Inputs
            var repositoryLocation   = RepositoryLocation.Get(context);
            var fileToUpload         = FileToUpload.Get(context);
            var commitMessage        = CommitMessage.Get(context);
            var repositoryUUIDOrSlug = RepositoryUUIDOrSlug.Get(context);
            var workspaceUUIDOrSlug  = WorkspaceUUIDOrSlug.Get(context);
            var branchName           = BranchName.Get(context);

            // Validate whether Workspace UUID or Name provided (assume name will never be a GUID format)
            if (Validation.IsUUID(workspaceUUIDOrSlug))
            {
                HttpUtility.UrlEncode(workspaceUUIDOrSlug);
            }

            // Validate whether Repository UUID or Slug provided (assume slug will never be a GUID format)
            if (Validation.IsUUID(repositoryUUIDOrSlug))
            {
                HttpUtility.UrlEncode(repositoryUUIDOrSlug);
            }

            // Create standard request URI
            var uri = "repositories/" + workspaceUUIDOrSlug + "/" + repositoryUUIDOrSlug + "/src";

            // Initialise and populate multipart content
            var multipartContent = new MultipartFormDataContent();

            multipartContent.Add(new ByteArrayContent(File.ReadAllBytes(fileToUpload)), repositoryLocation, Path.GetFileName(fileToUpload));
            multipartContent.Add(new StringContent(commitMessage), "message");

            // Check if optional branch name parameter provided. Add to request if not null.
            if (branchName != null)
            {
                multipartContent.Add(new StringContent(branchName), "branch");
            }

            // Execution Logic
            var response         = new JObject();
            var exceptionHandler = new ApiExceptionHandler();

            try
            {
                response = await AsyncRequests.PostRequest_WithBody(client, uri, cancellationToken, multipartContent);
            }
            catch (ApiException ex) // Catches any API exception and returns the message
            {
                await exceptionHandler.ParseExceptionAsync(ex);
            }

            // Outputs - API response as JObject
            return((ctx) =>
            {
                JsonResult.Set(ctx, response);
            });
        }
コード例 #4
0
        public void GetFile(string Login, FileToUpload File, string Name)
        {
            //Формирование полного пути
            string mainPath = Request.MapPath("..//data//" + Login);
            string fullPath = "";

            switch (File)
            {
            case FileToUpload.Backup:
                fullPath = mainPath + "\\Backups\\" + Name;
                break;

            case FileToUpload.Database:
                fullPath = mainPath + "\\" + Name;
                break;

            case FileToUpload.Document:
                fullPath = mainPath + "\\Documents\\" + Name;
                break;

            case FileToUpload.Photo:
                fullPath = mainPath + "\\Photos\\" + Name;
                break;

            case FileToUpload.Settings:
                fullPath = mainPath + "\\" + Name;
                break;
            }
            Response.WriteFile(fullPath);
        }
コード例 #5
0
        public override FileUploadResult ProcessUpload(HttpContext context)
        {
            if (!SecurityContext.IsAuthenticated)
            {
                throw new HttpException(403, "Access denied.");
            }

            var result = new FileUploadResult {
                Success = false
            };

            try
            {
                if (FileToUpload.HasFilesToUpload(context))
                {
                    var file        = new FileToUpload(context);
                    var maxFileSize = MaxFileSizeInMegabytes * 1024 * 1024;

                    if (string.IsNullOrEmpty(file.FileName))
                    {
                        throw new ArgumentException("Empty file name");
                    }

                    if (maxFileSize < file.ContentLength)
                    {
                        throw new Exception(CalendarJSResource.calendarEventAttachments_fileSizeError);
                    }

                    var fileName = System.IO.Path.GetFileName(file.FileName);

                    var document = new File
                    {
                        Title           = fileName,
                        FolderID        = AttachmentEngine.GetTmpFolderId(),
                        ContentLength   = file.ContentLength,
                        ThumbnailStatus = Thumbnail.NotRequired
                    };

                    document = AttachmentEngine.SaveFile(document, file.InputStream);

                    result.Data = new
                    {
                        id          = document.ID.ToString(),
                        title       = document.Title,
                        size        = document.ContentLength,
                        contentType = file.FileContentType,
                        fileUrl     = FileShareLink.GetLink(document) + "&tmp=true"
                    };

                    result.Success = true;
                }
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = ex.Message;
            }

            return(result);
        }
コード例 #6
0
        public IActionResult Post([FromBody] FileToUpload theFile)
        {
            string webRootPath  = _hostEnvironment.WebRootPath;
            var    FILE_PATH    = Path.Combine(webRootPath, @"UploadedFiles\");
            var    filePathName = FILE_PATH + theFile.UpdatedFileName + "_" +
                                  Path.GetFileNameWithoutExtension(theFile.FileName) +
                                  Path.GetExtension(theFile.FileName);

            // Remove file type from base64 encoding, if any
            if (theFile.FileAsBase64.Contains(","))
            {
                theFile.FileAsBase64 = theFile.FileAsBase64
                                       .Substring(theFile.FileAsBase64.IndexOf(",") + 1);
            }

            // Convert base64 encoded string to binary
            theFile.FileAsByteArray = Convert.FromBase64String(theFile.FileAsBase64);

            //convert bytes to memory stream
            //var contents = new StreamContent(new MemoryStream(theFile.FileAsByteArray));
            Stream stream = new MemoryStream(theFile.FileAsByteArray);

            string resFileName = Path.GetFileName(theFile.FileName);

            // Upload file to blob storage
            //AzureStorage.UploadFileAsync(ContainerType.incentiveappfiles, resFileName, stream);

            // Write binary file to server path
            using (var fs = new FileStream(filePathName, FileMode.Create))
            {
                fs.Write(theFile.FileAsByteArray, 0, theFile.FileAsByteArray.Length);
            }

            return(Ok());
        }
コード例 #7
0
        public Int32 UploadFile(FileToUpload file)
        {
            try
            {
                string newPath = Path.Combine(filePath, file.FolderName);
                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }
                string fullPath = Path.Combine(newPath, file.FileName);
                file.FileAsByteArray = Convert.FromBase64String(file.FileAsBase64);

                using (var fs = new FileStream(fullPath, FileMode.Create))
                {
                    fs.Write(file.FileAsByteArray, 0, file.FileAsByteArray.Length);
                }

                dtoMailAttachment dtoA = new dtoMailAttachment();
                dtoA.Attachment = file.FileName;
                dtoA.MailId     = Convert.ToInt32(file.FolderName);
                return(mailAttachmentService.SaveAttachment(dtoA));
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
コード例 #8
0
    public IActionResult Post([FromBody] FileToUpload theFile)
    {
        //Create the full path and file name to store the uploaded file into. Use the FILE_PATH constant, followed by the FileName property, without the
        // file extension, from the file object uploaded. To provide some uniqueness to the file name, add on the current date and time. Remove any characters that aren’t valid
        // for a file by using the Replace() method. Finish the file name by adding on the file extension from the file object uploaded.
        var filePathName = FILE_PATH +
                           Path.GetFileNameWithoutExtension(theFile.FileName) + "-" + DateTime.Now.ToString().Replace("/", "")
                           .Replace(":", "").Replace(" ", "") +
                           Path.GetExtension(theFile.FileName);


        //Write the following code to strip off the file type.
        if (theFile.FileAsBase64.Contains(","))
        {
            theFile.FileAsBase64 = theFile.FileAsBase64
                                   .Substring(theFile.FileAsBase64
                                              .IndexOf(",") + 1);
        }

        // Don’t store the file uploaded as a Base64-encoded string. You want the file to be useable on the server just like it was on the user’s hard drive.
        //Convert the file data into a byte array using the FromBase64String() method on the .NET Convert class.
        // Store the results of calling this method in to the FileAsByteArray property on the FileToUpload object.
        theFile.FileAsByteArray = Convert.FromBase64String(theFile.FileAsBase64);

        // Write to a File.
        //You’re finally ready to write the file to disk on your server. Create a new FileStream object and pass the byte array to the Write() method of this method.
        using (var fs = new FileStream(
                   filePathName, FileMode.CreateNew)) {
            fs.Write(theFile.FileAsByteArray, 0,
                     theFile.FileAsByteArray.Length);
        }

        return(Ok());
    }
コード例 #9
0
        public FileUploadResult ProcessUpload(HttpContext context)
        {
            var fileUploadResult = new FileUploadResult();

            if (!FileToUpload.HasFilesToUpload(context))
            {
                return(fileUploadResult);
            }

            var file = new FileToUpload(context);

            String assignedPath;

            Global.GetStore().SaveTemp("temp", out assignedPath, file.InputStream);

            file.InputStream.Position = 0;

            var jObject = ImportFromCSV.GetInfo(file.InputStream, context.Request["importSettings"]);

            jObject.Add("assignedPath", assignedPath);

            fileUploadResult.Success = true;
            fileUploadResult.Data    = Global.EncodeTo64(jObject.ToString());

            return(fileUploadResult);
        }
コード例 #10
0
        public IActionResult Add([FromForm] FileToUpload fileToUpload, int carId)
        {
            var result = _carImageService.Add(carId, DateTime.Now, fileToUpload.file);

            if (result.Success)
            {
                return(Ok(result));
            }
            return(BadRequest(result));
        }
コード例 #11
0
ファイル: FileInfoData.cs プロジェクト: Damian109/NIRSManager
 public FileInfoData(string name, string path, bool isChanged, DateTime date, FileToUpload fileType, bool isUp, bool isDown)
 {
     NameFile   = name;
     PathFile   = path;
     IsChanged  = isChanged;
     DateChange = date;
     FileType   = fileType;
     IsUpload   = isUp;
     IsDownload = isDown;
 }
コード例 #12
0
        public static async Task <FileObjectResponse> UploadFileAsync(SlackClient slackClient, string channelName)
        {
            await using var fileStream = File.Open("./appsettings.json", FileMode.Open);
            var fileMessage = new FileToUpload
            {
                ChannelNamesOrIds = channelName,
                Stream            = fileStream,
                Comment           = $"{nameof(UploadFileAsync)} method"
            };

            return(await slackClient.Files.UploadFileAsync(fileMessage));
        }
コード例 #13
0
 public IActionResult Upload(FileToUpload theFile)
 {
     try
     {
         _contexto.AdicionarFile(theFile);
         return(Created("api/FileToUpload", theFile));
     }
     catch (Exception ex)
     {
         return(BadRequest($"Erro: {ex.ToString()}"));
     }
 }
コード例 #14
0
        public FileUploadResult ProcessUpload(HttpContext context)
        {
            if (!CRMSecurity.IsAdmin)
            {
                throw CRMSecurity.CreateSecurityException();
            }

            var fileUploadResult = new FileUploadResult();

            if (!FileToUpload.HasFilesToUpload(context))
            {
                return(fileUploadResult);
            }

            var file = new FileToUpload(context);

            if (String.IsNullOrEmpty(file.FileName) || file.ContentLength == 0)
            {
                throw new InvalidOperationException(CRMErrorsResource.InvalidFile);
            }

            if (0 < SetupInfo.MaxImageUploadSize && SetupInfo.MaxImageUploadSize < file.ContentLength)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = FileSizeComment.GetFileImageSizeNote(CRMCommonResource.ErrorMessage_UploadFileSize, false).HtmlEncode();
                return(fileUploadResult);
            }

            if (FileUtility.GetFileTypeByFileName(file.FileName) != FileType.Image)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = CRMJSResource.ErrorMessage_NotImageSupportFormat.HtmlEncode();
                return(fileUploadResult);
            }

            try
            {
                var imageData   = Global.ToByteArray(file.InputStream);
                var imageFormat = ContactPhotoManager.CheckImgFormat(imageData);
                var photoUri    = OrganisationLogoManager.UploadLogo(imageData, imageFormat);

                fileUploadResult.Success = true;
                fileUploadResult.Data    = photoUri;
                return(fileUploadResult);
            }
            catch (Exception exception)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = exception.Message.HtmlEncode();
                return(fileUploadResult);
            }
        }
コード例 #15
0
        public FusFile UploadFile(Guid uploaderId, FileToUpload fileToUpload)
        {
            //TODO: Need to implement abstraction to get specyfic uploader for uploaderId - now there is no db
            var file = new FileInfo(fileToUpload.FileName);

            File.WriteAllBytes(@"d:\UploadTest\" + file.Name, Convert.FromBase64String(fileToUpload.FileContentBase64));
            return(new FusFile()
            {
                Id = Guid.NewGuid(),
                UploaderId = uploaderId,
                FileName = file.Name
            });
        }
コード例 #16
0
        public async Task <IActionResult> Update([FromForm] FileToUpload fileToUpload, [FromForm] CarImage carImage)
        {
            try
            {
                if (fileToUpload.file.Length > 0)
                {
                    string formerFileName    = carImage.ImagePath;
                    string uploadingFileName = fileToUpload.file.FileName;
                    string imagePath         = _webHostEnvironment.WebRootPath + "\\uploads\\carimages\\";

                    System.IO.FileInfo fileInfo      = new System.IO.FileInfo(uploadingFileName);
                    string             fileExtension = fileInfo.Extension;

                    DateTime currentDate      = DateTime.Now;
                    String   carImageFileName = Guid.NewGuid().ToString("N") + "_" +
                                                String.Format("Number {0, 0:D2}", currentDate.Year) +
                                                String.Format("Number {0, 0:D2}", currentDate.Month) +
                                                String.Format("Number {0, 0:D2}", currentDate.Day) +
                                                String.Format("Number {0, 0:D2}", currentDate.Hour) +
                                                String.Format("Number {0, 0:D2}", currentDate.Minute) +
                                                String.Format("Number {0, 0:D2}", currentDate.Second) + fileExtension;

                    using (FileStream fileStream = System.IO.File.Create(imagePath + carImageFileName))
                    {
                        await fileToUpload.file.CopyToAsync(fileStream);

                        imagePath += carImageFileName;

                        fileStream.Flush();
                    }

                    carImage.ImagePath = imagePath;
                    carImage.Date      = currentDate;

                    var result = _carImageService.Update(carImage, formerFileName);
                    if (result.Success)
                    {
                        return(Ok(result));
                    }
                    return(BadRequest(result));
                }
                else
                {
                    return(BadRequest("Cannot uploaded"));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
コード例 #17
0
        public override FileUploadResult ProcessUpload(HttpContext context)
        {
            var fileUploadResult = new FileUploadResult();

            if (!FileToUpload.HasFilesToUpload(context))
            {
                return(fileUploadResult);
            }

            var file = new FileToUpload(context);

            if (String.IsNullOrEmpty(file.FileName) || file.ContentLength == 0)
            {
                throw new InvalidOperationException(CRMErrorsResource.InvalidFile);
            }

            if (0 < SetupInfo.MaxUploadSize && SetupInfo.MaxUploadSize < file.ContentLength)
            {
                throw FileSizeComment.FileSizeException;
            }

            if (CallContext.GetData("CURRENT_ACCOUNT") == null)
            {
                CallContext.SetData("CURRENT_ACCOUNT", new Guid(context.Request["UserID"]));
            }


            var fileName = file.FileName.LastIndexOf('\\') != -1
                               ? file.FileName.Substring(file.FileName.LastIndexOf('\\') + 1)
                               : file.FileName;

            var document = new File
            {
                Title         = fileName,
                FolderID      = Global.DaoFactory.GetFileDao().GetRoot(),
                ContentLength = file.ContentLength
            };

            document = Global.DaoFactory.GetFileDao().SaveFile(document, file.InputStream);

            fileUploadResult.Data     = document.ID;
            fileUploadResult.FileName = document.Title;
            fileUploadResult.FileURL  = document.FileDownloadUrl;


            fileUploadResult.Success = true;


            return(fileUploadResult);
        }
コード例 #18
0
        public MainViewModel()
        {
            string exFilename = Logger.ExceptionLogFilename;

            _backupFolderPath = ServiceProvider.TempBackupDir;
            Task.Run(() => DeleteYesterdaysFiles(_backupFolderPath, DateTime.Now.AddDays(-1)));
            BackupCommand                 = new[] { IsProcessing, HasExceptionOccuredWhileBackingup }.CombineLatest(M => !M[0] && !M[1]).ToReactiveCommand().WithSubscribe(StartDatabaseBackup);
            SetBackupIntervalCommand      = new[] { IsProcessing }.CombineLatest(M => !M[0]).ToReactiveCommand <string>().WithSubscribe(SetBackupInervals);
            RemoveConnectionStringCommand = new[] { IsProcessing }.CombineLatest(M => !M[0]).ToReactiveCommand <CString>().WithSubscribe(RemoveConnectionString);
            AddConnectionStringCommand    = new[] { IsProcessing }.CombineLatest(M => !M[0]).ToReactiveCommand <string>().WithSubscribe(AddConnectionString);
            CleanUpLocalAndGDriveCommand  = new[] { IsProcessing }.CombineLatest(M => !M[0]).ToReactiveCommand().WithSubscribe(() => Last5DeleteFilesTimer(false));
            CStringsDBToBackup            = CString.AddInit(true);
            _fileAppAttributes.Add("UpId", "");
            Task.Run(() => LastUploadedFiles = FileToUpload.GetFileToUploadListFromSettings());
            Task.Run(() => Last5DeleteFilesTimer(null));
        }
コード例 #19
0
        public override FileUploadResult ProcessUpload(HttpContext context)
        {
            var fileUploadResult = new FileUploadResult();

            if (!FileToUpload.HasFilesToUpload(context))
            {
                return(fileUploadResult);
            }

            var file = new FileToUpload(context);

            if (String.IsNullOrEmpty(file.FileName) || file.ContentLength == 0)
            {
                throw new InvalidOperationException(CRMErrorsResource.InvalidFile);
            }

            if (0 < SetupInfo.MaxUploadSize && SetupInfo.MaxUploadSize < file.ContentLength)
            {
                throw FileSizeComment.FileSizeException;
            }

            var fileName = file.FileName.LastIndexOf('\\') != -1
                ? file.FileName.Substring(file.FileName.LastIndexOf('\\') + 1)
                : file.FileName;

            using (var scope = DIHelper.Resolve())
            {
                var daoFactory = scope.Resolve <DaoFactory>();
                var document   = new File
                {
                    Title           = fileName,
                    FolderID        = daoFactory.FileDao.GetRoot(),
                    ContentLength   = file.ContentLength,
                    ThumbnailStatus = Thumbnail.NotRequired,
                };

                document = daoFactory.FileDao.SaveFile(document, file.InputStream);

                fileUploadResult.Data     = document.ID;
                fileUploadResult.FileName = document.Title;
                fileUploadResult.FileURL  = document.DownloadUrl;
                fileUploadResult.Success  = true;


                return(fileUploadResult);
            }
        }
コード例 #20
0
        public IActionResult UploadFiles([FromBody] FileToUpload theFile)
        {
            var filePathName = FILE_PATH + Path.GetFileNameWithoutExtension(theFile.FileName) + "-" +
                               DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "") +
                               Path.GetExtension(theFile.FileName);

            if (theFile.FileAsBase64.Contains(","))
            {
                theFile.FileAsBase64 = theFile.FileAsBase64.Substring(theFile.FileAsBase64.IndexOf(",") + 1);
            }
            theFile.FileAsByteArray = Convert.FromBase64String(theFile.FileAsBase64);
            using (var fs = new FileStream(filePathName, FileMode.CreateNew))
            {
                fs.Write(theFile.FileAsByteArray, 0, theFile.FileAsByteArray.Length);
            }
            return(Ok());
        }
コード例 #21
0
        /// <summary>
        /// Lets user select images to upload and validates selected items
        /// </summary>
        private void OnSelectImages()
        {
            string[] files = DialogManager.ShowOpenMultiselectDialog();
            if (files == null)
            {
                return;
            }

            foreach (string file in files)
            {
                string   fileName = Path.GetFileName(file);
                FileInfo fi       = new FileInfo(file);

                // check for duplicates
                if (this.ImagesToUpload.Any(x => x.Name.Equals(fileName)))
                {
                    DialogManager.ShowErrorDialog("Found duplicate image name - " + fileName +
                                                  ". Uploaded images should have unique names!");
                    continue;
                }

                // get size in kb
                long sizeInKb = fi.Length / 1024;

                if (sizeInKb >= this.maxNoWarningUploadSizeKb)
                {
                    bool uploadAnyway = DialogManager.ShowConfirmDialog(
                        string.Format(
                            "Are You sure You want to select image \"{0}\" that is {1}KB in size? This image seems to be too large for a logo and will burn your Cloud Storage traffic.",
                            fileName,
                            sizeInKb)
                        );

                    // user said no, skip to next item
                    if (!uploadAnyway)
                    {
                        continue;
                    }
                }

                var item = new FileToUpload(fileName, file, sizeInKb);
                this.ImagesToUpload.Add(item);
            }
        }
コード例 #22
0
ファイル: TableListPage.cs プロジェクト: Dariusz86/Bench
        public void FillFormWithTestData()
        {
            string name     = "Dariusz";
            string lastName = "Szudrzyński";

            Console.WriteLine("Filling form with name: " + name);
            NameTexEdit.SendKeys("Dariusz");
            Console.WriteLine("Filling for with lastname: " + lastName);
            LastNameTexEdit.SendKeys("Szudrzynski");

            ActiveInvestmentsTotalNumber.SendKeys("10");
            ActiveInvestmentsTotalAmount.SendKeys("200");
            ActiveInvestmentMaxValue.SendKeys("75");

            FileToUpload.Click();
            FileToUpload.SendKeys("C:\\Users\\e-dzsi\\Desktop\\Example123.csv");

            SubmitButton.Click();
        }
コード例 #23
0
        public async Task <IActionResult> PostFile(FileToUpload file, Guid idFilm)
        {
            await Task.Yield();

            try
            {
                if (((file.files.Length / 1024f) / 1024f) > 100)
                {
                    return(BadRequest("Error in file upload. File can't be greater than 100 mb corrupt or invalid"));
                }
                else if (file.files.Length != 0)
                {
                    if (!Directory.Exists(environment.WebRootPath + "\\UploadedFiles\\"))
                    {
                        Directory.CreateDirectory(environment.WebRootPath + "\\UploadedFiles\\");
                    }
                    using (FileStream fileStream = System.IO.File.Create(environment.WebRootPath + "\\UploadedFiles\\" + file.files.FileName))
                    {
                        file.files.CopyTo(fileStream);
                        fileStream.Flush();

                        FilmFile newFilmFile = new FilmFile()
                        {
                            Id         = Guid.NewGuid(),
                            Name       = file.files.FileName,
                            UploadDate = DateTime.Now,
                            Size       = ((file.files.Length / 1024f) / 1024f),
                        };
                        var createdFile = await filmFileLogic.CreateAsync(idFilm, newFilmFile).ConfigureAwait(false);

                        return(Ok(createdFile));
                    }
                }
                else
                {
                    return(BadRequest("Error in file upload. File was corrupt or invalid"));
                }
            }
            catch (Exception)
            {
                return(BadRequest("Error in file upload. File was corrupt or invalid"));
            }
        }
コード例 #24
0
        public BoolMessage SaveUploadedFile(FileToUpload file)
        {
            var filePath = System.Web.HttpRuntime.AppDomainAppPath.ToString() + file.FileName;
            var dir      = Path.GetDirectoryName(filePath);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            FileStream f = new FileStream(filePath, FileMode.Create);

            try
            {
                BinaryWriter writer = new BinaryWriter(f);
                BinaryReader reader = new BinaryReader(file.FileContent);
                byte[]       buffer;
                do
                {
                    buffer = reader.ReadBytes(20480);
                    writer.Write(buffer);
                } while (buffer.Length > 0);
                return(new BoolMessage {
                    Flag = true
                });
            }
            catch
            {
                return(new BoolMessage {
                    Flag = false
                });
            }
            finally
            {
                f.Close();
                file.FileContent.Close();
            }
        }
コード例 #25
0
        public IHttpActionResult Post([FromBody] FileToUpload file)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }


                if (file.FileAsBase64.Contains(","))
                {
                    file.FileAsBase64 = file.FileAsBase64
                                        .Substring(file.FileAsBase64
                                                   .IndexOf(",") + 1);
                }

                return(Ok(fileUploadService.UploadFile(file)));
            }
            catch (Exception ex)
            {
                return(InternalServerError(new Exception(ex.Message)));
            }
        }
コード例 #26
0
        public FileUploadResult ProcessUpload(HttpContext context)
        {
            var fileUploadResult = new FileUploadResult();

            if (!FileToUpload.HasFilesToUpload(context))
            {
                return(fileUploadResult);
            }

            var file = new FileToUpload(context);

            if (String.IsNullOrEmpty(file.FileName) || file.ContentLength == 0)
            {
                throw new InvalidOperationException(CRMErrorsResource.InvalidFile);
            }

            if (0 < SetupInfo.MaxImageUploadSize && SetupInfo.MaxImageUploadSize < file.ContentLength)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = FileSizeComment.GetFileImageSizeNote(CRMCommonResource.ErrorMessage_UploadFileSize, false).HtmlEncode();
                return(fileUploadResult);
            }

            if (FileUtility.GetFileTypeByFileName(file.FileName) != FileType.Image)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = CRMJSResource.ErrorMessage_NotImageSupportFormat.HtmlEncode();
                return(fileUploadResult);
            }

            var photoUri = OrganisationLogoManager.UploadLogo(file.InputStream, true);

            fileUploadResult.Success = true;
            fileUploadResult.Data    = photoUri;
            return(fileUploadResult);
        }
コード例 #27
0
        public FileUploadResult ProcessUpload(HttpContext context)
        {
            if (!WebItemSecurity.IsAvailableForUser(ProductEntryPoint.ID.ToString(), SecurityContext.CurrentAccount.ID))
            {
                throw CRMSecurity.CreateSecurityException();
            }

            var     contactId = Convert.ToInt32(context.Request["contactID"]);
            Contact contact   = null;

            if (contactId != 0)
            {
                contact = Global.DaoFactory.GetContactDao().GetByID(contactId);
                if (!CRMSecurity.CanAccessTo(contact))
                {
                    throw CRMSecurity.CreateSecurityException();
                }
            }

            var fileUploadResult = new FileUploadResult();

            if (!FileToUpload.HasFilesToUpload(context))
            {
                return(fileUploadResult);
            }

            var file = new FileToUpload(context);

            if (String.IsNullOrEmpty(file.FileName) || file.ContentLength == 0)
            {
                throw new InvalidOperationException(CRMErrorsResource.InvalidFile);
            }

            if (0 < SetupInfo.MaxImageUploadSize && SetupInfo.MaxImageUploadSize < file.ContentLength)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = FileSizeComment.GetFileImageSizeNote(CRMCommonResource.ErrorMessage_UploadFileSize, false).HtmlEncode();
                return(fileUploadResult);
            }

            if (FileUtility.GetFileTypeByFileName(file.FileName) != FileType.Image)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = CRMJSResource.ErrorMessage_NotImageSupportFormat.HtmlEncode();
                return(fileUploadResult);
            }

            var uploadOnly = Convert.ToBoolean(context.Request["uploadOnly"]);
            var tmpDirName = Convert.ToString(context.Request["tmpDirName"]);

            try
            {
                string photoUri;
                if (contactId != 0)
                {
                    photoUri = ContactPhotoManager.UploadPhoto(file.InputStream, contactId, uploadOnly);
                }
                else
                {
                    if (String.IsNullOrEmpty(tmpDirName))
                    {
                        tmpDirName = Guid.NewGuid().ToString();
                    }
                    photoUri = ContactPhotoManager.UploadPhoto(file.InputStream, tmpDirName);
                }

                fileUploadResult.Success = true;
                fileUploadResult.Data    = photoUri;
            }
            catch (Exception e)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = e.Message.HtmlEncode();
                return(fileUploadResult);
            }

            if (contact != null)
            {
                var messageAction = contact is Company ? MessageAction.CompanyUpdatedPhoto : MessageAction.PersonUpdatedPhoto;
                MessageService.Send(context.Request, messageAction, MessageTarget.Create(contact.ID), contact.GetTitle());
            }

            return(fileUploadResult);
        }
コード例 #28
0
        /// <summary>
        /// Асинхронный запрос на сервер, с целью получения необходимого файла
        /// </summary>
        /// <param name="fileExt">Тип файла</param>
        /// <param name="name">Название файла для сохранения</param>
        public static async Task <bool> GetFileFromServerAsync(FileToUpload fileExt, string name)
        {
            using (var client = new HttpClient())
            {
                //Формирование строки запроса
                string query = ProgramSettings.AdressServer + "Server/GetFile?";
                query += "Login="******"&";
                query += "File=";

                string dir = string.Empty;

                switch (fileExt)
                {
                case FileToUpload.Backup:
                    dir = "Backup";
                    break;

                case FileToUpload.Document:
                    dir = "Document";
                    break;

                case FileToUpload.Photo:
                    dir = "Photo";
                    break;

                case FileToUpload.Database:
                    dir = "Database";
                    break;

                case FileToUpload.Settings:
                    dir = "Settings";
                    break;
                }

                query += dir + "&Name=" + name;

                //Выполнение запроса
                HttpResponseMessage message = client.GetAsync(query).Result;

                if (!message.IsSuccessStatusCode)
                {
                    return(false);
                }

                //Сохранение файла
                string path = Environment.CurrentDirectory + "\\data\\" + _login;
                if (fileExt == FileToUpload.Settings || fileExt == FileToUpload.Database)
                {
                    path += "\\" + name;
                }
                else
                {
                    path += "\\" + dir + "s\\" + name;
                }

                FileInfo fileE = new FileInfo(path);
                if (fileE.Exists)
                {
                    fileE.Delete();
                }

                using (FileStream file = new FileStream(path, FileMode.Create))
                {
                    await message.Content.CopyToAsync(file);
                }

                //Изменение пути к БД
                if (fileExt == FileToUpload.Settings)
                {
                    try
                    {
                        FileSettings fileSettings = new FileSettings(_login, _md5);
                        fileSettings.Read();

                        string newPathDB = Environment.CurrentDirectory + "\\data\\" + _login + "\\database";
                        if (fileSettings.User.DBMSName == "MS SQL Express")
                        {
                            newPathDB += ".mdf";
                        }
                        else
                        {
                            newPathDB += ".db";
                        }
                        if (fileSettings.User.DBMSName == "SQLite")
                        {
                            fileSettings.User.ConnectionString = @"Data Source=" + newPathDB + ";pooling=false;";
                        }
                        fileSettings.Write();
                    }
                    catch (ErrorManager.NirsException e)
                    {
                        ErrorManager.ExecuteException(e);
                    }
                }
            }
            return(true);
        }
コード例 #29
0
        public void BackUpDatabase()
        {
            //while (IsDeletingLastHoursBackupFiles) {
            //    Thread.Sleep(1000);
            //    System.Windows.Forms.Application.DoEvents();
            //}
            HasExceptionOccuredWhileBackingup.Value = false;
            BackupUploadedSuccessfully.Value        = false;
            IsProcessing.Value = true;
            //LastBackupExceptionMsg.Value = "";
            CurrentGDriveUploadId      = DateTime.Now.ToString("dd-HH:mm:ss.fffff");
            _fileAppAttributes["UpId"] = CurrentGDriveUploadId;
            //LastUploadedFiles.Clear();
            string       currentTimeString = CurrentDTFileAppend;
            string       backupTaskLog1    = "Backing Up Databases Begins " + CurrentDateTimeString + "\n{0}\nBacking Up Databases Ends\n";
            string       backupTaskLog     = "Started\n{0}";
            FileToUpload ftu = null;

            foreach (CString cString in CStringsDBToBackup)
            {
                try
                {
                    SelectedCStringDBToBackup  = cString;
                    backupTaskLog              = $"******** Log for {SelectedCStringDBToBackup.Database} ************\nBacking up using SqlClient....\n";
                    cString.IsProcessing.Value = true;
                    CStringDBToBackup          = cString.SqlConnectionString;
                    DatabaseNameToBackup       = cString.Database;
                    SqlConnection sqlConnection = new SqlConnection(_cstringDBToBackup);
                    sqlConnection.Open();
                    if (!Directory.Exists(_backupFolderPath))
                    {
                        Directory.CreateDirectory(_backupFolderPath);
                    }
                    DirectoryInfo di = Directory.CreateDirectory(_backupFolderPath + "\\" + _databaseNameToBackup + currentTimeString);
                    string        tempBackupFilePath = Path.Combine(di.FullName, _databaseNameToBackup + ".bak");
                    string        backupQuery        = string.Format(_backupQuery, DatabaseNameToBackup, tempBackupFilePath);
                    using (SqlCommand cmd = new SqlCommand(backupQuery, sqlConnection))
                        cmd.ExecuteNonQuery();
                    sqlConnection.Dispose();
                    //UploadFile(di.FullName, currentTimeString, cString.Database);
                    backupTaskLog += $"Backed up database to {tempBackupFilePath}.....\nUploading {di.FullName} Backup File....\n";
                    Task <FileToUpload> fileToUploadTask = FileToUpload.UploadFile(di.FullName, cString, cString.Database + "_backup_" + currentTimeString + ".zip");
                    LatestUploadedFiles.Add(fileToUploadTask);
                    while (!fileToUploadTask.Wait(100))
                    {
                        Thread.Sleep(1000);
                    }
                    if (fileToUploadTask.Status == TaskStatus.Faulted)
                    {
                        throw fileToUploadTask.Exception;
                    }
                    else
                    {
                        ftu = fileToUploadTask.Result;
                        if (ftu.IsFaulted && !ftu.IsZipUploaded)
                        {
                            backupTaskLog += "FileToUpload Object:\n" + JsonConvert.SerializeObject(ftu) + "\n";
                            throw ftu.Error;
                        }
                        else if (ftu.IsZipUploaded)
                        {
                            backupTaskLog += $"Uploaded file {ftu.LocalFilePath} to gdrive with Id: {ftu.UploadedFileId}!\n";
                        }
                        lock (RecentFilesToUpload)
                            RecentFilesToUpload.Add(ftu);
                    }
                    cString.IsProcessing.Value = false;
                }
                catch (Exception ex)
                {
                    backupTaskLog += "Error: \n" + ex.ToString() + "\n\n";
                    cString.IsProcessing.Value = false;
                    cString.HasErrors          = true;
                    SetException(ex);
                }
            }
コード例 #30
0
        public override FileUploadResult ProcessUpload(HttpContext context)
        {
            var log = LogManager.GetLogger("ASC.Mail.FilesUploader");

            string message;

            var fileName = string.Empty;

            MailAttachmentData mailAttachmentData = null;

            try
            {
                if (!FileToUpload.HasFilesToUpload(context))
                {
                    throw new Exception(MailScriptResource.AttachmentsBadInputParamsError);
                }

                if (!SecurityContext.IsAuthenticated)
                {
                    throw new HttpException(403, "Access denied.");
                }

                Thread.CurrentThread.CurrentCulture   = CurrentCulture;
                Thread.CurrentThread.CurrentUICulture = CurrentCulture;

                var mailId         = Convert.ToInt32(context.Request["messageId"]);
                var copyToMy       = Convert.ToInt32(context.Request["copyToMy"]);
                var needSaveToTemp = Convert.ToBoolean(context.Request["needSaveToTemp"]);

                if (mailId < 1)
                {
                    throw new AttachmentsException(AttachmentsException.Types.MessageNotFound,
                                                   "Message not yet saved!");
                }

                var engine = new EngineFactory(TenantId, Username);

                var item = engine.MessageEngine.GetMessage(mailId, new MailMessageData.Options());
                if (item == null)
                {
                    throw new AttachmentsException(AttachmentsException.Types.MessageNotFound, "Message not found.");
                }

                if (string.IsNullOrEmpty(item.StreamId))
                {
                    throw new AttachmentsException(AttachmentsException.Types.BadParams, "Have no stream");
                }

                var postedFile = new FileToUpload(context);

                fileName = context.Request["name"];

                if (string.IsNullOrEmpty(fileName))
                {
                    throw new AttachmentsException(AttachmentsException.Types.BadParams, "Empty name param");
                }

                if (copyToMy == 1)
                {
                    var uploadedFile = FileUploader.Exec(Global.FolderMy.ToString(), fileName,
                                                         postedFile.ContentLength, postedFile.InputStream, true);

                    return(new FileUploadResult
                    {
                        Success = true,
                        FileName = uploadedFile.Title,
                        FileURL = FileShareLink.GetLink(uploadedFile, false),
                        Data = new MailAttachmentData
                        {
                            fileId = Convert.ToInt32(uploadedFile.ID),
                            fileName = uploadedFile.Title,
                            size = uploadedFile.ContentLength,
                            contentType = uploadedFile.ConvertedType,
                            attachedAsLink = true,
                            tenant = TenantId,
                            user = Username
                        }
                    });
                }

                mailAttachmentData = engine.AttachmentEngine
                                     .AttachFileToDraft(TenantId, Username, mailId, fileName, postedFile.InputStream,
                                                        postedFile.ContentLength, null, postedFile.NeedSaveToTemp);

                return(new FileUploadResult
                {
                    Success = true,
                    FileName = mailAttachmentData.fileName,
                    FileURL = mailAttachmentData.storedFileUrl,
                    Data = mailAttachmentData
                });
            }
            catch (HttpException he)
            {
                log.Error("FileUpload handler failed", he);

                context.Response.StatusCode = he.GetHttpCode();
                message = he.Message != null
                    ? HttpUtility.HtmlEncode(he.Message)
                    : MailApiErrorsResource.ErrorInternalServer;
            }
            catch (AttachmentsException ex)
            {
                log.Error("FileUpload handler failed", ex);

                switch (ex.ErrorType)
                {
                case AttachmentsException.Types.BadParams:
                    message = MailScriptResource.AttachmentsBadInputParamsError;
                    break;

                case AttachmentsException.Types.EmptyFile:
                    message = MailScriptResource.AttachmentsEmptyFileNotSupportedError;
                    break;

                case AttachmentsException.Types.MessageNotFound:
                    message = MailScriptResource.AttachmentsMessageNotFoundError;
                    break;

                case AttachmentsException.Types.TotalSizeExceeded:
                    message = MailScriptResource.AttachmentsTotalLimitError;
                    break;

                case AttachmentsException.Types.DocumentNotFound:
                    message = MailScriptResource.AttachmentsDocumentNotFoundError;
                    break;

                case AttachmentsException.Types.DocumentAccessDenied:
                    message = MailScriptResource.AttachmentsDocumentAccessDeniedError;
                    break;

                default:
                    message = MailScriptResource.AttachmentsUnknownError;
                    break;
                }
            }
            catch (TenantQuotaException ex)
            {
                log.Error("FileUpload handler failed", ex);
                message = ex.Message;
            }
            catch (Exception ex)
            {
                log.Error("FileUpload handler failed", ex);
                message = MailScriptResource.AttachmentsUnknownError;
            }

            return(new FileUploadResult
            {
                Success = false,
                FileName = fileName,
                Data = mailAttachmentData,
                Message = string.IsNullOrEmpty(message) ? MailApiErrorsResource.ErrorInternalServer : message
            });
        }