Пример #1
0
        public async Task <IActionResult> EditPicF340Ppd()
        {
            _logger.LogInformation(String.Format(@"****** DKSController EditPicF340Ppd fired!! ******"));

            var sampleNo    = HttpContext.Request.Form["sampleNo"].ToString().Trim();
            var treatMent   = HttpContext.Request.Form["treatMent"].ToString().Trim();
            var partName    = HttpContext.Request.Form["partName"].ToString().Trim();
            var article     = HttpContext.Request.Form["article"].ToString().Trim();
            var devSeason   = HttpContext.Request.Form["devSeason"].ToString().Trim();
            var fileName    = HttpContext.Request.Form["photo"].ToString().Trim();
            var loginUser   = HttpContext.Request.Form["loginUser"].ToString().Trim();
            var factoryId   = HttpContext.Request.Form["factoryId"].ToString().Trim();
            var partNo      = partName.Split(" ")[0];
            var treatMentNo = treatMent.Split(" ")[0];

            DateTime nowtime       = DateTime.Now;
            var      updateTimeStr = nowtime.ToString("yyyy-MM-dd HH:mm:ss");
            DateTime updateTime    = updateTimeStr.ToDateTime();


            if (fileName == "")
            {
                //fileName + yyyy_MM_dd_HH_mm_ss_
                var formateDate = nowtime.ToString("yyyyMMddHHmmss");
                fileName = string.Format("{0}_{1}_{2}_{3}.jpg", article, partNo, treatMentNo, formateDate);
            }

            List <string> nastFileName = new List <string>();

            nastFileName.Add(devSeason);
            nastFileName.Add(article);
            nastFileName.Add(fileName);

            DevTreatment model = _devTreatmentDAO.FindSingle(
                x => x.SAMPLENO.Trim() == sampleNo.Trim() &&
                x.PARTNO.Trim() == partNo &&
                x.TREATMENTCODE.Trim() == treatMentNo &&
                x.FACTORYID == factoryId);

            if (HttpContext.Request.Form.Files.Count > 0)
            {
                var file = HttpContext.Request.Form.Files[0];
                //IformFile  ==> img ==>byte array ==> IformFile
                Image image    = Image.FromStream(file.OpenReadStream(), true, true);
                var   newImage = new Bitmap(1024, 768);
                using (var g = Graphics.FromImage(newImage))
                {
                    g.DrawImage(image, 0, 0, 1024, 768);
                }
                ImageConverter converter  = new ImageConverter();
                byte[]         bt         = (byte[])converter.ConvertTo(newImage, typeof(byte[]));
                var            stream     = new MemoryStream(bt);
                IFormFile      resizeFile = new FormFile(stream, 0, bt.Length, file.Name, file.FileName);
                if (await _fileService.SaveFiletoServer(resizeFile, "F340PpdPic", nastFileName))
                {
                    model.PHOTO = fileName;
                    _devTreatmentDAO.Update(model);

                    DevTreatmentFile opRecord = new DevTreatmentFile();
                    opRecord.ARTICLE       = article;
                    opRecord.PARTNO        = partNo;
                    opRecord.TREATMENTCODE = treatMentNo;
                    opRecord.FILE_NAME     = fileName;
                    opRecord.KIND          = "1";// 1: JPG 2:PDF
                    opRecord.FILE_COMMENT  = "";
                    opRecord.UPUSR         = loginUser;
                    opRecord.UPTIME        = updateTime;
                    _devTreatmentFileDAO.Add(opRecord);
                    _logger.LogInformation(String.Format(@"******DKSController EditPicF340Ppd Add a Picture: {0}!! ******", fileName));
                }
            }
            else
            {   //do CRUD-D here.
                if (await _fileService.SaveFiletoServer(null, "F340PpdPic", nastFileName))
                {
                    model.PHOTO = "";
                    _devTreatmentDAO.Update(model);

                    DevTreatmentFile opRecord = _devTreatmentFileDAO.FindSingle(
                        x => x.FILE_NAME.Trim() == fileName.Trim());
                    _devTreatmentFileDAO.Remove(opRecord);
                    _logger.LogInformation(String.Format(@"******DKSController EditPicF340Ppd Delete a Picture: {0}!! ******", fileName));
                }
            }
            await _devTreatmentDAO.SaveAll();

            await _devTreatmentFileDAO.SaveAll();

            return(Ok(model));
        }
Пример #2
0
        public IActionResult ResolveDiscover(string idJob, string IdDiscoverItem, Dictionary <string, string> DissambiguationProblemsResolve)
        {
            DiscoverItem item = _discoverItemService.GetDiscoverItemById(new Guid(IdDiscoverItem));

            //Cargamos el RDF
            RohGraph dataGraph = new RohGraph();

            dataGraph.LoadFromString(item.DiscoverRdf, new RdfXmlParser());

            //Modificamos el RDF
            TripleStore store = new TripleStore();

            store.Add(dataGraph);
            //Cambiamos candidato.Key por entityID
            foreach (string uriOriginal in DissambiguationProblemsResolve.Keys)
            {
                if (!string.IsNullOrEmpty(DissambiguationProblemsResolve[uriOriginal]))
                {
                    //En caso de que la resolución sea una URI de Unidata añadimos el SameAs
                    if (!string.IsNullOrEmpty(_unidataPrefix.GetUnidataDomain()) && DissambiguationProblemsResolve[uriOriginal].StartsWith(_unidataPrefix.GetUnidataDomain()))
                    {
                        IUriNode t_subject   = dataGraph.CreateUriNode(UriFactory.Create(uriOriginal));
                        IUriNode t_predicate = dataGraph.CreateUriNode(UriFactory.Create("http://www.w3.org/2002/07/owl#sameAs"));
                        IUriNode t_object    = dataGraph.CreateUriNode(UriFactory.Create(DissambiguationProblemsResolve[uriOriginal]));
                        dataGraph.Assert(new Triple(t_subject, t_predicate, t_object));
                    }
                    else
                    {
                        //En caso de que la resolución NO sea una URI de Unidata modificamos las URLs
                        SparqlUpdateParser parser = new SparqlUpdateParser();
                        //Actualizamos los sujetos
                        SparqlUpdateCommandSet updateSubject = parser.ParseFromString(@"DELETE { ?s ?p ?o. }
                                                                    INSERT{<" + DissambiguationProblemsResolve[uriOriginal] + @"> ?p ?o.}
                                                                    WHERE 
                                                                    {
                                                                        ?s ?p ?o.   FILTER(?s = <" + uriOriginal + @">)
                                                                    }");
                        //Actualizamos los objetos
                        SparqlUpdateCommandSet   updateObject = parser.ParseFromString(@"DELETE { ?s ?p ?o. }
                                                                    INSERT{?s ?p <" + DissambiguationProblemsResolve[uriOriginal] + @">.}
                                                                    WHERE 
                                                                    {
                                                                        ?s ?p ?o.   FILTER(?o = <" + uriOriginal + @">)
                                                                    }");
                        LeviathanUpdateProcessor processor    = new LeviathanUpdateProcessor(store);
                        processor.ProcessCommandSet(updateSubject);
                        processor.ProcessCommandSet(updateObject);
                    }
                }
            }

            System.IO.StringWriter sw           = new System.IO.StringWriter();
            RdfXmlWriter           rdfXmlWriter = new RdfXmlWriter();

            rdfXmlWriter.Save(dataGraph, sw);
            string   rdfXml = sw.ToString();
            Stream   stream = new MemoryStream(Encoding.UTF8.GetBytes(rdfXml));
            FormFile file   = new FormFile(stream, 0, stream.Length, "rdfFile", "rdf.xml");

            //Actualizamos el item
            Dictionary <string, List <string> > discards = new Dictionary <string, List <string> >();

            foreach (DiscoverItem.DiscoverDissambiguation dissambiguation in item.DissambiguationProblems)
            {
                if (DissambiguationProblemsResolve.ContainsKey(dissambiguation.IDOrigin) && DissambiguationProblemsResolve[dissambiguation.IDOrigin] == null)
                {
                    discards.Add(dissambiguation.IDOrigin, dissambiguation.DissambiguationCandiates.Select(x => x.IDCandidate).ToList());
                }
            }

            item.UpdateDissambiguationDiscards(discards, rdfXml);
            item.DiscoverRdf = rdfXml;
            item.Status      = "Pending";

            _discoverItemService.ModifyDiscoverItem(item);

            //Lo reencolamos corregido junto con su identificador
            _callEDtlPublishService.CallDataPublish(file, idJob, false, IdDiscoverItem);

            return(RedirectToAction("DetailsJob", "Job", new { id = idJob }));
        }
Пример #3
0
        /// <summary>
        /// Upload an image to blob storage
        /// </summary>
        /// <param name="container">The container to upload the blob to.
        /// Container is an enum.</param>
        /// <param name="formFile">The FormFile object which contains the byte data and meta-data
        /// for the file being uploaded.</param>
        /// <returns>A Image object which contains the guid filename given to the blob in blob storage.
        /// This object also contains the URL that you can use to access the blob file from online.</returns>
        public async Task <Image> UploadImage(ContainerName container, FormFile formFile)
        {
            Guid blobName = Guid.NewGuid();

            return(await UploadOrReplaceImage(container, formFile, blobName));
        }
        private ApiResult GenerateQrCodeImg(QrCodeDataModel model, out UserFileInfo jpgFile, out UserFileInfo svgFile)
        {
            var      fileNameRaw = $"{model.Data}_{model.Margin}_{model.Icon}_{model.LightColor}_{model.DarkColor}_{model.Size}";
            var      fileName    = $"{fileNameRaw.ToMd5()}";
            var      imgFileName = $"{fileName}.jpg";
            var      svgFileName = $"{fileName}.svg";
            UserFile iconFileRaw = null;

            if (model.Icon?.FileName != null)
            {
                Guid.TryParse(model.Icon.FileName, out var fid);
                if (fid != Guid.Empty)
                {
                    iconFileRaw = _fileServices.Download(fid);
                }
            }

            Bitmap icon = null;

            if (iconFileRaw != null)
            {
                using (var iconMs = new MemoryStream(iconFileRaw.Data))
                {
                    icon = new Bitmap(iconMs);
                }
            }
            jpgFile = _fileServices.Load(QRCodePath, imgFileName);
            svgFile = _fileServices.Load(QRCodePath, svgFileName);
            if (jpgFile != null && svgFile != null)
            {
                return(null);
            }
            if (model == null)
            {
                return(ActionStatusMessage.StaticMessage.QrCode.NoData);
            }
            var rawText = model.Data;

            if (rawText == null)
            {
                return(ActionStatusMessage.StaticMessage.QrCode.NoData);
            }
            var qrCodeData = new QRCoder.QRCodeGenerator().CreateQrCode(rawText, QRCodeGenerator.ECCLevel.H);
            var svg        = new SvgQRCode(qrCodeData).GetGraphic(model.Size, model.DarkColor, model.LightColor, true, SvgQRCode.SizingMode.ViewBoxAttribute);
            var bitmap     = new QRCode(qrCodeData).GetGraphic(model.Size, ColorTranslator.FromHtml(model.DarkColor), ColorTranslator.FromHtml(model.LightColor), icon, model.Icon?.IconSize ?? 15, model.Icon?.BorderSize ?? 6, model?.Margin ?? false);

            if (jpgFile == null)
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    bitmap.Save(stream, ImageFormat.Jpeg);
                    var imgf = new FormFile(stream, 0, stream.Length, imgFileName, imgFileName);
                    jpgFile = _fileServices.Upload(imgf, QRCodePath, imgFileName, Guid.Empty, Guid.Empty).Result;
                }
            }
            if (svgFile == null)
            {
                using (var sr = new MemoryStream())
                {
                    sr.Write(Encoding.UTF8.GetBytes(svg));
                    var svgf = new FormFile(sr, 0, sr.Length, svgFileName, svgFileName);
                    svgFile = _fileServices.Upload(svgf, QRCodePath, svgFileName, Guid.Empty, Guid.Empty).Result;
                }
            }
            return(null);
        }
Пример #5
0
        public async Task Invoke(HttpContext context)
        {
            HttpRequest request = context.Request;
            FormFile    file    = null;

            try
            {
                file = (FormFile)request.Form.Files["data"];
            }
            catch (InvalidOperationException)
            {
                // Do nothing because the file isn't available
                // and that doesn't necessary indicate an error.
                // TODO: Find a better solution for this...
            }

            if (file != null)
            {
                Boolean compression = request.Form["c"] == "1";
                Stream  newBody     = file.OpenReadStream();

                if (compression)
                {
                    // GZipStream cannot be reused, so I need to copy the data out of it
                    using (GZipStream gzipStream = new GZipStream(newBody, CompressionMode.Decompress))
                    {
                        newBody = new MemoryStream();
                        await gzipStream.CopyToAsync(newBody);

                        newBody.Seek(0, SeekOrigin.Begin);
                    }
                }

                // The client doesn't inform us of the datatype of the data sent.
                // So I need to attempt to decode the data as JSON, and if it fails, then
                // assume the data is binary.
                try
                {
                    using (var reader = new StreamReader(newBody,
                                                         Encoding.UTF8,
                                                         false,
                                                         1024,
                                                         true
                                                         ))
                    {
                        JToken.ReadFrom(new JsonTextReader(reader));
                    }

                    request.ContentType = "application/json";
                }
                catch (JsonReaderException jex)
                {
                    Console.WriteLine(jex.Message);
                }
                finally
                {
                    newBody.Seek(0, SeekOrigin.Begin);
                }

                context.Request.Body = newBody;
            }

            await _next(context);
        }
        private DynamicForm SetupForm()
        {
            //1. Setup Form definition
            DynamicForm model = new DynamicForm();

            model.Add("Text", "David");
            model.Add("Email", "");
            model.Add("Website", "");
            model.Add("PhoneNumber", "");
            model.Add("TextArea", "");
            model.Add("Number", 0);
            model.Add("Slider", 50);

            decimal currency = 0;

            model.Add("Currency", currency);
            model.Add("Date", new DateTime());
            model.Add("DateTime", new DateTime());
            model.Add("Dropdown", "");
            model.Add("DropdownMany", new List <string>());
            model.Add("RadioList", "");
            model.Add("RadioListButtons", "");
            model.Add("CheckboxList", new List <string>());
            model.Add("CheckboxListButtons", new List <string>());
            model.Add("Checkbox", false);
            model.Add("YesButton", false);

            model.Add("YesNo", "");
            model.Add("YesNoButtons", "");

            model.Add("YesNoButtonsBoolean", false);

            model.Add("TrueFalse", "");
            model.Add("TrueFalseButtons", "");
            model.Add("TrueFalseButtonsBoolean", false);

            FormFile formFile = new FormFile(null, 0, 0, "", "");

            model.Add("File", formFile);
            model.Add("MultipleFiles", new List <FormFile>()
            {
            });
            model.Add("MultipleMediaFiles", new List <FormFile>()
            {
            });

            //2. Add Display and Validation
            model.AddAttribute("Text", new DisplayAttribute()
            {
                Name = "What is your Name?"
            });
            model.AddAttribute("Email", new DataTypeAttribute(DataType.EmailAddress));
            model.AddAttribute("Email", new HelpTextAttribute("Your personal email please"));
            model.AddAttribute("PhoneNumber", new DataTypeAttribute(DataType.PhoneNumber));
            model.AddAttribute("Website", new DataTypeAttribute(DataType.Url));
            model.AddAttribute("TextArea", new MultilineTextAttribute(5));

            model.AddAttribute("Number", new NumberValidatorAttribute());

            model.AddAttribute("Slider", new SliderAttribute(0, 100));

            //text-success
            model.Add("SectionHeading", "");
            model.AddAttribute("SectionHeading", new HeadingAttributeH3("text-danger"));

            //  model.AddAttribute("Dropdown", new DropdownAttribute(Type.GetType("DND.Domain.Blog.Tags.Tag, DND.Domain.Blog"), "Name", "Name"));
            // model.AddAttribute("DropdownMany", new DropdownAttribute(Type.GetType("DND.Domain.Blog.Tags.Tag, DND.Domain.Blog"), "Name", "Name"));

            // model.AddAttribute("RadioList", new CheckboxOrRadioAttribute(Type.GetType("DND.Domain.Blog.Tags.Tag, DND.Domain.Blog"), "Name", "Name"));
            model.AddAttribute("RadioListButtons", new CheckboxOrRadioButtonsAttribute(new List <string>()
            {
                "Option 1", "Option 2", "Option 3", "Option 4"
            }));

            //  model.AddAttribute("CheckboxList", new CheckboxOrRadioAttribute(Type.GetType("DND.Domain.Blog.Tags.Tag, DND.Domain.Blog"), "Name", "Name"));
            //wrapper.AddAttribute("CheckboxList", new CheckboxOrRadioInlineAttribute());
            model.AddAttribute("CheckboxList", new LimitCountAttribute(3, 5));

            model.AddAttribute("CheckboxListButtons", new CheckboxOrRadioButtonsAttribute(new List <string>()
            {
                "Option 1", "Option 2", "Option 3", "Option 4"
            }));

            model.AddAttribute("Currency", new DataTypeAttribute(DataType.Currency));

            model.AddAttribute("Date", new DataTypeAttribute(DataType.Date));
            model.AddAttribute("Date", new AgeValidatorAttribute(18));

            model.AddAttribute("DateTime", new DataTypeAttribute(DataType.DateTime));

            model.AddAttribute("YesButton", new BooleanYesButtonAttribute());

            model.AddAttribute("YesNo", new YesNoCheckboxOrRadioAttribute());
            model.AddAttribute("YesNo", new CheckboxOrRadioInlineAttribute());

            model.AddAttribute("YesNoButtons", new YesNoCheckboxOrRadioButtonsAttribute());

            model.AddAttribute("YesNoButtonsBoolean", new BooleanYesNoButtonsAttribute());

            model.AddAttribute("TrueFalse", new TrueFalseCheckboxOrRadioAttribute());
            model.AddAttribute("TrueFalse", new CheckboxOrRadioInlineAttribute());

            model.AddAttribute("TrueFalseButtons", new TrueFalseCheckboxOrRadioButtonsAttribute());

            model.AddAttribute("TrueFalseButtonsBoolean", new BooleanTrueFalseButtonsAttribute());

            model.AddAttribute("MultipleMediaFiles", new FileImageAudioVideoAcceptAttribute());

            model.Add("Submit", "");
            model.AddAttribute("Submit", new NoLabelAttribute());
            model.AddAttribute("Submit", new SubmitButtonAttribute("btn btn-block btn-success"));

            return(model);
        }
        public void UploadUploadFile_WithoutException_ReturnOK()
        {
            string header = "Konstruksi,Benang,Anyaman,Lusi,Pakan,Lebar,JL,JP,AL,AP,Grade,Piece,Qty,QtyPiece,Barcode,ProductionOrderDate";
            string isi    = "Konstruksi,Benang,Anyaman,Lusi,Pakan,Lebar,JL,JP,AL,AP,Grade,1,1,1,15-09,01/01/2020";

            //---continue
            var mockFacade = new Mock <IInventoryWeavingDocumentOutService>();

            mockFacade.Setup(f => f.UploadData(It.IsAny <InventoryWeavingDocument>(), It.IsAny <string>())).Returns(Task.CompletedTask);
            mockFacade.Setup(f => f.CsvHeaderUpload).Returns(header.Split(',').ToList());
            mockFacade.Setup(f => f.UploadValidate(ref It.Ref <List <InventoryWeavingUploadCsvOutViewModel> > .IsAny, It.IsAny <List <KeyValuePair <string, StringValues> > >())).Returns(new Tuple <bool, List <object> >(true, new List <object>()));

            var MockMapper = new Mock <IMapper>();

            var model = new InventoryWeavingDocument()
            {
                Date        = DateTimeOffset.Now,
                BonNo       = "test01",
                BonType     = "PRODUKSI",
                StorageCode = "test01",
                StorageId   = 2,
                StorageName = "Test",

                Type   = "OUT",
                Remark = "Remark",
                Items  = new List <InventoryWeavingDocumentItem>()
                {
                    new InventoryWeavingDocumentItem()
                    {
                        ProductOrderName           = "product",
                        ReferenceNo                = "referencce",
                        Construction               = "CD",
                        Grade                      = "A",
                        Piece                      = "1",
                        MaterialName               = "CD",
                        WovenType                  = "",
                        Yarn1                      = "yarn1",
                        Yarn2                      = "yarn2",
                        YarnType1                  = "yt1",
                        YarnType2                  = "yt2",
                        YarnOrigin1                = "yo1",
                        YarnOrigin2                = "yo2",
                        Width                      = "1",
                        UomUnit                    = "MTR",
                        UomId                      = 1,
                        Quantity                   = 1,
                        QuantityPiece              = 1,
                        ProductRemark              = "",
                        Barcode                    = "15-09",
                        ProductionOrderDate        = Convert.ToDateTime("01/01/2020"),
                        InventoryWeavingDocumentId = 1,
                    }
                }
            };

            MockMapper.Setup(x => x.Map <List <InventoryWeavingDocument> >(It.IsAny <List <InventoryWeavingUploadCsvOutViewModel> >())).Returns(new List <InventoryWeavingDocument>()
            {
                model
            });

            var mockIdentityService = new Mock <IIdentityService>();
            var mockValidateService = new Mock <IValidateService>();
            var mockMapperService   = new Mock <IMapper>();

            var controller = GetController((mockIdentityService, mockValidateService, mockFacade, mockMapperService));

            controller.ControllerContext.HttpContext.Request.Headers["x-timezone-offset"] = $"{It.IsAny<int>()}";
            controller.ControllerContext.HttpContext.Request.Headers.Add("Content-Type", "multipart/form-data");
            var file = new FormFile(new MemoryStream(Encoding.UTF8.GetBytes(header + "\n" + isi)), 0, Encoding.UTF8.GetBytes(header + "\n" + isi).LongLength, "Data", "test.csv");

            controller.ControllerContext.HttpContext.Request.Form = new FormCollection(new Dictionary <string, StringValues>(), new FormFileCollection {
                file
            });

            var response = controller.postCsvFileAsync("PRODUKSI", DateTime.Now);

            Assert.NotNull(response.Result);
        }
        public void SetUp()
        {
            estate = new Estate();
            var user = new User();

            sourceCharacter = new Character();
            targetCharacter = new Character();
            user.Characters.Add(new TestCharacter().SetEstate(estate));
            user.Characters.Add(sourceCharacter);
            user.Characters.Add(targetCharacter);

            file = new FormFile(new MemoryStream(Encoding.UTF8.GetBytes("This is a dummy file")), 0, 0, "Data",
                                "dummy.txt");

            addObjectProtectionRequest = new AddObjectProtectionRequest
            {
                ProtectionType = ObjectProtectionType.Estate,
                ObjectId       = estate.Id,
                Amount         = 1
            };

            addSerialSlotRequest = new AddSerialSlotRequest
            {
                Amount = 1
            };

            var characters = new List <Character>
            {
                new TestCharacter().SetEstate(estate),
                new TestCharacter()
            };

            database                  = new Mock <IDatabase>();
            characterService          = new Mock <ICharacterService>();
            userService               = new Mock <IUserService>();
            purchaseService           = new Mock <IPurchaseService>();
            adminActionService        = new Mock <IAdminActionService>();
            emailSender               = new Mock <IEmailSender>();
            mtaManager                = new Mock <IMtaManager>();
            orderService              = new Mock <IOrderService>();
            premiumUserLibraryManager = new Mock <IPremiumUserLibraryManager>();
            tempDatabaseCleaner       = new Mock <ITempDatabaseCleaner>();
            filesManager              = new Mock <IFilesManager>();
            customInteriorManager     = new Mock <ICustomInteriorManager>();
            httpContextReader         = new Mock <IHttpContextReader>();

            database.Setup(d => d.CharacterRepository.GetAccountCharactersWithEstatesAndVehicles(It.IsAny <int>()))
            .ReturnsAsync(characters);
            database.Setup(d => d.BeginTransaction()).Returns(new DatabaseTransaction());
            database.Setup(d => d.EstateRepository.Update(It.IsNotNull <Estate>())).ReturnsAsync(true);
            database.Setup(d => d.UserRepository.FindById(It.IsAny <int>())).ReturnsAsync(user);
            database.Setup(d => d.UserRepository.Update(It.IsAny <User>())).ReturnsAsync(true);
            database.Setup(d => d.CharacterRepository.Find(It.IsAny <string>()))
            .ReturnsAsync(new Character());
            userService.Setup(us => us.GetUserWithCharacters(It.IsAny <int>())).ReturnsAsync(user);
            characterService.Setup(cs => cs.HasAnyCharacterEstate(It.IsAny <IEnumerable <Character> >(), It.IsAny <int>()))
            .ReturnsAsync(estate);
            purchaseService.Setup(ps => ps.CreatePurchase(It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>()))
            .ReturnsAsync(new Purchase());
            orderService.Setup(os => os.CreateOrder(It.IsAny <Order>())).ReturnsAsync(new Order());
            premiumUserLibraryManager.Setup(pm => pm.AddFileToLibrary(It.IsAny <IFormFile>(),
                                                                      It.IsAny <PremiumFileType>(), It.IsAny <string>(), It.IsAny <int?>()))
            .ReturnsAsync(new PremiumFile());
            SetUpDefaultExecuteTransferCharacter();

            premiumAccountManager = new PremiumAccountManager(database.Object, characterService.Object,
                                                              userService.Object, purchaseService.Object, adminActionService.Object, emailSender.Object,
                                                              mtaManager.Object, orderService.Object, premiumUserLibraryManager.Object, tempDatabaseCleaner.Object,
                                                              filesManager.Object, customInteriorManager.Object, httpContextReader.Object);
        }
Пример #9
0
        public async Task <IActionResult> Speaking(SpeakingTestPaper paper, string audioBase64)
        {
            if (paper == null)
            {
                this.NotifyError("Not found yor test");
                return(Json(new { status = false, message = string.Empty, location = "/" }));
            }

            if (paper.PiceOfTestId <= 0)
            {
                this.NotifyError("Not found yor test");
                return(Json(new { status = false, message = string.Empty, location = "/" }));
            }

            // Lấy người dùng hiện tại
            var owner = _UserManager.Get(User.Id());

            // Nếu không tìm thấy người này là ai
            if (owner == null)
            {
                this.NotifyError("You are not authorized to view or manipulate this test");
                return(Json(new { status = false, message = string.Empty, location = "/" }));
            }

            // Sau khi hoàn tất lọc các lỗi, tiến hành xử lý, đếm số câu đúng
            PieceOfTest piece = _PieceOfTestManager.Get(paper.PiceOfTestId);

            if (piece == null)
            {
                this.NotifyError("Not found yor test");
                return(Json(new { status = false, message = string.Empty, location = "/" }));
            }

            if (piece.InstructorId != User.Id() && piece.UserId != User.Id())
            {
                this.NotifyError("You are not authorized to view or manipulate this test");
                return(Json(new { status = false, message = string.Empty, location = "/" }));
            }

            string fileName = $"{owner.Username.ToLower()}_{piece.TypeCode}_{piece.Id}";

            // Thời gian hoàn tất
            float timeToFinished = DateTime.UtcNow.Subtract((DateTime)piece.CreatedTime).TotalSeconds.ToFloat();

            if (!string.IsNullOrEmpty(audioBase64))
            {
                // Chuyển base64 thành stream
                var bytes        = Convert.FromBase64String(audioBase64.Replace("data:audio/mpeg;base64,", ""));
                var memoryStream = new MemoryStream(bytes);

                // Tạo tệp tin
                IFormFile file = new FormFile(memoryStream, 0, bytes.Length, null, $"{fileName}.mp3")
                {
                    Headers     = new HeaderDictionary(),
                    ContentType = "audio/mpeg"
                };

                // Nếu file null
                if (file == null)
                {
                    return(Json(new { status = false, message = "Can not upload your audio, please try again!", location = "/" }));
                }

                // Tiến hành lưu tệp tin cho người dùng
                string path = await host.UploadForUserAudio(file, owner);

                // Nếu path không đúng
                if (string.IsNullOrEmpty(path))
                {
                    return(Json(new { status = false, message = "Can not upload your speaking, please try again!", location = "/" }));
                }

                // Cập nhật đường dẫn bài nói của HV cho bài thi
                paper.SpeakingPart.UserAudioPath = path;
            }

            // Cập nhật dữ liệu
            piece.ResultOfUserJson = JsonConvert.SerializeObject(paper);

            // Chưa có điểm tổng
            piece.Scores = -1;

            // Cập nhật thời gian kết thúc
            piece.TimeToFinished = timeToFinished;

            // Cập nhật vào CSDL
            _PieceOfTestManager.Update(piece);

            // Chuyển đến trang kết quả
            return(Json(new { status = true, message = "Successful submission of exams", location = $"{Url.Action(nameof(Result), NameUtils.ControllerName<TestPaperController>())}/{piece.Id}" }));
        }
Пример #10
0
        /// <summary>
        /// Convert IFormFile to string
        /// </summary>
        /// <param name="equipmentFiles"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        private IFormFile Base64ToImage(string equipmentFiles, string name)
        {
            IFormFile file = new FormFile(null, 0, 1, name, equipmentFiles);

            return(file);
        }
Пример #11
0
        static EventWorkflowHelperData()
        {
            eventEntity = new EventEntity
            {
                EventId    = "ad4b2b43-1cb5-408d-ab8a-17e28edac2baz-1234-2345",
                TeamId     = "ad4b2b43-1cb5-408d-ab8a-17e28edac2baz-1234",
                Audience   = 3,
                CategoryId = "088ddf0d-4deb-4e95-b1f3-907fc4511b02",
                AutoRegisteredAttendees = "",
                CategoryName            = "Test_Category",
                CreatedBy                   = "Jack",
                CreatedOn                   = new DateTime(2020, 09, 24),
                Description                 = "Teams Event",
                EndDate                     = new DateTime(2020, 09, 25),
                EndTime                     = new DateTime(2020, 09, 25),
                ETag                        = "",
                GraphEventId                = "088ddf0d-4deb-4e95-b1f3-907fc4511b02g",
                IsAutoRegister              = false,
                IsRegistrationClosed        = false,
                IsRemoved                   = false,
                MandatoryAttendees          = "",
                MaximumNumberOfParticipants = 10,
                MeetingLink                 = "",
                Name                        = "Mandaotory Training Event",
                NumberOfOccurrences         = 1,
                OptionalAttendees           = "",
                Photo                       = "https://testurl/img.png",
                StartDate                   = new DateTime(2020, 09, 25),
                StartTime                   = new DateTime(2020, 09, 25),
                UpdatedBy                   = "Jack",
                Venue                       = "",
                SelectedUserOrGroupListJSON = "",
                RegisteredAttendeesCount    = 0,
                Type                        = 0,
                RegisteredAttendees         = ""
            };

            validEventEntity = new EventEntity
            {
                EventId    = "ad4b2b43-1cb5-408d-ab8a-17e28edac2baz-1234-2345",
                TeamId     = "ad4b2b43-1cb5-408d-ab8a-17e28edac2baz-1234",
                Audience   = 1,
                CategoryId = "088ddf0d-4deb-4e95-b1f3-907fc4511b02",
                AutoRegisteredAttendees = "",
                CategoryName            = "Test_Category",
                CreatedBy                   = "Jack",
                CreatedOn                   = DateTime.UtcNow,
                Description                 = "Teams Event",
                EndDate                     = DateTime.UtcNow.AddDays(4).Date,
                EndTime                     = DateTime.UtcNow.AddDays(4).Date,
                ETag                        = "",
                GraphEventId                = "088ddf0d-4deb-4e95-b1f3-907fc4511b02g",
                IsAutoRegister              = false,
                IsRegistrationClosed        = false,
                IsRemoved                   = false,
                MandatoryAttendees          = "",
                MaximumNumberOfParticipants = 10,
                MeetingLink                 = "",
                Name                        = "Mandaotory Training Event",
                NumberOfOccurrences         = 1,
                OptionalAttendees           = "",
                Photo                       = "https://www.testurl.com/img.png",
                StartDate                   = DateTime.UtcNow.AddDays(2).Date,
                StartTime                   = DateTime.UtcNow.AddDays(2).Date,
                UpdatedBy                   = "Jack",
                Venue                       = "",
                SelectedUserOrGroupListJSON = "",
                RegisteredAttendeesCount    = 0,
                Type                        = 2,
                RegisteredAttendees         = ""
            };

            eventEntities = new List <EventEntity>()
            {
                new EventEntity
                {
                    EventId      = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-888",
                    CategoryId   = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba",
                    CategoryName = ""
                },
                new EventEntity
                {
                    EventId      = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999",
                    CategoryId   = "ad4b2b43-1cb5-408d-ab8a-17e28edac3ba",
                    CategoryName = ""
                }
            };

            category = new Category
            {
                CategoryId  = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba",
                Name        = "Test_Category_1",
                Description = "Description",
                CreatedBy   = "ad4b2b43-1cb5-408d-ab8a-17e28edacabc",
                CreatedOn   = DateTime.UtcNow,
                UpdatedOn   = DateTime.UtcNow,
            };

            categoryList = new List <Category>
            {
                new Category
                {
                    CategoryId  = "ad4b2b43-1cb5-408d-ab8a-17e28edac1ba",
                    Name        = "Test_Category_1",
                    Description = "Description",
                    CreatedBy   = "ad4b2b43-1cb5-408d-ab8a-17e28edacabc",
                    CreatedOn   = DateTime.UtcNow,
                    UpdatedOn   = DateTime.UtcNow,
                    IsInUse     = false,
                },
                new Category
                {
                    CategoryId  = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba",
                    Name        = "Test_Category_1",
                    Description = "Description",
                    CreatedBy   = "ad4b2b43-1cb5-408d-ab8a-17e28edacabc",
                    CreatedOn   = DateTime.UtcNow,
                    UpdatedOn   = DateTime.UtcNow,
                    IsInUse     = false,
                },
                new Category
                {
                    CategoryId  = "ad4b2b43-1cb5-408d-ab8a-17e28edac3ba",
                    Name        = "Test_Category_1",
                    Description = "Description",
                    CreatedBy   = "ad4b2b43-1cb5-408d-ab8a-17e28edacabc",
                    CreatedOn   = DateTime.UtcNow,
                    UpdatedOn   = DateTime.UtcNow,
                    IsInUse     = false,
                }
            };

            teamEvent = new Event
            {
                Subject = "Teams Event",
                Body    = new ItemBody
                {
                    ContentType = BodyType.Html,
                    Content     = eventEntity.Type == (int)EventType.LiveEvent ?
                                  $"{eventEntity.Description}<br/><br/><a href='{eventEntity.MeetingLink}'>{eventEntity.MeetingLink}</a>" :
                                  eventEntity.Description,
                },
                Attendees        = new List <Attendee>(),
                OnlineMeetingUrl = eventEntity.Type == (int)EventType.LiveEvent ? eventEntity.MeetingLink : null,
                IsReminderOn     = true,
                Location         = eventEntity.Type == (int)EventType.InPerson ? new Location
                {
                    Address = new PhysicalAddress {
                        Street = eventEntity.Venue
                    },
                }
                    : null,
                AllowNewTimeProposals = false,
                IsOnlineMeeting       = true,
                OnlineMeetingProvider = OnlineMeetingProviderType.TeamsForBusiness,
                Id = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-rrtyy"
            };

            lndTeam = new LnDTeam
            {
                ETag         = "",
                PartitionKey = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999",
                TeamId       = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-000",
                RowKey       = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-000"
            };

            graphUser = new Graph.User
            {
                DisplayName       = "Jack",
                UserPrincipalName = "Jack",
                Id   = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-001",
                Mail = "*****@*****.**"
            };

            graphUsers = new List <Graph.User>()
            {
                new Graph.User
                {
                    DisplayName       = "Jack",
                    UserPrincipalName = "Jack",
                    Id   = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-001",
                    Mail = "*****@*****.**"
                },
                new Graph.User
                {
                    DisplayName       = "Jack",
                    UserPrincipalName = "Jack",
                    Id   = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-002",
                    Mail = "*****@*****.**"
                },
                new Graph.User
                {
                    DisplayName       = "Jack",
                    UserPrincipalName = "Jack",
                    Id   = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-003",
                    Mail = "*****@*****.**"
                }
            };

            graphGroups = new List <Graph.Group>()
            {
                new Graph.Group
                {
                    DisplayName = "Jack",
                    Id          = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-001",
                    Mail        = "*****@*****.**"
                },
                new Graph.Group
                {
                    DisplayName = "Jack",
                    Id          = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-002",
                    Mail        = "*****@*****.**"
                },
                new Graph.Group
                {
                    DisplayName = "Jack",
                    Id          = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-003",
                    Mail        = "*****@*****.**"
                }
            };

            graphGroupDirectoryObject = new List <Graph.DirectoryObject>()
            {
                new Graph.DirectoryObject
                {
                    Id = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-001"
                },
                new Graph.DirectoryObject
                {
                    Id = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-002"
                },
                new Graph.DirectoryObject
                {
                    Id = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-003"
                }
            };

            fileInfo = new FormFile(new MemoryStream(), 1, 1, "sample.jpeg", "sample.jpeg");

            teamsChannelAccount = new List <TeamsChannelAccount>()
            {
                new TeamsChannelAccount
                {
                    GivenName         = "sam",
                    UserPrincipalName = "s"
                },
                new TeamsChannelAccount
                {
                    GivenName         = "jack",
                    UserPrincipalName = "j"
                }
            };

            teamEvent = new Event
            {
                Subject = "Teams Event",
                Body    = new ItemBody
                {
                    ContentType = BodyType.Html,
                    Content     = eventEntity.Type == (int)EventType.LiveEvent ?
                                  $"{eventEntity.Description}<br/><br/><a href='{eventEntity.MeetingLink}'>{eventEntity.MeetingLink}</a>" :
                                  eventEntity.Description,
                },
                Attendees        = new List <Attendee>(),
                OnlineMeetingUrl = eventEntity.Type == (int)EventType.LiveEvent ? eventEntity.MeetingLink : null,
                IsReminderOn     = true,
                Location         = eventEntity.Type == (int)EventType.InPerson ? new Location
                {
                    Address = new PhysicalAddress {
                        Street = eventEntity.Venue
                    },
                }
                    : null,
                AllowNewTimeProposals = false,
                IsOnlineMeeting       = true,
                OnlineMeetingProvider = OnlineMeetingProviderType.TeamsForBusiness,
                Id = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-rrtyy"
            };

            lndTeam = new LnDTeam
            {
                ETag         = "",
                PartitionKey = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999",
                TeamId       = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-000",
                RowKey       = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-000"
            };

            graphUser = new Graph.User
            {
                DisplayName       = "Jack",
                UserPrincipalName = "Jack",
                Id   = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-001",
                Mail = "*****@*****.**"
            };

            graphUsers = new List <Graph.User>()
            {
                new Graph.User
                {
                    DisplayName       = "Jack",
                    UserPrincipalName = "Jack",
                    Id   = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-001",
                    Mail = "*****@*****.**"
                },
                new Graph.User
                {
                    DisplayName       = "Jack",
                    UserPrincipalName = "Jack",
                    Id   = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-002",
                    Mail = "*****@*****.**"
                },
                new Graph.User
                {
                    DisplayName       = "Jack",
                    UserPrincipalName = "Jack",
                    Id   = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-003",
                    Mail = "*****@*****.**"
                }
            };

            graphGroups = new List <Graph.Group>()
            {
                new Graph.Group
                {
                    DisplayName = "Jack",
                    Id          = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-001",
                    Mail        = "*****@*****.**"
                },
                new Graph.Group
                {
                    DisplayName = "Jack",
                    Id          = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-002",
                    Mail        = "*****@*****.**"
                },
                new Graph.Group
                {
                    DisplayName = "Jack",
                    Id          = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-003",
                    Mail        = "*****@*****.**"
                }
            };

            graphGroupDirectoryObject = new List <Graph.DirectoryObject>()
            {
                new Graph.DirectoryObject
                {
                    Id = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-001"
                },
                new Graph.DirectoryObject
                {
                    Id = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-002"
                },
                new Graph.DirectoryObject
                {
                    Id = "ad4b2b43-1cb5-408d-ab8a-17e28edac2ba-445567-999-003"
                }
            };

            fileInfo = new FormFile(new MemoryStream(), 1, 1, "sample.jpeg", "sample.jpeg");

            teamsChannelAccount = new List <TeamsChannelAccount>()
            {
                new TeamsChannelAccount
                {
                    GivenName         = "sam",
                    UserPrincipalName = "s"
                },
                new TeamsChannelAccount
                {
                    GivenName         = "jack",
                    UserPrincipalName = "j"
                }
            };
        }
Пример #12
0
        private async Task <FormCollection> GetMultipartFormCollection(ModificationContext modificationContext)
        {
            var formAccumulator = new KeyValueAccumulator();

            var multipartReader = new MultipartReader(_originalBoundary, modificationContext.ContentStream)
            {
                HeadersCountLimit  = _options.Value.FormOptions.MultipartHeadersCountLimit,
                HeadersLengthLimit = _options.Value.FormOptions.MultipartHeadersLengthLimit,
                BodyLengthLimit    = _options.Value.FormOptions.MultipartBodyLengthLimit,
            };

            var section = await multipartReader.ReadNextSectionAsync();

            while (section != null)
            {
                ContentDispositionHeaderValue contentDisposition;
                ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);

                if (contentDisposition.IsFileDisposition())
                {
                    var fileSection = new FileMultipartSection(section, contentDisposition);

                    await section.Body.DrainAsync(new System.Threading.CancellationToken());

                    FormFile file;

                    if (contentDisposition.FileName == "\"\"")
                    {
                        file = new FormFile(
                            section.Body,
                            0,
                            section.Body.Length,
                            fileSection.Name,
                            fileSection.FileName
                            );
                    }
                    else
                    {
                        file = new FormFile(
                            section.BaseStreamOffset.HasValue ? modificationContext.ContentStream : section.Body,
                            section.BaseStreamOffset.HasValue ? section.BaseStreamOffset.Value : 0,
                            section.Body.Length,
                            fileSection.Name,
                            fileSection.FileName
                            );
                    }

                    file.Headers = new HeaderDictionary(section.Headers);

                    if (_formFiles == null)
                    {
                        _formFiles = new FormFileCollection();
                    }

                    if (_formFiles.Count >= _options.Value.FormOptions.ValueCountLimit)
                    {
                        throw new InvalidDataException($"Form value count limit {_options.Value.FormOptions.ValueCountLimit} exceeded.");
                    }

                    _formFiles.Add(file);
                }
                else if (contentDisposition.IsFormDisposition())
                {
                    var formDataSection = new FormMultipartSection(section, contentDisposition);

                    var value = await formDataSection.GetValueAsync();

                    formAccumulator.Append(formDataSection.Name, value);

                    if (formAccumulator.ValueCount > _options.Value.FormOptions.ValueCountLimit)
                    {
                        throw new InvalidDataException($"Form value count limit {_options.Value.FormOptions.ValueCountLimit} exceeded.");
                    }
                }
                else
                {
                    throw new InvalidDataException($"Unrecognized content-disposition for this section: {section.ContentDisposition}");
                }

                section = await multipartReader.ReadNextSectionAsync();
            }

            if (formAccumulator.HasValues || _formFiles != null)
            {
                return(new FormCollection(formAccumulator.HasValues ? formAccumulator.GetResults() : null, _formFiles));
            }
            else
            {
                return(null);
            }
        }
Пример #13
0
Файл: CFB.cs Проект: Ret4rd/MARS
 public CFB(ICoderBlock algorithm, byte[] c0, FormFile form0)
 {
     _c0        = c0;
     _algorithm = algorithm;
     form       = form0;
 }
Пример #14
0
 /// <summary>
 /// 发布作业
 /// </summary>
 /// <returns><c>true</c>, if job was published, <c>false</c> otherwise.</returns>
 /// <param name="file">form file</param>
 public new bool PublishJobPackage(string clusterName, FormFile file)
 {
     return(base.PublishJobPackage(clusterName, file));
 }
Пример #15
0
        public async Task <IActionResult> Edit(int id, [Bind("ID,Name,Type,PhoneNo,Website,Location,ImageUrl,FileName")] Recycle recycle, List <IFormFile> files, string filename)
        {
            if (id != recycle.ID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                var filepath = Path.GetTempFileName();

                foreach (var FormFile in files)
                {
                    if (FormFile.Length <= 0)
                    {
                        TempData["editmessage"] = "Please upload a proper image file";
                    }

                    else
                    {
                        if (filename != null)
                        {
                            //delete file from blob
                            CloudBlobContainer container1 = GetCloudBlobContainer();
                            CloudBlockBlob     blobfile   = container1.GetBlockBlobReference(filename);
                            string             name       = blobfile.Name;
                            var result = blobfile.DeleteIfExistsAsync().Result;

                            if (result == false)
                            {
                                TempData["message"] = "Unable to delete file";
                            }
                            else
                            {
                                TempData["message"] = "File is deleted";
                            }
                        }
                        //first all, get the container information
                        CloudBlobContainer container = GetCloudBlobContainer();
                        //give a name for the blob
                        CloudBlockBlob blob = container.GetBlockBlobReference(Path.GetFileName(FormFile.FileName));
                        try
                        {
                            using (var stream = FormFile.OpenReadStream())
                            {
                                await blob.UploadFromStreamAsync(stream);
                            }
                        }
                        catch (Exception ex)
                        {
                            TempData["message"] = ex.ToString();
                        }

                        // get the uri of the specific uploaded blob and save it
                        var blobUrl = blob.Uri.AbsoluteUri;
                        recycle.ImageUrl = blobUrl.ToString();
                        recycle.FileName = FormFile.FileName.ToString();
                        _context.Update(recycle);
                        await _context.SaveChangesAsync();

                        return(RedirectToAction(nameof(Index)));
                    }
                }
                try
                {
                    _context.Update(recycle);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!RecycleExists(recycle.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(recycle));
        }
Пример #16
0
 public async Task <string> saveImageToBlobStorage(FormFile file)
 {
     return("test.png");
 }
Пример #17
0
        /// <summary>
        /// 发布作业
        /// </summary>
        /// <returns><c>true</c>, if job was published, <c>false</c> otherwise.</returns>
        /// <param name="file">form file</param>
        public bool PublishJobPackage(string clusterName, FormFile file)
        {
            // 获取当前Manager
            var manager = GetManager(clusterName);

            if (manager == null)
            {
                throw new Exception("没有发现在线的Manager");
            }

            #region 检查作业包

            // 先保存作业包
            string pkgName       = file.FileName;
            string jobName       = pkgName.Substring(0, pkgName.LastIndexOf('.'));
            string uploadJobPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "uploadjobs");
            if (!Directory.Exists(uploadJobPath))
            {
                Directory.CreateDirectory(uploadJobPath);
            }

            var pkgPath = Path.Combine(uploadJobPath, pkgName);
            using (var stream = new FileStream(pkgPath, FileMode.Create))
            {
                file.CopyTo(stream);
            }

            // 然后解压作业包
            string jobPath = Path.Combine(uploadJobPath, jobName);
            if (Directory.Exists(jobPath))
            {
                // 作业包目录删除重建,以保证文件都是最新的
                Directory.Delete(jobPath, true);
                Directory.CreateDirectory(jobPath);
            }

            using (var zip = ZipFile.Open(pkgPath, ZipArchiveMode.Read))
            {
                zip.ExtractToDirectory(jobPath);
            }

            // 读取配置文件
            var jobConfigPath = Path.Combine(jobPath, "job.json");
            var jobConfig     = new JobConfig(jobConfigPath);

            if (string.IsNullOrWhiteSpace(jobConfig.Name) ||
                string.IsNullOrWhiteSpace(jobConfig.FileName) ||
                string.IsNullOrWhiteSpace(jobConfig.JobClassName) ||
                jobConfig.RunTimePlan.Length <= 0)
            {
                throw new Exception("作业配置项缺失,请检查作业名称、可执行文件名称、作业入口类、运行时间计划。");
            }

            var exePath = Path.Combine(jobPath, jobConfig.FileName);
            if (!File.Exists(exePath))
            {
                throw new Exception("作业配置指定的可执行文件不存在。");
            }

            // 设置版本为当前时间
            jobConfig.Version = DateTime.Now.ToString("yyyyMMddHHmmss");

            // 重新写配置文件
            File.WriteAllText(jobConfigPath, JsonConvert.SerializeObject(jobConfig));

            // 将新的配置文件打包
            using (var zip = ZipFile.Open(pkgPath, ZipArchiveMode.Update))
            {
                var entry = zip.GetEntry("job.json");
                entry.Delete();

                zip.CreateEntryFromFile(jobConfigPath, "job.json");
            }
            #endregion

            // 上传到Manager
            string    url    = string.Format("{0}upload/job/package?jobName={1}&jobVersion={2}", manager.CommunicationAddress, jobConfig.Name, jobConfig.Version);
            WebClient client = new WebClient();
            client.UploadData(url, File.ReadAllBytes(pkgPath));

            return(true);
        }
Пример #18
0
        private static async Task SeedRoomTypesAsync(
            ICloudinaryService cloudinaryService,
            IRoomTypesService roomTypesService,
            IWebHostEnvironment env)
        {
            var roomTypes = new AddRoomTypeInputModel[]
            {
                new AddRoomTypeInputModel
                {
                    Name           = "Single room",
                    Price          = 100,
                    CapacityAdults = 1,
                    CapacityKids   = 0,
                    Image          = "pictures/single-room.jpg",
                    Description    = @"Suitable for one adult; LCD TV with cable TV;
Free Wi-Fi access; Individually controlled air conditioning system; 
Separate bathroom and toilet; Non-smoking room; Telephone Hair dryer;",
                },
                new AddRoomTypeInputModel
                {
                    Name           = "Double room",
                    Price          = 150,
                    CapacityAdults = 2,
                    CapacityKids   = 1,
                    Image          = "pictures/double room.jpg",
                    Description    = @"Panoramic window room; Suitable for two adults; 
Individually controlled air conditioning system; LCD TV with cable television; 
Free Wi-Fi Separate beds; Separate bathroom and toilet; Non-smoking room; 
Mini bar; Telephone Hair dryer;",
                },
                new AddRoomTypeInputModel
                {
                    Name           = "Studio",
                    Price          = 200,
                    CapacityAdults = 3,
                    CapacityKids   = 1,
                    Image          = "pictures/club-floor-room.jpg",
                    Description    = @"Each of the spacious studios has a unique vision and interior.
Some of the studios have terraces with wonderful views, as well as baths in the bathrooms. 
The studios at the hotel are equipped with bedrooms, a dressing table, 
a living room with a sofa, armchairs and a coffee table, and the equipment 
includes multi split air conditioners, digital TV, telephone, 
mini bar and wireless internet. Each of the studios bathrooms is supplied with
healing mineral water.",
                },
                new AddRoomTypeInputModel
                {
                    Name           = "Apartment",
                    Price          = 250,
                    CapacityAdults = 4,
                    CapacityKids   = 1,
                    Image          = "pictures/suits.jpg",
                    Description    = @"Stylishly furnished apartments with an area of ​​90 sq.m. consisting
of a separate living and sleeping area and an extra spacious terrace, 
revealing a splendid panoramic view of the mountain.",
                },
            };

            foreach (var type in roomTypes)
            {
                var path = env.WebRootFileProvider.GetFileInfo(type.Image)?.PhysicalPath;

                using (var stream = File.OpenRead(path))
                {
                    var file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
                    {
                        Headers     = new HeaderDictionary(),
                        ContentType = "image/jpg",
                    };

                    type.RoomImage = file;

                    var photoUrl = await cloudinaryService.UploadPhotoAsync(
                        type.RoomImage,
                        $"Room - {type.Name}",
                        "Hotel_room_types_photos");

                    type.Image = photoUrl;
                }

                RoomType roomType = AutoMapperConfig.MapperInstance.Map <RoomType>(type);

                await roomTypesService.AddRoomTypeAsync(roomType);
            }
        }
        private Result <bool> ValidateImageType(FormFile uploadedFile)
        {
            var extension = Path.GetExtension(uploadedFile?.FileName)?.ToLower() ?? string.Empty;

            return(extension == ".jpg" || extension == ".jpeg" || extension == ".png");
        }
Пример #20
0
 public ImageFile ImageFileFromForm(FormFile file)
 {
     return(new PrivateImageFile(file.File));
 }
        private Task <Result <Image> > ConvertAndUpload(Image dbImage, FormFile uploadedFile)
        {
            return(GetBytes()
                   .Ensure(AreDimensionsValid,
                           $"Uploading image size must be at least {MinimumImageWidth}×{MinimumImageHeight} pixels and the width mustn't exceed two heights and vice versa")
                   .Bind(Convert)
                   .Bind(Upload));


            Result <byte[]> GetBytes()
            {
                using var binaryReader = new BinaryReader(uploadedFile.OpenReadStream());
                return(Result.Success(binaryReader.ReadBytes((int)uploadedFile.Length)));
            }

            async Task <bool> AreDimensionsValid(byte[] imageBytes)
            {
                var info = await ImageJob.GetImageInfo(new BytesSource(imageBytes));

                return(MinimumImageWidth <= info.ImageWidth &&
                       MinimumImageHeight <= info.ImageHeight &&
                       info.ImageWidth / info.ImageHeight < 2 &&
                       info.ImageHeight / info.ImageWidth < 2);
            }

            async Task <Result <ImageSet> > Convert(byte[] imageBytes)
            {
                var imagesSet = new ImageSet();

                using var imageJob = new ImageJob();
                var jobResult = await imageJob.Decode(imageBytes)
                                .Constrain(new Constraint(ConstraintMode.Within, ResizedLargeImageMaximumSideSize, ResizedLargeImageMaximumSideSize))
                                .Branch(f => f.ConstrainWithin(ResizedSmallImageMaximumSideSize, ResizedSmallImageMaximumSideSize).EncodeToBytes(new MozJpegEncoder(TargetJpegQuality, true)))
                                .EncodeToBytes(new MozJpegEncoder(TargetJpegQuality, true))
                                .Finish().InProcessAsync();

                imagesSet.SmallImage = GetImage(1);
                imagesSet.MainImage  = GetImage(2);

                return(imagesSet.MainImage.Any() && imagesSet.SmallImage.Any()
                    ? Result.Success(imagesSet)
                    : Result.Failure <ImageSet>("Processing of the images failed"));


                byte[] GetImage(int index)
                {
                    var encodeResult = jobResult?.TryGet(index);
                    var bytes        = encodeResult?.TryGetBytes();

                    return(bytes != null?bytes.Value.ToArray() : new byte[]
                    {
                    });
                }
            }

            async Task <Result <Image> > Upload(ImageSet imageSet)
            {
                dbImage.Position = _dbContext.Images.Count(i => i.ReferenceId == dbImage.ReferenceId && i.ImageType == dbImage.ImageType);
                var entry = _dbContext.Images.Add(dbImage);
                await _dbContext.SaveChangesAsync();

                var imageId = entry.Entity.Id;

                SetImageKeys();

                var addToBucketResult = await AddImagesToBucket();

                if (!addToBucketResult)
                {
                    _dbContext.Images.Remove(entry.Entity);

                    await _dbContext.SaveChangesAsync();

                    return(Result.Failure <Image>("Uploading of the image failed"));
                }

                _dbContext.Images.Update(entry.Entity);

                await _dbContext.SaveChangesAsync();

                _dbContext.DetachEntry(entry.Entity);

                return(Result.Success(dbImage));


                void SetImageKeys()
                {
                    var basePartOfKey = $"{S3FolderName}/{dbImage.ServiceSupplierId}/{imageId}";

                    dbImage.Keys.MainImage  = $"{basePartOfKey}-main.jpg";
                    dbImage.Keys.SmallImage = $"{basePartOfKey}-small.jpg";
                }

                async Task <bool> AddImagesToBucket()
                {
                    await using var largeStream = new MemoryStream(imageSet.MainImage);
                    await using var smallStream = new MemoryStream(imageSet.SmallImage);
                    var imageList = new List <(string key, Stream stream)>
                    {
                        (dbImage.Keys.MainImage, largeStream),
                        (dbImage.Keys.SmallImage, smallStream)
                    };

                    var resultList = await _amazonS3ClientService.Add(_bucketName, imageList);

                    foreach (var result in resultList)
                    {
                        if (result.IsFailure)
                        {
                            var keyList = new List <string>
                            {
                                dbImage.Keys.MainImage,
                                dbImage.Keys.SmallImage
                            };
                            await _amazonS3ClientService.Delete(_bucketName, keyList);

                            return(false);
                        }
                    }

                    return(true);
                }
            }
        }
Пример #22
0
        public static async Task SeedMangas(IHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                var provider = scope.ServiceProvider;

                IMediator mediator = provider.GetRequiredService <IMediator>();

                string mangaInfoPath = Path.Combine(GetSeeededDataDirectory(), "Manga.json");

                MangaUploadCommand manga =
                    JsonConvert.DeserializeObject <MangaUploadCommand>(GetFileContent(mangaInfoPath));

                string mangaId = await mediator.Send(manga);

                string chaptersInfoPath = Path.Combine(GetSeeededDataDirectory(), "Chapters.json");

                List <ChapterUploadCommand> chapters =
                    JsonConvert.DeserializeObject <List <ChapterUploadCommand> >(GetFileContent(chaptersInfoPath));
                List <string> ChapterIds = new List <string>();
                foreach (var chapter in chapters)
                {
                    chapter.MangaId = mangaId;
                    string id = await mediator.Send(chapter);

                    ChapterIds.Add(id);
                }

                string picturesInfoPath = Path.Combine(GetSeeededDataDirectory(), "Pictures.json");

                List <PictureIntermediary> pictures =
                    JsonConvert.DeserializeObject <List <PictureIntermediary> >(GetFileContent(picturesInfoPath));

                Dictionary <string, string> ChapterNumberToChapterId = new Dictionary <string, string>();

                var picturesWithUniqueChapter = pictures
                                                .GroupBy(x => x.Chapter)
                                                .Select(x => x.First())
                                                .ToList();

                for (int i = 0; i < picturesWithUniqueChapter.Count; i++)
                {
                    ChapterNumberToChapterId.TryAdd(picturesWithUniqueChapter[i].Chapter, ChapterIds[i]);
                }

                string pictureLocationBase = Path.Combine(GetSeeededDataDirectory(), "Pictures");

                Dictionary <PictureIntermediary, IFormFile> pictureToFile =
                    new Dictionary <PictureIntermediary, IFormFile>();

                foreach (var picture in pictures)
                {
                    string path = Path.Combine(pictureLocationBase, picture.Chapter, picture.Order);

                    path = Path.ChangeExtension(path, "jpg");

                    FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read);

                    IFormFile formFile = new FormFile(file, 0, file.Length,
                                                      "Alexander", "Oleg.jpg");
                    pictureToFile.Add(picture, formFile);
                }

                List <ImageUploadCommand> images = new List <ImageUploadCommand>();

                foreach (var picture in pictures)
                {
                    var form = pictureToFile.GetValueOrDefault(picture);

                    int order = int.Parse(picture.Order);

                    string ChapterId = ChapterNumberToChapterId.GetValueOrDefault(picture.Chapter);

                    images.Add(new ImageUploadCommand(form, ChapterId, order));
                }

                foreach (var image in images)
                {
                    await mediator.Send(image);
                }
            }
        }
Пример #23
0
 public byte[]  ConvertToByteArray()
 {
     using var ms = new MemoryStream();
     FormFile.CopyTo(ms);
     return(ms.ToArray());
 }
        public async Task When_uploading_a_file_that_is_a_zip()
        {
            var client    = new MemoryBlobClient();
            var store     = new InMemoryStreamStore();
            var validator = new ZipArchiveValidator(Encoding.UTF8);
            var resolver  = Resolve.WhenEqualToMessage(
                new RoadNetworkChangesArchiveCommandModule(
                    client,
                    store,
                    new FakeRoadNetworkSnapshotReader(),
                    validator,
                    SystemClock.Instance
                    )
                );
            var controller = new UploadController(Dispatch.Using(resolver),
                                                  client)
            {
                ControllerContext = new ControllerContext {
                    HttpContext = new DefaultHttpContext()
                }
            };

            using (var sourceStream = new MemoryStream())
            {
                using (var archive = new ZipArchive(sourceStream, ZipArchiveMode.Create, true, Encoding.UTF8))
                {
                    var entry = archive.CreateEntry("entry");
                    using (var entryStream = entry.Open())
                    {
                        entryStream.Write(new byte[] { 1, 2, 3, 4 });
                        entryStream.Flush();
                    }
                }

                sourceStream.Position = 0;

                var formFile = new FormFile(sourceStream, 0L, sourceStream.Length, "name", "name")
                {
                    Headers = new HeaderDictionary(new Dictionary <string, StringValues>
                    {
                        { "Content-Type", StringValues.Concat(StringValues.Empty, "application/zip") }
                    })
                };
                var result = await controller.Post(formFile);

                Assert.IsType <OkResult>(result);

                var page = await store.ReadAllForwards(Position.Start, 1, true);

                var message = Assert.Single(page.Messages);
                Assert.Equal(nameof(Messages.RoadNetworkChangesArchiveUploaded), message.Type);
                var uploaded =
                    JsonConvert.DeserializeObject <Messages.RoadNetworkChangesArchiveUploaded>(
                        await message.GetJsonData());

                Assert.True(await client.BlobExistsAsync(new BlobName(uploaded.ArchiveId)));
                var blob = await client.GetBlobAsync(new BlobName(uploaded.ArchiveId));

                using (var openStream = await blob.OpenAsync())
                {
                    var resultStream = new MemoryStream();
                    openStream.CopyTo(resultStream);
                    resultStream.Position = 0;
                    sourceStream.Position = 0;
                    Assert.Equal(sourceStream.ToArray(), resultStream.ToArray());
                }
            }
        }
Пример #25
0
        public async Task <IActionResult> UpdateBlog(AddBlog blog, int blogid)
        {
            var result = new SuccessResult();

            try
            {
                using (var db = new TryNetCoreContext())
                {
                    var updateblog = db.Blog.Where(i => i.Id == blogid)
                                     .Include(i => i.BlogTags)
                                     .Include(i => i.BlogImages)
                                     .FirstOrDefault();

                    updateblog.BlogName         = blog.blogname;
                    updateblog.BlogAuthor       = blog.blogauthorname;
                    updateblog.BlogCategoryName = blog.blogcategoryname;

                    var blogcount = db.Blog.Count();
                    updateblog.BlogRouteUrl = FriendlyUrl.FriendlyUrlMethod(blog.blogname + "-" + blogcount);

                    if (blog.blogimage != null && blog.blogimage.Length > 0)
                    {
                        updateblog.BlogImagePath = await TryNetCore.Utils.FileUpload.ImageUpload(host.ContentRootPath, blog.blogimage, updateblog.BlogImagePath);
                    }

                    updateblog.BlogTags.Clear();



                    var blogtags = blog.blogtags.Split(',');
                    for (int i = 0; i < blogtags.Length; i++)
                    {
                        updateblog.BlogTags.Add(new BlogTags()
                        {
                            BlogTagName = blogtags[i]
                        });
                    }

                    // ------------------------- //
                    // BLOG CONTENT AGİLİTY PACK //

                    HtmlDocument deletedoc = new HtmlDocument();
                    deletedoc.LoadHtml(updateblog.BlogContent);



                    HtmlDocument doc = new HtmlDocument();
                    doc.LoadHtml(blog.blogcontent);


                    var           htmlimages   = doc.DocumentNode.SelectNodes("//img");
                    List <String> deleteimages = new List <String>();

                    if (htmlimages != null)
                    {
                        foreach (var htmlimage in htmlimages)
                        {
                            var srcattribute        = htmlimage.GetAttributeValue("src", "defaultvalue");
                            var parseattributearray = srcattribute.Split(',');
                            if (parseattributearray.Length > 1)
                            {
                                var parsebase64 = parseattributearray[1];

                                byte[] imageBytes = Convert.FromBase64String(parsebase64);

                                using (var ms = new MemoryStream())
                                {
                                    ms.Write(imageBytes, 0, imageBytes.Length);
                                    IFormFile file = new FormFile(ms, 0, imageBytes.Length, "denemeisim", "denemeisim.jpg");

                                    var blogimagepath = await TryNetCore.Utils.FileUpload.ImageUpload(host.ContentRootPath, file, null);

                                    updateblog.BlogImages.Add(new BlogImages()
                                    {
                                        ImagePath = blogimagepath
                                    });

                                    var updatesrcattribute = blogimagepath;
                                    htmlimage.SetAttributeValue("src", updatesrcattribute);
                                }
                            }
                            else
                            {
                                deleteimages.Add(parseattributearray[0]);
                            }
                        }
                    }



                    updateblog.BlogContent = doc.DocumentNode.InnerHtml;

                    await db.SaveChangesAsync();
                }

                result.isSuccess = true;
                result.Message   = "Başarılı";
                return(Json(result));
            }
            catch (Exception e)
            {
                var a = e.Message;

                result.isSuccess = false;
                result.Message   = "Hata";
                return(Json(result));
            }
        }
Пример #26
0
        public async Task Upload_WithBulkUploadFile_UploadsApprenticeshipsAndReturnsRedirectToActionResult()
        {
            var ukPrn    = 12345678;
            var userInfo = new AuthenticatedUserInfo
            {
                CurrentProviderId = Guid.NewGuid(),
                UserId            = Guid.NewGuid().ToString(),
                Email             = "*****@*****.**"
            };

            _session.SetInt32("UKPRN", ukPrn);

            _blobStorageService.SetupGet(s => s.InlineProcessingThreshold).Returns(400);

            _currentUserProvider.Setup(s => s.GetCurrentUser())
            .Returns(userInfo);

            _standardsAndFrameworksCache.Setup(s => s.GetStandard(It.IsAny <int>(), It.IsAny <int>()))
            .ReturnsAsync <int, int, IStandardsAndFrameworksCache, Core.Models.Standard>((c, v) => new Core.Models.Standard {
                StandardCode = c, Version = v
            });

            _standardsAndFrameworksCache.Setup(s => s.GetFramework(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>()))
            .ReturnsAsync <int, int, int, IStandardsAndFrameworksCache, Core.Models.Framework>((c, t, p) => new Core.Models.Framework {
                FrameworkCode = c, ProgType = t, PathwayCode = p
            });

            _cosmosDbQueryDispatcher.Setup(s => s.ExecuteQuery(It.IsAny <GetVenuesByProvider>()))
            .ReturnsAsync(new List <Core.DataStore.CosmosDb.Models.Venue>()
            {
                new Core.DataStore.CosmosDb.Models.Venue()
                {
                    VenueName = "Fenestra Centre Scunthorpe",
                    Status    = Core.Models.VenueStatus.Live
                }
            });

            var addedApprenticeships = new List <CreateApprenticeship>();

            _cosmosDbQueryDispatcher.Setup(s => s.ExecuteQuery(It.IsAny <CreateApprenticeship>()))
            .Callback <ICosmosDbQuery <OneOf.Types.Success> >(q => addedApprenticeships.Add((CreateApprenticeship)q))
            .ReturnsAsync(new OneOf.Types.Success());

            const string csv = "STANDARD_CODE,STANDARD_VERSION,FRAMEWORK_CODE,FRAMEWORK_PROG_TYPE,FRAMEWORK_PATHWAY_CODE,APPRENTICESHIP_INFORMATION,APPRENTICESHIP_WEBPAGE,CONTACT_EMAIL,CONTACT_PHONE,CONTACT_URL,DELIVERY_METHOD,VENUE,RADIUS,DELIVERY_MODE,ACROSS_ENGLAND, NATIONAL_DELIVERY,REGION,SUB_REGION\r\n" +
                               "105,1,,,,\"This apprenticeship is applicable to any industry and perfect for those already in a team leading role or entering a management role for the first time.It lasts around 15 months and incorporates 14 one day modules plus on - the job learning and mentoring.It involves managing projects, leading and managing teams, change, financial management and coaching.If you choose to do this qualification with Azesta, you can expect exciting and engaging day long modules fully utilising experiential learning methods(one per month), high quality tutorial support, access to e-mail and telephone support whenever you need it and great results in your end point assessments.\",http://www.azesta.co.uk/apprenticeships/,[email protected],1423711904,http://www.azesta.co.uk/contact-us/,Both,Fenestra Centre Scunthorpe,100,Employer,No,,,\r\n" +
                               "104,1,,,,\"This apprenticeship is great for current managers. It involves managing projects, leading and managing teams, change, financial and resource management, talent management and coaching and mentoring. It takes around 2.5 years to complete and if you choose to do this qualification with Azesta, you can expect exciting and engaging day long modules fully utilising experiential learning methods (one per month), high quality tutorial support, access to e-mail and telephone support whenever you need it and great results in your end point assessments.\",http://www.azesta.co.uk/apprenticeships/,[email protected],1423711904,http://www.azesta.co.uk,Both,Fenestra Centre Scunthorpe,100,Employer,Yes,,,\r\n";

            using var stream = new MemoryStream(Encoding.UTF8.GetBytes(csv));
            var bulkUploadFile = new FormFile(stream, 0, stream.Length, "bulkUploadFile", "Test.csv")
            {
                Headers = new HeaderDictionary
                {
                    { "Content-Disposition", "filename" }
                }
            };

            var result = await _controller.Upload(bulkUploadFile);

            var redirectResult = Assert.IsType <RedirectToActionResult>(result);

            Assert.Equal("PublishYourFile", redirectResult.ActionName);
            Assert.Equal("BulkUploadApprenticeships", redirectResult.ControllerName);

            Assert.True(addedApprenticeships.Any());
            Assert.Equal(2, addedApprenticeships.Count);

            var apprenticeship1 = addedApprenticeships.First();
            var apprenticeship2 = addedApprenticeships.Skip(1).First();

            Assert.Equal(ukPrn, apprenticeship1.ProviderUkprn);
            Assert.Equal(userInfo.CurrentProviderId, apprenticeship1.ProviderId);
            Assert.Equal(userInfo.UserId.ToString(), apprenticeship1.CreatedByUser.UserId);
            Assert.Equal(105, apprenticeship1.StandardOrFramework.Standard.StandardCode);
            Assert.Equal("This apprenticeship is applicable to any industry and perfect for those already in a team leading role or entering a management role for the first time.It lasts around 15 months and incorporates 14 one day modules plus on - the job learning and mentoring.It involves managing projects, leading and managing teams, change, financial management and coaching.If you choose to do this qualification with Azesta, you can expect exciting and engaging day long modules fully utilising experiential learning methods(one per month), high quality tutorial support, access to e-mail and telephone support whenever you need it and great results in your end point assessments.", apprenticeship1.MarketingInformation);
            Assert.Equal("http://www.azesta.co.uk/apprenticeships/", apprenticeship1.Url);
            Assert.Equal("*****@*****.**", apprenticeship1.ContactEmail);
            Assert.Equal("1423711904", apprenticeship1.ContactTelephone);
            Assert.Equal("http://www.azesta.co.uk/contact-us/", apprenticeship1.ContactWebsite);

            var apprenticeship1Location = apprenticeship1.ApprenticeshipLocations.Single();

            Assert.Equal("Fenestra Centre Scunthorpe", apprenticeship1Location.Name);

            Assert.Equal(ukPrn, apprenticeship2.ProviderUkprn);
            Assert.Equal(userInfo.CurrentProviderId, apprenticeship2.ProviderId);
            Assert.Equal(userInfo.UserId.ToString(), apprenticeship2.CreatedByUser.UserId);
            Assert.Equal(104, apprenticeship2.StandardOrFramework.Standard.StandardCode);
            Assert.Equal("This apprenticeship is great for current managers. It involves managing projects, leading and managing teams, change, financial and resource management, talent management and coaching and mentoring. It takes around 2.5 years to complete and if you choose to do this qualification with Azesta, you can expect exciting and engaging day long modules fully utilising experiential learning methods (one per month), high quality tutorial support, access to e-mail and telephone support whenever you need it and great results in your end point assessments.", apprenticeship2.MarketingInformation);
            Assert.Equal("http://www.azesta.co.uk/apprenticeships/", apprenticeship2.Url);
            Assert.Equal("*****@*****.**", apprenticeship2.ContactEmail);
            Assert.Equal("1423711904", apprenticeship2.ContactTelephone);
            Assert.Equal("http://www.azesta.co.uk", apprenticeship2.ContactWebsite);

            var apprenticeship2Location = apprenticeship2.ApprenticeshipLocations.Single();

            Assert.Equal("Fenestra Centre Scunthorpe", apprenticeship2Location.Name);
        }
Пример #27
0
        public async Task <JsonResult> AddBlog(AddBlog blog)
        {
            var result = new SuccessResult();

            try
            {
                using (var db = new TryNetCoreContext())
                {
                    var newblog = new Blog();

                    newblog.BlogName         = blog.blogname;
                    newblog.BlogAuthor       = blog.blogauthorname;
                    newblog.BlogCategoryName = blog.blogcategoryname;
                    newblog.BlogPostDate     = DateTime.Now;


                    var blogcount = db.Blog.Count();
                    newblog.BlogRouteUrl = FriendlyUrl.FriendlyUrlMethod(blog.blogname + "-" + blogcount);

                    newblog.BlogImagePath = await TryNetCore.Utils.FileUpload.ImageUpload(host.ContentRootPath, blog.blogimage, null);

                    var blogtags = blog.blogtags.Split(',');
                    for (int i = 0; i < blogtags.Length; i++)
                    {
                        newblog.BlogTags.Add(new BlogTags()
                        {
                            BlogTagName = blogtags[i]
                        });
                    }

                    // ------------------------- //
                    // BLOG CONTENT AGİLİTY PACK //


                    HtmlDocument doc = new HtmlDocument();
                    doc.LoadHtml(blog.blogcontent);


                    var htmlimages = doc.DocumentNode.SelectNodes("//img");

                    if (htmlimages != null)
                    {
                        foreach (var htmlimage in htmlimages)
                        {
                            var srcattribute        = htmlimage.GetAttributeValue("src", "defaultvalue");
                            var parseattributearray = srcattribute.Split(',');
                            var parsebase64         = parseattributearray[1];

                            byte[] imageBytes = Convert.FromBase64String(parsebase64);

                            using (var ms = new MemoryStream())
                            {
                                ms.Write(imageBytes, 0, imageBytes.Length);
                                IFormFile file = new FormFile(ms, 0, imageBytes.Length, blog.blogimage.Name, blog.blogimage.FileName);

                                var blogimagepath = await TryNetCore.Utils.FileUpload.ImageUpload(host.ContentRootPath, file, null);

                                newblog.BlogImages.Add(new BlogImages()
                                {
                                    ImagePath = blogimagepath
                                });

                                var updatesrcattribute = blogimagepath;
                                htmlimage.SetAttributeValue("src", updatesrcattribute);
                            }
                        }
                    }


                    newblog.BlogContent = doc.DocumentNode.InnerHtml;
                    await db.Blog.AddAsync(newblog);

                    await db.SaveChangesAsync();
                }

                result.isSuccess = true;
                result.Message   = "Başarılı";
                return(Json(result));
            }
            catch (Exception e)
            {
                result.isSuccess = false;
                result.Message   = "Hata";
                return(Json(result));
            }
        }
        private async Task <IFormCollection> InnerReadFormAsync(CancellationToken cancellationToken)
        {
            if (!HasFormContentType)
            {
                throw new InvalidOperationException("Incorrect Content-Type: " + _request.ContentType);
            }

            cancellationToken.ThrowIfCancellationRequested();

            if (_options.BufferBody)
            {
                _request.EnableRewind(_options.MemoryBufferThreshold, _options.BufferBodyLengthLimit);
            }

            FormCollection     formFields = null;
            FormFileCollection files      = null;

            // Some of these code paths use StreamReader which does not support cancellation tokens.
            using (cancellationToken.Register((state) => ((HttpContext)state).Abort(), _request.HttpContext))
            {
                var contentType = ContentType;
                // Check the content-type
                if (HasApplicationFormContentType(contentType))
                {
                    var encoding = FilterEncoding(contentType.Encoding);
                    using (var formReader = new FormReader(_request.Body, encoding)
                    {
                        ValueCountLimit = _options.ValueCountLimit,
                        KeyLengthLimit = _options.KeyLengthLimit,
                        ValueLengthLimit = _options.ValueLengthLimit,
                    })
                    {
                        formFields = new FormCollection(await formReader.ReadFormAsync(cancellationToken));
                    }
                }
                else if (HasMultipartFormContentType(contentType))
                {
                    var formAccumulator = new KeyValueAccumulator();

                    var boundary        = GetBoundary(contentType, _options.MultipartBoundaryLengthLimit);
                    var multipartReader = new MultipartReader(boundary, _request.Body)
                    {
                        HeadersCountLimit  = _options.MultipartHeadersCountLimit,
                        HeadersLengthLimit = _options.MultipartHeadersLengthLimit,
                        BodyLengthLimit    = _options.MultipartBodyLengthLimit,
                    };
                    var section = await multipartReader.ReadNextSectionAsync(cancellationToken);

                    while (section != null)
                    {
                        ContentDispositionHeaderValue contentDisposition;
                        ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);
                        if (HasFileContentDisposition(contentDisposition))
                        {
                            // Enable buffering for the file if not already done for the full body
                            section.EnableRewind(_request.HttpContext.Response.RegisterForDispose,
                                                 _options.MemoryBufferThreshold, _options.MultipartBodyLengthLimit);
                            // Find the end
                            await section.Body.DrainAsync(cancellationToken);

                            var name     = HeaderUtilities.RemoveQuotes(contentDisposition.Name) ?? string.Empty;
                            var fileName = HeaderUtilities.RemoveQuotes(contentDisposition.FileName) ?? string.Empty;

                            FormFile file;
                            if (section.BaseStreamOffset.HasValue)
                            {
                                // Relative reference to buffered request body
                                file = new FormFile(_request.Body, section.BaseStreamOffset.Value, section.Body.Length, name, fileName);
                            }
                            else
                            {
                                // Individually buffered file body
                                file = new FormFile(section.Body, 0, section.Body.Length, name, fileName);
                            }
                            file.Headers = new HeaderDictionary(section.Headers);

                            if (files == null)
                            {
                                files = new FormFileCollection();
                            }
                            if (files.Count >= _options.ValueCountLimit)
                            {
                                throw new InvalidDataException($"Form value count limit {_options.ValueCountLimit} exceeded.");
                            }
                            files.Add(file);
                        }
                        else if (HasFormDataContentDisposition(contentDisposition))
                        {
                            // Content-Disposition: form-data; name="key"
                            //
                            // value

                            // Do not limit the key name length here because the mulipart headers length limit is already in effect.
                            var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                            MediaTypeHeaderValue mediaType;
                            MediaTypeHeaderValue.TryParse(section.ContentType, out mediaType);
                            var encoding = FilterEncoding(mediaType?.Encoding);
                            using (var reader = new StreamReader(section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
                            {
                                // The value length limit is enforced by MultipartBodyLengthLimit
                                var value = await reader.ReadToEndAsync();

                                formAccumulator.Append(key, value);
                                if (formAccumulator.ValueCount > _options.ValueCountLimit)
                                {
                                    throw new InvalidDataException($"Form value count limit {_options.ValueCountLimit} exceeded.");
                                }
                            }
                        }
                        else
                        {
                            System.Diagnostics.Debug.Assert(false, "Unrecognized content-disposition for this section: " + section.ContentDisposition);
                        }

                        section = await multipartReader.ReadNextSectionAsync(cancellationToken);
                    }

                    if (formAccumulator.HasValues)
                    {
                        formFields = new FormCollection(formAccumulator.GetResults(), files);
                    }
                }
            }

            // Rewind so later readers don't have to.
            if (_request.Body.CanSeek)
            {
                _request.Body.Seek(0, SeekOrigin.Begin);
            }

            if (formFields != null)
            {
                Form = formFields;
            }
            else if (files != null)
            {
                Form = new FormCollection(null, files);
            }
            else
            {
                Form = FormCollection.Empty;
            }

            return(Form);
        }
Пример #29
0
        public async Task GenerateReport(ParamReportModel model)
        {
            try
            {
                var reportName = "";

                // V แนวสูง
                // H แนวราบ
                await UpdatePathUrlFile(model.TDefectId);

                string bucketName = Environment.GetEnvironmentVariable("Minio_DefaultBucket") ?? UtilsProvider.AppSetting.MinioDefaultBucket;
                minio = new MinioServices();
                bool insertPDF = false;
                List <callResource> Signature = _masterRepository.GetSignatureByTdefectID(model.TDefectId);
                string lcSigAf  = Signature.Where(w => w.ResourceTagCode == "SAL-LC-AF").Any() ? Signature.Where(w => w.ResourceTagCode == "SAL-LC-AF").FirstOrDefault().FilePath : null;
                string cusSigBf = Signature.Where(w => w.ResourceTagCode == "CUST-BF").Any() ? Signature.Where(w => w.ResourceTagCode == "CUST-BF").FirstOrDefault().FilePath : null;
                string cusSigAf = Signature.Where(w => w.ResourceTagCode == "CUST-AF").Any() ? Signature.Where(w => w.ResourceTagCode == "CUST-AF").FirstOrDefault().FilePath : null;
                string conSigBf = Signature.Where(w => w.ResourceTagCode == "CON-MGR-BF").Any() ? Signature.Where(w => w.ResourceTagCode == "CON-MGR-BF").FirstOrDefault().FilePath : null;
                string conSigAf = Signature.Where(w => w.ResourceTagCode == "CON-MGR-AF").Any() ? Signature.Where(w => w.ResourceTagCode == "CON-MGR-AF").FirstOrDefault().FilePath : null;
                string cusSigRe = Signature.Where(w => w.ResourceTagCode == "CUST-RECE").Any() ? Signature.Where(w => w.ResourceTagCode == "CUST-RECE").FirstOrDefault().FilePath : null;

                var listCus = new List <string>()
                {
                    "CUST-BF", "CUST-AF", "CUST-RECE"
                };
                var orderCusSignature = Signature.Where(w => listCus.Contains(w.ResourceTagCode)).OrderBy(o => o.CreateDate).ToList();

                var dateCusSigBf = Signature.Where(w => w.ResourceTagCode == "CUST-BF").Any() ? Signature.Where(w => w.ResourceTagCode == "CUST-BF").FirstOrDefault().CreateDate : null;
                var dateCusSigAf = Signature.Where(w => w.ResourceTagCode == "CUST-AF").Any() ? Signature.Where(w => w.ResourceTagCode == "CUST-AF").FirstOrDefault().CreateDate : null;
                var dateCusSigRe = Signature.Where(w => w.ResourceTagCode == "CUST-RECE").Any() ? Signature.Where(w => w.ResourceTagCode == "CUST-RECE").FirstOrDefault().CreateDate : null;

                string cusBfDatetime = "";
                string cusAfDatetime = "";
                string cusReDatetime = "";

                if (dateCusSigBf != null)
                {
                    cusBfDatetime = dateCusSigBf.Value.ToString("dd/MM/yyyy");
                }

                if (dateCusSigAf != null)
                {
                    cusAfDatetime = dateCusSigAf.Value.ToString("dd/MM/yyyy");
                }

                if (dateCusSigRe != null)
                {
                    cusReDatetime = string.Format("ลูกค้าเช็นต์รับบ้านแล้ว {0}", dateCusSigRe.Value.ToString("dd/MM/yyyy"));
                }


                string alternativeDate = "";
                var    indexCusRe      = orderCusSignature.FindIndex(w => w.ResourceTagCode == "CUST-RECE");
                if (indexCusRe != 0 && indexCusRe != -1)
                {
                    if (orderCusSignature[indexCusRe - 1].ResourceTagCode == "CUST-BF")
                    {
                        alternativeDate = string.Format("ลูกค้าเช็นต์ก่อนซ่อมแล้ว {0}", cusBfDatetime);
                    }

                    if (orderCusSignature[indexCusRe - 1].ResourceTagCode == "CUST-AF")
                    {
                        alternativeDate = string.Format("ลูกค้าเช็นต์หลังซ่อมแล้ว {0}", cusAfDatetime);
                    }
                }

                if (model.ProjectType.Equals("V"))
                {
                    if (model.SignatureType == "CUST-BF")
                    {
                        reportName = "RPT_ReceiveUnit_Vertical_CUST_BF";
                    }
                    else if (model.SignatureType == "CUST-AF")
                    {
                        reportName = "RPT_ReceiveUnit_Vertical_CUST_AF";
                    }
                    else
                    {
                        reportName = "RPT_ReceiveUnit_Vertical_CUST_RECE";
                    }
                }
                else
                {
                    if (model.SignatureType == "CUST-BF")
                    {
                        reportName = "RPT_ReceiveUnit_Horizontal_CUST_BF";
                    }
                    else if (model.SignatureType == "CUST-AF")
                    {
                        reportName = "RPT_ReceiveUnit_Horizontal_CUST_AF";
                    }
                    else
                    {
                        reportName = "RPT_ReceiveUnit_Horizontal_CUST_RECE";
                    }
                }

                string lcSigAffilePath = String.IsNullOrEmpty(lcSigAf) ? null : await minio.GetFileUrlAsync(bucketName, lcSigAf);

                string cusSigBfFilePath = String.IsNullOrEmpty(cusSigBf) ? null : await minio.GetFileUrlAsync(bucketName, cusSigBf);

                string cusSigAfFilePath = String.IsNullOrEmpty(cusSigAf) ? null : await minio.GetFileUrlAsync(bucketName, cusSigAf);

                string conSigBfFilePath = String.IsNullOrEmpty(conSigBf) ? null : await minio.GetFileUrlAsync(bucketName, conSigBf);

                string conSigAfFilePath = String.IsNullOrEmpty(conSigAf) ? null : await minio.GetFileUrlAsync(bucketName, conSigAf);

                string cusSigReFilePath = String.IsNullOrEmpty(cusSigRe) ? null : await minio.GetFileUrlAsync(bucketName, cusSigRe);

                var requestMode = new RequestReportModel()
                {
                    Folder       = "defect",
                    FileName     = reportName,
                    Server       = Environment.GetEnvironmentVariable("ReportServer") ?? UtilsProvider.AppSetting.ReportServer,
                    DatabaseName = Environment.GetEnvironmentVariable("ReportDataBase") ?? UtilsProvider.AppSetting.ReportDataBase,
                    UserName     = Environment.GetEnvironmentVariable("ReportUserName") ?? UtilsProvider.AppSetting.ReportUserName,
                    Password     = Environment.GetEnvironmentVariable("ReportPassword") ?? UtilsProvider.AppSetting.ReportPassword,
                    Parameters   = new List <ParameterReport>()
                    {
                        new ParameterReport()
                        {
                            Name = "@TDefectId", Value = model.TDefectId.ToString()
                        },
                        new ParameterReport()
                        {
                            Name = "@CustRoundAuditNo", Value = "1"
                        },
                        new ParameterReport()
                        {
                            Name = "@CON_MGR_AF_URL", Value = conSigAfFilePath
                        },
                        new ParameterReport()
                        {
                            Name = "@CON_MGR_BF_URL", Value = conSigBfFilePath
                        },
                        new ParameterReport()
                        {
                            Name = "@CUST_AF_URL", Value = cusSigAfFilePath
                        },
                        new ParameterReport()
                        {
                            Name = "@CUST_BF_URL", Value = cusSigBfFilePath
                        },
                        new ParameterReport()
                        {
                            Name = "@CUST_RECE", Value = cusSigReFilePath
                        },
                        new ParameterReport()
                        {
                            Name = "@SAL_LC_AF", Value = lcSigAffilePath
                        },
                        new ParameterReport()
                        {
                            Name = "@ALTERNATIVE_DATE", Value = alternativeDate
                        },
                        new ParameterReport()
                        {
                            Name = "@CUS_RECE_SIGN_DATE", Value = cusReDatetime
                        }
                    }
                };
                ResponsetReportModel resultObject = new ResponsetReportModel();
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = new TimeSpan(0, 0, 1000);
                    var urlReport = Environment.GetEnvironmentVariable("ReportURL") ?? UtilsProvider.AppSetting.ReportURL;
                    var reportKey = Environment.GetEnvironmentVariable("ReportKey") ?? UtilsProvider.AppSetting.ReportKey;
                    var Content   = new StringContent(JsonConvert.SerializeObject(requestMode));
                    Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    Content.Headers.Add("api_accesskey", reportKey);
                    var response = await client.PostAsync(urlReport, Content);

                    if (response.IsSuccessStatusCode)
                    {
                        response.EnsureSuccessStatusCode();
                        var result = await response.Content.ReadAsStringAsync();

                        resultObject = JsonConvert.DeserializeObject <ResponsetReportModel>(result);
                    }
                    client.Dispose();
                }
                await Task.Delay(3000);

                long sizeFile = 0;
                var  fullUrl  = "";
                var  path     = $"{model.ProjectCode}/{model.UnitNo}/DefectDocument";
                if (resultObject.Success)
                {
                    using (HttpClient client = new HttpClient())
                    {
                        HttpResponseMessage resDownload = await client.GetAsync(resultObject.URL.ToString()).ConfigureAwait(false);

                        HttpContent content = resDownload.Content;

                        // ... Read the string.
                        var result = await content.ReadAsByteArrayAsync().ConfigureAwait(false);

                        Stream stream = new MemoryStream(result);
                        var    file   = new FormFile(stream, 0, stream.Length, null, resultObject.FileName)
                        {
                            Headers     = new HeaderDictionary(),
                            ContentType = "application/pdf"
                        };
                        sizeFile = file.Length;
                        var resultMinio = await minio.UploadFile(file, path, resultObject.FileName);

                        fullUrl = resultMinio.Url;

                        client.Dispose();
                    }

                    callResource callResourcePDF = new callResource();
                    callResourcePDF.FilePath           = $"{path}/{resultObject.FileName}";
                    callResourcePDF.FileLength         = sizeFile;
                    callResourcePDF.CreateDate         = DateTime.Now;
                    callResourcePDF.RowState           = "Original";
                    callResourcePDF.ResourceType       = 8;
                    callResourcePDF.ResourceTagCode    = "1";
                    callResourcePDF.ResourceTagSubCode = "1";
                    callResourcePDF.ResourceGroupSet   = null;
                    callResourcePDF.StorageServerId    = 1400;
                    callResourcePDF.ResourceGroupOrder = 0;
                    callResourcePDF.TDefectDetailId    = 0;
                    callResourcePDF.TDefectId          = (int)model.TDefectId;
                    callResourcePDF.ProjectNo          = model.ProjectCode;
                    callResourcePDF.SerialNo           = model.UnitNo;
                    callResourcePDF.Active             = true;
                    callResourcePDF.FullFilePath       = fullUrl;
                    callResourcePDF.UserId             = model.EmpCode;
                    callResourcePDF.ExpirePathDate     = DateTime.Now.AddDays(6);;
                    insertPDF = InsertCallResource(callResourcePDF);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #30
0
        public async Task <IActionResult> Edit(int id)
        {
            Checker.CheckLangId(HttpContext, db, "adminLangId").Wait();
            HttpContext.SetCurrentPage("Index", "Product");
            int langId  = HttpContext.GetLanguage("adminLangId");
            var product = await db.Products
                          .Where(p => p.Id == id)
                          .FirstOrDefaultAsync();


            //Find Product Photos
            var product_photos = await db.ProductPhotos.Where(pp => pp.Product == product).ToListAsync();

            foreach (var product_photo in product_photos)
            {
                string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Admin", "Uploads", "Products", product_photo.PhotoPath);
                if (PhotoUpload.HasPhoto(path))
                {
                    using (var file = System.IO.File.Open(path, FileMode.Open))
                    {
                        FileInfo  info  = new FileInfo(path);
                        IFormFile photo = new FormFile(file, 0, file.Length, file.Name, info.Name);
                        product.Photos.Add(photo);
                    }
                }
            }

            #region Make ProductEditViewModel
            ProductEditViewModel model = new ProductEditViewModel()
            {
                ProductLanguages = await db.ProductLanguages
                                   .Where(pl => pl.ProductId == id)
                                   .Include(pl => pl.Product)
                                   .ThenInclude(pl => pl.Subcategory)
                                   .ToListAsync(),

                CategoryLanguages = await db.CategoryLanguages
                                    .Where(cl => cl.LanguageId == langId)
                                    .Include(cl => cl.Category)
                                    .ToListAsync(),
                SubcategoryLanguages = await db.SubcategoryLanguages
                                       .Where(sl => sl.LanguageId == langId)
                                       .Include(sl => sl.Subcategory)
                                       .ToListAsync(),

                Sizes = await db.Sizes.ToListAsync(),

                ProductSizeCounts = await db.ProductSizeCounts.Where(ps => ps.ProductId == product.Id).Include(ps => ps.Size).ToListAsync(),

                //Colors = await db.ColorLanguage
                //                            .Include(cl => cl.Color)
                //                                 .Where(cl => cl.LanguageId == langId)
                //                                    .ToListAsync(),
                ProductColors = await db.ProductColors
                                .Where(pc => pc.ProductId == product.Id)
                                .Include(pc => pc.Product)
                                .ToListAsync(),

                Languages = await db.Languages.ToListAsync(),

                Product = await db.Products
                          .Where(p => p.Id == id)
                          .FirstOrDefaultAsync(),
            };
            #endregion
            return(View(model));
        }
Пример #31
0
        private async Task<IFormCollection> InnerReadFormAsync(CancellationToken cancellationToken)
        {
            if (!HasFormContentType)
            {
                throw new InvalidOperationException("Incorrect Content-Type: " + _request.ContentType);
            }

            cancellationToken.ThrowIfCancellationRequested();

            if (_options.BufferBody)
            {
                _request.EnableRewind(_options.MemoryBufferThreshold, _options.BufferBodyLengthLimit);
            }

            FormCollection formFields = null;
            FormFileCollection files = null;

            // Some of these code paths use StreamReader which does not support cancellation tokens.
            using (cancellationToken.Register((state) => ((HttpContext)state).Abort(), _request.HttpContext))
            {
                var contentType = ContentType;
                // Check the content-type
                if (HasApplicationFormContentType(contentType))
                {
                    var encoding = FilterEncoding(contentType.Encoding);
                    using (var formReader = new FormReader(_request.Body, encoding)
                    {
                        ValueCountLimit = _options.ValueCountLimit,
                        KeyLengthLimit = _options.KeyLengthLimit,
                        ValueLengthLimit = _options.ValueLengthLimit,
                    })
                    {
                        formFields = new FormCollection(await formReader.ReadFormAsync(cancellationToken));
                    }
                }
                else if (HasMultipartFormContentType(contentType))
                {
                    var formAccumulator = new KeyValueAccumulator();

                    var boundary = GetBoundary(contentType, _options.MultipartBoundaryLengthLimit);
                    var multipartReader = new MultipartReader(boundary, _request.Body)
                    {
                        HeadersCountLimit = _options.MultipartHeadersCountLimit,
                        HeadersLengthLimit = _options.MultipartHeadersLengthLimit,
                        BodyLengthLimit = _options.MultipartBodyLengthLimit,
                    };
                    var section = await multipartReader.ReadNextSectionAsync(cancellationToken);
                    while (section != null)
                    {
                        ContentDispositionHeaderValue contentDisposition;
                        ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);
                        if (HasFileContentDisposition(contentDisposition))
                        {
                            // Enable buffering for the file if not already done for the full body
                            section.EnableRewind(_request.HttpContext.Response.RegisterForDispose,
                                _options.MemoryBufferThreshold, _options.MultipartBodyLengthLimit);
                            // Find the end
                            await section.Body.DrainAsync(cancellationToken);

                            var name = HeaderUtilities.RemoveQuotes(contentDisposition.Name) ?? string.Empty;
                            var fileName = HeaderUtilities.RemoveQuotes(contentDisposition.FileName) ?? string.Empty;

                            FormFile file;
                            if (section.BaseStreamOffset.HasValue)
                            {
                                // Relative reference to buffered request body
                                file = new FormFile(_request.Body, section.BaseStreamOffset.Value, section.Body.Length, name, fileName);
                            }
                            else
                            {
                                // Individually buffered file body
                                file = new FormFile(section.Body, 0, section.Body.Length, name, fileName);
                            }
                            file.Headers = new HeaderDictionary(section.Headers);

                            if (files == null)
                            {
                                files = new FormFileCollection();
                            }
                            if (files.Count >= _options.ValueCountLimit)
                            {
                                throw new InvalidDataException($"Form value count limit {_options.ValueCountLimit} exceeded.");
                            }
                            files.Add(file);
                        }
                        else if (HasFormDataContentDisposition(contentDisposition))
                        {
                            // Content-Disposition: form-data; name="key"
                            //
                            // value

                            // Do not limit the key name length here because the mulipart headers length limit is already in effect.
                            var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                            MediaTypeHeaderValue mediaType;
                            MediaTypeHeaderValue.TryParse(section.ContentType, out mediaType);
                            var encoding = FilterEncoding(mediaType?.Encoding);
                            using (var reader = new StreamReader(section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
                            {
                                // The value length limit is enforced by MultipartBodyLengthLimit
                                var value = await reader.ReadToEndAsync();
                                formAccumulator.Append(key, value);
                                if (formAccumulator.ValueCount > _options.ValueCountLimit)
                                {
                                    throw new InvalidDataException($"Form value count limit {_options.ValueCountLimit} exceeded.");
                                }
                            }
                        }
                        else
                        {
                            System.Diagnostics.Debug.Assert(false, "Unrecognized content-disposition for this section: " + section.ContentDisposition);
                        }

                        section = await multipartReader.ReadNextSectionAsync(cancellationToken);
                    }

                    if (formAccumulator.HasValues)
                    {
                        formFields = new FormCollection(formAccumulator.GetResults(), files);
                    }
                }
            }

            // Rewind so later readers don't have to.
            if (_request.Body.CanSeek)
            {
                _request.Body.Seek(0, SeekOrigin.Begin);
            }

            if (formFields != null)
            {
                Form = formFields;
            }
            else if (files != null)
            {
                Form = new FormCollection(null, files);
            }
            else
            {
                Form = FormCollection.Empty;
            }

            return Form;
        }