Exemple #1
0
 private void SetConfigFilePath(string filePath)
 {
     ConsoleMessage.Print("Start file validation.");
     FileValidation.FileExists(filePath);
     configFilePath = filePath;
     ConsoleMessage.Print("File validation finished with success.", "success");
 }
Exemple #2
0
        private static string uperror(HtmlInputFile ControlId, float FileSize)
        {
            string output   = "";
            string filename = ControlId.PostedFile.FileName;

            if (filename == "")
            {
                output = "请选择图片...";
            }
            else
            {
                float FileLength = float.Parse((float.Parse(ControlId.PostedFile.ContentLength.ToString()) / 1024 / 1024).ToString("#0.00"));
                if (FileLength > FileSize)
                {
                    output = "文件大小不得超过" + FileSize + "M" + "<font style=\"color:#000;\">(&nbsp;当前文件大小约为&nbsp;" + FileLength + "M&nbsp;)</font>";
                }
                FileExtension[] fe = { FileExtension.GIF, FileExtension.JPG, FileExtension.BMP };
                if (!FileValidation.IsAllowedExtension(ControlId, fe))
                {
                    string style = FileNodeName(fe);
                    output = "只支持" + style + "格式图片";
                }
                else
                {
                    output = "";
                }
            }
            return(output);
        }
        public JsonResult UploadImage(int type)
        {
            if (HttpContext.Request.Files.Count > 0)
            {
                string mongodbName = MongoDbNameArray[type];
                if (string.IsNullOrEmpty(mongodbName))
                {
                    return(Json(new JsonBaseEntity {
                        ErrorCode = "10000", ErrorMessage = "上传参数错误!"
                    }));
                }

                try
                {
                    var             file   = HttpContext.Request.Files[0];
                    FileExtension[] fileEx = { FileExtension.BMP, FileExtension.JPG, FileExtension.GIF, FileExtension.PNG };
                    if (!FileValidation.IsAllowedExtension(file, fileEx))
                    {
                        return(Json(new JsonBaseEntity {
                            ErrorCode = "10000", ErrorMessage = "请上传JPG、JPEG、PNG、BMP格式的图片!"
                        }));
                    }

                    string newFileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
                    newFileName = newFileName.ToUpper();

                    if (file.InputStream.Length > 1024 * 1024 * 1)                                   //大于1M,就等比压缩
                    {
                        file.InputStream.Seek(0, SeekOrigin.Begin);                                  //将当前流的位置设置为初始位置。很重要,很重要,很重要!!!
                        Image  uploaderImg = Image.FromStream(file.InputStream);
                        Image  newImage    = ImageHelper.UniformScaleDeflate(uploaderImg, 600, 600); // 压缩图片,保证图片的最大宽度为800px,高度按照比例等比压缩。
                        Stream newStream   = ImageToByteHelper.ImgToStream(newImage);
                        MongoDBHelper.SetFileByName(mongodbName, newStream, newFileName);
                    }
                    else
                    {
                        MongoDBHelper.SetFileByName(mongodbName, file.InputStream, newFileName);
                    }

                    return(Json(new JsonUploadFileEntity {
                        ErrorCode = "10001", ErrorMessage = "上传成功", FileUrl = string.Format("{0}/TuPian/Images/{1}/Show/{2}", "", type, newFileName), FileName = newFileName
                    }));
                }
                catch (Exception ex)
                {
                    logger.ErrorFormat("function:{0},location:{1},params:type={2},Message={3},StackTrace={4},Source={5}", "UploadImage", "MongoDBLegacyHelper.SetFileByName", type, ex.Message, ex.StackTrace, ex.Source);
                    return(Json(new JsonBaseEntity {
                        ErrorCode = "10000", ErrorMessage = "服务端异常"
                    }));
                }
            }
            else
            {
                return(Json(new JsonBaseEntity {
                    ErrorCode = "10002", ErrorMessage = "请选择图片"
                }));
            }
        }
Exemple #4
0
        public void FileSizeValidate(int fileSize, int maxSize, string field, string messageFormat)
        {
            FileValidation validate = new FileValidation();

            if (validate.ExceedSize(fileSize, maxSize))
            {
                this.errorMessageList.Add(String.Format(messageFormat, field, FileUtility.GetFileSizeFormat(maxSize)));
            }
        }
        private static void EnterFilePath(out string lightningDataFilePath, out string assetDataFilePath)
        {
            Console.WriteLine("Please enter file path for Lightning Data: ");
            lightningDataFilePath = Console.ReadLine().ToString();
            lightningDataFilePath = FileValidation.FileChecker(lightningDataFilePath);
            Console.WriteLine("");

            Console.WriteLine("Please enter file path for Asset Data: ");
            assetDataFilePath = Console.ReadLine().ToString();
            assetDataFilePath = FileValidation.FileChecker(assetDataFilePath);
            Console.WriteLine("");
        }
Exemple #6
0
        public bool PatchStream(Stream input, FileValidation targetChk, Stream output, out FileValidation outputChk)
        {
            unsafe
            {
                fixed (byte* pPatch = Data)
                    Diff.Apply(input, pPatch, Data.LongLength, output);
            }

            output.Seek(0, SeekOrigin.Begin);
            outputChk = new FileValidation(output, targetChk.Type);

            return targetChk == outputChk;
        }
Exemple #7
0
        public void FileExtensionValidate(IFileExtensions extensions, string value, bool ignoreEmpty, string field, string messageFormat)
        {
            FileValidation validate = new FileValidation();

            if (!ignoreEmpty || !String.IsNullOrWhiteSpace(value))
            {
                if (!validate.IsExtension(value, extensions))
                {
                    string extension = Path.GetExtension(value).ToLower();
                    this.errorMessageList.Add(String.Format(messageFormat, field, extension));
                }
            }
        }
        public void FileCheckerTestEmptyString()
        {
            path = null;

            //Arrange
            var expected = "";

            //Act
            var actual = FileValidation.FileChecker(path);

            //Assert
            Assert.Equal(expected, actual);
        }
Exemple #9
0
        private void SetWebDriverSettings(string filePath)
        {
            ConsoleMessage.Print("Read config file and applying settings.");

            FileValidation.ExtensionIsValid(filePath, ".json");

            string   file = File.ReadAllText(filePath);
            JsonFile data = JsonSerializer.Deserialize <JsonFile>(file);

            settings = data;

            ConsoleMessage.Print("Settings applied with success.", "success");
        }
Exemple #10
0
        public void Image_Valid()
        {
            //Arrange
            string test     = "test.jpg";
            bool   expected = true;

            //Act
            IFileExtensions extension = new ImageFileExtensions();
            FileValidation  validate  = new FileValidation();
            bool            result    = validate.IsExtension(test, extension);

            //Assert
            Assert.AreEqual(expected, result);
        }
Exemple #11
0
        public void ExceedSize()
        {
            //Arrange
            int  test     = 4000;
            int  max      = 2048;
            bool expected = true;

            //Act
            FileValidation validate = new FileValidation();
            bool           result   = validate.ExceedSize(test, max);

            //Assert
            Assert.AreEqual(expected, result);
        }
        public async Task <ActionResult> Create([Bind(Include = "Id,TicketId,Description,Created,UserId,FileUrl")] TicketAttachment ticketAttachment, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                if (FileValidation.IsWebFriendlyImage(file))
                {
                    var fileName = Path.GetFileName(file.FileName);
                    file.SaveAs(Path.Combine(Server.MapPath("~/uploads/"), fileName));
                    ticketAttachment.FileUrl = "/uploads/" + fileName;
                }
                var ticket      = db.Tickets.Find(ticketAttachment.TicketId);
                var sendeeemail = db.Users.Find(ticket.AssignedToUserId).Email;
                ticketAttachment.UserId  = User.Identity.GetUserId();
                ticketAttachment.Created = DateTime.Now;
                db.TicketAttachments.Add(ticketAttachment);
                db.SaveChanges();

                var callbackUrl = Url.Action("Details", "Tickets", new { id = ticketAttachment.TicketId }, protocol: Request.Url.Scheme);
                try
                {
                    EmailService    ems = new EmailService();
                    IdentityMessage msg = new IdentityMessage();

                    msg.Body        = "A new attachment has been added" + " to" + " ticket " + ticketAttachment.Ticket.Title + " on project " + ticketAttachment.Ticket.Project.Name + Environment.NewLine + "Please click the following link to view the details" + "<a href=\"" + callbackUrl + "\"> New Attachment</a>";
                    msg.Destination = sendeeemail;
                    msg.Subject     = "TicketAttachment";

                    TicketNotification ticketNotification = new TicketNotification();
                    ticketNotification.TicketId = ticketAttachment.TicketId;
                    ticketNotification.Created  = DateTime.Now;
                    ticketNotification.UserId   = User.Identity.GetUserId();
                    ticketNotification.Message  = msg.Body;
                    db.TicketNotifications.Add(ticketNotification);
                    db.SaveChanges();

                    await ems.SendMailAsync(msg);
                }
                catch (Exception ex)
                {
                    await Task.FromResult(0);
                }
                return(RedirectToAction("Details", "Tickets", new { id = ticketAttachment.TicketId }));
            }

            ViewBag.TicketId = new SelectList(db.Tickets, "Id", "Title", ticketAttachment.TicketId);
            ViewBag.UserId   = new SelectList(db.Users, "Id", "FirstName", ticketAttachment.UserId);
            return(RedirectToAction("index", "Tickets"));
        }
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            FileValidation logType = (FileValidation)value;

            switch (logType)
            {
            case FileValidation.Error:
                return(new SolidColorBrush(Colors.Red));

            case FileValidation.Warning:
                var color = Colors.Orange;
                color.A = 40;
                return(new SolidColorBrush(color));                        // Transparent orange
            }

            return(new SolidColorBrush(Colors.Transparent));
        }
        static void Main(string[] args)
        {
            XmlConfigurator.Configure();

            string op = "";

            FileValidation fv = new FileValidation();
            DataValidation dv = new DataValidation();

            log.Info("Execution Start");

            while (true)
            {
                Console.WriteLine(" ==============================");
                Console.WriteLine("\t MENU PRINCIPAL");
                Console.WriteLine(" ==============================");

                Console.WriteLine("  1- Verificar Arquivos");
                Console.WriteLine("  2- Verificar Dados");
                Console.WriteLine("  3- Sair");

                Console.Write("\n  Opção: ");
                op = Console.ReadLine();

                if (op.Equals("1"))
                {
                    fv.FileValidationMenu();
                }
                else if (op.Equals("2"))
                {
                    dv.DataValidationMenu();
                }
                else if (op.Equals("3"))
                {
                    log.Info("Execution Ending");
                    Environment.Exit(0);
                }
                else
                {
                    Console.WriteLine("Opção Inválida");
                    Thread.Sleep(1000);
                    Console.Clear();
                }
            }
        }
        public bool IsValid()
        {
            IFileValidation fileValidator = new FileValidation(this.path);
            bool            fileValid     = fileValidator.IsFileValid();

            if (fileValid)
            {
                var                reader           = new Reader(this.path);
                string[]           content          = reader.GetContent();
                IContentValidation contentValidator = new ContentValidator(content);
                bool               contentValid     = contentValidator.IsTSVContentValid();
                if (contentValid)
                {
                    this.TSVContent = contentValidator.Content;
                    return(true);
                }
            }
            return(false);
        }
Exemple #16
0
        public bool PatchBytes(byte[] inputBytes, FileValidation targetChk, out byte[] outputBytes, out FileValidation outputChk)
        {
            using (var output = new MemoryStream())
            {
                unsafe
                {
                    fixed (byte* pInput = inputBytes)
                    fixed (byte* pPatch = Data)
                        Diff.Apply(pInput, inputBytes.LongLength, pPatch, Data.LongLength, output);
                }

                outputBytes = output.ToArray();

                output.Seek(0, SeekOrigin.Begin);
                outputChk = new FileValidation(outputBytes, targetChk.Type);

                return targetChk == outputChk;
            }
        }
Exemple #17
0
        private static void BuildMasterPatch(string esm, ILookup <string, string> knownEsmVersions)
        {
            var fixPath = Path.Combine(OutDir, Path.ChangeExtension(esm, ".pat"));

            if (File.Exists(fixPath))
            {
                return;
            }

            var ttwESM   = Path.Combine(_dirTTWMain, esm);
            var ttwBytes = File.ReadAllBytes(ttwESM);
            var ttwChk   = new FileValidation(ttwBytes);

            var altVersions = knownEsmVersions[esm].ToList();

            var patches =
                altVersions.Select(dataESM =>
            {
                var dataBytes = File.ReadAllBytes(dataESM);
                byte[] patchBytes;

                using (var msPatch = new MemoryStream())
                {
                    MakeDiff.Create(dataBytes, ttwBytes, Diff.SIG_LZDIFF41, msPatch);
                    patchBytes = msPatch.ToArray();
                }

                return(new PatchInfo
                {
                    Metadata = new FileValidation(dataESM),
                    Data = patchBytes
                });
            })
                .AsParallel()
                .ToArray();

            var patchDict = new PatchDict(altVersions.Count);

            patchDict.Add(esm, new Patch(ttwChk, patches));

            using (var fixStream = File.OpenWrite(fixPath))
                patchDict.WriteAll(fixStream);
        }
        /* Field validations */
        public List <FileValidation> GetFieldValidations(string selectedPlatform)
        {
            FileControl           filectr = FORIS.Interbilling.NTS.Mediation.Configurations.Configuration.GetNotCashedConfiguration <FileControl>();
            List <FileValidation> list    = new List <FileValidation>();

            foreach (var item in filectr.FieldsValidations.Find(p => p.FileType == selectedPlatform).Validations)
            {
                FileValidation fileVal = new FileValidation();
                fileVal.InputField     = item.InputField;
                fileVal.ValidationRule = item.ValidationRule.ToString();
                fileVal.DateFrom       = item.DateFrom;
                fileVal.DateTo         = item.DateTo;
                foreach (var it in item.FieldValues)
                {
                    //TODO
                    fileVal.ValidationValues += it.ToString() + ";";
                }
                fileVal.OutputFileType = item.OutputFileType.ToString();
                list.Add(fileVal);
            }
            return(list);
        }
Exemple #19
0
        public override ResultModel <Guid> AddFile(UploadFileViewModel dto, Guid tenantId)
        {
            var fileValidation =
                FileValidation.ValidateFile(dto.File, _options.Value.FirstOrDefault(x => x.TenantId == tenantId));

            if (!fileValidation.IsSuccess)
            {
                return(fileValidation);
            }

            if (dto.Id != Guid.Empty)
            {
                return(UpdateFile(dto));
            }


            var encryptedFile = SaveFilePhysical(dto.File);

            if (encryptedFile == null)
            {
                return(ExceptionMessagesEnum.NullIFormFile.ToErrorModel <Guid>());
            }

            var file = new FileBox
            {
                FileExtension = encryptedFile.FileExtension,
                Path          = encryptedFile.Path,
                Name          = encryptedFile.FileName,
                Size          = encryptedFile.Size
            };

            _context.FilesBox.Add(file);
            _context.SaveChanges();
            return(new ResultModel <Guid>
            {
                IsSuccess = true,
                Result = file.Id
            });
        }
Exemple #20
0
        private ResultModel <Guid> UpdateFile(UploadFileViewModel dto, Guid tenantId)
        {
            var file = _context.Files.FirstOrDefault(x => x.Id == dto.Id);

            if (file == null)
            {
                return(ExceptionMessagesEnum.FileNotFound.ToErrorModel <Guid>());
            }

            var fileValidation =
                FileValidation.ValidateFile(dto.File, _options.Value.FirstOrDefault(x => x.TenantId == tenantId));

            if (!fileValidation.IsSuccess)
            {
                return(fileValidation);
            }

            var encryptedFile = EncryptFile(dto.File);

            if (encryptedFile == null)
            {
                return(ExceptionMessagesEnum.NullIFormFile.ToErrorModel <Guid>());
            }

            file.FileExtension = encryptedFile.FileExtension;
            file.Hash          = encryptedFile.EncryptedFile;
            file.Name          = encryptedFile.FileName;
            file.Size          = encryptedFile.Size;
            _context.Files.Add(file);
            _context.SaveChanges();
            return(new ResultModel <Guid>
            {
                IsSuccess = true,
                Result = file.Id
            });
        }
        public async Task <IFileValidationResult> ValidateFileAsync(string productFileUri, string validationUri, IStatus status)
        {
            var fileValidation = new FileValidation
            {
                Filename = productFileUri
            };

            if (string.IsNullOrEmpty(productFileUri))
            {
                throw new ArgumentNullException();
            }

            if (string.IsNullOrEmpty(validationUri))
            {
                throw new ArgumentNullException();
            }

            fileValidation.ValidationExpected = confirmValidationExpectedDelegate.Confirm(productFileUri);

            if (!fileValidation.ValidationExpected)
            {
                return(fileValidation);
            }

            fileValidation.ValidationFileExists = VerifyValidationFileExists(validationUri);
            fileValidation.ProductFileExists    = VerifyProductFileExists(productFileUri);

            if (!fileValidation.ValidationFileExists ||
                !fileValidation.ProductFileExists)
            {
                return(fileValidation);
            }

            try
            {
                using (var xmlStream = streamController.OpenReadable(validationUri))
                    validationXml.Load(xmlStream);

                fileValidation.ValidationFileIsValid = true;
            }
            catch
            {
                fileValidation.ValidationFileIsValid = false;
                return(fileValidation);
            }

            var fileElement = validationXml.GetElementsByTagName("file");

            if (fileElement == null ||
                fileElement.Count < 1 ||
                fileElement[0] == null ||
                fileElement[0].Attributes == null)
            {
                fileValidation.ValidationFileIsValid = false;
                return(fileValidation);
            }

            long   expectedSize;
            string expectedName;
            int    chunks;
            bool   available;

            try
            {
                expectedSize = long.Parse(fileElement[0].Attributes["total_size"]?.Value);
                expectedName = fileElement[0].Attributes["name"]?.Value;
                chunks       = int.Parse(fileElement[0].Attributes["chunks"]?.Value);
                available    = fileElement[0].Attributes["available"]?.Value == "1";

                if (!available)
                {
                    var notAvailableMessage = fileElement[0].Attributes["notavailablemsg"]?.Value;
                    throw new Exception(notAvailableMessage);
                }
            }
            catch
            {
                fileValidation.ValidationFileIsValid = false;
                return(fileValidation);
            }

            fileValidation.FilenameVerified = VerifyFilename(productFileUri, expectedName);
            fileValidation.SizeVerified     = VerifySize(productFileUri, expectedSize);

            var chunksValidation = new List <IChunkValidation>();

            using (var fileStream = streamController.OpenReadable(productFileUri))
            {
                long length = 0;

                foreach (XmlNode chunkElement in fileElement[0].ChildNodes)
                {
                    if (chunkElement.Name != "chunk")
                    {
                        continue;
                    }

                    long   from, to = 0;
                    string expectedMd5 = string.Empty;

                    from        = long.Parse(chunkElement.Attributes["from"]?.Value);
                    to          = long.Parse(chunkElement.Attributes["to"]?.Value);
                    length     += (to - from);
                    expectedMd5 = chunkElement.FirstChild.Value;

                    chunksValidation.Add(await VerifyChunkAsync(fileStream, from, to, expectedMd5, status));

                    await statusController.UpdateProgressAsync(
                        status,
                        length,
                        expectedSize,
                        productFileUri,
                        DataUnits.Bytes);
                }

                fileValidation.Chunks = chunksValidation.ToArray();

                await statusController.UpdateProgressAsync(status, length, expectedSize, productFileUri);
            }

            await statusController.InformAsync(status, $"Validation result: {productFileUri} is valid: " +
                                               $"{validationResultController.ProductFileIsValid(fileValidation)}");

            return(fileValidation);
        }
        private UploadMessage _uploadImage(string companyID, bool convertToThumbnail = true)
        {
            if (HttpContext.Current.Request.Files.AllKeys.Any())
            {
                FileExtension[] allowFileExtension = { FileExtension.BMP, FileExtension.GIF, FileExtension.JPG, FileExtension.PNG };

                if (!FileValidation.IsAllowedExtension(HttpContext.Current.Request.Files["file"], allowFileExtension))
                {
                    return(errorMsg("不接受的文件格式"));
                }

                // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES.
                string folderPath = WebApiApplication.UploadFolderPath;

                if (folderPath.StartsWith("~") || folderPath.StartsWith(".")) //相对路径
                {
                    folderPath = HttpContext.Current.Server.MapPath(folderPath + "/images/" + companyID);
                }
                else
                {
                    folderPath = folderPath + "/images/" + companyID;
                }

                string originalFolderPath  = Path.Combine(folderPath, DateTime.Now.ToString("yyyyMM") + "/original");
                string thumbnailFolderPath = Path.Combine(folderPath, DateTime.Now.ToString("yyyyMM") + "/thumbnail");

                bool folderExists = Directory.Exists(originalFolderPath);
                if (!folderExists)
                {
                    Directory.CreateDirectory(originalFolderPath);
                }

                folderExists = Directory.Exists(thumbnailFolderPath);
                if (!folderExists)
                {
                    Directory.CreateDirectory(thumbnailFolderPath);
                }

                HttpPostedFile httpPostedFile       = HttpContext.Current.Request.Files["file"];
                string         fileType             = httpPostedFile.FileName.Substring(httpPostedFile.FileName.LastIndexOf("."));
                string         fileName             = DateTime.Now.ToString("ddHHmmssff");
                string         fileOriginalSavePath = Path.Combine(originalFolderPath, fileName + fileType);
                try
                {
                    httpPostedFile.SaveAs(fileOriginalSavePath);
                }
                catch (ApplicationException ex)
                {
                    return(errorMsg(ex.Message));
                }

                if (!convertToThumbnail)
                {
                    return(successfulMsg(httpPostedFile.FileName, fileName, httpPostedFile.ContentLength, fileType,
                                         fileOriginalSavePath,
                                         WebApiApplication.UploadFolderVirualPath + "/images/" + companyID + "/" + DateTime.Now.ToString("yyyyMM") + "/original/" + fileName + fileType));
                }
                try
                {
                    Image  originalImage         = StreamHelper.ImagePath2Img(fileOriginalSavePath);
                    string fileThumbnailSavePath = Path.Combine(thumbnailFolderPath, fileName + fileType);
                    Image  newImage = ImageHelper.GetThumbNailImage(originalImage, 160, 160);
                    newImage.Save(fileThumbnailSavePath);

                    return(successfulMsg(httpPostedFile.FileName, fileName, httpPostedFile.ContentLength, fileType,
                                         fileOriginalSavePath,
                                         WebApiApplication.UploadFolderVirualPath + "/images/" + companyID + "/" + DateTime.Now.ToString("yyyyMM") + "/thumbnail/" + fileName + fileType));
                }
                catch (ApplicationException ex)
                {
                    return(errorMsg(ex.Message));
                }
            }

            return(errorMsg("没有上传文件"));
        }
        private UploadMessage _uploadFile(string companyID, string fileFolderName)
        {
            if (HttpContext.Current.Request.Files.AllKeys.Any())
            {
                string          fileSubFolder      = "/files/" + fileFolderName + "/";
                FileExtension[] allowFileExtension = { FileExtension.BMP,  FileExtension.DOC,
                                                       FileExtension.DOCX, FileExtension.XLS,FileExtension.XLSX,
                                                       FileExtension.PDF,
                                                       FileExtension.GIF,  FileExtension.JPG,FileExtension.PNG };

                if (!FileValidation.IsAllowedExtension(HttpContext.Current.Request.Files["file"], allowFileExtension))
                {
                    return(errorMsg("不接受的文件格式"));
                }

                bool isImage = FileValidation.IsImageExtension(HttpContext.Current.Request.Files["file"]);

                // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES.
                string folderPath = WebApiApplication.UploadFolderPath;

                if (folderPath.StartsWith("~") || folderPath.StartsWith(".")) //相对路径
                {
                    folderPath = HttpContext.Current.Server.MapPath(folderPath + "/files/" + companyID);
                }
                else
                {
                    folderPath = folderPath + fileSubFolder + companyID;
                }

                string yearMonth = DateTime.Now.ToString("yyyyMM");
                folderPath = Path.Combine(folderPath, yearMonth);

                //folderPath = folderPath.Replace(".WebAPI", ".Web").Replace("UploadedDocuments", "content/images");

                bool folderExists = Directory.Exists(folderPath);
                if (!folderExists)
                {
                    Directory.CreateDirectory(folderPath);
                }

                HttpPostedFile httpPostedFile = HttpContext.Current.Request.Files["file"];
                string         fileType       = httpPostedFile.FileName.Substring(httpPostedFile.FileName.LastIndexOf("."));
                string         fileName       = Guid.NewGuid() + "-" + DateTime.Now.ToString("ddHHmmssff");
                string         fileSavePath   = Path.Combine(folderPath, fileName + fileType);
                try
                {
                    httpPostedFile.SaveAs(fileSavePath);
                }
                catch (ApplicationException ex)
                {
                    return(errorMsg(ex.Message));
                }

                if (isImage)
                {
                    string originalFolderPath  = folderPath;
                    string thumbnailFolderPath = Path.Combine(folderPath, "thumbnail");

                    Image  originalImage         = StreamHelper.ImagePath2Img(fileSavePath);
                    string fileThumbnailSavePath = Path.Combine(thumbnailFolderPath, fileName + fileType);

                    folderExists = Directory.Exists(thumbnailFolderPath);
                    if (!folderExists)
                    {
                        Directory.CreateDirectory(thumbnailFolderPath);
                    }

                    Image newImage = ImageHelper.GetThumbNailImage(originalImage, 320, 320);
                    newImage.Save(fileThumbnailSavePath);

                    UploadMessage uploadMessageImg = new UploadMessage()
                    {
                        OriginName           = httpPostedFile.FileName,
                        FileName             = fileName,
                        FileSize             = httpPostedFile.ContentLength,
                        FileType             = fileType,
                        DiskUploadPath       = fileThumbnailSavePath,
                        UploadFilePath       = WebApiApplication.UploadFolderVirualPath + fileSubFolder + companyID + "/" + yearMonth + "/" + "/thumbnail/" + fileName + fileType,
                        IsImage              = true,
                        HasThumbnail         = true,
                        OriginDiskUploadPath = fileSavePath,
                        OriginFilePath       = WebApiApplication.UploadFolderVirualPath + fileSubFolder + companyID + "/" + yearMonth + "/" + fileName + fileType,
                    };

                    return(uploadMessageImg);
                }

                UploadMessage uploadMessage = new UploadMessage()
                {
                    OriginName           = httpPostedFile.FileName,
                    FileName             = fileName,
                    FileSize             = httpPostedFile.ContentLength,
                    FileType             = fileType,
                    DiskUploadPath       = fileSavePath,
                    UploadFilePath       = WebApiApplication.UploadFolderVirualPath + fileSubFolder + companyID + "/" + yearMonth + "/" + fileName + fileType,
                    IsImage              = false,
                    HasThumbnail         = false,
                    OriginDiskUploadPath = fileSavePath,
                    OriginFilePath       = WebApiApplication.UploadFolderVirualPath + fileSubFolder + companyID + "/" + yearMonth + "/" + fileName + fileType,
                };

                return(uploadMessage);
            }

            return(errorMsg("没有上传文件"));
        }
Exemple #24
0
        private bool PatchMaster(string esm)
        {
            Log.Dual("Patching " + esm + "...");

            var patchPath = Path.Combine(PatchDir, Path.ChangeExtension(esm, ".pat"));

            if (File.Exists(patchPath))
            {
                var patchDict = new PatchDict(patchPath);

                Debug.Assert(patchDict.ContainsKey(esm));
                var patch   = patchDict[esm];
                var patches = patch.Item2;
                var newChk  = patch.Item1;

                var finalPath = Path.Combine(DirTTWMain, esm);
                if (File.Exists(finalPath))
                {
                    Log.Dual("\t" + esm + " already exists");
                    if (CheckExisting(finalPath, newChk))
                    {
                        Log.Dual("\t" + esm + " is up to date");
                        return(true);
                    }

                    Log.Dual("\t" + esm + " is out of date");
                }

                var dataPath = Path.Combine(DirFO3Data, esm);
                //TODO: change to a user-friendly condition and message
                Trace.Assert(File.Exists(dataPath));

                //make sure we didn't include old patches by mistake
                Debug.Assert(patches.All(p => p.Metadata.Type == FileValidation.ChecksumType.Murmur128));

                using (var dataChk = new FileValidation(dataPath))
                {
                    var matchPatch = patches.SingleOrDefault(p => p.Metadata == dataChk);
                    if (matchPatch == null)
                    {
                        Log.Display("\tA patch for your version of " + esm + " could not be found");
                        Log.File("\tA patch for " + esm + " version " + dataChk + " could not be found");
                    }
                    else
                    {
                        using (FileStream
                               dataStream = File.OpenRead(dataPath),
                               outputStream = File.Open(finalPath, FileMode.Create, FileAccess.ReadWrite))
                        {
                            FileValidation outputChk;
                            if (matchPatch.PatchStream(dataStream, newChk, outputStream, out outputChk))
                            {
                                Log.Dual("\tPatch successful");
                                return(true);
                            }

                            Log.File("\tPatch failed - " + outputChk);
                        }
                    }
                }
            }
            else
            {
                Log.Dual("\t" + esm + " patch is missing from " + PatchDir);
            }

            Fail("Your version of " + esm + " cannot be patched. This is abnormal.");

            return(false);
        }
Exemple #25
0
 public override bool IsValid()
 {
     ValidationResult = new FileValidation().Validate(this);
     return(ValidationResult.IsValid);
 }
Exemple #26
0
        private static void BuildMasterPatch(string esm, ILookup<string, string> knownEsmVersions)
        {
            var fixPath = Path.Combine(OutDir, Path.ChangeExtension(esm, ".pat"));
            if (File.Exists(fixPath))
                return;

            var ttwESM = Path.Combine(_dirTTWMain, esm);
            var ttwBytes = File.ReadAllBytes(ttwESM);
            var ttwChk = new FileValidation(ttwBytes);

            var altVersions = knownEsmVersions[esm].ToList();

            var patches =
                altVersions.Select(dataESM =>
                {
                    var dataBytes = File.ReadAllBytes(dataESM);
                    byte[] patchBytes;

                    using (var msPatch = new MemoryStream())
                    {
                        MakeDiff.Create(dataBytes, ttwBytes, Diff.SIG_LZDIFF41, msPatch);
                        patchBytes = msPatch.ToArray();
                    }

                    return new PatchInfo
                    {
                        Metadata = new FileValidation(dataESM),
                        Data = patchBytes
                    };
                })
                .AsParallel()
                .ToArray();

            var patchDict = new PatchDict(altVersions.Count);
            patchDict.Add(esm, new Patch(ttwChk, patches));

            using (var fixStream = File.OpenWrite(fixPath))
                patchDict.WriteAll(fixStream);
        }
Exemple #27
0
 public static PatchInfo FromOldDiff(byte[] diffData, FileValidation oldChk)
 {
     return new PatchInfo
     {
         Metadata = oldChk,
         Data = diffData
     };
 }
Exemple #28
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string Act           = HTTPRequest.GetString("Act");
            int    ReCode        = 0;
            int    CertificateID = HTTPRequest.GetInt("CertificateID", 0);
            string uCode_tem     = HTTPRequest.GetString("c");

            if (uCode_tem.Trim() != "")
            {
                //username|pwd
                uCode_tem = DES.Decode(uCode_tem, config.Passwordkey);
                if (uCode_tem.Trim() != "")
                {
                    string[] uCode_temArr = Utils.SplitString(uCode_tem, "|");
                    if (uCode_temArr != null)
                    {
                        this.userid = tbUserInfo.CheckPassword(uCode_temArr[0], uCode_temArr[1], false);
                    }
                }
            }
            if (this.userid > 0)
            {
                if (Page.Request.InputStream != null)
                {
                    string PathStr = "/ufile/" + DateTime.Now.Year + "-" + DateTime.Now.Month;
                    string PicData = HTTPRequest.GetString("PicData");
                    string filestr;
                    int    picsize = 0;
                    int    picID   = 0;

                    string          sCode    = Utils.GetRanDomCode();
                    string          _PathStr = HttpContext.Current.Server.MapPath("/") + PathStr;
                    FileExtension[] fe       = { FileExtension.GIF, FileExtension.JPG, FileExtension.PNG, FileExtension.BMP };
                    if (!Directory.Exists(_PathStr))
                    {
                        Directory.CreateDirectory(_PathStr);
                    }
                    filestr = _PathStr + "/" + sCode + ".jpg";

                    try
                    {
                        if (FileValidation.IsAllowedExtension(new MemoryStream(Convert.FromBase64String(PicData)), fe))
                        {
                            Thumbnail.SaveBmp(Thumbnail.BytesToImage(Convert.FromBase64String(PicData)), filestr);

                            FileStream stream = new FileStream(filestr, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                            try
                            {
                                picsize = int.Parse(stream.Length.ToString());
                            }
                            finally
                            {
                                stream.Close();
                                stream.Dispose();
                            }
                            CertificatePicInfo cpi = new CertificatePicInfo();
                            try
                            {
                                cpi.UserID        = userid;
                                cpi.cCode         = Utils.GetRanDomCode();
                                cpi.CertificateID = CertificateID;
                                cpi.cPic          = PathStr + "/" + sCode + ".jpg";;
                                cpi.cAppendTime   = DateTime.Now;

                                picID = Certificates.AddCertificatePicInfo(cpi);
                                if (picID > 0)
                                {
                                    eStr   = "<re picid=\"" + picID.ToString() + "\" />";
                                    ReCode = 0;
                                }
                            }
                            finally
                            {
                                cpi = null;
                            }
                        }
                        else
                        {
                            eStr   = "<error>数据错误</error>";
                            ReCode = 4;
                        }
                    }
                    catch
                    {
                        try
                        {
                            HttpFileCollection files = HttpContext.Current.Request.Files;
                            try
                            {
                                if (files.Count > 0)
                                {
                                    HttpPostedFile postedFile = files[0];
                                    int            upLength   = postedFile.ContentLength;
                                    byte[]         upArray    = new Byte[upLength];
                                    Stream         upStream   = postedFile.InputStream;
                                    upStream.Read(upArray, 0, upLength);

                                    if (FileValidation.IsAllowedExtension(new MemoryStream(upArray), fe))
                                    {
                                        Thumbnail.SaveBmp(Thumbnail.BytesToImage(upArray), filestr);

                                        FileStream stream = new FileStream(filestr, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                                        try
                                        {
                                            picsize = int.Parse(stream.Length.ToString());
                                        }
                                        finally
                                        {
                                            stream.Close();
                                            stream.Dispose();
                                        }
                                        CertificatePicInfo cpi = new CertificatePicInfo();
                                        try
                                        {
                                            cpi.UserID        = userid;
                                            cpi.cCode         = Utils.GetRanDomCode();
                                            cpi.CertificateID = CertificateID;
                                            cpi.cPic          = PathStr + "/" + sCode + ".jpg";;
                                            cpi.cAppendTime   = DateTime.Now;

                                            picID = Certificates.AddCertificatePicInfo(cpi);
                                            if (picID > 0)
                                            {
                                                eStr   = "<re picid=\"" + picID.ToString() + "\" />";
                                                ReCode = 0;
                                            }
                                        }
                                        finally
                                        {
                                            cpi = null;
                                        }
                                    }
                                }
                            }
                            finally
                            {
                                files = null;
                            }
                        }
                        catch (Exception ex)
                        {
                            eStr   = "<error>" + ex.Message.ToString() + "</error>";
                            ReCode = 3;
                        }
                    }
                }
                else
                {
                    eStr   = "<error>数据校验失败</error>";
                    ReCode = 4;
                }
            }
            else
            {
                eStr   = "<error>鉴权失败</error>";
                ReCode = 4;
            }
            ReMsg(ReCode);
        }
Exemple #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FileValidationException"/> class.
 /// </summary>
 /// <param name="fileValidation">The <see cref="FileValidation"/> rule that caused the exception.</param>
 /// <param name="message">The message.</param>
 /// <param name="record">The <see cref="FileRecord"/> where applicable.</param>
 internal FileValidationException(FileValidation fileValidation, string message, FileRecord record = null) : base(message)
 {
     FileValidation = fileValidation;
     Record         = record;
 }
Exemple #30
0
 private static bool CheckExisting(string path, FileValidation newChk)
 {
     using (var existingChk = new FileValidation(path, newChk.Type))
         return(newChk == existingChk);
 }
Exemple #31
0
 public FileOperations(IFileRepository repository, IMapper mapper)
 {
     _mapper     = mapper;
     _repository = repository;
     _validator  = new FileValidation();
 }
Exemple #32
0
        private static void BuildBsaPatch(string inBsaName, string outBsaName)
        {
            string outBSAFile = Path.ChangeExtension(outBsaName, ".bsa");
            string outBSAPath = Path.Combine(_dirTTWMain, outBSAFile);

            string inBSAFile = Path.ChangeExtension(inBsaName, ".bsa");
            string inBSAPath = Path.Combine(_dirFO3Data, inBSAFile);

            var renameDict = BuildRenameDict(outBsaName);

            Debug.Assert(renameDict != null);

            var patPath = Path.Combine(OutDir, Path.ChangeExtension(outBsaName, ".pat"));

            if (File.Exists(patPath))
            {
                return;
            }

            var prefix = Path.Combine(InDir, "TTW Patches", outBsaName);

            using (var inBSA = new BSA(inBSAPath))
                using (var outBSA = new BSA(outBSAPath))
                {
                    BsaDiff
                    .CreateRenameQuery(inBSA, renameDict)
                    .ToList(); // execute query

                    var oldFiles = inBSA.SelectMany(folder => folder).ToList();
                    var newFiles = outBSA.SelectMany(folder => folder).ToList();

                    var newChkDict = FileValidation.FromBSA(outBSA);

                    var joinedPatches = from patKvp in newChkDict
                                        join newBsaFile in newFiles on patKvp.Key equals newBsaFile.Filename
                                        select new
                    {
                        newBsaFile,
                        file  = patKvp.Key,
                        patch = patKvp.Value
                    };
                    var allJoinedPatches = joinedPatches.ToList();

                    var patchDict = new PatchDict(allJoinedPatches.Count);
                    foreach (var join in allJoinedPatches)
                    {
                        var oldBsaFile = oldFiles.SingleOrDefault(file => file.Filename == join.file);
                        Debug.Assert(oldBsaFile != null, "File not found: " + join.file);

                        var oldChk = FileValidation.FromBSAFile(oldBsaFile);
                        var newChk = join.patch;

                        var oldFilename = oldBsaFile.Filename;
                        if (oldFilename.StartsWith(TaleOfTwoWastelands.Properties.Resources.VoicePrefix))
                        {
                            patchDict.Add(join.file, new Patch(newChk, null));
                            continue;
                        }

                        var patches = new List <PatchInfo>();

                        var md5OldStr = Util.GetMD5String(oldBsaFile.GetContents(true));
                        var md5NewStr = Util.GetMD5String(join.newBsaFile.GetContents(true));

                        var diffPath = Path.Combine(prefix, oldFilename + "." + md5OldStr + "." + md5NewStr + ".diff");
                        var usedPath = Path.ChangeExtension(diffPath, ".used");
                        if (File.Exists(usedPath))
                        {
                            File.Move(usedPath, diffPath); //fixes moronic things
                        }
                        var altDiffs = Util.FindAlternateVersions(diffPath);
                        if (altDiffs != null)
                        {
                            foreach (var altDiff in altDiffs)
                            {
                                var altDiffBytes = GetDiff(altDiff.Item1, Diff.SIG_LZDIFF41);
                                patches.Add(new PatchInfo
                                {
                                    Metadata = new FileValidation(altDiff.Item2, 0, FileValidation.ChecksumType.Md5),
                                    Data     = altDiffBytes
                                });
                            }
                        }

                        if (newChk != oldChk)
                        {
                            byte[] diffData = GetDiff(diffPath, Diff.SIG_LZDIFF41);

                            var patchInfo = PatchInfo.FromOldDiff(diffData, oldChk);
                            Debug.Assert(patchInfo.Data != null);

                            patches.Add(patchInfo);
                        }

                        patchDict.Add(join.file, new Patch(newChk, patches.ToArray()));
                    }

                    using (var stream = File.OpenWrite(patPath))
                        patchDict.WriteAll(stream);
                }
        }
        protected virtual void Page_Load(object sender, EventArgs e)
        {
            this.DataType = HTTPRequest.GetString("DataType");
            this.Act      = HTTPRequest.GetString("Act");
            this.Do       = HTTPRequest.GetString("Do");
            DataTable dt       = new DataTable();
            string    filename = "";

            if (ispost)
            {
                string _PathStr = HttpContext.Current.Server.MapPath("/") + PathStr;
                if (!Directory.Exists(_PathStr))
                {
                    Directory.CreateDirectory(_PathStr);
                }
                HttpFileCollection files = HttpContext.Current.Request.Files;
                try
                {
                    if (files.Count > 0)
                    {
                        FileExtension[] fe         = { FileExtension.XLS, FileExtension.XLSX };
                        HttpPostedFile  postedFile = files[0];
                        int             fileLen    = postedFile.ContentLength;
                        byte[]          fileArray  = new byte[fileLen];
                        postedFile.InputStream.Read(fileArray, 0, fileLen);
                        System.IO.MemoryStream fs = new System.IO.MemoryStream(fileArray);
                        try
                        {
                            if (FileValidation.IsAllowedExtension(fs, fe))
                            {
                                filename = _PathStr + '/' + postedFile.FileName;
                                postedFile.SaveAs(filename);
                                dt = Public.Excels.ExcelToTableForXLSX(filename);
                            }
                        }
                        finally
                        {
                            fs.Close();
                        }
                    }
                    else
                    {
                        this.AddErrLine("没有文件数据");
                    }
                }
                catch (Exception ex) {
                    this.AddErrLine(ex.Message);
                }
            }

            switch (this.DataType)
            {
            case "Products":
                if (CheckUserPopedoms("2-2-2-1") || CheckUserPopedoms("X"))
                {
                    this.Products_do(this.Act, this.Do, dt);
                }
                else
                {
                    AddErrLine("权限不足!");
                }
                break;

            case "Supplier":
                if (CheckUserPopedoms("2-2-3-1") || CheckUserPopedoms("X"))
                {
                    this.Supplier_do(this.Act, this.Do, dt);
                }
                else
                {
                    AddErrLine("权限不足!");
                }
                break;

            case "Stores":
                if (CheckUserPopedoms("2-2-4-1") || CheckUserPopedoms("X"))
                {
                    this.Stores_do(this.Act, this.Do, dt);
                }
                else
                {
                    AddErrLine("权限不足!");
                }
                break;

            case "Storage":
                if (CheckUserPopedoms("2-2-1-1") || CheckUserPopedoms("X"))
                {
                    this.Storage_do(this.Act, this.Do, dt);
                }
                else
                {
                    AddErrLine("权限不足!");
                }
                break;
            }
        }
Exemple #34
0
 public ProductImagesController(IEntityRepository <ProductImage> repository
                                , FileValidation validation)
 {
     this.repository = repository;
     this.validation = validation;
 }