コード例 #1
0
        public async Task <IActionResult> EditMusic(Guid id, StreamFormDataMusic formData)
        {
            await _unitOfWork.MusicControl.UpdateMusicTrack(id, formData);

            _unitOfWork.Complete();
            return(RedirectToAction(nameof(Index)));
        }
コード例 #2
0
        public async Task <IActionResult> EditMusic(Guid id)
        {
            var model = await _unitOfWork.MusicControl.GetAsyncMusicTrack(id);

            StreamFormDataMusic result = new StreamFormDataMusic()
            {
                SongTitle  = model.SongTitle,
                SongArtist = model.SongArtist,
                Status     = model.Status.ToString()
            };

            List <bool> decisions = new List <bool>()
            {
                true, false
            };
            var dictionary = new Dictionary <string, bool>()
            {
                { "Public", true },
                { "Private", false }
            };
            List <SelectListItem> viewingStatus = new List <SelectListItem>();

            foreach (var item in dictionary)
            {
                viewingStatus.Add(new SelectListItem()
                {
                    Text  = item.Key,
                    Value = item.Value.ToString()
                });
            }
            ViewBag.ViewStatus = viewingStatus;
            ViewBag.MusicId    = id;
            return(View(result));
        }
コード例 #3
0
        public async Task UpdateMusicTrack(Guid id, StreamFormDataMusic formData)
        {
            var model = await _context.ClamUserMusic.FindAsync(id);

            _context.Entry(model).Entity.SongTitle    = formData.SongTitle;
            _context.Entry(model).Entity.SongArtist   = formData.SongArtist;
            _context.Entry(model).Entity.Status       = bool.Parse(formData.Status);
            _context.Entry(model).Entity.LastModified = DateTime.Now;
            _context.Entry(model).State = EntityState.Modified;
            _context.Update(model);
            await _context.SaveChangesAsync();
        }
コード例 #4
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);

                        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 StreamFormDataMusic();
            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 ClamUserMusic()
            {
                SongTitle   = formData.SongTitle,
                SongArtist  = formData.SongArtist,
                ItemPath    = storedPaths[0],
                Size        = keyConvert.Length,
                DateCreated = DateTime.Now,
                Status      = bool.Parse(formData.Status),
                UserId      = profile.Id
            };

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

            return(RedirectToAction(nameof(Index)));
        }