예제 #1
1
        private async Task<bool> GuardarImagen(IFormFile imagen, int personajeId)
        {
            bool resultado = true;

            string carpetaImagenes = Path.Combine(_environment.WebRootPath, "personajes");
            string extension = Path.GetExtension(imagen.FileName);

            if (!EsExtensionValida(extension))
            {
                resultado = false;
                _mensaje = "La extension de la imagen no es valida. Solo se admiten JPG, JPEG, GIF y PNG";
            }
            if (resultado && imagen.Length > 1024*1024)
            {
                resultado = false;
                _mensaje = "Te has colado; la imagen no debe ser mayor de 1 mega";
            }
            if ( resultado && imagen.Length > 0)
            {
                using (var fileStream = new FileStream(Path.Combine(carpetaImagenes, personajeId.ToString() + ".png"), FileMode.Create))
                {
                    await imagen.CopyToAsync(fileStream);
                }
            }

            return resultado;
        }
        public async Task<IActionResult> Create([Bind] Participant partner, IFormFile image)
        {
            if (this.ModelState.IsValid)
            {
                var uploads = Path.Combine(this.environment.WebRootPath, "uploads/participants");
                if (!Directory.Exists(uploads))
                {
                    Directory.CreateDirectory(uploads);
                }

                if (image.Length > 0)
                {
                    var fileName = $"{Guid.NewGuid()}.{image.FileName}";
                    using (var fileStream = new FileStream(Path.Combine(uploads, fileName), FileMode.Create))
                    {
                        await image.CopyToAsync(fileStream);
                        partner.ImgPath = $"/uploads/participants/{fileName}";
                    }
                }

                this.context.Add(partner);
                await this.context.SaveChangesAsync();
                return this.RedirectToAction("Index");
            }

            return this.View(partner);
        }
 public async Task UploadDocumentAsync(IFormFile file)
 {
   using (var fileStream = new FileStream(Path.Combine(_documentUploadConfiguration.UploadPath, file.FileName), FileMode.Create))
   {
     await file.CopyToAsync(fileStream);
   }
 }
        public async Task <ActionResult> PutPictureAsync(int categoryId, IFormFile formFile)
        {
            if (categoryId < 1)
            {
                throw new ArgumentException("CategoryId can't be less than one.", nameof(categoryId));
            }

            using var stream = new MemoryStream();
            await formFile?.CopyToAsync(stream);

            if (!(await this.productCategoryPicturesService.UpdatePictureAsync(categoryId, stream)))
            {
                return(this.NotFound());
            }

            return(this.NoContent());
        }
예제 #5
0
        public async Task<IActionResult> PutFilme(int id, [FromForm]Filme filme, IFormFile poster)
        {
            if (id != filme.Id)
            {
                return BadRequest();
            }

            string caminhoCompleto = "";
            var deprecatedFilme = await _context.Filme.FindAsync(id);

            if (poster.FileName == "null")
            {
                filme.Poster = deprecatedFilme.Poster;
            }
            else
            {

                // definir o novo nome da fotografia     
                Guid g;
                g = Guid.NewGuid();

                //apagar a imagem anterior
                string localizacaoFicheiro = _path.WebRootPath;
                    caminhoCompleto = Path.Combine(localizacaoFicheiro, "Imagens", deprecatedFilme.Poster);
                if (System.IO.File.Exists(caminhoCompleto))
                {
                    System.IO.File.Delete(caminhoCompleto);
                }

                caminhoCompleto = g.ToString(); // determinar a extensão do nome da imagem

                string extensao = Path.GetExtension(poster.FileName).ToLower();
                // caminho completo do ficheiro
                caminhoCompleto += extensao;

                // associar este ficheiro aos dados ds foto
                filme.Poster = caminhoCompleto;

                // localização do armazenamento da imagem

                caminhoCompleto = Path.Combine(localizacaoFicheiro, "Imagens", caminhoCompleto);
            }
            _context.Entry<Filme>(deprecatedFilme).State = EntityState.Detached;
            try
            {
                _context.Entry(filme).State = EntityState.Modified;
                await _context.SaveChangesAsync();
                if(poster.FileName != "null")
                {
                    using var stream = new FileStream(caminhoCompleto, FileMode.Create);
                    await poster.CopyToAsync(stream);
                }
                
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!FilmeExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }
        public async Task <IActionResult> Create([Bind("Id,NameOfPhoto,Date,Local,DogFK")] Photos photos, IFormFile photoOfDog)
        {
            /*
             * Algorithm to deal with file of photos of dogs
             * - if there is no file,
             *     - do not accept the record
             *     - write it to user, at browser
             * - if the file was not good (.png ,.jpg are good files)
             *     - do not accept the record
             *     - write it to user, at browser
             * - if you came to here, is because the file is good
             *    - decide the name of file
             *    - assign the file name to data colected by the form
             *    - write the file on the disc drive
             */

            if (photoOfDog == null)
            {
                // if you came to here, there is no file
                // write a error message
                ModelState.AddModelError("", "you haven't choose a file. Please, pick one...");
                // send the control to Browser
                ViewData["Dogs"] = new SelectList(_db.Dogs.OrderBy(d => d.Name), "Id", "Name");
                return(View());
            }

            if (photoOfDog.ContentType != "image/jpeg" && photoOfDog.ContentType != "image/png")
            {
                // if you came to here, there is a file
                // but, the file is not good
                // write a error message
                ModelState.AddModelError("", "Your file is not of correct type. Please, choose PNG or JPG image...");
                // send the control to Browser
                ViewData["Dogs"] = new SelectList(_db.Dogs.OrderBy(d => d.Name), "Id", "Name");
                return(View());
            }

            // if you came to here, you have a good file...
            //Decide the name of your file
            Guid g;

            g = Guid.NewGuid();
            // determining the extension of file
            string extension = Path.GetExtension(photoOfDog.FileName).ToLower();
            // new name of file
            string nameOfFile = photos.DogFK + "_" + g.ToString() + extension;

            // assign new file name to 'photos'
            photos.NameOfPhoto = nameOfFile;

            if (ModelState.IsValid)
            {
                _db.Add(photos);
                await _db.SaveChangesAsync();

                // because all data was stored on DB,
                // we are going to store de file on the disc drive of server
                // Where you want the file to be stored?
                string whereToStoreTheFile = _path.WebRootPath;
                nameOfFile = Path.Combine(whereToStoreTheFile, "fotos", nameOfFile);
                // write the file
                using var stream = new FileStream(nameOfFile, FileMode.Create);
                await photoOfDog.CopyToAsync(stream);

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["DogFK"] = new SelectList(_db.Dogs, "Id", "Id", photos.DogFK);
            return(View(photos));
        }
        public async Task <IActionResult> Register([Bind("acc_type,CompanyName,FirstName,LastName,ProfilePicture,BirthDate,Email,Password")] UserModel userModel, IFormFile file)
        {
            // CREATE SELECTLIST TO DISPLAY ACCOUNT TYPES IN DROPDOWN LIST WHEN THE VIEW IS REDISPLAYED WITH ERROR
            List <string> AccTypeList = new List <string> {
                "Business", "Personal"
            };

            ViewBag.AccType = new SelectList(AccTypeList, "Business");

            // FETCH THE SELECTED ACCOUNT TYPE FROM DROPDOWN LIST
            string selectedAccType = Request.Form["acc_type"].ToString();

            if (selectedAccType == "Business")
            {
                userModel.FirstName = "";
                userModel.LastName  = "";
            }
            else
            {
                userModel.acc_type    = "Personal";
                userModel.CompanyName = "";
            }

            // TRY TO REGISTER USER INTO THE DATABASE
            try
            {
                // CHECK EMAIL ADDRESS FOR DUPLICATE RECORD
                var DbEmail = from e in _context.UserModel
                              where e.Email == userModel.Email
                              select e.Email;

                // COMPARE EMAIL ADDRESS IGNORING CASES, RETURN 0 IF BOTH ARE SAME
                if (string.Compare(userModel.Email, DbEmail.FirstOrDefault(), true) == 0)
                {
                    ViewBag.Message = "Email address already exists.";
                    return(View());
                }
                else
                {
                    // CHECK FOR USER'S AGE (18 YEARS ~ 6575 DAYS)
                    var age = Utility.AgeSpan(userModel.BirthDate);

                    if (Math.Ceiling(age) <= 6575)
                    {
                        ViewBag.Message = "You should be 18 years or older to register.";
                        return(View());
                    }
                    else
                    {
                        // RENAME IMAGE AND STORE IT TO THE SERVER DIRECTORY
                        if (file != null)
                        {
                            //var fileName = Path.GetFileNameWithoutExtension(file.FileName);
                            //var extension = Path.GetExtension(file.FileName);
                            //fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;

                            // CHECK THE SIZE OF IMAGE 1MB = 1000000 BYTES
                            if (file.Length > 1000000)
                            {
                                ViewBag.Message = "Image size should not exceed 1 MB";
                                return(View());
                            }
                            else
                            {
                                var fileName = Utility.GetProfilePictureFileName(file);
                                userModel.ProfilePicture = fileName;
                                var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\ProfilePicture", fileName);
                                using (var stream = new FileStream(path, FileMode.Create))
                                {
                                    await file.CopyToAsync(stream);
                                }
                            }
                        }

                        // SALT AND HASH PASSWORD BEFORE SAVING TO DATABASE
                        String passwordHash = pwdManager.GeneratePasswordHash(userModel.Password, out string salt);
                        userModel.PasswordHash = passwordHash;
                        userModel.PasswordSalt = salt;

                        // SET THE SESSION VALUE AND REGISTER USER
                        HttpContext.Session.SetString(SessionKeyUserEmail, userModel.Email);
                        _context.Add(userModel);
                        await _context.SaveChangesAsync();

                        var DbUserRec = _context.UserModel.Where(u => u.Email == userModel.Email && u.Password == userModel.Password).FirstOrDefault();
                        HttpContext.Session.SetString(SessionKeyUserID, DbUserRec.ID.ToString());
                        return(RedirectToAction(nameof(Index)));
                    }
                }
            }
            catch (Exception e)
            {
                ViewBag.Message = e.ToString(); // "Something went wrong.";
                return(View());
            }
        }
        public async Task <IActionResult> ImportMunicipalitiesWeatherStations(string id, IFormFile file)
        {
            Message msg    = null;
            State   entity = null;

            try
            {
                ObjectId state_id = getId(id);
                entity = await db.state.byIdAsync(id);

                if (file != null && file.Length > 0)
                {
                    // Save a copy in the web site
                    await file.CopyToAsync(new FileStream(importPath + DateTime.Now.ToString("yyyyMMddHHmmss") + "-state-mws-" + file.FileName, FileMode.Create));

                    // Read the file
                    StreamReader reader = new StreamReader(file.OpenReadStream());
                    // Variables to process the file
                    IEnumerable <string> m_name = null, ws_ext_id = null, ws_name = null, ws_lat = null, ws_lon = null;
                    string ws_origin = string.Empty;
                    string line = string.Empty;
                    // Read the file
                    while (!reader.EndOfStream)
                    {
                        line = await reader.ReadLineAsync();

                        // read the headers
                        if (line.StartsWith("ext_id"))
                        {
                            ws_ext_id = line.Split(',').Skip(1);
                        }
                        else if (line.StartsWith("municipality"))
                        {
                            m_name = line.Split(',').Skip(1);
                        }
                        else if (line.StartsWith("name"))
                        {
                            ws_name = line.Split(',').Skip(1);
                        }
                        else if (line.StartsWith("latitude"))
                        {
                            ws_lat = line.Split(',').Skip(1);
                        }
                        else if (line.StartsWith("longitude"))
                        {
                            ws_lon = line.Split(',').Skip(1);
                        }
                        else if (line.StartsWith("origin"))
                        {
                            ws_origin = line.Split(',')[1];
                        }
                    }
                    // Variables to management the import process
                    int          count_municipalities = 0, count_weather_stations = 0;
                    Municipality m_temp;
                    // Create all municipalities
                    foreach (string m in m_name)
                    {
                        m_temp = await db.municipality.byNameAsync(m);

                        if (m_temp == null)
                        {
                            await db.municipality.insertAsync(new Municipality()
                            {
                                name = m, state = state_id, visible = false
                            });

                            count_municipalities += 1;
                        }
                    }

                    // Create all weather stations
                    for (int i = 0; i < ws_name.Count(); i++)
                    {
                        m_temp = await db.municipality.byNameAsync(m_name.ElementAt(i));

                        await db.weatherStation.insertAsync(new WeatherStation()
                        {
                            ext_id       = ws_ext_id.ElementAt(i),
                            latitude     = double.Parse(ws_lat.ElementAt(i), CultureInfo.InvariantCulture),
                            longitude    = double.Parse(ws_lon.ElementAt(i), CultureInfo.InvariantCulture),
                            municipality = m_temp.id,
                            name         = ws_name.ElementAt(i).Trim(),
                            origin       = ws_origin,
                            visible      = false
                        });

                        count_weather_stations += 1;
                    }
                    msg = new Message()
                    {
                        content = "Import MWS. The file was imported correctly. Records imported: (" +
                                  count_municipalities.ToString() + ") municipalities (" + count_weather_stations.ToString() + ") weather stations",
                        type = MessageType.successful
                    };
                    await writeEventAsync(msg.content, LogEvent.cre, new List <LogEntity>() { LogEntity.lc_state, LogEntity.lc_municipality, LogEntity.lc_weather_station });
                }
                else
                {
                    msg = new Message()
                    {
                        content = "Import MWS. An error occurred with the file imported", type = MessageType.error
                    };
                    await writeEventAsync(msg.content, LogEvent.err, new List <LogEntity>() { LogEntity.lc_state, LogEntity.lc_municipality, LogEntity.lc_weather_station });
                }
            }
            catch (Exception ex)
            {
                await writeExceptionAsync(ex);

                msg = new Message()
                {
                    content = "Import MWS. An error occurred in the system, contact the administrator", type = MessageType.error
                };
            }
            ViewBag.message = msg;
            return(View("Import", entity));
        }
        private async Task<JsonResult> ProcessUpload(IFormFile file)
        {
            Trace.TraceInformation("Process upload for {0}", file.ToString());

            var t = DateTime.UtcNow - new DateTime(1970, 1, 1);
            var epoch = (int)t.TotalSeconds;
            var sourceName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
            var filePath = Path.GetTempFileName();
            string url = null;

            // Save locally
            using (var stream = System.IO.File.OpenWrite(filePath))
            {
                await file.CopyToAsync(stream);
            }
            
            try
            {
                var resultPaths = ConvertFiles(filePath, sourceName);
            

                if (resultPaths != null && resultPaths.Any())
                {
                    foreach (var path in resultPaths)
                    {
                        Trace.TraceInformation("Moving to blob store: {0}", path);
                        var blobUri = await _storage.UploadFileToBlob(path, Path.GetFileName(path));

                        // Hack - Grab the destination URI for use later
                        if (blobUri.Contains(".dat"))
                        {
                            url = blobUri.Replace(".dat", string.Empty);
                        }
                    
                    }

                    // update project name if appropriate
                    string projectName = Path.GetFileNameWithoutExtension(sourceName);
                    var projects = _storage.GetProjectsForUser(GetEmailFromUser());

                    if (projects.Where(p => string.Equals(p.Name, projectName, StringComparison.OrdinalIgnoreCase)).Any())
                    {
                        int versionNumber = projects.Count(p => p.Name.Contains(projectName)) + 1;
                        projectName = string.Format("{0} (v{1})", projectName, versionNumber);
                    }
                    _storage.SaveFileToTables(projectName, url, GetEmailFromUser());
                }

            }
            catch (Exception ex)
            {
                var result = new JsonResult(new { error = "The server failed to process this file.  Please verify source data is compatible." });
                result.StatusCode = 500;
                return result;
            }

            return Json(new { thumbnail = "url" + ".jpg" });
        }
예제 #10
0
        public async Task <IActionResult> Index(InputModel input, [Bind(Prefix = "Input.ImageURL")] IFormFile image)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction(nameof(Index)));
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }

            var email = await _userManager.GetEmailAsync(user);

            if (input.Email != email)
            {
                var setEmailResult = await _userManager.SetEmailAsync(user, input.Email);

                if (!setEmailResult.Succeeded)
                {
                    var userId = await _userManager.GetUserIdAsync(user);

                    throw new InvalidOperationException($"Unexpected error occurred setting email for user with ID '{userId}'.");
                }
            }

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            if (input.PhoneNumber != phoneNumber)
            {
                var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, input.PhoneNumber);

                if (!setPhoneResult.Succeeded)
                {
                    var userId = await _userManager.GetUserIdAsync(user);

                    throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'.");
                }
            }

            if (input.Name != user.Name || input.Birthday != user.Birthday)
            {
                user.Birthday = input.Birthday;
                user.Name     = input.Name;
            }

            if (image != null)
            {
                using (var memoryStream = new MemoryStream())
                {
                    await image.CopyToAsync(memoryStream);

                    memoryStream.Position = 0;
                    Account    account      = new Account("adotaqui", "763436643874459", "G8jgeFUttCwjs-y-aJ0vjzLkUOA");
                    Cloudinary cloudinary   = new Cloudinary(account);
                    Random     random       = new Random();
                    var        uploadParams = new ImageUploadParams()
                    {
                        Folder = "adotaquiusers",
                        File   = new FileDescription(random.Next(10000000, 99999999).ToString(), memoryStream)
                    };
                    var uploadResult = cloudinary.Upload(uploadParams);
                    user.ImageURL = uploadResult.SecureUri.ToString();
                }
            }

            var result = await _userManager.UpdateAsync(user);

            if (!result.Succeeded)
            {
                var userId = await _userManager.GetUserIdAsync(user);

                throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'.");
            }

            await _signInManager.RefreshSignInAsync(user);

            var model = new IndexViewModel
            {
                IsEmailConfirmed = user.EmailConfirmed,
                Username         = user.UserName,
                StatusMessage    = new StatusMessage {
                    Type = MessageType.Success, Value = "Perfil foi actualizado com sucesso!"
                },
                Input = new InputModel
                {
                    Birthday    = user.Birthday,
                    Email       = user.Email,
                    PhoneNumber = user.PhoneNumber,
                    Name        = user.Name,
                    ImageURL    = user.ImageURL
                }
            };

            return(View(model));
        }
예제 #11
0
        public async Task <IActionResult> UploadImageAsync(IFormFile file, [FromServices] IFileNameGenerator fileNameGenerator)
        {
            try
            {
                if (null == file)
                {
                    Logger.LogError("file is null.");
                    return(BadRequest());
                }

                if (file.Length <= 0)
                {
                    return(BadRequest());
                }

                var name = Path.GetFileName(file.FileName);
                if (name == null)
                {
                    return(BadRequest());
                }

                var ext = Path.GetExtension(name).ToLower();
                var allowedImageFormats = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".gif" };
                if (!allowedImageFormats.Contains(ext))
                {
                    Logger.LogError($"Invalid file extension: {ext}");
                    return(BadRequest());
                }

                var primaryFileName  = fileNameGenerator.GetFileName(name);
                var secondaryFieName = fileNameGenerator.GetFileName(name, "origin");

                await using var stream = new MemoryStream();
                await file.CopyToAsync(stream);

                // Add watermark
                MemoryStream watermarkedStream = null;
                if (_blogConfig.WatermarkSettings.IsEnabled && ext != ".gif")
                {
                    using var watermarker = new ImageWatermarker(stream, ext)
                          {
                              SkipWatermarkForSmallImages = true,
                              SmallImagePixelsThreshold   = Constants.SmallImagePixelsThreshold
                          };
                    Logger.LogInformation($"Adding watermark onto image '{primaryFileName}'");

                    watermarkedStream = watermarker.AddWatermark(
                        _blogConfig.WatermarkSettings.WatermarkText,
                        Color.FromArgb(128, 128, 128, 128),
                        WatermarkPosition.BottomRight,
                        15,
                        _blogConfig.WatermarkSettings.FontSize);
                }

                var response = await _imageStorageProvider.InsertAsync(primaryFileName,
                                                                       watermarkedStream != null?
                                                                       watermarkedStream.ToArray() :
                                                                           stream.ToArray());

                if (_blogConfig.WatermarkSettings.KeepOriginImage)
                {
                    var arr = stream.ToArray();
                    _ = Task.Run(async() => await _imageStorageProvider.InsertAsync(secondaryFieName, arr));
                }

                Logger.LogInformation($"Image '{primaryFileName}' uloaded.");

                if (response.IsSuccess)
                {
                    return(Json(new { location = $"/uploads/{response.Item}" }));
                }
                Logger.LogError(response.Message);
                return(ServerError());
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error uploading image.");
                return(ServerError());
            }
        }
예제 #12
0
        public async Task <string> UploadAttachment(IFormFile File)
        {
            try
            {
                if (await AmazonS3Util.DoesS3BucketExistV2Async(_client, bucketName))
                {
                    var transfacility = new TransferUtility(_client);

                    var folderName = Path.Combine("StaticFiles", "Images");
                    var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
                    var fileName   = File.FileName;

                    if (File.Length > 0)
                    {
                        var fullPath = Path.Combine(pathToSave, fileName);
                        var dbPath   = Path.Combine(folderName, fileName);



                        using (var stream = new FileStream(fullPath, FileMode.Create))
                        {
                            await File.CopyToAsync(stream);

                            await transfacility.UploadAsync(stream,
                                                            bucketName, fileName);
                        }



                        //  using (var fileToUpload =
                        //new FileStream(fullPath, FileMode.Open, FileAccess.Read))
                        //  {
                        //      await transfacility.UploadAsync(fileToUpload,
                        //                                 "newfeatureimages", fileName);
                        //  }

                        //GetObjectRequest request = new GetObjectRequest();
                        //request.BucketName = "newfeatureattachments";
                        //request.Key = fileName;
                        //var getresponse = await _client.GetObjectAsync(request);

                        string urlString = "";

                        GetPreSignedUrlRequest request1 = new GetPreSignedUrlRequest
                        {
                            BucketName = bucketName,
                            Key        = fileName,
                            Expires    = DateTime.UtcNow.AddHours(168)
                        };
                        urlString = _client.GetPreSignedURL(request1);



                        return(urlString);
                        // return Ok(new { dbPath });
                    }
                    else
                    {
                        return("");
                    }
                }
                else
                {
                    return("");
                }
            }
            catch (Exception ex)
            {
                return("");
            }
        }
예제 #13
0
    public ActionResult <DictionaryImportModel> Upload(IFormFile file)
    {
        if (file == null)
        {
            return(ValidationProblem(
                       _localizedTextService.Localize("media", "failedFileUpload"),
                       _localizedTextService.Localize("speechBubbles", "fileErrorNotFound")));
        }

        var fileName = file.FileName.Trim(Constants.CharArrays.DoubleQuote);
        var ext      = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower();
        var root     = _hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.TempFileUploads);
        var tempPath = Path.Combine(root, fileName);

        if (!Path.GetFullPath(tempPath).StartsWith(Path.GetFullPath(root)))
        {
            return(ValidationProblem(
                       _localizedTextService.Localize("media", "failedFileUpload"),
                       _localizedTextService.Localize("media", "invalidFileName")));
        }

        if (!ext.InvariantEquals("udt"))
        {
            return(ValidationProblem(
                       _localizedTextService.Localize("media", "failedFileUpload"),
                       _localizedTextService.Localize("media", "disallowedFileType")));
        }

        using (FileStream stream = System.IO.File.Create(tempPath))
        {
            file.CopyToAsync(stream).GetAwaiter().GetResult();
        }

        var xd = new XmlDocument {
            XmlResolver = null
        };

        xd.Load(tempPath);

        if (xd.DocumentElement == null)
        {
            return(ValidationProblem(
                       _localizedTextService.Localize("media", "failedFileUpload"),
                       _localizedTextService.Localize("speechBubbles", "fileErrorNotFound")));
        }

        var model = new DictionaryImportModel()
        {
            TempFileName    = tempPath,
            DictionaryItems = new List <DictionaryPreviewImportModel>(),
        };

        var level         = 1;
        var currentParent = string.Empty;

        foreach (XmlNode dictionaryItem in xd.GetElementsByTagName("DictionaryItem"))
        {
            var name      = dictionaryItem.Attributes?.GetNamedItem("Name")?.Value ?? string.Empty;
            var parentKey = dictionaryItem?.ParentNode?.Attributes?.GetNamedItem("Key")?.Value ?? string.Empty;

            if (parentKey != currentParent || level == 1)
            {
                level        += 1;
                currentParent = parentKey;
            }

            model.DictionaryItems.Add(new DictionaryPreviewImportModel()
            {
                Level = level, Name = name
            });
        }

        if (!model.DictionaryItems.Any())
        {
            return(ValidationProblem(
                       _localizedTextService.Localize("media", "failedFileUpload"),
                       _localizedTextService.Localize("dictionary", "noItemsInFile")));
        }

        return(model);
    }
예제 #14
0
        public async Task <IActionResult> Import(IFormFile fileExcel)
        {
            if (ModelState.IsValid)
            {
                if (fileExcel != null)
                {
                    using (var stream = new FileStream(fileExcel.FileName, FileMode.Create))
                        if (Path.GetExtension(stream.Name) == ".xlsx" || Path.GetExtension(stream.Name) == ".xls")
                        {
                            await fileExcel.CopyToAsync(stream);

                            using (XLWorkbook workBook = new XLWorkbook(stream, XLEventTracking.Disabled))
                            {
                                foreach (IXLWorksheet worksheet in workBook.Worksheets)
                                {
                                    //worksheet.Name - назва категорії. Пробуємо знайти в БД, якщо відсутня, то створюємо нову
                                    Categories newcat;
                                    var        c = (from cat in _context.Categories
                                                    where cat.CategoryName.Contains(worksheet.Name)
                                                    select cat).ToList();
                                    if (c.Count > 0)
                                    {
                                        newcat = c[0];
                                    }
                                    else
                                    {
                                        newcat = new Categories();
                                        newcat.CategoryName = worksheet.Name;
                                        _context.Categories.Add(newcat);
                                    }
                                    //перегляд усіх рядків
                                    foreach (IXLRow row in worksheet.RowsUsed().Skip(1))
                                    {
                                        try
                                        {
                                            Books book = new Books();
                                            book.Name = row.Cell("1").Value.ToString();
                                            if (Int16.Parse(row.Cell("2").Value.ToString()) < 1 || Int16.Parse(row.Cell("2").Value.ToString()) > 25000)
                                            {
                                                throw new Exception();
                                            }
                                            book.NumberOfPages = Int16.Parse(row.Cell("2").Value.ToString());

                                            if (Int16.Parse(row.Cell("3").Value.ToString()) < 1300 || Int16.Parse(row.Cell("3").Value.ToString()) > 2020)
                                            {
                                                throw new Exception();
                                            }

                                            book.YearOfPublication = Int16.Parse(row.Cell("3").Value.ToString());
                                            BookCategory bookCategory = new BookCategory();
                                            bookCategory.Category = newcat;
                                            bookCategory.Book     = book;
                                            _context.Books.Add(book);
                                            _context.BookCategory.Add(bookCategory);
                                            for (int i = 4; i <= 6; i++)
                                            {
                                                /* if(!Regex.IsMatch(row.Cell(i).Value.ToString(), @"^([A-Z][a-z]+)\ ([A-Z][a-z]+)(\ ?([A-Z][a-z]+)?)|([А-ЯІЇЄЩ][а-яіїщє]+)\ ([А-ЯІЇЄЩ][а-яіїщє]+)(\ ?([А-ЯІЇЄЩ][а-яіїщє]+)?)$")) {
                                                 *   throw new Exception();
                                                 * }                     */
                                                if (row.Cell(i).Value.ToString().Length > 0)
                                                {
                                                    Authors author;
                                                    var     a = (from aut in _context.Authors
                                                                 where aut.FullName.Contains(row.Cell(i).Value.ToString())
                                                                 select aut).ToList();
                                                    if (a.Count > 0)
                                                    {
                                                        author = a[0];
                                                    }
                                                    else
                                                    {
                                                        author          = new Authors();
                                                        author.FullName = row.Cell(i).Value.ToString();
                                                        _context.Add(author);
                                                    }
                                                    Authorship ab = new Authorship();
                                                    ab.Book   = book;
                                                    ab.Author = author;
                                                    _context.Authorship.Add(ab);
                                                }
                                            }
                                        }

                                        catch (Exception e)
                                        {
                                            TempData["msgDATA"] = "<script>alert('Некоректний зміст файлу');</script>";
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            TempData["msgDATA"] = "<script>alert('Некоректний формат файлу');</script>";
                        }
                }

                await _context.SaveChangesAsync();
            }
            return(RedirectToAction(nameof(Index)));
        }
예제 #15
0
        public static async Task <byte[]> ProcessFormFile <T>(IFormFile formFile,
                                                              ModelStateDictionary modelState, IEnumerable <string> permittedExtensions,
                                                              long sizeLimit)
        {
            if (formFile == null)
            {
                throw new ArgumentNullException(nameof(formFile));
            }
            var fieldDisplayName = string.Empty;
            var property         = typeof(T).GetProperty(formFile.Name.Substring(formFile.Name.IndexOf(".", StringComparison.Ordinal) + 1));

            if (property != null)
            {
                if (property.GetCustomAttribute(typeof(DisplayAttribute)) is
                    DisplayAttribute displayAttribute)
                {
                    fieldDisplayName = $"{displayAttribute.Name} ";
                }
            }

            var trustedFileNameForDisplay = WebUtility.HtmlEncode(
                formFile.FileName);

            if (formFile.Length == 0)
            {
                modelState.AddModelError(formFile.Name,
                                         $"{fieldDisplayName}({trustedFileNameForDisplay}) is empty.");

                return(new byte[0]);
            }

            if (formFile.Length > sizeLimit)
            {
                var megabyteSizeLimit = sizeLimit / 1048576;
                modelState.AddModelError(formFile.Name,
                                         $"{fieldDisplayName}({trustedFileNameForDisplay}) exceeds " +
                                         $"{megabyteSizeLimit:N1} MB.");

                return(new byte[0]);
            }

            try
            {
                await using var memoryStream = new MemoryStream();
                await formFile.CopyToAsync(memoryStream);

                if (memoryStream.Length == 0)
                {
                    modelState.AddModelError(formFile.Name,
                                             $"{fieldDisplayName}({trustedFileNameForDisplay}) is empty.");
                }

                if (!IsValidFileExtensionAndSignature(
                        formFile.FileName, memoryStream, permittedExtensions))
                {
                    modelState.AddModelError(formFile.Name,
                                             $"{fieldDisplayName}({trustedFileNameForDisplay}) file " +
                                             "type isn't permitted or the file's signature " +
                                             "doesn't match the file's extension.");
                }
                else
                {
                    return(memoryStream.ToArray());
                }
            }
            catch (Exception ex)
            {
                modelState.AddModelError(formFile.Name,
                                         $"{fieldDisplayName}({trustedFileNameForDisplay}) upload failed. " + $"Please contact the Help Desk for support. Error: {ex.HResult}");
            }

            return(new byte[0]);
        }
        public async Task <IActionResult> Edit(int id, [Bind("AmazonProductColorID,AmazonProductID,AmazonColorID,DesignURL,Name,Opacity,Top,Left,Right,Bot")] AmazonProductColor amazonProductColor, IFormFile DesignURL, string oldURL, string oldThumb)
        {
            if (id != amazonProductColor.AmazonProductColorID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    if (DesignURL != null)
                    {
                        var fullUploadPath = Path.Combine(_environment.WebRootPath, COLOR_DIR);
                        var extension      = DesignURL.FileName.Split('.').Last();
                        var filename       = amazonProductColor.AmazonProductColorID + "." + extension;
                        fullUploadPath = Path.Combine(fullUploadPath, filename);
                        using (var fileStream = new FileStream(fullUploadPath, FileMode.Create))
                        {
                            System.IO.File.Delete(Path.Combine(_environment.WebRootPath, oldURL));
                            await DesignURL.CopyToAsync(fileStream);

                            amazonProductColor.DesignURL = Path.Combine(COLOR_DIR, filename);
                        }
                    }
                    else
                    {
                        amazonProductColor.DesignURL = oldURL;
                    }

                    var thumbURL    = Path.Combine(THUMB_DIR, amazonProductColor.AmazonProductColorID + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg");
                    var outputImage = Path.Combine(_environment.WebRootPath, thumbURL);
                    var baseImage   = Path.Combine(_environment.WebRootPath, amazonProductColor.DesignURL);

                    System.IO.File.Delete(Path.Combine(_environment.WebRootPath, oldThumb));

                    System.Drawing.Image m_baseimage = System.Drawing.Image.FromFile(baseImage);
                    System.Drawing.Pen   myPen       = new System.Drawing.Pen(System.Drawing.Color.Black);

                    System.Drawing.Graphics.FromImage(m_baseimage).DrawLine(myPen, new System.Drawing.Point(amazonProductColor.Left, 0), new System.Drawing.Point(amazonProductColor.Left, m_baseimage.Height));
                    System.Drawing.Graphics.FromImage(m_baseimage).DrawLine(myPen, new System.Drawing.Point(amazonProductColor.Right, 0), new System.Drawing.Point(amazonProductColor.Right, m_baseimage.Height));
                    System.Drawing.Graphics.FromImage(m_baseimage).DrawLine(myPen, new System.Drawing.Point(0, amazonProductColor.Top), new System.Drawing.Point(m_baseimage.Width, amazonProductColor.Top));
                    System.Drawing.Graphics.FromImage(m_baseimage).DrawLine(myPen, new System.Drawing.Point(0, amazonProductColor.Bot), new System.Drawing.Point(m_baseimage.Width, amazonProductColor.Bot));

                    m_baseimage.Save(outputImage);
                    m_baseimage.Dispose();

                    amazonProductColor.ThumbURL = thumbURL;

                    _context.Update(amazonProductColor);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!AmazonProductColorExists(amazonProductColor.AmazonProductColorID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction("Edit", new { id = amazonProductColor.AmazonProductColorID }));
            }

            amazonProductColor = await _context.AmazonProductColors
                                 .Include(i => i.AmazonProduct)
                                 .Include(i => i.AmazonColor)
                                 .SingleOrDefaultAsync(m => m.AmazonProductColorID == id);

            ViewData["AmazonProductID"] = new SelectList(_context.AmazonProducts, "AmazonProductID", "Name", amazonProductColor.AmazonProductID);
            ViewData["AmazonColorID"]   = new SelectList(_context.AmazonColors, "AmazonColorID", "Name", amazonProductColor.AmazonColorID);
            return(View(amazonProductColor));
        }
예제 #17
0
        public async Task <IActionResult> EditTeacherProfile([FromForm] Teacher teacher, IFormFile file)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("ErrorMessage:", "You unAuthorize to Get Data of this Teacher");
                return(BadRequest(ModelState));
            }
            var identity = User.Identity as ClaimsIdentity;

            if (identity == null)
            {
                ModelState.AddModelError("ErrorMessage:", "You are not Authanticated");
                return(BadRequest(ModelState));
            }
            IEnumerable <Claim> claims = identity.Claims;
            var teacherId = claims.Where(p => p.Type == "TeacherId").FirstOrDefault()?.Value;

            if (teacherId == null)   // check teacher is exists or no
            {
                ModelState.AddModelError("ErrorMessage:", "You are not Authanticated");
                return(BadRequest(ModelState));
            }
            // teacher in DB
            var teacherById = await _teacherRegisterRepository.GetTeacherById(int.Parse(teacherId));

            var fileName = teacherById.Picture;  // old picture

            if (int.Parse(teacherId) != 0)
            {
                if (teacherById == null)
                {
                    return(Content("not found , please Check!..."));
                }
                if (file != null)
                {
                    if (file.Length == 0)
                    {
                        return(BadRequest("Empty file"));
                    }
                    if (file.Length > _photoSetting.MaxBytes)
                    {
                        return(BadRequest("Max file size exceeded"));
                    }
                    if (!_photoSetting.IsSupported(file.FileName))
                    {
                        return(BadRequest("Invalid file type"));
                    }
                    var uploadsFolderPath = Path.Combine(_host.WebRootPath, "uploads");
                    if (!Directory.Exists(uploadsFolderPath))
                    {
                        Directory.CreateDirectory(uploadsFolderPath);
                    }
                    fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
                    var filePath = Path.Combine(uploadsFolderPath, fileName);  // filepath

                    if (teacherById.Picture != null)
                    {
                        var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\uploads", teacherById.Picture);
                        if (System.IO.File.Exists(path))
                        {
                            System.IO.File.Delete(path);
                            using (var stream = new FileStream(filePath, FileMode.Create))
                            {
                                await file.CopyToAsync(stream); // picture saved to the path (folder)
                            }
                            //teacher.Picture = fileName;
                        }
                    }
                    else
                    {
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            await file.CopyToAsync(stream); // picture saved to the path (folder)

                            //teacher.Picture = fileName;
                        }
                    }
                }
            }
            // for hashing password
            string password = teacher.Password;

            byte[] salt = new byte[128 / 8];
            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(salt);
            }
            string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
                                                       password: password,
                                                       salt: salt,
                                                       prf: KeyDerivationPrf.HMACSHA1,
                                                       iterationCount: 10000,
                                                       numBytesRequested: 256 / 8));

            teacher.Password = hashed;
            await _teacherRegisterRepository.EditTeacherProfile(teacher, teacherById.TeacherId, fileName);

            return(Created("TeacherTable", teacherById));
        }
예제 #18
0
 private static async Task Download(IFormFile formFile, string downloadsPath)
 {
     using var fileStream = new FileStream(Path.Combine(downloadsPath, formFile.Name), FileMode.Create);
     await formFile.CopyToAsync(fileStream).ConfigureAwait(false);
 }
 public async Task <IActionResult> CreateAsync(Burial burial,
                                               IFormFile img_file, string img_description,
                                               IFormFile notes_file, string notes_description,
                                               IFormFile bone_file, string bone_description)
 {
     // Image Upload
     if (img_file != null)
     {
         var  basePath       = Path.Combine(Directory.GetCurrentDirectory() + "\\wwwroot\\Files\\img\\" + burial.BurialID + "\\");
         bool basePathExists = System.IO.Directory.Exists(basePath);
         if (!basePathExists)
         {
             Directory.CreateDirectory(basePath);
         }
         var fileName  = Path.GetFileNameWithoutExtension(img_file.FileName);
         var filePath  = Path.Combine(basePath, img_file.FileName);
         var extension = Path.GetExtension(img_file.FileName);
         if (!System.IO.File.Exists(filePath))
         {
             using (var stream = new FileStream(filePath, FileMode.Create))
             {
                 await img_file.CopyToAsync(stream);
             }
             var fileModel = new FileOnFileSystemModel
             {
                 CreatedOn   = DateTime.UtcNow,
                 FileType    = img_file.ContentType,
                 Extension   = extension,
                 Name        = fileName,
                 Description = img_description,
                 FilePath    = filePath
             };
             _BurialContext.FileOnFileSystemModels.Add(fileModel);
             _BurialContext.SaveChanges();
             burial.ImgOnSystem = _BurialContext.FileOnFileSystemModels.Where(f => f.FilePath == fileModel.FilePath).FirstOrDefault().Id;
         }
         else
         {
             ViewBag.status = "Photo already esists with this name and file type";
             return(View());
         }
     }
     // Field Notes Upload
     if (notes_file != null)
     {
         var  basePath       = Path.Combine(Directory.GetCurrentDirectory() + "\\wwwroot\\Files\\notes\\" + burial.BurialID + "\\");
         bool basePathExists = System.IO.Directory.Exists(basePath);
         if (!basePathExists)
         {
             Directory.CreateDirectory(basePath);
         }
         var fileName  = Path.GetFileNameWithoutExtension(notes_file.FileName);
         var filePath  = Path.Combine(basePath, notes_file.FileName);
         var extension = Path.GetExtension(notes_file.FileName);
         if (!System.IO.File.Exists(filePath))
         {
             using (var stream = new FileStream(filePath, FileMode.Create))
             {
                 await notes_file.CopyToAsync(stream);
             }
             var fileModel = new FileOnFileSystemModel
             {
                 CreatedOn   = DateTime.UtcNow,
                 FileType    = notes_file.ContentType,
                 Extension   = extension,
                 Name        = fileName,
                 Description = notes_description,
                 FilePath    = filePath
             };
             _BurialContext.FileOnFileSystemModels.Add(fileModel);
             _BurialContext.SaveChanges();
             burial.NoteBookOnSystem = _BurialContext.FileOnFileSystemModels.Where(f => f.FilePath == fileModel.FilePath).FirstOrDefault().Id;
         }
         else
         {
             ViewBag.status = "Photo already esists with this name and file type";
             return(View());
         }
     }
     // Bone Book Upload
     if (bone_file != null)
     {
         var  basePath       = Path.Combine(Directory.GetCurrentDirectory() + "\\wwwroot\\Files\\bonebooks\\" + burial.BurialID + "\\");
         bool basePathExists = System.IO.Directory.Exists(basePath);
         if (!basePathExists)
         {
             Directory.CreateDirectory(basePath);
         }
         var fileName  = Path.GetFileNameWithoutExtension(bone_file.FileName);
         var filePath  = Path.Combine(basePath, bone_file.FileName);
         var extension = Path.GetExtension(bone_file.FileName);
         if (!System.IO.File.Exists(filePath))
         {
             using (var stream = new FileStream(filePath, FileMode.Create))
             {
                 await bone_file.CopyToAsync(stream);
             }
             var fileModel = new FileOnFileSystemModel
             {
                 CreatedOn   = DateTime.UtcNow,
                 FileType    = bone_file.ContentType,
                 Extension   = extension,
                 Name        = fileName,
                 Description = bone_description,
                 FilePath    = filePath
             };
             _BurialContext.FileOnFileSystemModels.Add(fileModel);
             _BurialContext.SaveChanges();
             burial.BoneBookOnSystem = _BurialContext.FileOnFileSystemModels.Where(f => f.FilePath == fileModel.FilePath).FirstOrDefault().Id;
         }
         else
         {
             ViewBag.status = "Photo already esists with this name and file type";
             return(View());
         }
     }
     _BurialContext.Burials.Add(burial);
     _BurialContext.SaveChanges();
     return(View("Success", burial));
 }
예제 #20
0
        public async Task <IActionResult> Import(IFormFile fileExcel)
        {
            int errorCount = 0;

            if (ModelState.IsValid)
            {
                if (fileExcel != null)
                {
                    using (var stream = new FileStream(fileExcel.FileName, FileMode.Create))
                    {
                        await fileExcel.CopyToAsync(stream);

                        using (XLWorkbook workBook = new XLWorkbook(stream, XLEventTracking.Disabled))
                        {
                            //перегляд усіх листів (в даному випадку категорій)
                            foreach (IXLWorksheet worksheet in workBook.Worksheets)
                            {
                                //worksheet.Name - назва категорії. Пробуємо знайти в БД, якщо відсутня, то створюємо нову
                                GarbageType newtype;
                                var         t = (from typ in _context.GarbageType
                                                 where typ.Name.Contains(worksheet.Name)
                                                 select typ).ToList();
                                if (t.Count > 0)
                                {
                                    newtype = t[0];
                                }
                                else
                                {
                                    newtype      = new GarbageType();
                                    newtype.Name = worksheet.Name;
                                    if (TryValidateModel(newtype))
                                    {
                                        _context.GarbageType.Add(newtype);
                                    }
                                    else
                                    {
                                        ++errorCount;
                                    }
                                }
                                //перегляд усіх рядків
                                foreach (IXLRow row in worksheet.RowsUsed().Skip(1))
                                {
                                    try
                                    {
                                        Material material;

                                        var g = (from mat in _context.Material
                                                 where mat.Name.Contains(row.Cell(1).Value.ToString())
                                                 select mat).ToList();
                                        if (g.Count > 0)
                                        {
                                            material = g[0];
                                            errorCount++;
                                        }
                                        else
                                        {
                                            material      = new Material();
                                            material.Name = row.Cell(1).Value.ToString();
                                            if (TryValidateModel(material, nameof(Material)))
                                            {
                                                _context.Material.Add(material);
                                            }
                                            else
                                            {
                                                ++errorCount;
                                            }
                                        }
                                        //у разі наявності автора знайти його, у разі відсутності - додати
                                        for (int i = 2; i <= 5; i++)
                                        {
                                            if (row.Cell(i).Value.ToString().Length > 0)
                                            {
                                                Garbage garbage;

                                                var a = (from gar in _context.Garbage
                                                         where gar.Name.Contains(row.Cell(i).Value.ToString())
                                                         select gar).ToList();
                                                if (a.Count > 0)
                                                {
                                                    garbage = a[0];
                                                }
                                                else
                                                {
                                                    garbage      = new Garbage();
                                                    garbage.Name = row.Cell(i).Value.ToString();
                                                    if (TryValidateModel(garbage, nameof(Garbage)))
                                                    {
                                                        _context.Garbage.Add(garbage);
                                                        GarbageMaterial gm;
                                                        var             b = (from garmat in _context.GarbageMaterial
                                                                             where garmat.IdGarbageNavigation.Name == garbage.Name &&
                                                                             garmat.IdMaterialNavigation.Name == material.Name
                                                                             select garmat).ToList();
                                                        if (a.Count > 0)
                                                        {
                                                            errorCount++;
                                                        }
                                                        else
                                                        {
                                                            gm = new GarbageMaterial();
                                                            gm.IdGarbageNavigation  = garbage;
                                                            gm.IdMaterialNavigation = material;
                                                            _context.GarbageMaterial.Add(gm);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        ++errorCount;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        ++errorCount;
                                    }
                                }
                            }
                        }
                    }
                }

                await _context.SaveChangesAsync();
            }
            return(RedirectToAction(nameof(Index), new { errorCount = errorCount }));
        }
예제 #21
0
        public async Task <IActionResult> FillProfile(FillFreelanceProfileVM vm, int[] skillIds, IFormFile file)
        {
            var user = await userManager.FindByNameAsync(User.Identity.Name);

            if (ModelState.IsValid)
            {
                if (file != null)
                {
                    var filename = $"{Guid.NewGuid().ToString()}{file.FileName}";
                    var path     = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\img", filename);

                    using (var fs = new FileStream(path, FileMode.OpenOrCreate))
                    {
                        await file.CopyToAsync(fs);
                    }
                    vm.ImageUrl      = filename;
                    user.FullName    = vm.FullName;
                    user.BirthDay    = vm.BirthDay;
                    user.Experience  = vm.Experience;
                    user.PhoneNumber = vm.PhoneNumber;
                    user.Description = vm.Description;
                    user.City        = vm.City;
                    user.Age         = vm.Age;
                    user.ImageUrl    = vm.ImageUrl;
                    user.UserName    = vm.UserName;

                    if (user.UserSkills == null)
                    {
                        context.UserSkills.AddRange(skillIds.Select(i => new UserSkill {
                            SkillId = i, AppUserId = user.Id
                        }));
                    }
                    else
                    {
                        context.UpdateManyToMany(
                            context.UserSkills.Where(x => x.AppUserId == user.Id),
                            skillIds.Select(x => new UserSkill {
                            AppUserId = user.Id, SkillId = x
                        }),
                            x => x.SkillId);
                    }

                    var b = await context.SaveChangesAsync();


                    var result = await userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        TempData["OK"] = "Profile sucsessfully filled!!!";
                        return(Redirect("/"));
                    }
                }
            }
            var selectedItems = context.UserSkills.Where(i => i.AppUserId == user.Id).Select(i => i.SkillId);

            if (selectedItems == null)
            {
                ViewBag.Skills = new MultiSelectList(context.Skills, "Id", "SkillName");
            }
            ViewBag.Skills = new MultiSelectList(context.Skills, "Id", "SkillName", selectedItems);
            return(View(vm));
        }
예제 #22
0
        // **WARNING!**
        // In the following file processing methods, the file's content isn't scanned.
        // In most production scenarios, an anti-virus/anti-malware scanner API is
        // used on the file before making the file available to users or other
        // systems. For more information, see the topic that accompanies this sample
        // app.

        public static async Task <byte[]> ProcessFormFile <T>(IFormFile formFile,
                                                              ModelStateDictionary modelState, string[] permittedExtensions,
                                                              long sizeLimit)
        {
            var fieldDisplayName = string.Empty;

            // Use reflection to obtain the display name for the model
            // property associated with this IFormFile. If a display
            // name isn't found, error messages simply won't show
            // a display name.
            MemberInfo property =
                typeof(T).GetProperty(
                    formFile.Name.Substring(formFile.Name.IndexOf(".",
                                                                  StringComparison.Ordinal) + 1));

            if (property != null)
            {
                if (property.GetCustomAttribute(typeof(DisplayAttribute)) is
                    DisplayAttribute displayAttribute)
                {
                    fieldDisplayName = $"{displayAttribute.Name} ";
                }
            }

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

            // Check the file length. This check doesn't catch files that only have
            // a BOM as their content.
            if (formFile.Length == 0)
            {
                modelState.AddModelError(formFile.Name,
                                         $"{fieldDisplayName}({trustedFileNameForDisplay}) is empty.");

                return(new byte[0]);
            }

            if (formFile.Length > sizeLimit)
            {
                var megabyteSizeLimit = sizeLimit / 1048576;
                modelState.AddModelError(formFile.Name,
                                         $"{fieldDisplayName}({trustedFileNameForDisplay}) exceeds " +
                                         $"{megabyteSizeLimit:N1} MB.");

                return(new byte[0]);
            }

            try
            {
                using (var memoryStream = new MemoryStream())
                {
                    await formFile.CopyToAsync(memoryStream);

                    // Check the content length in case the file's only
                    // content was a BOM and the content is actually
                    // empty after removing the BOM.
                    if (memoryStream.Length == 0)
                    {
                        modelState.AddModelError(formFile.Name,
                                                 $"{fieldDisplayName}({trustedFileNameForDisplay}) is empty.");
                    }

                    if (!IsValidFileExtensionAndSignature(
                            formFile.FileName, memoryStream, permittedExtensions) && false)
                    {
                        modelState.AddModelError(formFile.Name,
                                                 $"{fieldDisplayName}({trustedFileNameForDisplay}) file " +
                                                 "type isn't permitted or the file's signature " +
                                                 "doesn't match the file's extension.");
                    }
                    else
                    {
                        return(memoryStream.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
                modelState.AddModelError(formFile.Name,
                                         $"{fieldDisplayName}({trustedFileNameForDisplay}) upload failed. " +
                                         $"Please contact the Help Desk for support. Error: {ex.HResult}");
                // Log the exception
            }

            return(new byte[0]);
        }
예제 #23
0
        public async Task <ActionResult> AddResume(AddResumeViewModel model, IFormFile Image)
        {
            var candidate = db.Candidates.Include(c => c.AccountUser)
                            .FirstOrDefault(x => x.Id == model.CandidateId);

            var newResume = new Resume()
            {
                Id   = Guid.NewGuid(),
                Name = model.Name,
                // FieldActivities.
            };
            FieldActivityResume fieldActResume = null;

            var fieldActivity = db.FieldActivities.FirstOrDefault(f => f.Id == model.FieldId);

            if (fieldActivity != null)
            {
                fieldActResume = new FieldActivityResume()
                {
                    Resume        = newResume,
                    Id            = Guid.NewGuid(),
                    FieldActivity = fieldActivity,
                };
            }

            newResume.Candidate = candidate;

            if (Image != null)
            {
                string     name       = Image.FileName;
                string     path       = $"/files/{name}";
                string     serverPath = $"{_environment.WebRootPath}{path}";
                FileStream fs         = new FileStream(serverPath, FileMode.Create,
                                                       FileAccess.Write);
                await Image.CopyToAsync(fs);

                fs.Close();
                newResume.Foto = path;
            }


            newResume.Salary = model.Salary;

            // Todo AnonimResume  IsAnonymousResume

            newResume.Candidate.LastName = model.LastName;
            newResume.Candidate.Name     = model.Name;

            newResume.Candidate.Surname  = model.Surname;
            newResume.Candidate.Sex      = model.Sex;
            newResume.Candidate.Birthday = model.Birthday;
            // Todo Phones ????
            newResume.Candidate.PhoneNumber = model.Phone;
            newResume.Candidate.Email       = model.Email;
            newResume.Candidate.Facebook    = model.Fasebook;
            newResume.Candidate.Linkedin    = model.Linkedin;
            newResume.Candidate.Skype       = model.Skype;

            newResume.DateCreate = DateTime.Now;
            newResume.DateChange = DateTime.Now;


            newResume.Candidate.Country = model.Country;
            newResume.Candidate.Region  = model.Region;
            // newResume.Candidate.City = city;
            newResume.Candidate.Street          = model.Street;
            newResume.Candidate.ApartmentNumber = model.ApartmentNumber;

            db.Resumes.Add(newResume);
            db.SaveChanges();

            return(RedirectToAction(nameof(ResumeController.Edit), "Resume", new { resumeId = newResume.Id }));

            // return Redirect("Edit", "Resume", new { resumeId  == newResume.Id});
        }
        public async Task <IActionResult> ManageProfile([Bind("ID, acc_type, CompanyName, FirstName, LastName, ProfilePicture, BirthDate, Email")] UserModel userModel, IFormFile file)
        {
            // FETCH USER ID FROM SESSION TO GET THE DATABASE VALUE
            var UserID = HttpContext.Session.GetString(SessionKeyUserID);

            //List<string> AccTypeList = new List<string> { "Business", "Personal" };
            ViewBag.AccType = new SelectList(AccTypeList, userModel.acc_type);

            // USER IS NOT ALLOWED TO UPATE PASSWORD,
            // SO FETCH REGISTERED PASSWORD DETAILS FROM DATABASE,
            // AND STORE IT INTO USERMODEL
            // TO AVOID NULL UPDATION TO PASSWORD FIELD
            var DbPasswordSalt = from e in _context.UserModel
                                 where (e.ID == Convert.ToInt32(UserID))
                                 select e.PasswordSalt;
            var DbPasswordHash = from e in _context.UserModel
                                 where (e.ID == Convert.ToInt32(UserID))
                                 select e.PasswordHash;

            userModel.PasswordHash = DbPasswordHash.FirstOrDefault();
            userModel.PasswordSalt = DbPasswordSalt.FirstOrDefault();


            // IF USER DOESN'T EXIST IN DATABASE
            if (UserID != userModel.ID.ToString())
            {
                return(NotFound());
            }

            // TRY UPDATING RECORD
            try
            {
                // GET THE SELECTED ACCOUNT TYPE BY USER
                string SelectedAccType = Request.Form["acc_type"].ToString();
                if (SelectedAccType == "Business")
                {
                    userModel.FirstName = "";
                    userModel.LastName  = "";
                }
                else
                {
                    userModel.acc_type    = "Personal";
                    userModel.CompanyName = "";
                }

                // FETCH EMAIL OF OTHER USER TO CHECK
                // IF USER EDITED EMAIL ADDRESS MATCHES
                // WITH ANY OTHER USER EMAIL ADDRESS
                var DbEmail = from e in _context.UserModel
                              where e.Email == userModel.Email &&
                              e.ID != Convert.ToInt32(UserID)
                              select e.Email;

                if (userModel.Email == DbEmail.FirstOrDefault())
                {
                    // SEND SESSION INFO TO CONTROL THE VIEW
                    ViewBag.UserID          = HttpContext.Session.GetString(SessionKeyUserEmail);
                    ViewBag.Message         = "Email address already exists.";
                    ViewBag.MessageCssClass = "alert-info col-md-4";
                    return(View());
                }
                else
                {
                    // FETCH EXISTING PROFILE PICTURE NAME
                    var existingProfilePicture = from p in _context.UserModel
                                                 where p.ID == Convert.ToInt32(UserID)
                                                 select p.ProfilePicture;

                    // CHECK FOR THE USER'S AGE (18 YEARS ~ 6575 DAYS)
                    var Age = Utility.AgeSpan(userModel.BirthDate);

                    if (Math.Ceiling(Age) <= 6575)
                    {
                        ViewBag.Message         = "You should be 18 years or older to register.";
                        ViewBag.MessageCssClass = "alert-danger col-md-4";
                        ViewBag.ProfileSrc      = existingProfilePicture.FirstOrDefault();
                        return(View());
                    }
                    else
                    {
                        // RENAME IMAGE AND STORE IT TO THE SERVER DIRECTORY
                        if (file != null)
                        {
                            // DELETE PREVIOUS FILE FROM DIRECTORY
                            var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\ProfilePicture");

                            if (existingProfilePicture.FirstOrDefault() != null)
                            {
                                path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\ProfilePicture", existingProfilePicture.FirstOrDefault());
                                if (System.IO.File.Exists(path))
                                {
                                    System.IO.File.Delete(path);
                                }
                            }

                            // UPDATE FILE NAME
                            //var fileName = Path.GetFileNameWithoutExtension(file.FileName);
                            //var extension = Path.GetExtension(file.FileName);
                            //fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;

                            // CHECK THE SIZE OF IMAGE 1MB = 1000000 BYTES
                            if (file.Length > 1000000)
                            {
                                ViewBag.Message    = "Image size should not exceed 1 MB";
                                ViewBag.ProfileSrc = existingProfilePicture.FirstOrDefault();
                                return(View(userModel));
                            }
                            var fileName = Utility.GetProfilePictureFileName(file);
                            userModel.ProfilePicture = fileName;
                            path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\ProfilePicture", fileName);
                            using (var stream = new FileStream(path, FileMode.Create))
                            {
                                await file.CopyToAsync(stream);
                            }
                            // SEND FILENAME TO <IMG> TAG
                            ViewBag.ProfileSrc = fileName;
                        }
                        else
                        {
                            // IF PROFILE PICTURE NOT UPLOADED, KEEP THE EXISITING FILENAME
                            userModel.ProfilePicture = existingProfilePicture.FirstOrDefault();
                            ViewBag.ProfileSrc       = existingProfilePicture.FirstOrDefault();
                        }

                        // UPDATE SESSION INFO FOR ANY CHANGES
                        // AND UPDATE THE DATABASE
                        HttpContext.Session.SetString(SessionKeyUserID, userModel.ID.ToString());
                        HttpContext.Session.SetString(SessionKeyUserEmail, userModel.Email);

                        _context.Update(userModel);
                        await _context.SaveChangesAsync();

                        ViewBag.MessageCssClass = "alert-info col-md-4";
                        ViewBag.Message         = "Record updated.";

                        // SEND SESSION INFO TO CONTROL THE VIEW
                        ViewBag.UserID          = HttpContext.Session.GetString(SessionKeyUserEmail);
                        ViewBag.MessageCssClass = "";
                        return(View(userModel));
                    }
                }
            }
            catch (Exception e)
            {
                //ViewBag.Message = e.ToString();
                ViewBag.Message         = "Something went wrong.";
                ViewBag.MessageCssClass = "alert-danger col-md-4";
            }
            //return RedirectToAction(nameof(Index));
            return(View(userModel));
        }
        public async Task <IActionResult> Create([Bind("DataFoto,Local,CaoFK")] Fotografias fotografias, IFormFile fotoCao)

        /* processar o ficheiro
         * - existe ficheiro?
         *  - se não existe, o que fazer? => gerar uma mensagem de erro e devolver o controlo à View
         *  - se continua é porque o ficheiro existe
         *      - mas será que é do tipo correto?
         *          - avaliar se é imagem
         *              - se sim: - especificar o seu novo nome
         *                  - específicar a localização
         *                  - associar ao objeto 'foto' o nome deste ficheiro
         *                  - guardar ficheiro no disco rígido do servidor
         *              - se não => gerar uma mensagem de erro e devolver o controlo à View
         */



        {
            //var auxiliar
            string nomeImagem = "";

            if (fotoCao == null)
            {
                // não há ficheiro
                // adicionar msg de erro
                ModelState.AddModelError("", "Adicione, por favor, a fotografia do cão");
                ViewData["CaoFK"] = new SelectList(_context.Caes.OrderBy(c => c.Nome), "Id", "Nome");
                // devolver o controlo à View
                return(View(fotografias));
            }
            else
            {
                // há ficheiro. Mas será um ficheiro válido?
                if (fotoCao.ContentType == "image/jpeg" || fotoCao.ContentType == "image/png")
                {
                    //definir o novo nome da foto da fotografia
                    Guid g;
                    g          = Guid.NewGuid();
                    nomeImagem = fotografias.CaoFK + "_" + g.ToString(); // tambem poderia ser usado a formatação
                    // determinar a extensão do nome da imagem
                    string extensao = Path.GetExtension(fotoCao.FileName).ToLower();
                    // agora, consigo ter o nome final do ficheiro
                    nomeImagem = nomeImagem + extensao;

                    //associar este ficheiro aos dados da Fotografia do cão
                    fotografias.Fotografia = nomeImagem;

                    //localização do amazenamento da imagem
                    string localizacaoFicheiro = _caminho.WebRootPath;
                    nomeImagem = Path.Combine(localizacaoFicheiro, "fotos", nomeImagem);
                }
                else
                {
                    // ficheiro não é válido
                    // adicionar msg de erro
                    ModelState.AddModelError("", "Só pode escolher uma imagem para a associar ao cão");
                    ViewData["CaoFK"] = new SelectList(_context.Caes.OrderBy(c => c.Nome), "Id", "Nome");
                    // devolver o controlo à View
                    return(View(fotografias));
                }
            }

            if (ModelState.IsValid)
            {
                // Adicionar os dados da nova fotografia à base de dados
                _context.Add(fotografias);
                // Consolidar os dados na base de dados
                await _context.SaveChangesAsync();

                // Se cheguei aqui, tudo correu bem
                //Vou guardar, agora, no disco rígido do Servidor a imagem
                using var stream = new FileStream(nomeImagem, FileMode.Create);
                await fotoCao.CopyToAsync(stream);

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["CaoFK"] = new SelectList(_context.Caes, "Id", "Id", fotografias.CaoFK);
            return(View(fotografias));
        }
예제 #26
0
        public async Task <IActionResult> Import(IFormFile fileExcel)
        {
            if (ModelState.IsValid)
            {
                if (fileExcel != null)
                {
                    using var stream = new FileStream(fileExcel.FileName, FileMode.Create);
                    await fileExcel.CopyToAsync(stream);

                    using XLWorkbook workBook = new XLWorkbook(stream, XLEventTracking.Disabled);
                    List <List <string> > Errors = new List <List <string> >();
                    foreach (IXLWorksheet worksheet in workBook.Worksheets)
                    {
                        Price price;
                        var   g = (from pr in _context.Price
                                   where pr.Price1 == worksheet.Name
                                   select pr).ToList();
                        if (g.Count > 0)
                        {
                            price = g[0];
                        }
                        else
                        {
                            price = new Price
                            {
                                Price1 = worksheet.Name
                            };
                            _context.Price.Add(price);
                        }
                        await _context.SaveChangesAsync();

                        foreach (IXLRow row in worksheet.RowsUsed().Skip(1))
                        {
                            Router router = new Router();
                            string name   = row.Cell(1).Value.ToString();
                            if (name.Length > 50 || name.Length < 3)
                            {
                                continue;
                            }
                            var f = (from rou in _context.Router where rou.Name == name select rou).ToList();
                            if (f.Count() > 0)
                            {
                                router = f[0];
                                await _context.SaveChangesAsync();
                            }
                            else
                            {
                                router.Name  = row.Cell(1).Value.ToString();
                                router.Price = price;
                                string name1 = row.Cell(2).Value.ToString();
                                if (name1.Length > 50 || name1.Length < 3)
                                {
                                    continue;
                                }
                                Speed speed;
                                var   a = (from pr in _context.Speed
                                           where pr.Speed1 == row.Cell(2).Value.ToString()
                                           select pr).ToList();
                                if (a.Count() > 0)
                                {
                                    speed        = a[0];
                                    router.Speed = speed;
                                }
                                else
                                {
                                    speed = new Speed
                                    {
                                        Speed1 = row.Cell(2).Value.ToString()
                                    };
                                    _context.Add(speed);
                                    router.Speed = speed;
                                }
                                string name2 = row.Cell(3).Value.ToString();

                                if (name2.Length > 50 || name2.Length < 2)
                                {
                                    continue;
                                }
                                Diapason diapason;
                                var      b = (from pr in _context.Diapason
                                              where pr.Diapason1 == row.Cell(3).Value.ToString()
                                              select pr).ToList();
                                if (b.Count() > 0)
                                {
                                    diapason        = b[0];
                                    router.Diapason = diapason;
                                }
                                else
                                {
                                    diapason = new Diapason
                                    {
                                        Diapason1 = row.Cell(3).Value.ToString()
                                    };
                                    _context.Add(diapason);
                                    router.Diapason = diapason;
                                }
                                _context.Router.Add(router);
                                await _context.SaveChangesAsync();
                            }
                        }
                    }
                    await _context.SaveChangesAsync();
                }
            }
            return(RedirectToAction("Index", "Routers"));
        }
예제 #27
0
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }

            if (!ModelState.IsValid)
            {
                await LoadAsync(user);

                return(Page());
            }

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            if (Input.PhoneNumber != phoneNumber)
            {
                var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);

                if (!setPhoneResult.Succeeded)
                {
                    StatusMessage = "Unexpected error when trying to set phone number.";
                    return(RedirectToPage());
                }
            }

            var firstName      = user.FirstName;
            var lastName       = user.LastName;
            var details        = user.Details;
            var profilePicture = user.ProfilePicture;

            if (Input.FirstName != firstName)
            {
                user.FirstName = Input.FirstName;
                await _userManager.UpdateAsync(user);
            }
            if (Input.LastName != lastName)
            {
                user.LastName = Input.LastName;
                await _userManager.UpdateAsync(user);
            }
            if (Input.Details != details)
            {
                user.Details = Input.Details;
                await _userManager.UpdateAsync(user);
            }
            if (Input.ProfilePicture != profilePicture)
            {
                user.ProfilePicture = Input.ProfilePicture;
                await _userManager.UpdateAsync(user);
            }

            if (Request.Form.Files.Count > 0)
            {
                IFormFile file = Request.Form.Files.FirstOrDefault();
                using (var dataStream = new MemoryStream())
                {
                    await file.CopyToAsync(dataStream);

                    user.ProfilePicture = dataStream.ToArray();
                }
                await _userManager.UpdateAsync(user);
            }

            await _signInManager.RefreshSignInAsync(user);

            StatusMessage = "Your profile has been updated";
            return(RedirectToPage());
        }
예제 #28
0
        //[Authorize(Roles = "Administrator, Moderator")]
        public async Task <IActionResult> AddFile(IFormFile uploadedFile)
        {
            if (uploadedFile != null)
            {
                //-----------Проверяем, существует ли уже файл с таким именем----------
                //string[] dirs = Directory.GetFiles((Path.Combine(_appEnvironment.WebRootPath, "Uploaded")), "*.nc");
                //for (int i = 0; i < dirs.Length; i++)
                //{
                //    dirs[i] = Path.GetFileName(dirs[i]);
                //}
                //foreach (string nameFile in dirs)
                //{
                //    if (uploadedFile.FileName == nameFile)
                //    {
                //        ViewBag.Message = "A file with this name already exists!";
                //        return RedirectToAction("Index");
                //    }
                //}
                //---------------------------------------------------------------------------

                // путь к папке Uploaded
                //string path = "/Uploaded/" + uploadedFile.FileName;
                string path = Path.Combine(_appEnvironment.WebRootPath, "Uploaded", Path.GetFileName(uploadedFile.FileName.Replace(',', '.')));
                // сохраняем файл в папку Uploaded в каталоге wwwroot
                //using (var fileStream = new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create))
                using (var fileStream = new FileStream(path, FileMode.Create))
                {
                    await uploadedFile.CopyToAsync(fileStream);
                }
                if (Path.GetExtension(path) == ".nc")
                {
                    string folder   = Path.Combine(_appEnvironment.WebRootPath, "Uploaded");
                    string batfile  = Path.Combine(folder, "bat.bat");
                    string filename = Path.GetFileNameWithoutExtension(uploadedFile.FileName);
                    filename = filename.Replace(',', '.');

                    using (var sw = new StreamWriter(batfile))
                    {
                        sw.WriteLine("ncdump -f c " + filename + ".nc > " + filename + ".txt");
                    }

                    Process process = new Process();
                    try
                    {
                        process.StartInfo.UseShellExecute        = false;
                        process.StartInfo.RedirectStandardOutput = true;
                        process.StartInfo.RedirectStandardError  = true;


                        process.StartInfo.WorkingDirectory = folder;
                        process.StartInfo.FileName         = batfile;
                        process.Start();

                        string output = "",
                               error  = "";
                        while (!process.StandardOutput.EndOfStream)
                        {
                            output += process.StandardOutput.ReadLine();
                        }
                        while (!process.StandardError.EndOfStream)
                        {
                            error += process.StandardError.ReadLine();
                        }

                        process.WaitForExit();
                        System.IO.File.Delete(batfile);
                    }
                    catch (Exception exception)
                    {
                        throw new Exception(exception.ToString(), exception.InnerException);
                    }
                    //Получение необходимой информации из созданного файла *.txt
                    path = Path.Combine(_appEnvironment.WebRootPath, "Uploaded", filename + ".txt");

                    string         name, gase, unit, date;
                    List <decimal> value = new List <decimal>();
                    List <decimal> lon   = new List <decimal>();
                    List <decimal> lat   = new List <decimal>();
                    name = gase = unit = null;
                    DateTime dateTime = new DateTime();
                    int      indexOfSubstring;
                    string   subString;

                    using (StreamReader sr = new StreamReader(path, System.Text.Encoding.Default))
                    {
                        string line;
                        while ((line = sr.ReadLine()) != "data:")
                        {
                            if (name == null)
                            {
                                subString        = "long_name = \"";
                                indexOfSubstring = line.IndexOf(subString);
                                if (indexOfSubstring != -1)
                                {
                                    indexOfSubstring = indexOfSubstring + subString.Length;
                                    name             = line.Substring(indexOfSubstring);
                                    name             = name.Remove(name.IndexOf('"'));
                                }
                            }
                            if (gase == null)
                            {
                                subString        = "quantity_type = \"";
                                indexOfSubstring = line.IndexOf(subString);
                                if (indexOfSubstring != -1)
                                {
                                    indexOfSubstring = indexOfSubstring + subString.Length;
                                    gase             = line.Substring(indexOfSubstring);
                                    gase             = gase.Remove(gase.IndexOf('"'));
                                }
                            }
                            if (unit == null)
                            {
                                subString        = "units = \"";
                                indexOfSubstring = line.IndexOf(subString);
                                if (indexOfSubstring != -1)
                                {
                                    indexOfSubstring = indexOfSubstring + subString.Length;
                                    unit             = line.Substring(indexOfSubstring);
                                    unit             = unit.Remove(unit.IndexOf('"'));
                                }
                            }
                            if (dateTime == new DateTime())
                            {
                                subString        = "\"over ";
                                indexOfSubstring = line.IndexOf(subString);
                                if (indexOfSubstring != -1)
                                {
                                    indexOfSubstring = indexOfSubstring + subString.Length;
                                    date             = line.Substring(indexOfSubstring);
                                    date             = date.Remove(date.IndexOf(','));
                                    indexOfSubstring = date.IndexOf(' ');
                                    if (indexOfSubstring != -1)
                                    {
                                        date = date.Remove(date.IndexOf(' '));
                                    }
                                    int      dateYear, dateMonth = 0, dateDay;
                                    string[] months = { "Jan",  "Feb", "Mar",  "Apr", "May", "June",
                                                        "July", "Aug", "Sept", "Oct", "Nov", "Dec" };
                                    string[] words = date.Split(new char[] { '-' });
                                    dateYear = Convert.ToInt32(words[0]);
                                    for (int i = 0; i < months.Length; i++)
                                    {
                                        if (String.Compare(words[1], months[i]) == 0)
                                        {
                                            dateMonth = i + 1;
                                            break;
                                        }
                                    }
                                    if (dateMonth == 0)
                                    {
                                        dateMonth = Convert.ToInt32(words[1]);
                                    }
                                    if (words.Length == 2)
                                    {
                                        dateTime = new DateTime(dateYear, dateMonth, 01);
                                    }
                                    else
                                    {
                                        dateDay  = Convert.ToInt32(words[2]);
                                        dateTime = new DateTime(dateYear, dateMonth, dateDay);
                                    }
                                }
                            }
                        }
                        line = sr.ReadLine() + Environment.NewLine;
                        line = sr.ReadLine();
                        List <int> x = new List <int>();
                        List <int> y = new List <int>();
                        while ((line = sr.ReadLine().Trim(' ')) != "")
                        {
                            subString        = "_";
                            indexOfSubstring = line.IndexOf(subString);
                            if (indexOfSubstring > 10)
                            {
                                line             = line.Replace(" ", "").Replace("\t", "");
                                indexOfSubstring = line.IndexOf("(");
                                subString        = line.Remove(0, line.IndexOf("(") + 1);

                                x.Add(Convert.ToInt32(subString.Remove(subString.IndexOf(","), subString.Length - subString.IndexOf(","))));
                                y.Add(Convert.ToInt32(subString.Remove(subString.IndexOf(")"), subString.Length - subString.IndexOf(")")).Remove(0, subString.IndexOf(",") + 1)));

                                string val;
                                if (line.IndexOf(';') != -1)
                                {
                                    val = line.Remove(line.IndexOf(';'));
                                }
                                else
                                {
                                    val = line.Remove(line.IndexOf(','));
                                }

                                try
                                {
                                    value.Add(Decimal.Parse(val, CultureInfo.InvariantCulture));
                                }
                                catch
                                {
                                    value.Add(Decimal.Parse(val, NumberStyles.Any, CultureInfo.InvariantCulture));
                                }
                            }
                        }
                        while ((line = sr.ReadLine()) != null)
                        {
                            if (line.IndexOf("lat =") != -1 || line.IndexOf("lon =") != -1)
                            {
                                do
                                {
                                    string numb = null;
                                    if (line.IndexOf(",") != -1)
                                    {
                                        line = line.Remove(line.IndexOf(","), line.Length - line.IndexOf(","));
                                    }
                                    else
                                    {
                                        line = line.Remove(line.IndexOf(";"), line.Length - line.IndexOf(";"));
                                    }
                                    foreach (char s in line)
                                    {
                                        if (char.IsDigit(s) || (s == '.'))
                                        {
                                            numb = numb + s;
                                        }
                                    }
                                    lat.Add(Decimal.Parse(numb, CultureInfo.InvariantCulture));
                                } while ((line = sr.ReadLine().Trim(' ')) != "");
                                break;
                            }
                        }

                        while ((line = sr.ReadLine()) != null)
                        {
                            if (line.IndexOf("lon =") != -1 || line.IndexOf("lat =") != -1)
                            {
                                do
                                {
                                    string numb = null;
                                    if (line.IndexOf(",") != -1)
                                    {
                                        line = line.Remove(line.IndexOf(","), line.Length - line.IndexOf(","));
                                    }
                                    else
                                    {
                                        line = line.Remove(line.IndexOf(";"), line.Length - line.IndexOf(";"));
                                    }
                                    foreach (char s in line)
                                    {
                                        if (char.IsDigit(s) || char.IsPunctuation(s))
                                        {
                                            numb = numb + s;
                                        }
                                    }
                                    lon.Add(Decimal.Parse(numb, CultureInfo.InvariantCulture));
                                } while ((line = sr.ReadLine().Trim(' ')) != "");
                                break;
                            }
                        }
                        List <decimal> latValue = new List <decimal>();
                        List <decimal> lonValue = new List <decimal>();
                        for (int i = 0; i < x.Count; i++)
                        {
                            for (int j = 0; j < lat.Count; j++)
                            {
                                if (x[i] == j)
                                {
                                    latValue.Add(lat[j]);
                                }
                            }
                        }
                        for (int i = 0; i < y.Count; i++)
                        {
                            for (int j = 0; j < lon.Count; j++)
                            {
                                if (y[i] == j)
                                {
                                    lonValue.Add(lon[j]);
                                }
                            }
                        }

                        int idGase = _context.Gase.Where(d => d.Formula == gase).First().Id;
                        //idGase = idGase == null ? 0 : idGase;

                        for (int i = 0; i < value.Count; i++)
                        {
                            NetCDF(idGase, dateTime, name, unit, lonValue[i], latValue[i], value[i]);
                        }
                    }
                }
            }
            return(RedirectToAction("Index"));
        }
예제 #29
0
 public async Task SaveImage(IFormFile file)
 {
     await using var stream = System.IO.File.Create($"{ImageDirectory}/{file.Name}");
     await file.CopyToAsync(stream);
 }
        public async Task <IActionResult> Edit(int id, [Bind("Id,Title,Price,Rating,ReleaseDate,Platform,Description,Image,ManufacturerId")] Game game, int[] Genres, IFormFile Image)
        {
            if (id != game.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    //Update the data in the connection table between games and genres
                    if (Genres != null)
                    {
                        var gameGenres = _context.GameGenreConnection.Where(g => g.GameId == id).ToList();

                        var genersId = gameGenres.Select(g => g.GenreId).ToList();
                        foreach (var genreId in Genres)
                        {
                            if (!genersId.Contains(genreId))
                            {
                                var genre = _context.Genres.Find(genreId);

                                var gameGenre = new GameGenreConnection()
                                {
                                    Game  = game,
                                    Genre = genre
                                };

                                _context.GameGenreConnection.Update(gameGenre);
                            }
                        }
                    }

                    //Update the image of the selected game.
                    using (var stream = new MemoryStream())
                    {
                        await Image.CopyToAsync(stream);

                        game.Image = stream.ToArray();
                    }

                    _gameRepository.Update(game);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!GameExists(game.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ManufacturerId"] = new SelectList(_context.Manufacturers, "Id", "Name", game.ManufacturerId);
            return(View(game));
        }
예제 #31
0
        public async Task<string> UpdateLogoAsync(string clubName, IFormFile file)
        {
            string path = clubName;

            var relativePath = path;
            if (string.IsNullOrEmpty(path) || !path.Contains(LogoPath))
            {
                var newName = (string.IsNullOrWhiteSpace(path) ? GenerateNewName() : path) + "." + file.FileName.Split('.').Last();
                var newPath = GenerateNewPath(LogoPath);
                relativePath = Path.Combine(newPath, newName);
                path = GetFullPath(relativePath);
            }
            else
            {
                path = GetFullPath(path);
            }

            await file.CopyToAsync(new FileStream(path, FileMode.Create));
            relativePath = Regex.Replace(relativePath, "\\\\", "/");

         //   await _clubService.UpdateLogoAsync(clubName, relativePath);
            
            return relativePath;
        }
 /// <summary>
 /// Store the current file in the server, for later use
 /// </summary>
 /// <param name="file">the file that you want to store in the server</param>
 /// <param name="directoryPath">the directory path, that you want to store in it.</param>
 /// <returns>Task of storing the file in the server</returns>
 /// <example>
 /// await StoreFileToServerFolderAsync(file,"images/files");
 /// </example>
 public static async Task StoreFileToServerFolderAsync(this IFormFile file, string directoryPath)
 {
     Directory.CreateDirectory(directoryPath);
     await file?.CopyToAsync(new FileStream($"{directoryPath}/{file.FileName}", FileMode.Create));
 }
예제 #33
0
        public async Task <IActionResult> UploadLecturerFile(IFormFile file)
        {
            var uploadFolderPath = Path.Combine(host.ContentRootPath, "uploads/project");

            if (!Directory.Exists(uploadFolderPath))
            {
                Directory.CreateDirectory(uploadFolderPath);
            }

            if (file == null)
            {
                return(BadRequest("STOP HACKING OUR WEBSITE. SEND A FILE FOR US TO EXECUTE, PLEASE"));
            }

            if (file.Length == 0)
            {
                return(BadRequest("DO YOU THINK A EMPTY FILE CAN CRASH OUR WEBSITE"));
            }

            if (file.Length > MAX_BYTES)
            {
                return(BadRequest("PLEASE CHOOSE A FILE WHICH SIZE < 10 MB. OUR SYSTEM IS TOO BUSY TO DO EXECUTE THIS FILE"));
            }

            if (!ACCEPTED_FILE_TYPES.Any(s => s == Path.GetExtension(file.FileName.ToLower())))
            {
                return(BadRequest("ARE YOU HAPPY WHEN DO THAT. CHOOSE VALID TYPE, PLEASE"));
            }

            var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
            var filePath = Path.Combine(uploadFolderPath, fileName);

            //create excel
            using (var stream = new FileStream(filePath, FileMode.Create)) {
                await file.CopyToAsync(stream);
            }

            // add projects
            using (ExcelPackage package = new ExcelPackage(new FileInfo(filePath))) {
                ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                int            rowCount  = worksheet.Dimension.Rows;
                try {
                    for (int row = 3; row <= rowCount; row++)
                    {
                        var val = worksheet.Cells[row, 2].Value;
                        if (val == null)
                        {
                            break;
                        }
                        else
                        {
                            Project project = new Project();
                            await excelRepository.AddProject(project, worksheet, row);

                            projectRepository.AddProject(project);
                        }
                        await unitOfWork.Complete();
                    }
                } catch (Exception ex) {
                    return(BadRequest("CHECK YOUR FILE AGAIN, PLEASE. SOME WRONG WITH THIS FILE" +
                                      "\n" + "Detail: " + ex.Message));
                }
            }

            //add to db
            var excel = new Excel {
                FileName = fileName
            };

            excelRepository.AddExcel(excel);
            await unitOfWork.Complete();

            return(Ok(mapper.Map <Excel, ExcelResource> (excel)));
        }
        public async Task <IActionResult> UploadFile(int id, IFormFile file)
        {
            var size     = file?.Length;
            var sizeInMB = (size / 1024f) / 1024f;

            if (size <= 0 || sizeInMB > appSettings.MaxFileSizeInMB)
            {
                return(BadRequest("Niepoprawny format pliku"));
            }

            var fileExtension = MimeTypesMap.GetExtension(file.ContentType);

            var availableFileFormats = new List <string> {
                "docx", "pdf", "jpeg", "png"
            };

            if (!availableFileFormats.Any(a => a.Equals(fileExtension)))
            {
                return(BadRequest("Niepoprawny format pliku"));
            }

            var userId = GetUserId();

            var groupRecord = await context.Set <Group>().Include(a => a.Members).FirstOrDefaultAsync(a => a.Id == id);

            var userRecord = await context.Set <User>().FindAsync(userId);

            if (groupRecord == null || userRecord == null)
            {
                return(NotFound());
            }

            if (!groupRecord.Members.Any(a => a.UserId == userId))
            {
                return(BadRequest());
            }

            if (!Directory.Exists(appSettings.FilesPath))
            {
                Directory.CreateDirectory(appSettings.FilesPath);
            }

            var filePath = Path.Combine(appSettings.FilesPath, Path.GetRandomFileName());

            try
            {
                using var stream = System.IO.File.Create(filePath);

                await file.CopyToAsync(stream);

                var dbFile = new DBFile
                {
                    DateAdded = DateTime.UtcNow,
                    DrivePath = filePath,
                    Name      = file.FileName,
                    Owner     = userRecord,
                    Group     = groupRecord,
                    Size      = GetFileSizeAsString(size.Value),
                    FileType  = fileExtension.Equals(".pdf") || fileExtension.Equals(".docx") ? FileType.Document : FileType.Photo
                };

                context.Set <DBFile>().Add(dbFile);

                await context.SaveChangesAsync();

                return(Ok(new FileDto
                {
                    Id = dbFile.Id,
                    Owner = dbFile.Owner.Name,
                    DateAdded = dbFile.DateAdded,
                    FileName = dbFile.Name,
                    IsOwner = true
                }));
            }
            catch (ArgumentException ex)
            {
                Logger.Log($"{nameof(FilesController)} {nameof(UploadFile)}", ex.Message, NLog.LogLevel.Error, ex);

                return(BadRequest());
            }
            catch (DbUpdateException ex)
            {
                System.IO.File.Delete(filePath);

                Logger.Log($"{nameof(FilesController)} {nameof(UploadFile)}", ex.Message, NLog.LogLevel.Error, ex);

                return(BadRequest());
            }
            catch (Exception ex)
            {
                Logger.Log($"{nameof(FilesController)} {nameof(UploadFile)}", ex.Message, NLog.LogLevel.Error, ex);

                return(BadRequest());
            }
        }
예제 #35
0
        public async Task <IActionResult> SaveMapPhoto(IList <IFormFile> fileInput, IFormCollection formData)
        {
            StringBuilder error      = new StringBuilder();
            int           locationId = int.Parse(formData["locationId"]);
            int           level      = 0;
            DbSet <Map>   maps       = Database.Maps;

            try
            {
                if (locationId == 0)
                {
                    error.Append("location required, ");
                }
                if (formData["level"] == "")
                {
                    error.Append("level required ");
                }
                else
                {
                    level = int.Parse(formData["level"]);
                    if (maps.AsNoTracking().Where(m => m.Level == level && m.LocationId == locationId && m.MapId != int.Parse(formData["mapId"])).Count() > 0)
                    {
                        error.Append("the location already has a map for that level");
                    }
                }

                if (error.Length == 0)
                {
                    Map foundMap = maps.Single(b => b.MapId == int.Parse(formData["mapId"]));

                    if (fileInput.Count != 0)
                    {
                        // Deleting current image
                        Image image = Database.Images.Single(input => input.ImageId == foundMap.ImageId);
                        System.IO.File.Delete(Path.Combine(_hostingEnvironment.WebRootPath, image.ImageURL.Substring(1)));
                        Database.Remove(image);

                        // Adding new image
                        IFormFile oneFile     = fileInput[0];
                        Image     mapPhoto    = new Image();
                        string    contentType = oneFile.ContentType.Substring(6, 3);
                        string    fileId      = Guid.NewGuid().ToString().Replace("-", "");
                        string    path        = Path.Combine(_hostingEnvironment.WebRootPath, "images/uploads/", fileId + "." + contentType);
                        using (FileStream fileStream = new FileStream(path, FileMode.Create))
                            await oneFile.CopyToAsync(fileStream);
                        XDocument XD = XDocument.Load(path);
                        if (XD.Descendants("{http://www.w3.org/2000/svg}font") != null)
                        {
                            XD.Descendants("{http://www.w3.org/2000/svg}font").Remove();
                            using (FileStream fileStream = new FileStream(path, FileMode.Create))
                                XD.Save(fileStream);
                        }

                        mapPhoto.ImageURL = "/images/uploads/" + fileId + "." + contentType;
                        Database.Images.Add(mapPhoto);
                        foundMap.ImageId = mapPhoto.ImageId;
                        foundMap.XML     = XD.ToString();
                    }

                    foundMap.LocationId = int.Parse(formData["locationId"]);
                    foundMap.Level      = level;

                    Database.SaveChanges();
                }
                else
                {
                    throw new Exception();
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(new { error = error.ToString() }));
            }

            return(new OkObjectResult(new { message = "Saved map photo and data" }));
        }