Ejemplo n.º 1
0
        public async Task <string> SaveImage(Stream imageStream)
        {
            var imageId = Guid.NewGuid().ToString();
            await _blobStorage.UploadAsync(imageId, imageStream);

            return(imageId);
        }
Ejemplo n.º 2
0
        public async Task Given_AString_WhenIsUploadInStorage_Then_Should_BeThere()
        {
            //Assert
            JObject testJObject = new JObject
            {
                { "Cpu", "Intel" },
                { "Memory", 32 },
                {
                    "Drives", new JArray
                    {
                        "DVD",
                        "SSD"
                    }
                }
            };

            using (var memoryStream = new MemoryStream())
            {
                using (var s = Convertors.GenerateStreamFromString(testJObject))
                {
                    await s.CopyToAsync(memoryStream);

                    await _sut.UploadAsync("nameTest", memoryStream);
                }
            }
            Assert.AreEqual(await _sut.ExistBlob("nameTest"), true);
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (FileUpload == null)
            {
                ModelState.AddModelError("File", "FileUpload is null");
            }
            if (FileUpload.File == null || FileUpload.File.Length == 0)
            {
                ModelState.AddModelError("File", "No file selected to upload");
            }

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

            var blobName = FileUpload.File.FileName;

            blobName = (FileUpload.Folder != null) ? string.Format(@"{0}\{1}", FileUpload.Folder, blobName) : blobName;
            var ms = new MemoryStream();

            ms.Position = 0;
            await FileUpload.File.CopyToAsync(ms);

            await BlobStorage.UploadAsync(containerName, blobName, ms);

            return(RedirectToPage(routeName));
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> UploadFile(FileInputModel inputModel)
        {
            if (inputModel == null)
            {
                return(Content("Argument null"));
            }

            if (inputModel.File == null || inputModel.File.Length == 0)
            {
                return(Content("file not selected"));
            }

            var blobName   = inputModel.File.GetFilename();
            var fileStream = await inputModel.File.GetFileStream();

            if (!string.IsNullOrEmpty(inputModel.Folder))
            {
                blobName = string.Format(@"{0}\{1}", inputModel.Folder, blobName);
            }

            await blobStorage.UploadAsync(blobName, fileStream);

            ViewBag.Message = "Estamos processando seus arquivos, por favor aguarde!";
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> UploadPhoto([FromForm] FileInputModel inputModel)
        {
            try
            {
                if (inputModel == null)
                {
                    return(BadRequest("Argument null"));
                }

                if (inputModel.File == null || inputModel.File.Length == 0)
                {
                    return(BadRequest("file not selected"));
                }

                var blobName   = Guid.NewGuid().ToString();
                var fileStream = await inputModel.File.GetFileStream();

                var isUploaded = await _blobStorage.UploadAsync("event", blobName, fileStream);

                if (isUploaded)
                {
                    return(Ok(blobName));
                }
                else
                {
                    return(BadRequest("photo not uploaded."));
                }
            }
            catch (Exception ex)
            {
                _logHelper.Log("EventsController", 500, "UploadPhoto", ex.Message);
                return(null);
            }
        }
Ejemplo n.º 6
0
        public async Task <string> UploadFile(Asset assset)
        {
            var blobName   = Guid.NewGuid().ToString() + Path.GetExtension(assset.Data.FileName);
            var fileStream = GetFileStream(assset.Data);

            await _blobStorage.UploadAsync(blobName, fileStream);

            return(blobName);
        }
Ejemplo n.º 7
0
        public async Task <ActionResult> Upload(IFormFile image, IAzureBlobStorage storage)
        {
            if (image != null)
            {
                string id = Guid.NewGuid().ToString();

                await storage.UploadAsync(id, image.FileName);

                return(RedirectToAction("Show", new { id = id }));
            }
            return(PartialView("_Image"));
        }
Ejemplo n.º 8
0
        public async Task <bool> UploadAsync(string blobName, MemoryStream fileStream)
        {
            try
            {
                await _iAzureBlobStorage.UploadAsync(blobName, fileStream);

                return(true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Error, ex.Message);
                throw;
            }
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> UploadPhoto([FromForm] FileInputModel inputModel)
        {
            try
            {
                if (inputModel == null)
                {
                    return(BadRequest("Argument null"));
                }

                if (inputModel.File == null || inputModel.File.Length == 0)
                {
                    return(BadRequest("file not selected"));
                }

                Guid userId     = User.GetUserId();
                var  blobName   = userId + "_" + inputModel.File.GetFilename();
                var  fileStream = await inputModel.File.GetFileStream();

                var isUploaded = await _blobStorage.UploadAsync("user", blobName, fileStream);

                if (isUploaded)
                {
                    var selectedUser = await _userRepo.GetUser(userId);

                    selectedUser.UpdateAt = DateTime.UtcNow;
                    selectedUser.Photo    = "https://evantstorage.blob.core.windows.net/users/" + blobName;

                    var response = await _userRepo.Update(selectedUser);

                    if (response)
                    {
                        return(Ok("photo uploaded."));
                    }
                    else
                    {
                        return(BadRequest("photo not uploaded."));
                    }
                }
                else
                {
                    return(Ok("photo uploaded."));
                }
            }
            catch (Exception ex)
            {
                _logHelper.Log("AccountController", 500, "UploadPhoto", ex.Message);
                return(null);
            }
        }
Ejemplo n.º 10
0
        public async Task Process(byte[] b, Document docData, string fileName)
        {
            try
            {
                using (MemoryStream stream = new MemoryStream(b))
                {
                    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(stream, true))
                    {
                        string docText = null;

                        using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
                        {
                            docText = sr.ReadToEnd();
                        }

                        foreach (var item in docData.GetData())
                        {
                            Regex regexText = new Regex(item.Key.ToUpper(), RegexOptions.CultureInvariant);
                            docText = regexText.Replace(docText, item.Value);
                        }

                        using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
                        {
                            sw.Write(docText);
                        }

                        wordDoc.Save();
                    }

                    await azureBlobStorage.UploadAsync(fileName, stream);

                    docData.Status = "Processado";
                    log.Info($"Documento criado!");
                    await documentService.Update(docData);

                    log.Info($"Documento atualizado no storage");
                }
            }
            catch (Exception ex)
            {
                docData.Status = "Erro ao processar";
                await documentService.Update(docData);

                log.Info($"Erro ao processar documento");
            }
        }
Ejemplo n.º 11
0
        public async Task <Uri> GetCroppedUri(Guid name, int withSize, int heightSize, Stream originalStream = null)
        {
            var nameInStorage = GetNameInStorage(name, Tipo.cropped, withSize, heightSize);

            if (originalStream == null)
            {
                if (_linkCache.Cache.ContainsKey(nameInStorage))
                {
                    return(_linkCache.Cache[nameInStorage]);
                }

                if (await _azureBlobStorage.ExistsAsync(nameInStorage))
                {
                    var uri = GetTrueUri(nameInStorage);
                    _linkCache.Cache.Add(nameInStorage, uri);
                    return(uri);
                }

                var originalNameInStorge = GetNameInStorage(name, Tipo.original, 0, 0);//obtem a uri da imagem  original para gerar a cropped

                if (!await _azureBlobStorage.ExistsAsync(originalNameInStorge))
                {
                    await _notifications.Handle(new DomainNotification("Id", "Imagem não localizada"), new System.Threading.CancellationToken());

                    return(GetErroUri());
                }

                originalStream = await _azureBlobStorage.GetStreamAsync(originalNameInStorge);
            }
            originalStream.Seek(0, SeekOrigin.Begin);
            using (Image <Rgba32> image = SixLabors.ImageSharp.Image.Load(originalStream))
            {
                //verifica se da pra fazer o crop
                if (withSize < image.Width && heightSize < image.Height)
                {
                    Image <Rgba32> result = image.Clone(ctx => ctx.Resize(
                                                            new ResizeOptions
                    {
                        Size = new Size(withSize, heightSize),
                        Mode = ResizeMode.Crop
                    }));
                    var resultStream = new MemoryStream();
                    result.SaveAsPng(resultStream);

                    await _azureBlobStorage.UploadAsync(nameInStorage, resultStream);

                    var uri = GetTrueUri(nameInStorage);
                    _linkCache.Cache.Add(nameInStorage, uri);
                    return(uri);
                }
                else // se não der pra fazer pega dimensões abaixo das solicitadas
                {
                    double fator = 1;
                    fator = withSize - image.Width > heightSize - image.Height ?   (double)image.Width / (double)withSize :  (double)image.Height / (double)heightSize;
                    var novoWidth = (int)Math.Floor(withSize * fator);

                    if (dimensoes.Where(q => q < novoWidth).Any())
                    {
                        novoWidth = dimensoes.Where(q => q < novoWidth).Max();
                    }
                    var novoHeight = (int)Math.Round(((double)novoWidth / (double)withSize) * heightSize); // para manter a proporção solicitada

                    if (novoWidth != image.Width && novoHeight != image.Height)
                    {
                        var novoUri = await GetCroppedUri(name, novoWidth, novoHeight);

                        _linkCache.Cache.Add(nameInStorage, novoUri);
                        return(novoUri);
                    }

                    //retorna o original se estiver menor q o solicitado e nas proporsoes solicitadas
                    var originalNameInStorge = GetNameInStorage(name, Tipo.original, 0, 0);//obtem a uri da imagem  original para gerar a cropped
                    var uri = GetTrueUri(originalNameInStorge);
                    _linkCache.Cache.Add(nameInStorage, uri);
                    return(uri);
                }
            }
        }
Ejemplo n.º 12
0
        public async Task <IActionResult> UploadPhoto(string jobId, IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return(BadRequest("Invalid file"));
            }

            var job = await jobRepository.GetItemAsync(jobId);

            if (job == null)
            {
                return(BadRequest("Can't find the job to attach the photo to"));
            }

            try
            {
                // Create Blob
                var photoId    = Guid.NewGuid().ToString();
                var fileEnding = file.FileName.Substring(file.FileName.LastIndexOf('.'));
                var blobName   = photoId + fileEnding;

                // Upload photo to blob
                var uri = await blobStorage.UploadAsync(string.Format($"{blobName}"), file.OpenReadStream());

                // Generate photo object
                var photo = new Photo
                {
                    Id        = photoId,
                    LargeUrl  = uri.ToString(),
                    MediumUrl = uri.ToString(),
                    IconUrl   = uri.ToString(),
                };

                // Add the photo to Job
                if (job.Photos == null)
                {
                    job.Photos = new List <Photo>();
                }

                job.Photos.Add(photo);
                var updatedJob = await jobRepository.UpdateItemAsync(jobId, job);

                try
                {
                    // Create a message on our queue for the Azure Function to process the image.
                    string json = JsonConvert.SerializeObject(new Models.PhotoProcess()
                    {
                        PhotoId = photoId, BlobName = blobName, JobId = jobId
                    }, Formatting.Indented);
                    await queue.AddMessage(json);
                }
                catch (ArgumentException)
                {
                    // Appears if Azure Storage Queue is not configured correctly which happens during the workshop,
                    // as Storage Queues appear at a later point.
                }

                // Return job object
                return(new ObjectResult(job));
            }
            catch
            {
                return(new ObjectResult(false));
            }
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> CreateForm([FromBody] FormModel formModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new ApiResponse {
                    Status = false, ModelState = ModelState
                }));
            }

            var options = new DbContextOptionsBuilder <ContentDbContext>()
                          .UseSqlServer(new SqlConnection(_configuration.GetConnectionString("ContentDbConnection")))
                          .Options;

            using (var context = new ContentDbContext(options))
            {
                using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        var generate            = new GenerateCandidate();
                        var candidateIncomplete = new Candidate
                        {
                            Email     = formModel.Email,
                            Approved  = formModel.Approved,
                            Completed = formModel.Completed
                        };

                        var candidate       = generate.Generate(formModel.BlobObject, candidateIncomplete);
                        var actualCandidate =
                            await context.Candidates.SingleOrDefaultAsync(x => x.Email.Equals(formModel.Email));

                        if (actualCandidate != null)
                        {
                            context.Candidates.Remove(actualCandidate);
                        }
                        await context.SaveChangesAsync();

                        context.Candidates.Add(candidate);
                        await context.SaveChangesAsync();

                        //Now Delete existing blob
                        if (await _storage.ExistBlob(formModel.Email))
                        {
                            await _storage.DeleteAsync(formModel.Email);
                        }

                        using (var memoryStream = new MemoryStream())
                        {
                            using (var s = Convertors.GenerateStreamFromString(formModel.BlobObject))
                            {
                                await s.CopyToAsync(memoryStream);

                                await _storage.UploadAsync(formModel.Email, memoryStream);
                            }
                        }
                        transaction.Commit();
                        return(CreatedAtRoute("GetFormsRoute", new { email = formModel.Email },
                                              new ApiResponse {
                            Status = true
                        }));
                    }
                    catch (Exception exp)
                    {
                        _logger.LogError(exp.Message);
                        return(BadRequest(new ApiResponse {
                            Status = false
                        }));
                    }
                }
            }
        }