Esempio n. 1
0
    private void ProcessXml(XmlDocument doc, string photoPath)
    {
        try
        {
            //var cats = new Dictionary<string, string>();
            //XmlNodeList categories = doc.GetElementsByTagName("Category");
            //if (categories.Count != 0)
            //{
            //    int i = 0;
            //    foreach (XmlNode categoryXml in categories)
            //    {
            //        if (categoryXml.Attributes != null)
            //        {
            //            Category category = CategoryService.GetCategoryFromDbByCategoryId(int.Parse(categoryXml.Attributes["ID"].InnerText));
            //            if (category == null)
            //            {
            //                try
            //                {
            //                    Category cat = new Category();
            //                    cat.Name = categoryXml.Attributes["Name"].InnerText;
            //                    cat.ParentCategoryId = int.Parse(categoryXml.Attributes["ParentCategory"].InnerText);
            //                    cat.Picture = string.Empty;
            //                    cat.SortOrder = Math.Max(Interlocked.Increment(ref i), i - 1);
            //                    cat.Enabled = true;

            //                    cats.Add(categoryXml.Attributes["ID"].InnerText, CategoryService.AddCategory(cat, true).ToString());
            //                    //cats.Add(categoryXml.Attributes["ID"].InnerText,
            //                    //         CategoryService.AddCategory(categoryXml.Attributes["Name"].InnerText,
            //                    //                                     int.Parse(categoryXml.Attributes["ParentCategory"].InnerText), "",
            //                    //                                     Math.Max(Interlocked.Increment(ref i), i - 1), true,
            //                    //                                     true).ToString());
            //                    CategoryService.UpdateCategory(category, true);
            //                }
            //                catch (Exception ex)
            //                {
            //                    AdvantShop.Diagnostics.Debug.LogError(ex);
            //                }
            //            }
            //            else
            //            {
            //                category.Name = categoryXml.Attributes["Name"].InnerText;
            //                category.ParentCategoryId = int.Parse(categoryXml.Attributes["ParentCategory"].InnerText);
            //                CategoryService.UpdateCategory(category, true);
            //                cats.Add(category.CategoryId.ToString(), category.CategoryId.ToString());
            //            }
            //        }
            //    }
            //}
            if (doc.GetElementsByTagName("Products").Count != 0)
            {
                var     products     = new Dictionary <string, Product>();
                var     productCats  = new Dictionary <string, string>();
                var     productUnits = new Dictionary <string, string>();
                XmlNode productsXml  = doc.GetElementsByTagName("Products")[0];
                foreach (XmlNode prodXml in productsXml.ChildNodes)
                {
                    if (prodXml.Attributes != null)
                    {
                        var product = new Product
                        {
                            ArtNo       = prodXml.Attributes["SKU"].InnerText,
                            Name        = prodXml.Attributes["Name"].InnerText,
                            Description = prodXml.Attributes["Description"].InnerText,
                            Enabled     = true,
                            UrlPath     = UrlService.GetEvalibleValidUrl(0, ParamType.Product, prodXml.Attributes["SKU"].InnerText)
                        };
                        productUnits.Add(product.ArtNo, prodXml.Attributes["Unit"].InnerText);
                        productCats.Add(product.ArtNo, prodXml.Attributes["Category"].InnerText);
                        try
                        {
                            products.Add(product.ArtNo, product);
                        }
                        catch (Exception ex)
                        {
                            Log(ex.Message, "InvalidData");
                        }
                    }
                }

                XmlNodeList offers = doc.GetElementsByTagName("Offer");
                if (offers.Count != 0)
                {
                    foreach (XmlNode offer in offers)
                    {
                        if (offer.Attributes != null)
                        {
                            Product product = products[offer.Attributes["ProductSKU"].InnerText];
                            if (product == null)
                            {
                                break;
                            }
                            var     pOffer = new Offer();
                            decimal price;
                            if (decimal.TryParse(offer.Attributes["Price"].Value.Replace('.', ','), out price))
                            {
                                pOffer.Price = price;
                            }
                            int amount;
                            if (int.TryParse(offer.Attributes["Amount"].InnerText, out amount))
                            {
                                pOffer.Amount = amount;
                            }
                            pOffer.Unit        = productUnits[product.ArtNo];
                            pOffer.OfferListId = CatalogService.DefaultOfferListId;
                            if (product.Offers == null)
                            {
                                product.Offers = new List <Offer>();
                            }

                            product.Offers.Add(pOffer);
                        }
                    }
                }

                foreach (Product product in products.Values)
                {
                    UpdateInsertProduct(product, productCats[product.ArtNo]);
                }

                LuceneSearch.CreateAllIndexInBackground();

                if (!string.IsNullOrEmpty(photoPath))
                {
                    XmlNodeList photos = doc.GetElementsByTagName("Photo");
                    if (photos.Count != 0)
                    {
                        FileHelpers.UpdateDirectories();
                        var flagIsFrirst = true;
                        foreach (XmlNode photo in photos)
                        {
                            if (photo.Attributes != null)
                            {
                                var fullfilename = photoPath + photo.Attributes["FileName"].Value;
                                if (File.Exists(fullfilename))
                                {
                                    ProductService.AddProductPhotoByArtNo(photo.Attributes["ProductSKU"].Value, fullfilename,
                                                                          photo.Attributes["Description"].Value, flagIsFrirst);
                                    flagIsFrirst = false;
                                }
                                File.Delete(fullfilename);
                            }
                        }
                    }
                }
                XmlNodeList props = doc.GetElementsByTagName("Property");
                if (props.Count != 0)
                {
                    foreach (XmlNode prop in props)
                    {
                        if (prop.Attributes != null)
                        {
                            var product = ProductService.GetProduct(prop.Attributes["ProductSKU"].InnerText);
                            if (product.ID == 0)
                            {
                                break;
                            }

                            // TODO use PropertyService
                            //ProductService.AddProperty(product.Id, prop.Attributes["Name"].Value,
                            //                           prop.Attributes["Value"].Value, 0);
                        }
                    }
                }
            }
            Log("Import successfull", "SuccessImport");
        }
        catch (Exception ex)
        {
            Log(ex.Message, "InvalidData");
        }
        CategoryService.RecalculateProductsCountManual();
        XmlElement summary = _sdsLog.CreateElement("LogSummary");
        XmlElement el      = _sdsLog.CreateElement("Added");

        el.InnerText = _added.ToString("d");
        summary.AppendChild(el);
        el           = _sdsLog.CreateElement("Updated");
        el.InnerText = _updated.ToString("d");
        summary.AppendChild(el);
        el           = _sdsLog.CreateElement("Errors");
        el.InnerText = _errors.ToString("d");
        summary.AppendChild(el);
        if (_sdsLog.DocumentElement != null)
        {
            _sdsLog.DocumentElement.AppendChild(summary);
        }
    }
        public ScenarioCampaignFailureOutput ProcessFile(Guid scenarioId, string folder)
        {
            string filename = FileHelpers.GetPathToFileIfExists(folder, FileName);
            var    result   = new ScenarioCampaignFailureOutput
            {
                ScenarioId = scenarioId,
                Data       = new List <ScenarioCampaignFailure>()
            };

            if (String.IsNullOrEmpty(filename))
            {
                return(result);
            }

            _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                                 0, $"Processing output file {filename}"));

            var importSettings = CSVImportSettings.GetImportSettings(filename, typeof(ScenarioCampaignFailureHeaderMap), typeof(ScenarioCampaignFailureIndexMap));

            using var scenarioCampaignFailureImportRepository = new CSVScenarioCampaignFailureImportRepository(importSettings);

            var fileData = scenarioCampaignFailureImportRepository.GetAll();

            if (fileData is null || !fileData.Any())
            {
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForException(0, 0,
                                                                                            $"Error generating Scenario Campaign Failure, data not found", new ObjectNotFoundException()));

                return(result);
            }

            var salesAreas = _dataSnapshot.AllSalesAreas.Value.ToDictionary(s => s.CustomId);
            var campaigns  = _dataSnapshot.AllCampaigns.Value.ToDictionary(c => c.ExternalId);

            foreach (var data in fileData)
            {
                try
                {
                    _ = salesAreas.TryGetValue(data.SalesAreaNumber, out var salesArea);
                    _ = campaigns.TryGetValue(data.CampaignExternalId, out var campaign);
                    var salesAreaName      = salesArea?.Name ?? "Unknown";
                    var salesAreaGroupName = campaign?.SalesAreaCampaignTarget
                                             .Where(sact => !(sact.SalesAreaGroup is null))
                                             .Select(sact => sact.SalesAreaGroup)
                                             .FirstOrDefault(sag =>
                                                             sag.SalesAreas.Any(sa => sa.Equals(salesAreaName, StringComparison.OrdinalIgnoreCase)))
                                             ?.GroupName;

                    var scenarioCampaignFailure = new ScenarioCampaignFailure
                    {
                        ScenarioId                = scenarioId,
                        ExternalCampaignId        = data.CampaignExternalId,
                        SalesArea                 = salesAreaName,
                        SalesAreaGroup            = salesAreaGroupName,
                        Length                    = Duration.FromSeconds(data.SpotLength),
                        MultipartNo               = data.MultipartNumber,
                        StrikeWeightStartDate     = DateHelper.GetDate(data.StrikeWeightStartDate.ToString(), "yyyyMMdd"),
                        StrikeWeightEndDate       = DateHelper.GetDate(data.StrikeWeightEndDate.ToString(), "yyyyMMdd"),
                        DayPartStartTime          = ToTimeSpan(data.DayPartStartTime.ToString().PadLeft(6, '0')),
                        DayPartEndTime            = ToTimeSpan(data.DayPartEndTime.ToString().PadLeft(6, '0')),
                        DayPartDays               = data.DayPartDays,
                        FailureType               = data.FailureType,
                        FailureCount              = data.NumberOfFailures,
                        PassesEncounteringFailure = DecryptPassIds(data.PassesEncounteringFailure),
                    };

                    result.Data.Add(scenarioCampaignFailure);
                }
                catch (ObjectNotFoundException exception)
                {
                    _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForException(0, 0,
                                                                                                $"Error generating Scenario Campaign Failure for campaign id {data.CampaignExternalId}", exception));
                }
            }

            _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                                 0, $"Processed output file {filename}"));

            return(result);
        }
Esempio n. 3
0
        public async Task UpdateProject(ProjectFormData model, ModelStateDictionary modelState, Guid id, string userName)
        {
            var user = await _userManager.FindByNameAsync(userName);

            var trustedFileNameForDisplay     = string.Empty;
            var streamedFileImageContent      = new byte[0];
            var untrustedFileNameForStorage   = string.Empty;
            var trustedFilePathStorage        = string.Empty;
            var trustedFileNameForFileStorage = string.Empty;
            var checkState = string.Empty;

            // Get Project Id and update all new fields
            var getProject = await _context.ClamUserProjects.FindAsync(id);

            if (model.File != null)
            {
                streamedFileImageContent =
                    await FileHelpers.ProcessFormFile <ProjectFormData>(
                        model.File, modelState, _permittedExtentions,
                        _fileSizeLimit);

                // Filter Check the state of the file
                if (!modelState.IsValid)
                {
                    checkState = "ModelState is Invalid";
                }

                untrustedFileNameForStorage = model.File.FileName;
                // Don't trust the file name sent by the client. To display
                // the file name, HTML-encode the value.
                trustedFileNameForDisplay = WebUtility.HtmlEncode(
                    model.File.FileName);

                // Bind form data to the model
                var keyPathFolder     = FilePathUrlHelper.GenerateKeyPath(user.Id);
                var generateKeyFolder = GenerateSecurity.Encode(user.Id);

                // Path Location & Directory Check
                trustedFilePathStorage = String.Format("{0}\\{1}\\{2}\\{3}",
                                                       _targetFolderPath,
                                                       keyPathFolder,
                                                       generateKeyFolder,
                                                       Path.GetRandomFileName());

                Directory.CreateDirectory(trustedFilePathStorage);

                using (var fileStream = new FileStream(Path.Combine(trustedFilePathStorage, untrustedFileNameForStorage),
                                                       FileMode.Create, FileAccess.Write))
                {
                    await model.File.CopyToAsync(fileStream);

                    fileStream.Close();
                }
                // Remove Physical Location
                await RemoveProject(id);

                _context.Entry(getProject).Entity.Title            = model.Title;
                _context.Entry(getProject).Entity.Author           = model.Author;
                _context.Entry(getProject).Entity.Description      = model.Description;
                _context.Entry(getProject).Entity.Language         = model.Language;
                _context.Entry(getProject).Entity.GithubLink       = model.GithubLink;
                _context.Entry(getProject).Entity.Status           = bool.Parse(model.Status);
                _context.Entry(getProject).Entity.LastModified     = DateTime.Now;
                _context.Entry(getProject).Entity.ImageGifLocation = Path.Combine(trustedFilePathStorage, untrustedFileNameForStorage);
                _context.Update(getProject);
                await _context.SaveChangesAsync();
            }
            else
            {
                _context.Entry(getProject).Entity.Title        = model.Title;
                _context.Entry(getProject).Entity.Author       = model.Author;
                _context.Entry(getProject).Entity.Description  = model.Description;
                _context.Entry(getProject).Entity.Language     = model.Language;
                _context.Entry(getProject).Entity.GithubLink   = model.GithubLink;
                _context.Entry(getProject).Entity.Status       = bool.Parse(model.Status);
                _context.Entry(getProject).Entity.LastModified = DateTime.Now;
                _context.Update(getProject);
                await _context.SaveChangesAsync();
            }
        }
        private async Task RetrieveFile(HttpContext context)
        {
            var  fileRepositoryIdStr = context.Request.Query["id"];
            bool returnThumbNail     = true;

            {
                var returnThumbnailStr = context.Request.Query["thumbnail"];
                bool.TryParse(returnThumbnailStr, out returnThumbNail);
            }

            if (int.TryParse(fileRepositoryIdStr, out int fileRepositoryId))
            {
                //Scope name: AutofacWebRequest is mandatory to match the WebApi scope created.
                //If the scope is changed some injections stop working with the message that "AutofacWebRequest" scope was not found.
                using (var scope = IoCGlobal.NewScope("AutofacWebRequest"))
                {
                    try
                    {
                        var getFileDataRetriever = IoCGlobal.Resolve <IFileRetriever>(null, scope);

                        var fileInfoResult = getFileDataRetriever.GetFileData(fileRepositoryId);
                        if (!fileInfoResult.IsSucceed || fileInfoResult.Bag == null)
                        {
                            throw new Exception();
                        }

                        var fileInfo = fileInfoResult.Bag;

                        string mimeType           = null;
                        var    fileStorageService = IoCGlobal.Resolve <IFileStorageService>(fileInfo.FileSystemTypeId, scope);
                        byte[] result             = null;
                        if (returnThumbNail)
                        {
                            var thumbnailFileName = fileInfo.ThumbnailFileName ?? fileInfo.FileName;
                            result = await fileStorageService.RetrieveFile(fileInfo.RootPath, fileInfo.AccessPath, fileInfo.RelativePath, thumbnailFileName);

                            mimeType = FileHelpers.GetMimeTypeByExtension(thumbnailFileName);
                        }
                        else
                        {
                            result = await fileStorageService.RetrieveFile(fileInfo.RootPath, fileInfo.AccessPath, fileInfo.RelativePath, fileInfo.FileName);

                            mimeType = FileHelpers.GetMimeTypeByExtension(fileInfo.FileName);
                        }

                        if (result == null || result.Length == 0)
                        {
                            throw new FileNotFoundException();
                        }

                        context.Response.OnStarting(state =>
                        {
                            var httpContext = (HttpContext)state;
                            httpContext.Response.ContentType = mimeType;
                            return(Task.FromResult(0));
                        }, context);



                        var memStream = new MemoryStream(result);
                        memStream.CopyTo(context.Response.Body);
                        //context.Response.ContentType = mimeType;
                        context.Response.Body.Flush();
                    }
                    catch (Exception ex)
                    {
                        Logger.Error($"File Retrieve - {fileRepositoryId}", ex);
                        throw;
                    }
                    return;
                }
            }
            else
            {
                throw new Exception();
            }
        }
 /// <summary>
 /// When overridden in the derived class, performs clean-up
 /// after the command execution.
 /// Default implementation in the base class just returns.
 /// </summary>
 /// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
 /// <exception cref="T:System.IO.DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive).</exception>
 /// <exception cref="T:System.IO.IOException">An I/O error occurs.</exception>
 protected override void EndProcessing()
 {
     FileHelpers.WriteFileJson(FileNames.UserData, AzureDevOpsConfiguration.Config.Configuration);
 }
Esempio n. 6
0
        //[RequestFormLimits(MultipartBodyLengthLimit = 209715200)]
        //[RequestSizeLimit(209715200)]
        public async Task <IActionResult> UploadPhysical([ModelBinder(BinderType = typeof(JsonModelBinder))] List <FileTag> tags)
        {
            Program.CleanAppMre.WaitOne();
            Program.CleanChatMre.WaitOne();
            Program.StreamingMre.Reset();

            try
            {
                _logger.LogInformation("File tags: {FileTags}", tags);

                var i = 0;
                var successUploads = new List <UploadInfoDto>();
                var failedUploads  = new List <UploadInfoDto>();

                if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
                {
                    throw new ClientException("上传失败", new List <string> {
                        "Not multipart content type."
                    });
                }

                var boundary = MultipartRequestHelper.GetBoundary(
                    MediaTypeHeaderValue.Parse(Request.ContentType),
                    _defaultFormOptions.MultipartBoundaryLengthLimit);
                var reader  = new MultipartReader(boundary, HttpContext.Request.Body);
                var section = await reader.ReadNextSectionAsync();

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

                    if (hasContentDispositionHeader)
                    {
                        // 1. This check assumes that there's a file
                        // present without form data. If form data
                        // is present, this method immediately fails
                        // and returns the model error.
                        // 2. also check there is a tag correspond to the file
                        if (!MultipartRequestHelper.HasFileContentDisposition(contentDisposition) || (tags != null && i >= tags.Count))
                        {
                            if (tags != null && i >= tags.Count)
                            {
                                _logger.LogError($"Upload file {contentDisposition.FileName.Value} failed, no conresponding tag.");
                            }
                            else
                            {
                                _logger.LogError($"Upload file {contentDisposition.FileName.Value} failed, no file content disposition.");
                            }

                            // 记录上传失败的文件
                            failedUploads.Add(new UploadInfoDto {
                                Name = contentDisposition.FileName.Value, Index = i
                            });
                        }
                        else
                        {
                            _logger.LogInformation($"Uploading file {contentDisposition.FileName.Value} with tag {tags?[i].ToString() ?? "N/A"}.");

                            // Don't trust the file name sent by the client. To display
                            // the file name, HTML-encode the value.
                            var trustedFileNameForDisplay = WebUtility.HtmlEncode(contentDisposition.FileName.Value);
                            //var trustedFileNameForFileStorage = Path.GetRandomFileName();
                            var trustedFileNameForFileStorage = trustedFileNameForDisplay;

                            var fileInfo = tags == null ? null : await _fileInfoRepository.GetFileInfoAsync(trustedFileNameForFileStorage, tags[i]);

                            if (fileInfo == null)
                            {
                                // 文件不存在,保存文件并记录到数据库
                                // **WARNING!**
                                // In the following example, the file is saved without
                                // scanning the file's contents. In most production
                                // scenarios, an anti-virus/anti-malware scanner API
                                // is used on the file before making the file available
                                // for download or for use by other systems.
                                // For more information, see the topic that accompanies
                                // this sample.

                                var streamedFileContent = await FileHelpers.ProcessStreamedFile(
                                    section, contentDisposition, ModelState,
                                    _permittedExtensions, _streamingSettings.Value.FileSizeLimit);

                                if (!ModelState.IsValid)
                                {
                                    // 记录上传失败的文件
                                    failedUploads.Add(new UploadInfoDto {
                                        Name = trustedFileNameForFileStorage, Index = i
                                    });
                                    ModelState.Clear();

                                    _logger.LogError($"Upload file {contentDisposition.FileName.Value} failed.");
                                }
                                else
                                {
                                    var folder = tags == null ? _streamingSettings.Value.StoredFilesPath : GetFolderByTag(tags[i]);
                                    //var folder = Path.Combine(_streamingSettings.Value.StoredFilesPath, tags?[i].ToString().ToLower() ?? string.Empty);

                                    _logger.LogInformation("folder: {folder}", folder);

                                    //Directory.CreateDirectory(folder);
                                    var filePath = Path.Combine(folder, trustedFileNameForFileStorage);

                                    _logger.LogInformation("Save file at path: {filePath}", filePath);

                                    // 文件写入文件系统
                                    using (var targetStream = System.IO.File.Create(filePath))
                                    {
                                        await targetStream.WriteAsync(streamedFileContent);
                                    }

                                    // 文件信息存入到数据库中
                                    var command = new CreateFileInfoCommand {
                                        Name = trustedFileNameForFileStorage, FileTag = tags[i]
                                    };
                                    await _mediator.Send(command);

                                    // 记录上传成功的文件
                                    successUploads.Add(new UploadInfoDto {
                                        Name = trustedFileNameForFileStorage, Index = i
                                    });

                                    // 向前兼容:拷贝文件
                                    if (tags == null)
                                    {
                                        //var distFolder = Path.Combine(_streamingSettings.Value.StoredFilesPath, FileTag.App.ToString().ToLower());
                                        var distFolder = GetFolderByTag(FileTag.App);
                                        System.IO.File.Copy(filePath, Path.Combine(distFolder, trustedFileNameForFileStorage), true);
                                        _logger.LogInformation($"Copied file {filePath} to {distFolder}");

                                        //distFolder = Path.Combine(_streamingSettings.Value.StoredFilesPath, FileTag.AppOriginal.ToString().ToLower());
                                        distFolder = GetFolderByTag(FileTag.AppOriginal);
                                        System.IO.File.Copy(filePath, Path.Combine(distFolder, trustedFileNameForFileStorage), true);
                                        _logger.LogInformation($"Copied file {filePath} to {distFolder}");

                                        //distFolder = Path.Combine(_streamingSettings.Value.StoredFilesPath, FileTag.AppThumbnail.ToString().ToLower());
                                        distFolder = GetFolderByTag(FileTag.AppThumbnail);
                                        System.IO.File.Copy(filePath, Path.Combine(distFolder, trustedFileNameForFileStorage), true);
                                        _logger.LogInformation($"Copied file {filePath} to {distFolder}");

                                        //distFolder = Path.Combine(_streamingSettings.Value.StoredFilesPath, FileTag.AppVideo.ToString().ToLower());
                                        distFolder = GetFolderByTag(FileTag.AppVideo);
                                        System.IO.File.Copy(filePath, Path.Combine(distFolder, trustedFileNameForFileStorage), true);
                                        _logger.LogInformation($"Copied file {filePath} to {distFolder}");

                                        //distFolder = Path.Combine(_streamingSettings.Value.StoredFilesPath, FileTag.Chat.ToString().ToLower());
                                        distFolder = GetFolderByTag(FileTag.Chat);
                                        System.IO.File.Copy(filePath, Path.Combine(distFolder, trustedFileNameForFileStorage), true);
                                        _logger.LogInformation($"Copied file {filePath} to {distFolder}");

                                        //distFolder = Path.Combine(_streamingSettings.Value.StoredFilesPath, FileTag.ChatThumbnail.ToString().ToLower());
                                        distFolder = GetFolderByTag(FileTag.ChatThumbnail);
                                        System.IO.File.Copy(filePath, Path.Combine(distFolder, trustedFileNameForFileStorage), true);
                                        _logger.LogInformation($"Copied file {filePath} to {distFolder}");

                                        //distFolder = Path.Combine(_streamingSettings.Value.StoredFilesPath, FileTag.ChatVideo.ToString().ToLower());
                                        distFolder = GetFolderByTag(FileTag.ChatVideo);
                                        System.IO.File.Copy(filePath, Path.Combine(distFolder, trustedFileNameForFileStorage), true);
                                        _logger.LogInformation($"Copied file {filePath} to {distFolder}");
                                    }
                                    else
                                    {
                                        var distFolder = _streamingSettings.Value.StoredFilesPath;
                                        System.IO.File.Copy(filePath, Path.Combine(distFolder, trustedFileNameForFileStorage), true);
                                        _logger.LogInformation($"Copied file {filePath} to {distFolder}");
                                    }

                                    _logger.LogInformation(
                                        "Uploaded file '{TrustedFileNameForDisplay}' saved to " +
                                        "'{TargetFilePath}' as {TrustedFileNameForFileStorage}",
                                        trustedFileNameForDisplay, folder,
                                        trustedFileNameForFileStorage);
                                }
                            }
                            else
                            {
                                // 文件已存在,直接记录为上传成功
                                successUploads.Add(new UploadInfoDto {
                                    Name = trustedFileNameForFileStorage, Index = i
                                });
                                _logger.LogInformation($"File {trustedFileNameForFileStorage} already exists in database, skip.");
                            }
                        }
                    }

                    i++;
                    // Drain any remaining section body that hasn't been consumed and
                    // read the headers for the next section.
                    section = await reader.ReadNextSectionAsync();
                }

                //return Created(nameof(StreamingController), null);
                var uploadStatus = new UploadStatusDto {
                    SuccessUploads = successUploads, FailedUploads = failedUploads
                };
                if (failedUploads.Count > 0)
                {
                    return(StatusCode((int)HttpStatusCode.BadRequest,
                                      ResponseWrapper.CreateErrorResponseWrapper(Arise.DDD.API.Response.StatusCode.ClientError, "Upload Failed.", null, uploadStatus)));
                }
                else
                {
                    return(Ok(ResponseWrapper.CreateOkResponseWrapper(uploadStatus)));
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                Program.StreamingMre.Set();
            }
        }
Esempio n. 7
0
        private string GetFileName(string name)
        {
            string validFileName = FileHelpers.GetValidFileName(name.ToLowerInvariant());

            return(System.IO.Path.Combine(Hub.Instance.AppSettings.SettingsFolder, $"{validFileName}.libcfg"));
        }
Esempio n. 8
0
        public async Task <IActionResult> OnPostAsync(int?id)
        {
            if (!ModelState.IsValid)
            {
                var institutionalId = Context.Users.Single(u => u.Email.Equals(User.Identity.Name)).InstitutionId;
                var courses         = Context.Courses.Where(c => c.InstitutionId.Equals(institutionalId)).ToList();
                courses = courses.Prepend(new Course()
                {
                    Id         = 0,
                    CourseName = "Portal Only"
                }).ToList();
                ViewData["CourseId"]                              = new SelectList(courses, "Id", "CourseName");
                ViewData["LanguageId"]                            = new SelectList(Context.Languages, "Id", "Name");
                ViewData["FeedbackLevelOptionId"]                 = new SelectList(Context.FeedbackLevelOptions, "Id", "Name");
                ViewData["CoverageTypeLevelOptionId"]             = new SelectList(Context.CoverageTypeOptions, "Id", "Name");
                ViewData["TestingTypeOptionsId"]                  = new SelectList(Context.TestingTypeOptions, "Id", "Name");
                ViewData["AssignmentVisibilityProtectionLevelId"] = new SelectList(Context.AssignmentVisibilityProtectionLevels, "Id", "Name");
                ViewData["DifficultiesId"]                        = new SelectList(Context.Difficulties, "Id", "Value");
                ViewData["TagsId"] = new SelectList(Context.Tags, "Id", "Name");
                return(Page());
            }

            var assignmentToUpdate = await Context.GetAssignmentById(id);

            try
            {
                if (Assignment.CourseId == 0)
                {
                    Assignment.CourseId = null;
                }

                if (AssignmentSpecificationUpload != null)
                {
                    var file = FileHelpers.ProcessFormFile(AssignmentSpecificationUpload, ModelState);
                    var assignmentSpecification = new AssignmentSpecification
                    {
                        FileName  = file.FileName,
                        FileBytes = file.FileBytes
                    };

                    Context.AssignmentSpecifications.Add(assignmentSpecification);
                    await Context.SaveChangesAsync();

                    assignmentToUpdate.AssignmentSpecificationId = 0;
                    assignmentToUpdate.AssignmentSpecification   = assignmentSpecification;
                    await Context.SaveChangesAsync();
                }

                if (ReferenceSolutionUpload != null)
                {
                    var file = FileHelpers.ProcessFormFile(ReferenceSolutionUpload, ModelState);
                    var referenceSolution = new ReferenceSolution
                    {
                        FileName  = file.FileName,
                        FileBytes = file.FileBytes
                    };

                    Context.ReferenceSolutions.Add(referenceSolution);
                    await Context.SaveChangesAsync();

                    assignmentToUpdate.ReferenceSolutionId = 0;
                    assignmentToUpdate.ReferenceSolution   = referenceSolution;
                    await Context.SaveChangesAsync();
                }

                if (ReferenceTestCasesSolutionsUpload != null)
                {
                    var file = FileHelpers.ProcessFormFile(ReferenceTestCasesSolutionsUpload, ModelState);
                    var referenceTestCasesSolutions = new ReferenceTestCasesSolutions
                    {
                        FileName  = file.FileName,
                        FileBytes = file.FileBytes
                    };

                    Context.ReferenceTestCasesSolutions.Add(referenceTestCasesSolutions);
                    await Context.SaveChangesAsync();

                    assignmentToUpdate.ReferenceTestCasesSolutionsId = 0;
                    assignmentToUpdate.ReferenceTestCasesSolutions   = referenceTestCasesSolutions;
                    await Context.SaveChangesAsync();
                }

                assignmentToUpdate.Name = Assignment.Name;
                assignmentToUpdate.TestCoverageLevel     = Assignment.TestCoverageLevel;
                assignmentToUpdate.RedundantTestLevel    = Assignment.RedundantTestLevel;
                assignmentToUpdate.LanguageId            = Assignment.LanguageId;
                assignmentToUpdate.CourseId              = Assignment.CourseId;
                assignmentToUpdate.FeedbackLevelOptionId = Assignment.FeedbackLevelOptionId;
                assignmentToUpdate.TestingTypeOptionId   = Assignment.TestingTypeOptionId;
                assignmentToUpdate.AssignmentVisibilityProtectionLevelId =
                    Assignment.AssignmentVisibilityProtectionLevelId;

                ApplicationModes.ToList().ForEach(m =>
                {
                    if (assignmentToUpdate.AssignmentApplicationModes.ToList().Exists(x => x.ApplicationMode.Name.Equals(m.Name)))
                    {
                        assignmentToUpdate.AssignmentApplicationModes.First(x => x.ApplicationMode.Name.Equals(m.Name)).IsChecked =
                            m.IsChecked ? true : false;
                    }
                });

                CoverageTypeOptions.ToList().ForEach(o =>
                {
                    if (assignmentToUpdate.AssignmentCoverageTypeOptions.ToList().Exists(x => x.CoverageTypeOption.Name.Equals(o.Name)))
                    {
                        assignmentToUpdate.AssignmentCoverageTypeOptions.First(a => a.CoverageTypeOption.Name.Equals(o.Name)).IsChecked = o.IsChecked ? true : false;
                    }
                });


                await Context.SaveChangesAsync();

                foreach (var tag in AddedTags)
                {
                    if (await Context.Tags.FirstOrDefaultAsync(t => t.Name.Equals(tag)) == null)
                    {
                        Context.Tags.Add(new Tag()
                        {
                            Name = tag
                        });
                    }
                }

                await Context.SaveChangesAsync();

                assignmentToUpdate.Tags = new List <AssignmentTag>();
                foreach (var tag in Tags)
                {
                    if (tag < 0)
                    {
                        assignmentToUpdate.Tags.Add(new AssignmentTag()
                        {
                            Tag = Context.Tags.First(t => t.Name.Equals(AddedTags[tag * -1 - 1]))
                        });
                    }
                    else if (assignmentToUpdate.Tags.FirstOrDefault(t => t.TagId.Equals(tag)) == null)
                    {
                        assignmentToUpdate.Tags.Add(new AssignmentTag()
                        {
                            Tag = Context.Tags.First(t => t.Id.Equals(tag))
                        });
                    }
                }

                Context.Update(assignmentToUpdate);
                await Context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AssignmentExists(Assignment.Id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(RedirectToPage("./Index"));
        }
Esempio n. 9
0
        /// <param name="audioEngine">AudioEngine that will be associated with this sound bank.</param>
        /// <param name="fileName">Path to a .xsb SoundBank file.</param>
        public SoundBank(AudioEngine audioEngine, string fileName)
        {
            _audioengine = audioEngine;
            fileName     = FileHelpers.NormalizeFilePathSeparators(fileName);

#if !ANDROID
            using (var stream = TitleContainer.OpenStream(fileName))
            {
#else
            using (var fileStream = Game.Activity.Assets.Open(fileName))
            {
                MemoryStream stream = new MemoryStream();
                fileStream.CopyTo(stream);
                stream.Position = 0;
#endif
                using (var reader = new BinaryReader(stream))
                {
                    // Thanks to Liandril for "xactxtract" for some of the offsets.

                    uint magic = reader.ReadUInt32();
                    if (magic != 0x4B424453) //"SDBK"
                    {
                        throw new Exception("Bad soundbank format");
                    }

                    reader.ReadUInt16(); // toolVersion

                    uint formatVersion = reader.ReadUInt16();
                    // TODO: This does not match XNA, XNA uses 43.
                    if (formatVersion != 46)
                    {
                        Debug.WriteLine("Warning: SoundBank format {0} not supported.", formatVersion);
                    }

                    reader.ReadUInt16(); // crc, TODO: Verify crc (FCS16)

                    reader.ReadUInt32(); // lastModifiedLow
                    reader.ReadUInt32(); // lastModifiedHigh
                    reader.ReadByte();   // platform ???

                    uint numSimpleCues  = reader.ReadUInt16();
                    uint numComplexCues = reader.ReadUInt16();
                    reader.ReadUInt16(); //unkn
                    reader.ReadUInt16(); // numTotalCues
                    uint numWaveBanks = reader.ReadByte();
                    reader.ReadUInt16(); // numSounds
                    uint cueNameTableLen = reader.ReadUInt16();
                    reader.ReadUInt16(); //unkn

                    uint simpleCuesOffset  = reader.ReadUInt32();
                    uint complexCuesOffset = reader.ReadUInt32(); //unkn
                    uint cueNamesOffset    = reader.ReadUInt32();
                    reader.ReadUInt32();                          //unkn
                    reader.ReadUInt32();                          // variationTablesOffset
                    reader.ReadUInt32();                          //unkn
                    uint waveBankNameTableOffset = reader.ReadUInt32();
                    reader.ReadUInt32();                          // cueNameHashTableOffset
                    reader.ReadUInt32();                          // cueNameHashValsOffset
                    reader.ReadUInt32();                          // soundsOffset

                    //name = System.Text.Encoding.UTF8.GetString(soundbankreader.ReadBytes(64),0,64).Replace("\0","");

                    //parse wave bank name table
                    stream.Seek(waveBankNameTableOffset, SeekOrigin.Begin);
                    _waveBanks     = new WaveBank[numWaveBanks];
                    _waveBankNames = new string[numWaveBanks];
                    for (int i = 0; i < numWaveBanks; i++)
                    {
                        _waveBankNames[i] = System.Text.Encoding.UTF8.GetString(reader.ReadBytes(64), 0, 64).Replace("\0", "");
                    }

                    //parse cue name table
                    stream.Seek(cueNamesOffset, SeekOrigin.Begin);
                    string[] cueNames = System.Text.Encoding.UTF8.GetString(reader.ReadBytes((int)cueNameTableLen), 0, (int)cueNameTableLen).Split('\0');

                    // Simple cues
                    if (numSimpleCues > 0)
                    {
                        stream.Seek(simpleCuesOffset, SeekOrigin.Begin);
                        for (int i = 0; i < numSimpleCues; i++)
                        {
                            reader.ReadByte(); // flags
                            uint soundOffset = reader.ReadUInt32();

                            var oldPosition = stream.Position;
                            stream.Seek(soundOffset, SeekOrigin.Begin);
                            XactSound sound = new XactSound(this, reader);
                            stream.Seek(oldPosition, SeekOrigin.Begin);

                            Cue cue = new Cue(_audioengine, cueNames[i], sound);
                            _cues.Add(cue.Name, cue);
                        }
                    }

                    // Complex cues
                    if (numComplexCues > 0)
                    {
                        stream.Seek(complexCuesOffset, SeekOrigin.Begin);
                        for (int i = 0; i < numComplexCues; i++)
                        {
                            Cue cue;

                            byte flags = reader.ReadByte();
                            if (((flags >> 2) & 1) != 0)
                            {
                                uint soundOffset = reader.ReadUInt32();
                                reader.ReadUInt32(); //unkn

                                var oldPosition = stream.Position;
                                stream.Seek(soundOffset, SeekOrigin.Begin);
                                XactSound sound = new XactSound(this, reader);
                                stream.Seek(oldPosition, SeekOrigin.Begin);

                                cue = new Cue(_audioengine, cueNames[numSimpleCues + i], sound);
                            }
                            else
                            {
                                uint variationTableOffset = reader.ReadUInt32();
                                reader.ReadUInt32(); // transitionTableOffset

                                //parse variation table
                                long savepos = stream.Position;
                                stream.Seek(variationTableOffset, SeekOrigin.Begin);

                                uint numEntries     = reader.ReadUInt16();
                                uint variationflags = reader.ReadUInt16();
                                reader.ReadByte();
                                reader.ReadUInt16();
                                reader.ReadByte();

                                XactSound[] cueSounds = new XactSound[numEntries];
                                float[]     probs     = new float[numEntries];

                                uint tableType = (variationflags >> 3) & 0x7;
                                for (int j = 0; j < numEntries; j++)
                                {
                                    switch (tableType)
                                    {
                                    case 0:     //Wave
                                    {
                                        int trackIndex    = reader.ReadUInt16();
                                        int waveBankIndex = reader.ReadByte();
                                        reader.ReadByte();         // weightMin
                                        reader.ReadByte();         // weightMax

                                        cueSounds[j] = new XactSound(this, waveBankIndex, trackIndex);
                                        break;
                                    }

                                    case 1:
                                    {
                                        uint soundOffset = reader.ReadUInt32();
                                        reader.ReadByte();         // weightMin
                                        reader.ReadByte();         // weightMax

                                        var oldPosition = stream.Position;
                                        stream.Seek(soundOffset, SeekOrigin.Begin);
                                        cueSounds[j] = new XactSound(this, reader);
                                        stream.Seek(oldPosition, SeekOrigin.Begin);
                                        break;
                                    }

                                    case 3:
                                    {
                                        uint soundOffset = reader.ReadUInt32();
                                        reader.ReadSingle();         // weightMin
                                        reader.ReadSingle();         // weightMax
                                        reader.ReadUInt32();         // flags

                                        var oldPosition = stream.Position;
                                        stream.Seek(soundOffset, SeekOrigin.Begin);
                                        cueSounds[j] = new XactSound(this, reader);
                                        stream.Seek(oldPosition, SeekOrigin.Begin);
                                        break;
                                    }

                                    case 4:     //CompactWave
                                    {
                                        int trackIndex    = reader.ReadUInt16();
                                        int waveBankIndex = reader.ReadByte();
                                        cueSounds[j] = new XactSound(this, waveBankIndex, trackIndex);
                                        break;
                                    }

                                    default:
                                        throw new NotSupportedException();
                                    }
                                }

                                stream.Seek(savepos, SeekOrigin.Begin);

                                cue = new Cue(_audioengine, cueNames[numSimpleCues + i], cueSounds, probs);
                            }

                            // Instance limiting
                            reader.ReadByte();   //instanceLimit
                            reader.ReadUInt16(); //fadeInSec, divide by 1000.0f
                            reader.ReadUInt16(); //fadeOutSec, divide by 1000.0f
                            reader.ReadByte();   //instanceFlags

                            _cues.Add(cue.Name, cue);
                        }
                    }
                }
            }
        }
Esempio n. 10
0
 public void Save()
 {
     FileHelpers.Save(this, FilePath);
 }
Esempio n. 11
0
        public async Task <IActionResult> UploadDatabase()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                ModelState.AddModelError("File",
                                         $"The request couldn't be processed (Error 1).");
                // Log error

                return(BadRequest(ModelState));
            }

            // Accumulate the form data key-value pairs in the request (formAccumulator).
            var formAccumulator             = new KeyValueAccumulator();
            var trustedFileNameForDisplay   = string.Empty;
            var untrustedFileNameForStorage = string.Empty;
            var streamedFileContent         = new byte[0];

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

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

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper
                        .HasFileContentDisposition(contentDisposition))
                    {
                        untrustedFileNameForStorage = contentDisposition.FileName.Value;
                        // Don't trust the file name sent by the client. To display
                        // the file name, HTML-encode the value.
                        trustedFileNameForDisplay = WebUtility.HtmlEncode(
                            contentDisposition.FileName.Value);

                        streamedFileContent =
                            await FileHelpers.ProcessStreamedFile(section, contentDisposition,
                                                                  ModelState, _permittedExtentions, _fileSizeLimit);

                        if (!ModelState.IsValid)
                        {
                            return(BadRequest(ModelState));
                        }
                    }
                    else if (MultipartRequestHelper
                             .HasFormDataContentDisposition(contentDisposition))
                    {
                        // Don't limit the key name length because the
                        // multipart headers length limit is already in effect.
                        var key = HeaderUtilities
                                  .RemoveQuotes(contentDisposition.Name).Value;
                        var encoding = GetEncoding(section);

                        if (encoding == null)
                        {
                            ModelState.AddModelError("File",
                                                     $"The request couldn't be processed (Error 2).");
                            // Log error

                            return(BadRequest(ModelState));
                        }

                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by
                            // MultipartBodyLengthLimit
                            var value = await streamReader.ReadToEndAsync();

                            if (string.Equals(value, "undefined",
                                              StringComparison.OrdinalIgnoreCase))
                            {
                                value = string.Empty;
                            }

                            formAccumulator.Append(key, value);

                            if (formAccumulator.ValueCount >
                                _defaultFormOptions.ValueCountLimit)
                            {
                                // Form key count limit of
                                // _defaultFormOptions.ValueCountLimit
                                // is exceeded.
                                ModelState.AddModelError("File",
                                                         $"The request couldn't be processed (Error 3).");
                                // Log error

                                return(BadRequest(ModelState));
                            }
                        }
                    }
                }

                // Drain any remaining section body that hasn't been consumed and
                // read the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            // Bind form data to the model
            var formData          = new FormData();
            var formValueProvider = new FormValueProvider(
                BindingSource.Form,
                new FormCollection(formAccumulator.GetResults()),
                CultureInfo.CurrentCulture);
            var bindingSuccessful = await TryUpdateModelAsync(formData, prefix : "",
                                                              valueProvider : formValueProvider);

            if (!bindingSuccessful)
            {
                ModelState.AddModelError("File",
                                         "The request couldn't be processed (Error 5).");
                // Log error

                return(BadRequest(ModelState));
            }

            // **WARNING!**
            // In the following example, the file is saved without
            // scanning the file's contents. In most production
            // scenarios, an anti-virus/anti-malware scanner API
            // is used on the file before making the file available
            // for download or for use by other systems.
            // For more information, see the topic that accompanies
            // this sample app.

            var file = new ClamSectionAcademicSubCategoryItem()
            {
                ItemPath        = null,
                ItemTitle       = untrustedFileNameForStorage,
                ItemDescription = formData.Note,
                Size            = streamedFileContent.Length,
                DateAdded       = DateTime.Now,
                SubCategoryId   = new Guid("8d7af8fa-4659-4aef-1746-08d7d7789232")
            };

            _context.Add(file);
            await _context.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Esempio n. 12
0
        public async Task <IActionResult> UploadDatabase()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                ModelState.AddModelError("File",
                                         $"The request couldn't be processed (Error 1).");
                // Log error

                return(BadRequest(ModelState));
            }

            // User Profile
            var name    = User.Identity.Name;
            var profile = await _userManager.FindByNameAsync(name);

            // Accumulate the form data key-value pairs in the request (formAccumulator).
            var formAccumulator               = new KeyValueAccumulator();
            var trustedFileNameForDisplay     = string.Empty;
            var untrustedFileNameForStorage   = string.Empty;
            var trustedFilePathStorage        = string.Empty;
            var trustedFileNameForFileStorage = string.Empty;
            var streamedFileImageContent      = new byte[0];
            var streamedFilePhysicalContent   = new byte[0];


            // List Byte for file storage
            List <byte[]> filesByteStorage         = new List <byte[]>();
            List <string> filesNameStorage         = new List <string>();
            List <string> storedPaths              = new List <string>();
            List <string> storedPathDictionaryKeys = new List <string>();
            var           fileStoredData           = new Dictionary <string, byte[]>();

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

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

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper
                        .HasFileContentDisposition(contentDisposition))
                    {
                        untrustedFileNameForStorage = contentDisposition.FileName.Value;
                        // Don't trust the file name sent by the client. To display
                        // the file name, HTML-encode the value.
                        trustedFileNameForDisplay = WebUtility.HtmlEncode(
                            contentDisposition.FileName.Value);

                        if (!Directory.Exists(_targetFilePath))
                        {
                            string path = String.Format("{0}", _targetFilePath);
                            Directory.CreateDirectory(path);
                        }

                        //streamedFileContent =
                        //    await FileHelpers.ProcessStreamedFile(section, contentDisposition,
                        //        ModelState, _permittedExtentions, _fileSizeLimit);

                        streamedFilePhysicalContent = await FileHelpers.ProcessStreamedFile(
                            section, contentDisposition, ModelState,
                            _permittedExtentions, _fileSizeLimit);

                        filesNameStorage.Add(trustedFileNameForDisplay);
                        filesByteStorage.Add(streamedFilePhysicalContent);
                        fileStoredData.Add(trustedFileNameForDisplay, streamedFilePhysicalContent);
                        // Debug
                        //var errors = ModelState.ErrorCount;
                        //var errorView = ModelState.Where(x => x.Value.Errors.Count > 0)
                        //    .Select(x => new { x.Key, x.Value.Errors }).ToArray();
                        if (!ModelState.IsValid)
                        {
                            return(BadRequest(ModelState));
                        }
                    }
                    else if (MultipartRequestHelper
                             .HasFormDataContentDisposition(contentDisposition))
                    {
                        // Don't limit the key name length because the
                        // multipart headers length limit is already in effect.
                        var key = HeaderUtilities
                                  .RemoveQuotes(contentDisposition.Name).Value;
                        var encoding = GetEncoding(section);

                        if (encoding == null)
                        {
                            ModelState.AddModelError("File",
                                                     $"The request couldn't be processed (Error 2).");
                            // Log error

                            return(BadRequest(ModelState));
                        }

                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by
                            // MultipartBodyLengthLimit
                            var value = await streamReader.ReadToEndAsync();

                            if (string.Equals(value, "undefined",
                                              StringComparison.OrdinalIgnoreCase))
                            {
                                value = string.Empty;
                            }

                            formAccumulator.Append(key, value);

                            if (formAccumulator.ValueCount >
                                _defaultFormOptions.ValueCountLimit)
                            {
                                // Form key count limit of
                                // _defaultFormOptions.ValueCountLimit
                                // is exceeded.
                                ModelState.AddModelError("File",
                                                         $"The request couldn't be processed (Error 3).");
                                // Log error

                                return(BadRequest(ModelState));
                            }
                        }
                    }
                }

                // Drain any remaining section body that hasn't been consumed and
                // read the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            // Bind form data to the model
            var formData          = new StreamFormDataBooks();
            var formValueProvider = new FormValueProvider(
                BindingSource.Form,
                new FormCollection(formAccumulator.GetResults()),
                CultureInfo.CurrentCulture);
            var bindingSuccessful = await TryUpdateModelAsync(formData, prefix : "",
                                                              valueProvider : formValueProvider);

            var keyPathFolder = FilePathUrlHelper.GenerateKeyPath(profile.Id);

            trustedFilePathStorage = String.Format("{0}\\{1}\\{2}\\{3}",
                                                   _targetFolderPath,
                                                   keyPathFolder,
                                                   GenerateSecurity.Encode(profile.Id),
                                                   Path.GetRandomFileName());

            if (!bindingSuccessful)
            {
                ModelState.AddModelError("File",
                                         "The request couldn't be processed (Error 5).");
                // Log error

                return(BadRequest(ModelState));
            }

            // **WARNING!**
            // In the following example, the file is saved without
            // scanning the file's contents. In most production
            // scenarios, an anti-virus/anti-malware scanner API
            // is used on the file before making the file available
            // for download or for use by other systems.
            // For more information, see the topic that accompanies
            // this sample app.

            Directory.CreateDirectory(trustedFilePathStorage);

            foreach (var item in fileStoredData)
            {
                using (var targetStream = System.IO.File.Create(
                           Path.Combine(trustedFilePathStorage, item.Key)))
                {
                    await targetStream.WriteAsync(item.Value);

                    _logger.LogInformation(
                        "Uploaded file '{TrustedFileNameForDisplay}' saved to " +
                        "'{TargetFilePath}' as {TrustedFileNameForFileStorage}",
                        item.Key, trustedFilePathStorage,
                        item.Key);
                }
                storedPaths.Add(Path.Combine(trustedFilePathStorage, item.Key));
                storedPathDictionaryKeys.Add(item.Key);
            }

            var keyValue   = storedPathDictionaryKeys[0];
            var keyConvert = fileStoredData[keyValue];
            var file       = new ClamUserBooks()
            {
                BookTitle   = formData.BookTitle,
                ItemPath    = storedPaths[0],
                ImagePath   = storedPaths[1],
                Size        = keyConvert.Length,
                DateCreated = DateTime.Now,
                Status      = bool.Parse(formData.Status),
                UserId      = profile.Id
            };

            _context.Add(file);
            await _context.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Esempio n. 13
0
        public async Task <IActionResult> OnPostAsync(int id)
        {
            if (!ModelState.IsValid)
            {
                Result = "Please correct the form.";

                return(Page());
            }

            // load group data from db
            Group = await _context.Groups
                    .Include(m => m.Images)
                    .FirstOrDefaultAsync(m => m.GroupId == id);

            if (Group == null)
            {
                return(NotFound());
            }

            ImagesOriginalFileName = Group.Images.Select(m => m.UntrustedFileName).ToList();

            if (FileUpload == null)
            {
            }
            else
            {
                var formFileContent =
                    await FileHelpers.ProcessFormFile(
                        FileUpload, ModelState, _permittedExtensions,
                        _fileSizeLimit, ImagesOriginalFileName);

                if (formFileContent.Length == 0)
                {
                    // the file user attempted to upload doesn't check out, so do nothing
                }
                else
                {
                    // For the file name of the uploaded file stored
                    // server-side, use Path.GetRandomFileName to generate a safe
                    // random file name, but change extension back to that of the original image, so it's usable
                    var    trustedFileNameForFileStorage = Path.GetRandomFileName();
                    string extension = Path.GetExtension(FileUpload.FileName);
                    trustedFileNameForFileStorage = Path.ChangeExtension(trustedFileNameForFileStorage, extension);
                    var filePath = Path.Combine(
                        _targetFilePath, trustedFileNameForFileStorage);

                    // Get image data and store it in database
                    Image.UntrustedFileName = FileUpload.FileName;
                    Image.SafeFileName      = trustedFileNameForFileStorage;
                    Image.GroupId           = id;

                    // store image in separate location
                    using (var fileStream = System.IO.File.Create(filePath))
                    {
                        await fileStream.WriteAsync(formFileContent);
                    }

                    _context.Images.Add(Image);
                    await _context.SaveChangesAsync();

                    // after storing image data, get the image ID from db and store as group BannerImg
                    Image.Id = (from g in _context.Images
                                where g.GroupId == id && g.SafeFileName == Image.SafeFileName
                                select g.Id).First();

                    // store new group BannerImg
                    Group.BannerImg = Image;
                }
            }

            // update group data from form
            if (await TryUpdateModelAsync <Group>(
                    Group,
                    "group",
                    m => m.Name, m => m.PrivacyType, m => m.Description, m => m.CityState))
            {
                await _context.SaveChangesAsync();

                return(RedirectToPage("Landing",
                                      new { id = id }));
            }

            return(Page());
        }
Esempio n. 14
0
 static void engine_BeforeWriteRecord(EngineBase engine, FileHelpers.Events.BeforeWriteEventArgs<FixedSampleRecord> e)
 {
 }
Esempio n. 15
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var activity = await result as Activity;

            // Strip out all mentions.  As all channel messages to a bot must @mention the bot itself, you must strip out the bot name at minimum.
            // This uses the extension SDK function GetTextWithoutMentions() to strip out ALL mentions
            var text = activity.GetTextWithoutMentions();

            if (text == null && (activity.Attachments != null && activity.Attachments.Count == 0))
            {
                // if the activity is not a system event, and it does not have text or attachment, treat it as a SubmitAction
                //await HandleSubmitAction(context, activity);
            }
            else
            {
                #region Receive file
                // If a file was sent, echo back its name try to read it.
                if (activity.Attachments != null && activity.Attachments.Count > 0)
                {
                    foreach (var attachment in activity.Attachments)
                    {
                        if (attachment.ContentType == FileDownloadInfo.ContentType)
                        {
                            //await context.PostAsync($"Received a file named {attachment.Name}");
                            await FileHelpers.ProcessAttachment(attachment, context);
                        }
                    }
                }
                #endregion

                if (!String.IsNullOrEmpty(text))
                {
                    // Check for suppported commands
                    // This simple text parsing assumes the command is the first two tokens,
                    // and parameters are the remainder.
                    var split = text.Split(' ');
                    // The user is asking for one of the supported commands.
                    if (split.Length >= 2)
                    {
                        var cmd      = split[0].ToLower();
                        var keywords = split.Skip(2).ToArray();

                        #region Commands

                        if (cmd.Contains("resume"))
                        {
                            // Return "resume file" for the given candidate name.
                            await HandleResumeCommand(context, keywords);
                        }
                        else if (cmd.Contains("schedule"))
                        {
                            await CommandHandlers.HandleScheduleCommand(context, activity, keywords);
                        }
                        else if (cmd.Contains("open"))
                        {
                            await CommandHandlers.HandleOpenCommand(context);
                        }
                        else if (cmd.Contains("candidate"))
                        {
                            await CommandHandlers.HandleCandidateCommand(context, activity, keywords);
                        }
                        else if (cmd.Contains("new"))
                        {
                            await CommandHandlers.HandleNewCommand(context);
                        }
                        else if (cmd.Contains("assign"))
                        {
                            await CommandHandlers.HandleAssignCommand(context, split);
                        }

                        #endregion
                    }
                    else if (text.Contains("help"))
                    {
                        // Respond with standard help message.
                        await MessageHelpers.SendMessage(context, MessageHelpers.CreateHelpMessage("Sure, I can provide help info about me."));
                    }
                    else if (text.Contains("profile"))
                    {
                        await CommandHandlers.HandleProfileCommand(context);

                        return;
                    }
                    else if (text.Contains("welcome") || text.Contains("hello") || text.Contains("hi"))
                    {
                        await MessageHelpers.SendMessage(context, MessageHelpers.CreateHelpMessage("## Welcome to the Contoso Talent Management app"));
                    }
                    else
                    // Don't know what to say so this is the generic handling here.
                    {
                        await MessageHelpers.SendMessage(context, MessageHelpers.CreateHelpMessage("I'm sorry, I did not understand you :("));
                    }
                }
            }
            context.Wait(MessageReceivedAsync);
        }
        public async Task <IActionResult> OnPostAsync(int id)
        {
            Validation = await _context.Validation
                         .Include(m => m.MalfunctionWorkOrder)
                         .ThenInclude(m => m.Instrument)
                         .FirstOrDefaultAsync(m => m.ID == id);

            if (Validation == null)
            {
                return(NotFound());
            }

            // 如果信息已确认或工单已完成则跳转到工单详情页
            if (Validation.IsConfirm || Validation.MalfunctionWorkOrder.Progress == WorkOrderProgress.Completed)
            {
                return(RedirectToPage("../WorkOrders/Details", new { id = Validation.MalfunctionWorkOrderID }));
            }

            var isAuthorized = await _authorizationService.AuthorizeAsync(User, Validation.MalfunctionWorkOrder, Operations.Update);

            if (!isAuthorized.Succeeded)
            {
                return(Forbid());
            }

            if (await TryUpdateModelAsync <Validation>(
                    Validation,
                    "Validation",
                    i => i.FinishedTime, i => i.IsConfirm, i => i.Summary))
            {
                // 更新进度
                if (Validation.MalfunctionWorkOrder.Progress < WorkOrderProgress.Validated)
                {
                    Validation.MalfunctionWorkOrder.Progress = WorkOrderProgress.Validated;
                }

                // 上传故障修复后性能验证报告
                if (FileUpload.PerformanceReportFile != null)
                {
                    var formFileContent =
                        await FileHelpers.ProcessFormFile <Upload>(
                            FileUpload.PerformanceReportFile, ModelState, _fileSizeLimit);

                    if (!ModelState.IsValid)
                    {
                        return(Page());
                    }

                    var filename = Path.GetFileName(FileUpload.PerformanceReportFile.FileName);
                    var filepath = FileHelpers.CreateFilePath(_uploadFilePath, filename);
                    FileHelpers.SaveFile(formFileContent, filepath);
                    FileHelpers.DeleteOlderFile(Validation.PerformanceReportFilePath);

                    Validation.PerformanceReportFilePath = filepath;
                    Validation.PerformanceReportFileName = filename;
                }

                // 上传附件
                if (FileUpload.Attachment != null)
                {
                    var formFileContent =
                        await FileHelpers.ProcessFormFile <Upload>(
                            FileUpload.Attachment, ModelState, _fileSizeLimit);

                    if (!ModelState.IsValid)
                    {
                        return(Page());
                    }

                    var filename = Path.GetFileName(FileUpload.Attachment.FileName);
                    var filepath = FileHelpers.CreateFilePath(_uploadFilePath, filename);
                    FileHelpers.SaveFile(formFileContent, filepath);
                    FileHelpers.DeleteOlderFile(Validation.AttachmentFilePath);

                    Validation.AttachmentFilePath = filepath;
                    Validation.AttachmentName     = filename;
                }

                await _context.SaveChangesAsync();

                return(RedirectToPage("../WorkOrders/Details", new { id = Validation.MalfunctionWorkOrderID }));
            }
            return(Page());
        }
        protected async override Task <CompilerResult> RunCompilerAsync(string sourcePath, string targetPath)
        {
            var result = new MarkdownSharp.Markdown(WESettings.Instance.Markdown).Transform(await FileHelpers.ReadAllTextRetry(sourcePath));

            if (!string.IsNullOrEmpty(targetPath))
            {
                ProjectHelpers.CheckOutFileFromSourceControl(targetPath);   // TODO: Only if output changed?
                await FileHelpers.WriteAllTextRetry(targetPath, result);
            }

            var compilerResult = await CompilerResultFactory.GenerateResult(sourcePath, targetPath, true, result, null);

            return(compilerResult);
        }
Esempio n. 18
0
        /// <param name="audioEngine">Instance of the AudioEngine to associate this wave bank with.</param>
        /// <param name="nonStreamingWaveBankFilename">Path to the .xwb file to load.</param>
        /// <remarks>This constructor immediately loads all wave data into memory at once.</remarks>
        public WaveBank(AudioEngine audioEngine, string nonStreamingWaveBankFilename)
        {
            //XWB PARSING
            //Adapted from MonoXNA
            //Originally adaped from Luigi Auriemma's unxwb

            WaveBankHeader wavebankheader;
            WaveBankData   wavebankdata;
            WaveBankEntry  wavebankentry;

            wavebankdata.EntryNameElementSize = 0;
            wavebankdata.CompactFormat        = 0;
            wavebankdata.Alignment            = 0;
            wavebankdata.BuildTime            = 0;

            wavebankentry.Format            = 0;
            wavebankentry.PlayRegion.Length = 0;
            wavebankentry.PlayRegion.Offset = 0;

            int wavebank_offset = 0;

            nonStreamingWaveBankFilename = FileHelpers.NormalizeFilePathSeparators(nonStreamingWaveBankFilename);

#if !ANDROID
            BinaryReader reader = new BinaryReader(TitleContainer.OpenStream(nonStreamingWaveBankFilename));
#else
            Stream       stream = Game.Activity.Assets.Open(nonStreamingWaveBankFilename);
            MemoryStream ms     = new MemoryStream();
            stream.CopyTo(ms);
            stream.Close();
            ms.Position = 0;
            BinaryReader reader = new BinaryReader(ms);
#endif
            reader.ReadBytes(4);

            wavebankheader.Version = reader.ReadInt32();

            int last_segment = 4;
            //if (wavebankheader.Version == 1) goto WAVEBANKDATA;
            if (wavebankheader.Version <= 3)
            {
                last_segment = 3;
            }
            if (wavebankheader.Version >= 42)
            {
                reader.ReadInt32();                                  // skip HeaderVersion
            }
            wavebankheader.Segments = new Segment[5];

            for (int i = 0; i <= last_segment; i++)
            {
                wavebankheader.Segments[i].Offset = reader.ReadInt32();
                wavebankheader.Segments[i].Length = reader.ReadInt32();
            }

            reader.BaseStream.Seek(wavebankheader.Segments[0].Offset, SeekOrigin.Begin);

            //WAVEBANKDATA:

            wavebankdata.Flags      = reader.ReadInt32();
            wavebankdata.EntryCount = reader.ReadInt32();

            if ((wavebankheader.Version == 2) || (wavebankheader.Version == 3))
            {
                wavebankdata.BankName = System.Text.Encoding.UTF8.GetString(reader.ReadBytes(16), 0, 16).Replace("\0", "");
            }
            else
            {
                wavebankdata.BankName = System.Text.Encoding.UTF8.GetString(reader.ReadBytes(64), 0, 64).Replace("\0", "");
            }

            _bankName = wavebankdata.BankName;

            if (wavebankheader.Version == 1)
            {
                //wavebank_offset = (int)ftell(fd) - file_offset;
                wavebankdata.EntryMetaDataElementSize = 20;
            }
            else
            {
                wavebankdata.EntryMetaDataElementSize = reader.ReadInt32();
                wavebankdata.EntryNameElementSize     = reader.ReadInt32();
                wavebankdata.Alignment = reader.ReadInt32();
                wavebank_offset        = wavebankheader.Segments[1].Offset; //METADATASEGMENT
            }

            if ((wavebankdata.Flags & Flag_Compact) != 0)
            {
                reader.ReadInt32(); // compact_format
            }

            int playregion_offset = wavebankheader.Segments[last_segment].Offset;
            if (playregion_offset == 0)
            {
                playregion_offset =
                    wavebank_offset +
                    (wavebankdata.EntryCount * wavebankdata.EntryMetaDataElementSize);
            }

            int segidx_entry_name = 2;
            if (wavebankheader.Version >= 42)
            {
                segidx_entry_name = 3;
            }

            if ((wavebankheader.Segments[segidx_entry_name].Offset != 0) &&
                (wavebankheader.Segments[segidx_entry_name].Length != 0))
            {
                if (wavebankdata.EntryNameElementSize == -1)
                {
                    wavebankdata.EntryNameElementSize = 0;
                }
                byte[] entry_name = new byte[wavebankdata.EntryNameElementSize + 1];
                entry_name[wavebankdata.EntryNameElementSize] = 0;
            }

            _sounds = new SoundEffect[wavebankdata.EntryCount];

            for (int current_entry = 0; current_entry < wavebankdata.EntryCount; current_entry++)
            {
                reader.BaseStream.Seek(wavebank_offset, SeekOrigin.Begin);
                //SHOWFILEOFF;

                //memset(&wavebankentry, 0, sizeof(wavebankentry));
                wavebankentry.LoopRegion.Length = 0;
                wavebankentry.LoopRegion.Offset = 0;

                if ((wavebankdata.Flags & Flag_Compact) != 0)
                {
                    int len = reader.ReadInt32();
                    wavebankentry.Format            = wavebankdata.CompactFormat;
                    wavebankentry.PlayRegion.Offset = (len & ((1 << 21) - 1)) * wavebankdata.Alignment;
                    wavebankentry.PlayRegion.Length = (len >> 21) & ((1 << 11) - 1);

                    // workaround because I don't know how to handke the deviation length
                    reader.BaseStream.Seek(wavebank_offset + wavebankdata.EntryMetaDataElementSize, SeekOrigin.Begin);

                    //MYFSEEK(wavebank_offset + wavebankdata.dwEntryMetaDataElementSize); // seek to the next
                    if (current_entry == (wavebankdata.EntryCount - 1))
                    {              // the last track
                        len = wavebankheader.Segments[last_segment].Length;
                    }
                    else
                    {
                        len = ((reader.ReadInt32() & ((1 << 21) - 1)) * wavebankdata.Alignment);
                    }
                    wavebankentry.PlayRegion.Length =
                        len -                             // next offset
                        wavebankentry.PlayRegion.Offset;  // current offset
                    goto wavebank_handle;
                }

                if (wavebankheader.Version == 1)
                {
                    wavebankentry.Format            = reader.ReadInt32();
                    wavebankentry.PlayRegion.Offset = reader.ReadInt32();
                    wavebankentry.PlayRegion.Length = reader.ReadInt32();
                    wavebankentry.LoopRegion.Offset = reader.ReadInt32();
                    wavebankentry.LoopRegion.Length = reader.ReadInt32();
                }
                else
                {
                    if (wavebankdata.EntryMetaDataElementSize >= 4)
                    {
                        wavebankentry.FlagsAndDuration = reader.ReadInt32();
                    }
                    if (wavebankdata.EntryMetaDataElementSize >= 8)
                    {
                        wavebankentry.Format = reader.ReadInt32();
                    }
                    if (wavebankdata.EntryMetaDataElementSize >= 12)
                    {
                        wavebankentry.PlayRegion.Offset = reader.ReadInt32();
                    }
                    if (wavebankdata.EntryMetaDataElementSize >= 16)
                    {
                        wavebankentry.PlayRegion.Length = reader.ReadInt32();
                    }
                    if (wavebankdata.EntryMetaDataElementSize >= 20)
                    {
                        wavebankentry.LoopRegion.Offset = reader.ReadInt32();
                    }
                    if (wavebankdata.EntryMetaDataElementSize >= 24)
                    {
                        wavebankentry.LoopRegion.Length = reader.ReadInt32();
                    }
                }

                if (wavebankdata.EntryMetaDataElementSize < 24)
                {                              // work-around
                    if (wavebankentry.PlayRegion.Length != 0)
                    {
                        wavebankentry.PlayRegion.Length = wavebankheader.Segments[last_segment].Length;
                    }
                }// else if(wavebankdata.EntryMetaDataElementSize > sizeof(WaveBankEntry)) {    // skip unused fields
                //   MYFSEEK(wavebank_offset + wavebankdata.EntryMetaDataElementSize);
                //}

wavebank_handle:
                wavebank_offset += wavebankdata.EntryMetaDataElementSize;
                wavebankentry.PlayRegion.Offset += playregion_offset;

                // Parse WAVEBANKMINIWAVEFORMAT

                int codec;
                int chans;
                int rate;
                int align;
                //int bits;

                if (wavebankheader.Version == 1)
                {         // I'm not 100% sure if the following is correct
                    // version 1:
                    // 1 00000000 000101011000100010 0 001 0
                    // | |         |                 | |   |
                    // | |         |                 | |   wFormatTag
                    // | |         |                 | nChannels
                    // | |         |                 ???
                    // | |         nSamplesPerSec
                    // | wBlockAlign
                    // wBitsPerSample

                    codec = (wavebankentry.Format) & ((1 << 1) - 1);
                    chans = (wavebankentry.Format >> (1)) & ((1 << 3) - 1);
                    rate  = (wavebankentry.Format >> (1 + 3 + 1)) & ((1 << 18) - 1);
                    align = (wavebankentry.Format >> (1 + 3 + 1 + 18)) & ((1 << 8) - 1);
                    //bits = (wavebankentry.Format >> (1 + 3 + 1 + 18 + 8)) & ((1 << 1) - 1);

                    /*} else if(wavebankheader.dwVersion == 23) { // I'm not 100% sure if the following is correct
                     *  // version 23:
                     *  // 1000000000 001011101110000000 001 1
                     *  // | |        |                  |   |
                     *  // | |        |                  |   ???
                     *  // | |        |                  nChannels?
                     *  // | |        nSamplesPerSec
                     *  // | ???
                     *  // !!!UNKNOWN FORMAT!!!
                     *
                     *  //codec = -1;
                     *  //chans = (wavebankentry.Format >>  1) & ((1 <<  3) - 1);
                     *  //rate  = (wavebankentry.Format >>  4) & ((1 << 18) - 1);
                     *  //bits  = (wavebankentry.Format >> 31) & ((1 <<  1) - 1);
                     *  codec = (wavebankentry.Format                    ) & ((1 <<  1) - 1);
                     *  chans = (wavebankentry.Format >> (1)             ) & ((1 <<  3) - 1);
                     *  rate  = (wavebankentry.Format >> (1 + 3)         ) & ((1 << 18) - 1);
                     *  align = (wavebankentry.Format >> (1 + 3 + 18)    ) & ((1 <<  9) - 1);
                     *  bits  = (wavebankentry.Format >> (1 + 3 + 18 + 9)) & ((1 <<  1) - 1); */
                }
                else
                {
                    // 0 00000000 000111110100000000 010 01
                    // | |        |                  |   |
                    // | |        |                  |   wFormatTag
                    // | |        |                  nChannels
                    // | |        nSamplesPerSec
                    // | wBlockAlign
                    // wBitsPerSample

                    codec = (wavebankentry.Format) & ((1 << 2) - 1);
                    chans = (wavebankentry.Format >> (2)) & ((1 << 3) - 1);
                    rate  = (wavebankentry.Format >> (2 + 3)) & ((1 << 18) - 1);
                    align = (wavebankentry.Format >> (2 + 3 + 18)) & ((1 << 8) - 1);
                    //bits = (wavebankentry.Format >> (2 + 3 + 18 + 8)) & ((1 << 1) - 1);
                }

                reader.BaseStream.Seek(wavebankentry.PlayRegion.Offset, SeekOrigin.Begin);
                byte[] audiodata = reader.ReadBytes(wavebankentry.PlayRegion.Length);

                if (codec == MiniFormatTag_PCM)
                {
                    //write PCM data into a wav
#if DIRECTX
                    // TODO: Wouldn't storing a SoundEffectInstance like this
                    // result in the "parent" SoundEffect being garbage collected?

                    SharpDX.Multimedia.WaveFormat waveFormat = new SharpDX.Multimedia.WaveFormat(rate, chans);
                    var sfx = new SoundEffect(audiodata, 0, audiodata.Length, rate, (AudioChannels)chans, wavebankentry.LoopRegion.Offset, wavebankentry.LoopRegion.Length)
                    {
                        _format = waveFormat
                    };

                    _sounds[current_entry] = sfx;
#else
                    _sounds[current_entry] = new SoundEffect(audiodata, rate, (AudioChannels)chans);
#endif
                }
                else if (codec == MiniForamtTag_WMA)     //WMA or xWMA (or XMA2)
                {
                    byte[] wmaSig = { 0x30, 0x26, 0xb2, 0x75, 0x8e, 0x66, 0xcf, 0x11, 0xa6, 0xd9, 0x0, 0xaa, 0x0, 0x62, 0xce, 0x6c };

                    bool isWma = true;
                    for (int i = 0; i < wmaSig.Length; i++)
                    {
                        if (wmaSig[i] != audiodata[i])
                        {
                            isWma = false;
                            break;
                        }
                    }

                    //Let's support m4a data as well for convenience
                    byte[][] m4aSigs = new byte[][] {
                        new byte[] { 0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41, 0x20, 0x00, 0x00, 0x02, 0x00 },
                        new byte[] { 0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41, 0x20, 0x00, 0x00, 0x00, 0x00 }
                    };

                    bool isM4a = false;
                    for (int i = 0; i < m4aSigs.Length; i++)
                    {
                        byte[] sig     = m4aSigs[i];
                        bool   matches = true;
                        for (int j = 0; j < sig.Length; j++)
                        {
                            if (sig[j] != audiodata[j])
                            {
                                matches = false;
                                break;
                            }
                        }
                        if (matches)
                        {
                            isM4a = true;
                            break;
                        }
                    }

                    if (isWma || isM4a)
                    {
                        //WMA data can sometimes be played directly
#if DIRECTX
                        throw new NotImplementedException();
#elif !WINRT
                        //hack - NSSound can't play non-wav from data, we have to give a filename
                        string filename = Path.GetTempFileName();
                        if (isWma)
                        {
                            filename = filename.Replace(".tmp", ".wma");
                        }
                        else if (isM4a)
                        {
                            filename = filename.Replace(".tmp", ".m4a");
                        }
                        using (var audioFile = File.Create(filename))
                        {
                            audioFile.Write(audiodata, 0, audiodata.Length);
                            audioFile.Seek(0, SeekOrigin.Begin);

                            _sounds[current_entry] = SoundEffect.FromStream(audioFile);
                        }
#else
                        throw new NotImplementedException();
#endif
                    }
                    else
                    {
                        //An xWMA or XMA2 file. Can't be played atm :(
                        throw new NotImplementedException();
                    }
#if !DIRECTX
                    /* DirectX platforms can use XAudio2 to stream MSADPCM natively.
                     * This code is cross-platform, but the problem is that it just
                     * decodes ALL of the wavedata here. For XAudio2 in particular,
                     * this is probably ludicrous.
                     *
                     * You need to write a DIRECTX ADPCM reader that just loads this
                     * into the SoundEffect. No decoding should be necessary.
                     * -flibit
                     */
                }
                else if (codec == MiniFormatTag_ADPCM)
                {
                    using (MemoryStream dataStream = new MemoryStream(audiodata)) {
                        using (BinaryReader source = new BinaryReader(dataStream)) {
                            _sounds[current_entry] = new SoundEffect(
                                MSADPCMToPCM.MSADPCM_TO_PCM(source, (short)chans, (short)align),
                                rate,
                                (AudioChannels)chans
                                );
                        }
                    }
#endif
                }
                else
                {
                    throw new NotImplementedException();
                }
            }

            audioEngine.Wavebanks[_bankName] = this;
        }
Esempio n. 19
0
        public Task <Stream> ReadFileAsync(string filePath, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            return(FileHelpers.ReadFileAsStreamAsync(filePath, cancellationToken));
        }
Esempio n. 20
0
        private async Task UpdateEmbeddedImageValues(ParseItem item)
        {
            if (!WESettings.Instance.Css.SyncBase64ImageValues)
            {
                return;
            }

            Declaration dec = item.FindType <Declaration>();

            if (dec == null || !Cache.Contains(dec))
            {
                return;
            }

            var url = dec.Values.FirstOrDefault() as UrlItem;

            if (url == null || !url.IsValid || url.UrlString == null || url.UrlString.Text.Contains(";base64,"))
            {
                return;
            }

            var matches = Cache.Where(d => d.IsValid && d != dec && d.Parent == dec.Parent && d.Values.Any() &&
                                      (d.Values[0].NextSibling as CComment) != null);

            // Undo sometimes messes with the positions, so we have to make this check before proceeding.
            if (!matches.Any() || dec.Text.Length < dec.Colon.AfterEnd - dec.Start || dec.Colon.AfterEnd < dec.Start)
            {
                return;
            }

            string urlText    = url.UrlString.Text.Trim('\'', '"');
            string filePath   = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(_buffer.GetFileName()), urlText));
            string b64UrlText = await FileHelpers.ConvertToBase64(filePath);

            string b64Url = url.Text.Replace(urlText, b64UrlText);
            IEnumerable <Tuple <SnapshotSpan, string> > changes = matches.Reverse().SelectMany(match =>
            {
                ParseItem value  = match.Values[0];
                CComment comment = value.NextSibling as CComment;

                SnapshotSpan span = new SnapshotSpan(_buffer.CurrentSnapshot, comment.CommentText.Start, comment.CommentText.Length);

                url = value as UrlItem;

                if (url == null)
                {
                    return(null);
                }

                SnapshotSpan b64Span = new SnapshotSpan(_buffer.CurrentSnapshot, url.Start, url.Length);

                return(new[] { new Tuple <SnapshotSpan, string>(span, urlText), new Tuple <SnapshotSpan, string>(b64Span, b64Url) });
            });

            await Dispatcher.CurrentDispatcher.InvokeAsync(() =>
            {
                using (ITextEdit edit = _buffer.CreateEdit())
                {
                    foreach (Tuple <SnapshotSpan, string> change in changes)
                    {
                        SnapshotSpan currentSpan = change.Item1.TranslateTo(_buffer.CurrentSnapshot, SpanTrackingMode.EdgeExclusive);
                        edit.Replace(currentSpan, change.Item2);
                    }

                    edit.Apply();
                }
            });
        }
Esempio n. 21
0
        protected T ReadAsset <T>(string assetName, Action <IDisposable> recordDisposableObject)
        {
            if (string.IsNullOrEmpty(assetName))
            {
                throw new ArgumentNullException("assetName");
            }
            if (disposed)
            {
                throw new ObjectDisposedException("ContentManager");
            }

            object result = null;

            // FIXME: Should this block be here? -flibit
            if (graphicsDeviceService == null)
            {
                graphicsDeviceService = ServiceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            Stream stream            = null;
            string modifiedAssetName = String.Empty;             // Will be used if we have to guess a filename

            try
            {
                stream = OpenStream(assetName);
            }
            catch (Exception e)
            {
                // Okay, so we couldn’t open it. Maybe it needs a different extension?
                // FIXME: Normalizing checks for a file on the disk, what about custom streams? -flibit
                modifiedAssetName = FileHelpers.NormalizeFilePathSeparators(
                    Path.Combine(RootDirectoryFullPath, assetName)
                    );
                if (typeof(T) == typeof(Texture2D) || typeof(T) == typeof(Texture))
                {
                    modifiedAssetName = Texture2DReader.Normalize(assetName);
                }
                else if ((typeof(T) == typeof(SoundEffect)))
                {
                    modifiedAssetName = SoundEffectReader.Normalize(assetName);
                }
                else if ((typeof(T) == typeof(Effect)))
                {
                    modifiedAssetName = EffectReader.Normalize(assetName);
                }
                else if ((typeof(T) == typeof(Song)))
                {
                    modifiedAssetName = SongReader.Normalize(assetName);
                }
                else if ((typeof(T) == typeof(Video)))
                {
                    modifiedAssetName = VideoReader.Normalize(assetName);
                }

                // Did we get anything…?
                if (String.IsNullOrEmpty(modifiedAssetName))
                {
                    // Nope, nothing we’re aware of!
                    throw new ContentLoadException(
                              "Could not load asset " + assetName + "! Error: " + e.Message,
                              e
                              );
                }

                stream = File.OpenRead(modifiedAssetName);
            }

            using (BinaryReader xnbReader = new BinaryReader(stream))
            {
                try
                {
                    // Try to load as XNB file
                    using (ContentReader reader = GetContentReaderFromXnb(assetName, ref stream, xnbReader, recordDisposableObject))
                    {
                        result = reader.ReadAsset <T>();
                        GraphicsResource resource = result as GraphicsResource;
                        if (resource != null)
                        {
                            resource.Name = assetName;
                        }
                    }
                }
                catch (Exception e)
                {
                    // FIXME: Assuming seekable streams! -flibit
                    stream.Seek(0, SeekOrigin.Begin);

                    // Try to load as a raw asset
                    if (typeof(T) == typeof(Texture2D) || typeof(T) == typeof(Texture))
                    {
                        Texture2D texture = Texture2D.FromStream(
                            graphicsDeviceService.GraphicsDevice,
                            stream
                            );
                        texture.Name = assetName;
                        result       = texture;
                    }
                    else if ((typeof(T) == typeof(SoundEffect)))
                    {
                        result = SoundEffect.FromStream(stream);
                    }
                    else if ((typeof(T) == typeof(Effect)))
                    {
                        byte[] data = new byte[stream.Length];
                        stream.Read(data, 0, (int)stream.Length);
                        result = new Effect(graphicsDeviceService.GraphicsDevice, data);
                    }
                    else if ((typeof(T) == typeof(Song)))
                    {
                        // FIXME: Not using the stream! -flibit
                        result = new Song(modifiedAssetName);
                    }
                    else if ((typeof(T) == typeof(Video)))
                    {
                        // FIXME: Not using the stream! -flibit
                        result = new Video(modifiedAssetName);
                    }
                    else
                    {
                        // We dunno WTF this is, give them the XNB Exception.
                        throw e;
                    }

                    /* Because Raw Assets skip the ContentReader step, they need to have their
                     * disposables recorded here. Doing it outside of this catch will
                     * result in disposables being logged twice.
                     */
                    IDisposable disposableResult = result as IDisposable;
                    if (disposableResult != null)
                    {
                        if (recordDisposableObject != null)
                        {
                            recordDisposableObject(disposableResult);
                        }
                        else
                        {
                            disposableAssets.Add(disposableResult);
                        }
                    }
                }
            }

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + assetName + " asset!");
            }

            return((T)result);
        }
Esempio n. 22
0
        public async Task AddAsyncInterests(ProjectImageData model, ModelStateDictionary modelState, string userName)
        {
            var user = await _userManager.FindByNameAsync(userName);

            var trustedFileNameForDisplay     = string.Empty;
            var streamedFileImageContent      = new byte[0];
            var untrustedFileNameForStorage   = string.Empty;
            var trustedFilePathStorage        = string.Empty;
            var trustedFileNameForFileStorage = string.Empty;

            var test = string.Empty;

            streamedFileImageContent =
                await FileHelpers.ProcessFormFile <ProjectFormData>(
                    model.File, modelState, _permittedExtentions,
                    _fileSizeLimit);

            if (!modelState.IsValid)
            {
                test = "ModelState is Invalid";
            }

            untrustedFileNameForStorage = model.File.FileName;
            // Don't trust the file name sent by the client. To display
            // the file name, HTML-encode the value.
            trustedFileNameForDisplay = WebUtility.HtmlEncode(
                model.File.FileName);

            // Bind form data to the model
            var keyPathFolder     = FilePathUrlHelper.GenerateKeyPath(user.Id);
            var generateKeyFolder = GenerateSecurity.Encode(user.Id);

            // Path Location & Directory Check
            trustedFilePathStorage = String.Format("{0}\\{1}\\{2}\\{3}",
                                                   _targetFolderPath,
                                                   keyPathFolder,
                                                   generateKeyFolder,
                                                   Path.GetRandomFileName());

            Directory.CreateDirectory(trustedFilePathStorage);

            using (var fileStream = new FileStream(Path.Combine(trustedFilePathStorage, untrustedFileNameForStorage),
                                                   FileMode.Create, FileAccess.Write))
            {
                await model.File.CopyToAsync(fileStream);

                fileStream.Close();
            }

            ClamProjectInterestsImageDisplay result = new ClamProjectInterestsImageDisplay()
            {
                Title         = Path.GetFileNameWithoutExtension(model.File.FileName),
                ImageLocation = Path.Combine(trustedFilePathStorage, untrustedFileNameForStorage),
                Status        = bool.Parse(model.Status),
                UserId        = user.Id,
                LastModified  = DateTime.Now,
                DateCreated   = DateTime.Now
            };

            await _context.AddAsync(result);

            await _context.SaveChangesAsync();
        }
Esempio n. 23
0
        public async Task <IActionResult> AddProductMedia()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                ModelState.AddModelError("File",
                                         $"The request couldn't be processed (Error 1).");
                // Log error

                return(BadRequest(ModelState));
            }

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader  = new MultipartReader(boundary, HttpContext.Request.Body);
            var section = await reader.ReadNextSectionAsync();

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

                if (hasContentDispositionHeader)
                {
                    // This check assumes that there's a file
                    // present without form data. If form data
                    // is present, this method immediately fails
                    // and returns the model error.
                    if (!MultipartRequestHelper
                        .HasFileContentDisposition(contentDisposition))
                    {
                        ModelState.AddModelError("File",
                                                 $"The request couldn't be processed (Error 2).");
                        // Log error

                        return(BadRequest(ModelState));
                    }
                    else
                    {
                        // Don't trust the file name sent by the client. To display
                        // the file name, HTML-encode the value.
                        var trustedFileNameForDisplay = WebUtility.HtmlEncode(
                            contentDisposition.FileName.Value);
                        var trustedFileNameForFileStorage = Path.GetRandomFileName();

                        // **WARNING!**
                        // In the following example, the file is saved without
                        // scanning the file's contents. In most production
                        // scenarios, an anti-virus/anti-malware scanner API
                        // is used on the file before making the file available
                        // for download or for use by other systems.
                        // For more information, see the topic that accompanies
                        // this sample.

                        var streamedFileContent = await FileHelpers.ProcessStreamedFile(
                            section, contentDisposition, ModelState,
                            _permittedExtensions, _fileSizeLimit);

                        if (!ModelState.IsValid)
                        {
                            return(BadRequest(ModelState));
                        }

                        using (var targetStream = System.IO.File.Create(
                                   Path.Combine(_targetFilePath, trustedFileNameForFileStorage)))
                        {
                            await targetStream.WriteAsync(streamedFileContent);

                            _logger.LogInformation(
                                "Uploaded file '{TrustedFileNameForDisplay}' saved to " +
                                "'{TargetFilePath}' as {TrustedFileNameForFileStorage}",
                                trustedFileNameForDisplay, _targetFilePath,
                                trustedFileNameForFileStorage);
                        }
                    }
                }

                // Drain any remaining section body that hasn't been consumed and
                // read the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            return(Ok());
        }
Esempio n. 24
0
        /// <summary>
        /// Converts a <code>.resx</code> files in specified directory
        /// </summary>
        /// <param name="resourceDirectory">The directory containing <code>.resx</code> files</param>
        /// <param name="resourceNamespace">Namespace of resource</param>
        /// <param name="internalAccessModifier">Flag for whether to set the access modifier of
        /// resource class to internal</param>
        /// <returns>Result of conversion (true - success; false - failure)</returns>
        private static bool Convert(string resourceDirectory, string resourceNamespace,
                                    bool internalAccessModifier)
        {
            bool   result = true;
            string processedResourceDirectory;
            string currentDirectory = Directory.GetCurrentDirectory();

            if (!string.IsNullOrWhiteSpace(resourceDirectory))
            {
                processedResourceDirectory = PathHelpers.ProcessSlashes(resourceDirectory.Trim());
                if (!Path.IsPathRooted(processedResourceDirectory))
                {
                    processedResourceDirectory = Path.Combine(currentDirectory, processedResourceDirectory);
                }
                processedResourceDirectory = Path.GetFullPath(processedResourceDirectory);

                if (!Directory.Exists(processedResourceDirectory))
                {
                    throw new AppUsageException(
                              string.Format("The {0} directory does not exist.",
                                            processedResourceDirectory)
                              );
                }
            }
            else
            {
                processedResourceDirectory = currentDirectory;
            }

            WriteInfoLine();
            WriteInfoLine("Starting conversion of `.resx` files in the '{0}' directory:", processedResourceDirectory);
            WriteInfoLine();

            int processedFileCount = 0;
            int сonvertedFileCount = 0;
            int failedFileCount    = 0;

            foreach (string filePath in Directory.EnumerateFiles(processedResourceDirectory, "*.resx", SearchOption.AllDirectories))
            {
                string relativeFilePath = filePath.Substring(processedResourceDirectory.Length);

                try
                {
                    FileConversionResult conversionResult = ResxToCsConverter.ConvertFile(filePath,
                                                                                          resourceNamespace, internalAccessModifier);
                    string outputFilePath   = conversionResult.OutputPath;
                    string convertedContent = conversionResult.ConvertedContent;
                    bool   changesDetected  = FileHelpers.HasFileContentChanged(outputFilePath, convertedContent);

                    if (changesDetected)
                    {
                        string outputDirPath = Path.GetDirectoryName(outputFilePath);
                        if (!Directory.Exists(outputDirPath))
                        {
                            Directory.CreateDirectory(outputDirPath);
                        }

                        File.WriteAllText(outputFilePath, convertedContent);

                        WriteInfoLine("	* '{0}' file has been successfully converted", relativeFilePath);
                        сonvertedFileCount++;
                    }
                    else
                    {
                        WriteInfoLine("	* '{0}' file has not changed", relativeFilePath);
                    }
                }
                catch (ResxConversionException e)
                {
                    WriteInfoLine("	* '{0}' file failed to convert");
                    WriteErrorLine(e.Message);
                    failedFileCount++;
                }

                processedFileCount++;
            }

            if (processedFileCount > 0)
            {
                WriteInfoLine();
                WriteInfoLine("Total files: {0}. Converted: {1}. Failed: {2}.",
                              processedFileCount, сonvertedFileCount, failedFileCount);

                result = failedFileCount == 0;
                if (result)
                {
                    WriteSuccessLine("Conversion is successfull.");
                }
                else
                {
                    WriteErrorLine("Conversion is failed.");
                }
            }
            else
            {
                WriteWarnLine("There are no resx files found in the '{0}' directory.", processedResourceDirectory);
            }

            WriteInfoLine();

            return(result);
        }
Esempio n. 25
0
        private void DoFileJobs()
        {
            if (!string.IsNullOrEmpty(Info.FilePath) && File.Exists(Info.FilePath))
            {
                if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.PerformActions) && Info.TaskSettings.ExternalPrograms != null)
                {
                    IEnumerable <ExternalProgram> actions = Info.TaskSettings.ExternalPrograms.Where(x => x.IsActive);

                    if (actions.Count() > 0)
                    {
                        bool   isFileModified = false;
                        string fileName       = Info.FileName;

                        foreach (ExternalProgram fileAction in actions)
                        {
                            string modifiedPath = fileAction.Run(Info.FilePath);

                            if (!string.IsNullOrEmpty(modifiedPath))
                            {
                                isFileModified = true;
                                Info.FilePath  = modifiedPath;

                                if (Data != null)
                                {
                                    Data.Dispose();
                                }

                                fileAction.DeletePendingInputFile();
                            }
                        }

                        if (isFileModified)
                        {
                            string extension = FileHelpers.GetFileNameExtension(Info.FilePath);
                            Info.FileName = FileHelpers.ChangeFileNameExtension(fileName, extension);

                            LoadFileStream();
                        }
                    }
                }

                if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.CopyFileToClipboard))
                {
                    ClipboardHelpers.CopyFile(Info.FilePath);
                }
                else if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.CopyFilePathToClipboard))
                {
                    ClipboardHelpers.CopyText(Info.FilePath);
                }

                if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.ShowInExplorer))
                {
                    FileHelpers.OpenFolderWithFile(Info.FilePath);
                }

                if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.ScanQRCode) && Info.DataType == EDataType.Image)
                {
                    QRCodeForm.OpenFormDecodeFromFile(Info.FilePath).ShowDialog();
                }
            }
        }
Esempio n. 26
0
        public async Task <ActionResult> CreateArticle(CreateArticleViewModel model)
        {
            try
            {
                var text = await FileHelpers.ProcessFormFile(model.ArticleContent, ModelState);

                if (ModelState.IsValid)
                {
                    //TODO: try catch ?
                    var article = this.mapper.Map <Article>(model);
                    var user    = await this.usersService.GetByUserName(User.Identity.Name);

                    article.Content   = text;
                    article.Author    = user;
                    article.Date      = DateTime.UtcNow;
                    article.IsDeleted = false;

                    var keywords            = model.Keywords;
                    var dbKeywords          = this.keywordsService.GetAll();
                    var articleKeywordsList = new HashSet <Keyword>();
                    var keywordsArticles    = new HashSet <KeywordArticle>();

                    foreach (var keyword in keywords)
                    {
                        var newKeyword = await dbKeywords.Where(x => x.Content.ToLower() == keyword.ToLower()).FirstOrDefaultAsync();

                        if (newKeyword == null)
                        {
                            newKeyword = new Keyword()
                            {
                                Content = keyword
                            };
                            await this.keywordsService.Add(newKeyword);
                        }

                        //articleKeywordsList.Add(newKeyword);

                        var newKeywordArticle = new KeywordArticle()
                        {
                            KeywordId = newKeyword.Id,
                            //                         Keyword = newKeyword,
                            ArticleId = article.Id,
                            //                           Article = article
                        };

                        keywordsArticles.Add(newKeywordArticle);
                        // newKeyword.KeywordArticles.Add(newKeywordArticle);
                        // await this.keywordsService.Update(newKeyword.Id, newKeyword);
                        article.KeywordArticles.Add(newKeywordArticle);
                    }

                    this.cache.Remove("ArticlesCache");

                    await this.articlesService.Add(article);

                    /// Adds collection of keywordsArticles
                    //await this.keywordArticlesService.Add(keywordsArticles);

                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(View(model));
                }
            }
            catch (Exception ex)
            {
                return(View(model));
            }
        }
Esempio n. 27
0
        protected T ReadAsset <T>(string assetName, Action <IDisposable> recordDisposableObject)
        {
            if (string.IsNullOrEmpty(assetName))
            {
                throw new ArgumentNullException("assetName");
            }
            if (disposed)
            {
                throw new ObjectDisposedException("ContentManager");
            }
            string originalAssetName = assetName;
            object result            = null;

            if (this.graphicsDeviceService == null)
            {
                this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (this.graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }
            Stream stream = null;

            try
            {
                // Try to load it traditionally
                stream = OpenStream(assetName);
                // Try to load as XNB file
                try
                {
                    using (BinaryReader xnbReader = new BinaryReader(stream))
                    {
                        using (ContentReader reader = GetContentReaderFromXnb(assetName, ref stream, xnbReader, recordDisposableObject))
                        {
                            result = reader.ReadAsset <T>();
                            GraphicsResource resource = result as GraphicsResource;
                            if (resource != null)
                            {
                                resource.Name = originalAssetName;
                            }
                        }
                    }
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }
                }
            }
            catch (ContentLoadException ex)
            {
                // Try to load as a non-content file
                assetName = FileHelpers.NormalizeFilePathSeparators(
                    Path.Combine(RootDirectoryFullPath, assetName)
                    );
                assetName = Normalize <T>(assetName);
                if (string.IsNullOrEmpty(assetName))
                {
                    throw new ContentLoadException(
                              "Could not load " +
                              originalAssetName +
                              " asset as a non-content file!",
                              ex
                              );
                }
                result = ReadRawAsset <T>(assetName, originalAssetName);

                /* Because Raw Assets skip the ContentReader step, they need to have their
                 * disposables recorded here. Doing it outside of this catch will
                 * result in disposables being logged twice.
                 */
                IDisposable disposableResult = result as IDisposable;

                if (disposableResult != null)
                {
                    if (recordDisposableObject != null)
                    {
                        recordDisposableObject(disposableResult);
                    }
                    else
                    {
                        disposableAssets.Add(disposableResult);
                    }
                }
            }

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            return((T)result);
        }
Esempio n. 28
0
    private void ProcessCsv(string fullPath)
    {
        ImportStatistic.Init();
        ImportStatistic.IsRun = true;

        var fieldMapping = new Dictionary <string, int>();

        using (var csv = new CsvHelper.CsvReader(new StreamReader(fullPath, Encoding.UTF8)))
        {
            csv.Configuration.Delimiter       = ';';
            csv.Configuration.HasHeaderRecord = false;
            csv.Read();
            for (int i = 0; i < csv.CurrentRecord.Length; i++)
            {
                if (csv.CurrentRecord[i] == ProductFields.GetStringNameByEnum(ProductFields.Fields.None))
                {
                    continue;
                }
                if (!fieldMapping.ContainsKey(csv.CurrentRecord[i]))
                {
                    fieldMapping.Add(csv.CurrentRecord[i], i);
                }
            }
        }

        using (var csv = new CsvHelper.CsvReader(new StreamReader(fullPath, Encoding.UTF8)))
        {
            csv.Configuration.Delimiter       = ';';
            csv.Configuration.HasHeaderRecord = true;

            while (csv.Read())
            {
                if (!ImportStatistic.IsRun)
                {
                    csv.Dispose();
                    FileHelpers.DeleteFile(fullPath);
                    return;
                }

                ImportStatistic.RowPosition++;
                try
                {
                    // Step by rows
                    var productInStrings = new Dictionary <ProductFields.Fields, string>();

                    string nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Sku);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        productInStrings.Add(ProductFields.Fields.Sku, Convert.ToString(csv[fieldMapping[nameField]]));
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Name).Trim('*');
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        var name = Convert.ToString(csv[fieldMapping[nameField]]);
                        if (!string.IsNullOrEmpty(name))
                        {
                            productInStrings.Add(ProductFields.Fields.Name, name);
                        }
                        else
                        {
                            Log(string.Format(Resource.Admin_ImportCsv_CanNotEmpty, ProductFields.GetDisplayNameByEnum(ProductFields.Fields.Name), ImportStatistic.RowPosition + 2), "InvalidData");
                            continue;
                        }
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Enabled).Trim('*');
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        string enabled = Convert.ToString(csv[fieldMapping[nameField]]);
                        productInStrings.Add(ProductFields.Fields.Enabled, enabled);
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Discount);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        string discount = Convert.ToString(csv[fieldMapping[nameField]]);
                        if (string.IsNullOrEmpty(discount))
                        {
                            discount = "0";
                        }
                        decimal tmp;
                        if (decimal.TryParse(discount, out tmp))
                        {
                            productInStrings.Add(ProductFields.Fields.Discount, tmp.ToString());
                        }
                        else if (decimal.TryParse(discount, NumberStyles.Any, CultureInfo.InvariantCulture, out tmp))
                        {
                            productInStrings.Add(ProductFields.Fields.Discount, tmp.ToString());
                        }
                        else
                        {
                            Log(string.Format(Resource.Admin_ImportCsv_MustBeNumber, ProductFields.GetDisplayNameByEnum(ProductFields.Fields.Discount), ImportStatistic.RowPosition + 2), "InvalidData");
                            continue;
                        }
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Weight);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        string weight = Convert.ToString(csv[fieldMapping[nameField]]);
                        if (string.IsNullOrEmpty(weight))
                        {
                            weight = "0";
                        }
                        decimal tmp;
                        if (decimal.TryParse(weight, out tmp))
                        {
                            productInStrings.Add(ProductFields.Fields.Weight, tmp.ToString());
                        }
                        else if (decimal.TryParse(weight, NumberStyles.Any, CultureInfo.InvariantCulture, out tmp))
                        {
                            productInStrings.Add(ProductFields.Fields.Weight, tmp.ToString());
                        }
                        else
                        {
                            Log(string.Format(Resource.Admin_ImportCsv_MustBeNumber, ProductFields.GetDisplayNameByEnum(ProductFields.Fields.Weight), ImportStatistic.RowPosition + 2), "InvalidData");
                            continue;
                        }
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Size);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        productInStrings.Add(ProductFields.Fields.Size, Convert.ToString(csv[fieldMapping[nameField]]));
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.BriefDescription);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        productInStrings.Add(ProductFields.Fields.BriefDescription, Convert.ToString(csv[fieldMapping[nameField]]));
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Description);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        productInStrings.Add(ProductFields.Fields.Description, Convert.ToString(csv[fieldMapping[nameField]]));
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Price).Trim('*');
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        string price = Convert.ToString(csv[fieldMapping[nameField]]);
                        if (string.IsNullOrEmpty(price))
                        {
                            price = "0";
                        }
                        decimal tmp;
                        if (decimal.TryParse(price, out tmp))
                        {
                            productInStrings.Add(ProductFields.Fields.Price, tmp.ToString());
                        }
                        else if (decimal.TryParse(price, NumberStyles.Any, CultureInfo.InvariantCulture, out tmp))
                        {
                            productInStrings.Add(ProductFields.Fields.Price, tmp.ToString());
                        }
                        else
                        {
                            Log(string.Format(Resource.Admin_ImportCsv_MustBeNumber, ProductFields.GetDisplayNameByEnum(ProductFields.Fields.Price), ImportStatistic.RowPosition + 2), "InvalidData");
                            continue;
                        }
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.PurchasePrice);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        string sypplyprice = Convert.ToString(csv[fieldMapping[nameField]]);
                        if (string.IsNullOrEmpty(sypplyprice))
                        {
                            sypplyprice = "0";
                        }
                        decimal tmp;
                        if (decimal.TryParse(sypplyprice, out tmp))
                        {
                            productInStrings.Add(ProductFields.Fields.PurchasePrice, tmp.ToString());
                        }
                        else if (decimal.TryParse(sypplyprice, NumberStyles.Any, CultureInfo.InvariantCulture, out tmp))
                        {
                            productInStrings.Add(ProductFields.Fields.PurchasePrice, tmp.ToString());
                        }
                        else
                        {
                            Log(string.Format(Resource.Admin_ImportCsv_MustBeNumber, ProductFields.GetDisplayNameByEnum(ProductFields.Fields.PurchasePrice), ImportStatistic.RowPosition + 2), "InvalidData");
                            continue;
                        }
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.ShippingPrice);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        string shippingPrice = Convert.ToString(csv[fieldMapping[nameField]]);
                        if (string.IsNullOrEmpty(shippingPrice))
                        {
                            shippingPrice = "0";
                        }
                        decimal tmp;
                        if (decimal.TryParse(shippingPrice, out tmp))
                        {
                            productInStrings.Add(ProductFields.Fields.ShippingPrice, tmp.ToString());
                        }
                        else if (decimal.TryParse(shippingPrice, NumberStyles.Any, CultureInfo.InvariantCulture, out tmp))
                        {
                            productInStrings.Add(ProductFields.Fields.ShippingPrice, tmp.ToString());
                        }
                        else
                        {
                            Log(string.Format(Resource.Admin_ImportCsv_MustBeNumber, ProductFields.GetDisplayNameByEnum(ProductFields.Fields.ShippingPrice), ImportStatistic.RowPosition + 2), "InvalidData");
                            continue;
                        }
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Amount);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        string amount = Convert.ToString(csv[fieldMapping[nameField]]);
                        if (string.IsNullOrEmpty(amount))
                        {
                            amount = "0";
                        }
                        int tmp;
                        if (int.TryParse(amount, out tmp))
                        {
                            productInStrings.Add(ProductFields.Fields.Amount, amount);
                        }
                        else
                        {
                            Log(string.Format(Resource.Admin_ImportCsv_MustBeNumber, ProductFields.GetDisplayNameByEnum(ProductFields.Fields.Amount), ImportStatistic.RowPosition + 2), "InvalidData");
                            continue;
                        }
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Unit);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        productInStrings.Add(ProductFields.Fields.Unit, Convert.ToString(csv[fieldMapping[nameField]]));
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.ParamSynonym);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        string rewurl = Convert.ToString(csv[fieldMapping[nameField]]);
                        productInStrings.Add(ProductFields.Fields.ParamSynonym, rewurl);
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Title);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        productInStrings.Add(ProductFields.Fields.Title, Convert.ToString(csv[fieldMapping[nameField]]));
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.MetaKeywords);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        productInStrings.Add(ProductFields.Fields.MetaKeywords, Convert.ToString(csv[fieldMapping[nameField]]));
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.MetaDescription);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        productInStrings.Add(ProductFields.Fields.MetaDescription, Convert.ToString(csv[fieldMapping[nameField]]));
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Photos);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        productInStrings.Add(ProductFields.Fields.Photos, Convert.ToString(csv[fieldMapping[nameField]]));
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Markers);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        productInStrings.Add(ProductFields.Fields.Markers, Convert.ToString(csv[fieldMapping[nameField]]));
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Properties);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        productInStrings.Add(ProductFields.Fields.Properties, Convert.ToString(csv[fieldMapping[nameField]]));
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Producer);
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        productInStrings.Add(ProductFields.Fields.Producer, Convert.ToString(csv[fieldMapping[nameField]]));
                    }

                    nameField = ProductFields.GetStringNameByEnum(ProductFields.Fields.Category).Trim('*');
                    if (fieldMapping.ContainsKey(nameField))
                    {
                        var parentCategory = Convert.ToString(csv[fieldMapping[nameField]]);
                        if (!string.IsNullOrEmpty(parentCategory))
                        {
                            productInStrings.Add(ProductFields.Fields.Category, parentCategory);
                        }
                    }

                    ImportProduct.UpdateInsertProduct(productInStrings);
                }
                catch (Exception ex)
                {
                    Log(ex.Message, "InvalidData");
                }
            }
            CategoryService.RecalculateProductsCountManual();
        }
        ImportStatistic.IsRun = false;
        FileHelpers.DeleteFile(fullPath);
    }
Esempio n. 29
0
File: Gif.cs Progetto: ajbadaj/AJut
        // =============[ Private Update Handlers ]================
        private static void HandlePathChanged(DependencyObject d, DependencyPropertyChangedEventArgs <Uri> e)
        {
            if (!(d is ImageControl) || e.HasOldValue)
            {
                ClearGifInfo(d);
            }

            if (!e.HasNewValue)
            {
                return;
            }

            Stream imageStream = null;

            try
            {
                ImageStorage image = null;
                if (!e.NewValue.IsAbsoluteUri || e.NewValue.IsFile)
                {
                    image = ImageStorage.FromFile(e.NewValue.OriginalString);
                }
                else if (e.NewValue.Scheme.Equals("pack", StringComparison.InvariantCultureIgnoreCase))
                {
                    int      stopInd              = e.NewValue.AbsolutePath.IndexOf(';');
                    string   assemblyName         = e.NewValue.AbsolutePath.Substring(0, stopInd).Trim('/');
                    Assembly assembly             = AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name == assemblyName);
                    string   embeddedResourcePath = e.NewValue.AbsolutePath.Replace($"{assemblyName};component/", "").Trim('/');
                    embeddedResourcePath = FileHelpers.GenerateEmbeddedResourceName(embeddedResourcePath, assembly);

                    imageStream = assembly.GetManifestResourceStream(embeddedResourcePath);
                    if (imageStream != null)
                    {
                        image = ImageStorage.FromStream(imageStream);
                    }
                }
                else
                {
                    using (HttpWebResponse response = (HttpWebResponse)WebRequest.Create(e.NewValue).GetResponse())
                    {
                        using (BinaryReader reader = new BinaryReader(response.GetResponseStream()))
                        {
                            imageStream = new MemoryStream();
                            byte[] transferBuffer = reader.ReadBytes(1024);
                            while (transferBuffer.Length > 0)
                            {
                                imageStream.Write(transferBuffer, 0, transferBuffer.Length);
                                transferBuffer = reader.ReadBytes(1024);
                            }

                            image = ImageStorage.FromStream(imageStream);
                        }
                    }
                }

                SetCurrentFrameIndex(d, -1);
                SetInfo(d, new GifInfoCache(image));
                SetCurrentFrameIndex(d, 0);
                ResetTimer(d);
            }
            catch (Exception exception)
            {
                Logger.LogError(exception);
                ClearGifInfo(d);
            }
            finally
            {
                if (imageStream != null)
                {
                    imageStream.Close();
                    imageStream.Dispose();
                    imageStream = null;
                }
            }
        }
Esempio n. 30
0
 static void engine_AfterReadRecord(EngineBase engine, FileHelpers.Events.AfterReadEventArgs<FixedSampleRecord> e)
 {
 }
        private static void CreateInternal(IEnumerable <DataBlock> dataBlocks, string path, PortalPlc parentPlc, AlarmworxSettings settings)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (!FileHelpers.IsValidFilePath(path, ".csv"))
            {
                throw new ArgumentException(path + " is not a valid path.", nameof(path));
            }

            var tagSeparationCharacter = settings?.ExportStyle == OpcTagStyle.OpcUa ? "/" : ".";

            try
            {
                using (var file = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.Read))
                    using (var writer = new StreamWriter(file))
                    {
                        AlarmWorxConfiguration.WriteHeaders(writer);

                        foreach (var block in dataBlocks)
                        {
                            if (block == null)
                            {
                                throw new ArgumentNullException(nameof(block));
                            }
                            if (block.Children?.Count <= 0)
                            {
                                throw new ArgumentException("Block '" + block.Name + "' contains no data", nameof(block));
                            }

                            foreach (var child in block)
                            {
                                WriteAlarmRow(writer, child, block.Name + tagSeparationCharacter, block.Comment);
                            }
                        }
                        AlarmWorxConfiguration.WriteFooter(writer);

                        writer.Flush();
                    }
            }
            catch (Exception e)
            {
                throw new SiemensException("Could not write AlarmWorX configuration", e);
            }

            void WriteAlarmRow(StreamWriter writer, DataEntry entry, string prependNameText, string prependCommentText)
            {
                string stackedComment;

                if (string.IsNullOrWhiteSpace(prependCommentText))
                {
                    stackedComment = entry.Comment;
                }
                else if (prependCommentText.EndsWith(" - "))
                {
                    stackedComment = prependCommentText + entry.Comment;
                }
                else
                {
                    stackedComment = prependCommentText + " - " + entry.Comment;
                }

                stackedComment = stackedComment.Replace(",", "-");

                switch (entry.DataType)
                {
                case DataType.ARRAY:
                    TagHelper.ResolveArrayChildren(entry, parentPlc);
                    foreach (var child in entry.Children)
                    {
                        WriteAlarmRow(writer, child, prependNameText, prependNameText);
                    }
                    break;

                case DataType.STRUCT:
                    foreach (var child in entry.Children)
                    {
                        WriteAlarmRow(writer, child, prependNameText + entry.Name + ".", stackedComment);
                    }
                    break;

                case DataType.UDT:
                    foreach (var child in parentPlc.UserDataTypes.FirstOrDefault(u => u.Name == entry.DataTypeName))
                    {
                        WriteAlarmRow(writer, child, prependNameText + entry.Name + ".", stackedComment);
                    }
                    break;

                case DataType.BOOL:
                    string tag = null;
                    if (settings.ExportStyle == OpcTagStyle.OpcDa)
                    {
                        tag = settings.OpcServerTagPrefix + "\\" + prependNameText + entry.Name;
                    }
                    else if (settings.ExportStyle == OpcTagStyle.OpcUa)
                    {
                        var indexOfLastDot  = prependNameText.LastIndexOf('.');
                        var modifiedPrepend = prependNameText.Replace('.', '/');
                        tag = settings.OpcServerTagPrefix + "/" + modifiedPrepend.Substring(0, indexOfLastDot)
                              + '.' + modifiedPrepend.Substring(indexOfLastDot + 1) + entry.Name;
                    }
                    var row = new AlarmWorxRow
                    {
                        LocationPath   = @"\Configurations\" + ALARM_FOLDER,
                        Name           = ALARM_FOLDER + "." + prependNameText + entry.Name,
                        Description    = stackedComment,
                        LastModified   = DateTime.UtcNow.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss'Z'"),
                        Input1         = tag,
                        BaseText       = stackedComment, // Message text
                        DigMessageText = " ",            // Prevents 'Digital Alarm' text at the end of each message
                        DigLimit       = "1",            // Alarm state value needs to be 1 for a digital
                        DigSeverity    = "500",          // Default severity is 500
                        DigRequiresAck = "1"             // Require an acknowledge by default
                    };

                    writer.WriteLine(row.ToString());
                    break;

                default:
                    throw new ArgumentException("Cannot export datatype '" + entry.DataType.ToString() + "' to AlarmWorX configuration");
                }
            }
        }
Esempio n. 32
0
 static void engine_Progress(object sender, FileHelpers.Events.ProgressEventArgs e)
 {
 }
Esempio n. 33
0
        private void ExecuteAction(ToastClickAction action)
        {
            switch (action)
            {
            case ToastClickAction.AnnotateImage:
                if (!string.IsNullOrEmpty(Config.FilePath) && FileHelpers.IsImageFile(Config.FilePath))
                {
                    TaskHelpers.AnnotateImageFromFile(Config.FilePath);
                }
                break;

            case ToastClickAction.CopyImageToClipboard:
                if (!string.IsNullOrEmpty(Config.FilePath))
                {
                    ClipboardHelpers.CopyImageFromFile(Config.FilePath);
                }
                break;

            case ToastClickAction.CopyFile:
                if (!string.IsNullOrEmpty(Config.FilePath))
                {
                    ClipboardHelpers.CopyFile(Config.FilePath);
                }
                break;

            case ToastClickAction.CopyFilePath:
                if (!string.IsNullOrEmpty(Config.FilePath))
                {
                    ClipboardHelpers.CopyText(Config.FilePath);
                }
                break;

            case ToastClickAction.CopyUrl:
                if (!string.IsNullOrEmpty(Config.URL))
                {
                    ClipboardHelpers.CopyText(Config.URL);
                }
                break;

            case ToastClickAction.OpenFile:
                if (!string.IsNullOrEmpty(Config.FilePath))
                {
                    FileHelpers.OpenFile(Config.FilePath);
                }
                break;

            case ToastClickAction.OpenFolder:
                if (!string.IsNullOrEmpty(Config.FilePath))
                {
                    FileHelpers.OpenFolderWithFile(Config.FilePath);
                }
                break;

            case ToastClickAction.OpenUrl:
                if (!string.IsNullOrEmpty(Config.URL))
                {
                    URLHelpers.OpenURL(Config.URL);
                }
                break;

            case ToastClickAction.Upload:
                if (!string.IsNullOrEmpty(Config.FilePath))
                {
                    UploadManager.UploadFile(Config.FilePath);
                }
                break;
            }
        }