public virtual Foto UpoadDeFotoViaAplicativo(UploadFotoViewModel upl, string watermarkHorizontal, string watermarkVertical, string destination, int newSize) { var status = _sigMng.PasswordSignIn(upl.Login, upl.Senha, false, false); if (status != SignInStatus.Success) { throw new Exception("Usuário ou Senha inválidos"); } return(SavePhoto(upl, watermarkHorizontal, watermarkVertical, destination, newSize)); }
public virtual Foto SavePhoto(UploadFotoViewModel upl, string watermarkHorizontal, string watermarkVertical, string destination, int newSize) { if (upl.ArquivoAnexo != null && upl.ArquivoAnexo.ContentLength > 0) { if (string.IsNullOrWhiteSpace(upl.NomeArquivo)) { upl.NomeArquivo = upl.ArquivoAnexo.FileName; } var evento = _eventSvc.GetById(upl.EventoId); var user = _userMng.FindByName(upl.Login); Foto foto = new Foto { Evento = evento, Nome = upl.Nome, NomeArquivo = upl.NomeArquivo, Numero = upl.Numero, Vitrine = upl.Vitrine, CapaDeEvento = upl.CapaDeEvento, Fotografo = user, }; ArquivoFoto arquivo = new ArquivoFoto(); arquivo.Foto = foto; arquivo.Id = foto.Id; foto.ArquivoFoto = arquivo; using (MemoryStream mem = new MemoryStream()) { upl.ArquivoAnexo.InputStream.CopyTo(mem); mem.Seek(0, SeekOrigin.Begin); arquivo.Bytes = mem.ToArray(); mem.Seek(0, SeekOrigin.Begin); foto.Retrato = _resizer.IsPortrait(mem); GenerateThumbs(watermarkHorizontal, watermarkVertical, destination, newSize, foto, mem); this.Save(foto); } return(foto); } return(null); }
public ActionResult Index() { var uploadFotoViewModel = new UploadFotoViewModel { TiposPropaganda = _db.TiposPropaganda .Where(tp => tp.Enabled) .Select(tp => new TipoPropagandaViewModel { TipoPropagandaId = tp.TipoPropagandaId, Descricao = tp.Descricao }) .OrderBy(tp => tp.Descricao) .ToList() }; return(View(uploadFotoViewModel)); }
public virtual ActionResult Upload(UploadFotoViewModel fotoVm) { PopulaEventos(fotoVm.EventoId); if (ModelState.IsValid) { try { var currentUsername = !string.IsNullOrWhiteSpace(this.HttpContext?.User?.Identity?.Name) ? HttpContext.User.Identity.Name : "Anonymous"; fotoVm.Login = currentUsername; Foto foto = _appSvc.UpoadDeFoto( fotoVm, Server.MapPath("~/content/images/horizontal.png"), Server.MapPath("~/content/images/vertical.png"), Server.MapPath("~/content/images/thumbnails/"), 450 ); if (foto != null) { MensagemParaUsuarioViewModel.MensagemSucesso("Registro Salvo.", TempData); ModelState.Clear(); return(RedirectToAction("Detalhes", new { id = foto.Id })); } else { MensagemParaUsuarioViewModel.MensagemErro(" Não foi possível salvar a foto ", TempData, ModelState); } } catch (DbUpdateConcurrencyException duce) { MensagemParaUsuarioViewModel.MensagemErro(" Talvez esse registro tenha sido excluído por outra pessoa. " + duce.Message, TempData, ModelState); } catch (Exception err) { MensagemParaUsuarioViewModel.MensagemErro("Esse registro não pôde ser salvo. " + err.Message, TempData, ModelState); } } return(View(fotoVm)); }
public JsonResult UploadFoto(UploadFotoViewModel vm) { try { return(Json(new { Sucesso = true, Mensagem = "", IdFoto = 0 })); } catch (Exception err) { return(Json(new { Sucesso = false, Mensagem = err.Message, IdFoto = 0 })); } }
public async Task <ActionResult> Index(UploadFotoViewModel viewModel) { var validImageTypes = new[] { "image/jpeg", "image/pjpeg", "image/png" }; if (viewModel.ImageUpload == null || viewModel.ImageUpload.ContentLength == 0) { ModelState.AddModelError("ImageUpload", ValidationErrorMessage.OcorrenciaFotoNotNull); } else if (!validImageTypes.Contains(viewModel.ImageUpload.ContentType)) { ModelState.AddModelError("ImageUpload", ValidationErrorMessage.OcorrenciaFotoInvalidFormat); } viewModel.TiposPropaganda = _db.TiposPropaganda.Select(x => new TipoPropagandaViewModel { TipoPropagandaId = x.TipoPropagandaId, Descricao = x.Descricao }).ToList(); if (ModelState.IsValid) { var extension = Path.GetExtension(viewModel.ImageUpload.FileName); var filePath = ""; try { var geolocationInfo = new GeolocationInfoFileExtractor(viewModel.ImageUpload.InputStream); var path = Server.MapPath( $"{WebConfigurationManager.AppSettings["DiretorioFotosSantinhos"]}{User.Identity.Name}/"); Directory.CreateDirectory(path); filePath = $"{path}{Guid.NewGuid()}{extension}"; ViewBag.FilePath = filePath; viewModel.ImageUpload.SaveAs(filePath); var googleGeocoder = new GoogleGeocoder(WebConfigurationManager.AppSettings["GoogleMapsAPIKey"]); var enderecos = googleGeocoder.ReverseGeocode(geolocationInfo.Latitude, geolocationInfo.Longitude); var endereco = enderecos.Where( e => e.LocationType == GoogleLocationType.Rooftop || e.LocationType == GoogleLocationType.RangeInterpolated).Select(x => new Endereco { EnderecoFormatado = x.FormattedAddress, Latitude = x.Coordinates.Latitude, Longitude = x.Coordinates.Longitude, Estado = x[GoogleAddressType.AdministrativeAreaLevel1].ShortName, Cidade = x[GoogleAddressType.Locality].LongName, CEP = x[GoogleAddressType.PostalCode].LongName, Bairro = x[GoogleAddressType.SubLocality].LongName }).FirstOrDefault(); var imageText = await MicrosoftCognitiveServicesHelper.UploadAndRecognizeImage(filePath); // Busca o(s) candidato(s) da cidade onde a foto foi tirada var candidatos = _db.Candidatos.Include(c => c.Eleicao) .Where(c => c.DescricaoUnidadeEleitoral == endereco.Cidade && c.Eleicao.Enabled) .ToList(); var compareInfo = CultureInfo.InvariantCulture.CompareInfo; var match = false; foreach (var candidato in candidatos) { //var matchByNomeUrna = compareInfo.IndexOf(imageText, candidato.NomeUrna, CompareOptions.IgnoreNonSpace) > -1; //var matchByNumeroEleitoral = compareInfo.IndexOf(imageText, candidato.NumeroEleitoral.ToString(), CompareOptions.IgnoreNonSpace) > -1; //if (matchByNomeUrna && matchByNumeroEleitoral) // ocorrenciaTipoMatch = OcorrenciaTipoMatch.NomeUrnaENumeroEleitoral; //else if (matchByNomeUrna) // ocorrenciaTipoMatch = OcorrenciaTipoMatch.NomeUrna; //else if (matchByNumeroEleitoral) // ocorrenciaTipoMatch = OcorrenciaTipoMatch.NumeroEleitoral; var ocorrenciaTipoMatch = PesquisarCandidatoTexto(candidato.NomeUrna, candidato.NumeroEleitoral, imageText); if (ocorrenciaTipoMatch.HasValue) { match = true; viewModel.CandidatosEncontrados.Add(candidato.NomeUrna); _db.Ocorrencias.Add(new Ocorrencia { FotoPath = filePath, TipoPropagandaId = viewModel.TipoPropaganda, OcorrenciaTipoMatch = ocorrenciaTipoMatch, Endereco = endereco, CandidatoId = candidato.CandidatoId }); } } if (!match) { _db.Ocorrencias.Add(new Ocorrencia { FotoPath = filePath, TipoPropagandaId = viewModel.TipoPropaganda, Endereco = endereco }); } _db.SaveChanges(); ViewBag.FotoSalva = true; } catch (GoogleGeocodingException) { if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } ViewBag.ErrorMessage = ValidationErrorMessage.UploadFotoGoogleGeocodingException; return(View(viewModel)); } catch (Exception ex) { if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } ViewBag.ErrorMessage = ex.Message; return(View(viewModel)); } } viewModel.CandidatosEncontrados = viewModel.CandidatosEncontrados.OrderBy(c => c).ToList(); return(View(viewModel)); }
public virtual Foto UpoadDeFoto(UploadFotoViewModel upl, string watermarkHorizontal, string watermarkVertical, string destination, int newSize) { return(SavePhoto(upl, watermarkHorizontal, watermarkVertical, destination, newSize)); }