public ActionResult SendMessage(ContatoModel model)
        {
            if (String.IsNullOrWhiteSpace(model.Email))
            {
                return Json(new JsonRequestResult
                {
                    ResultType = JsonRequestResultType.Error,
                    Message = Resource.Msg_Geral_FormatoEmailInvalido
                }, JsonRequestBehavior.AllowGet);
            }
            String errorMessage;
            // Enviar email para o usuário em questão
            var result = Email.SendContact(model, out errorMessage);
            if (result)
            {
                return Json(new JsonRequestResult
                                {
                                    ResultType = JsonRequestResultType.Success,
                                    Message = Resource.Msg_EmailEnviadoSucesso,
                                    ReturnUrl = Url.Content("~/Contact/")
                                }, JsonRequestBehavior.AllowGet);
            }
            var jsResult = new JsonRequestResult
                               {
                                   ResultType = JsonRequestResultType.Error,
                                   Message = Resource.Msg_Geral_Erro
                               };

            return Json(jsResult, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// Checks if user is authenticated.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        private static void CheckIfUserIsAuthenticated(AuthorizationContext filterContext)
        {
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                FormsAuthenticationUtil.SignOut();
                if (IsAjaxRequest(filterContext))
                {
                    var jsonResult = new JsonRequestResult
                                         {
                                             ResultType = JsonRequestResultType.Error,
                                             Message = Constants._msgExpiredSession,
                                             Description = Constants._msgExpiredSession
                                         };
                    filterContext.Result = new JsonResult { Data = jsonResult };
                    return;
                }


                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                {
                    action = "LogIn",
                    controller = "Account",
                    area = "Admin"
                }));
                return;
            }

            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                return;
            }

            //if result is null, we're OK        
            if (filterContext.Result == null)
            {
                return;
            }

            var result = new RedirectToRouteResult(new RouteValueDictionary(new
            {
                action = "AcessoNegado",
                controller = "Home",
                area = "Admin"
            }));
            filterContext.Result = result;
        }
        /// <summary>
        /// Ajax the error.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        private void AjaxError(ExceptionContext filterContext)
        {
            if (filterContext.Exception != null)
            {
                var jsonResult = new JsonRequestResult { ResultType = JsonRequestResultType.Error };

                if (filterContext.GetType() == typeof(ExceptionContext))
                {
                    if (filterContext.Result != null && ((ViewResultBase)(filterContext.Result)).Model != null)
                    {
                        // Get InnerException
                        jsonResult.Message = CustomException.TranslateException(filterContext.Exception);
                        jsonResult.Description = String.Format("Detalhes: {0}", CustomException.GetInnerException(filterContext.Exception).Message);

                        //LogService.Log("BaseController.AjaxError()", filterContext.Exception);
                    }
                }
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.StatusCode = 500;
                filterContext.Result = Json(jsonResult);
            }
        }
 /// <summary>
 /// Invokes the action in the current controller context.
 /// </summary>
 protected override void ExecuteCore()
 {
     try
     {
         base.ExecuteCore();
     }
     catch (HttpRequestValidationException ex)
     {
         LogService.Log("BaseController.ExecuteCore() :: HttpRequestValidationException : ", ex);
         // Get InnerException
         this.ControllerContext.RequestContext.HttpContext.Response.StatusCode = 500;
         JsonResult = new JsonRequestResult
                          {
                              ResultType = JsonRequestResultType.Error,
                              Message = CustomException.TranslateException(ex),
                              Description =
                                  String.Format("Detalhes: {0}", CustomException.GetInnerException(ex).Message)
                          };
         //throw new Exception(ex.Message, ex);
     }
     catch (Exception ex)
     {
         LogService.Log("BaseController.ExecuteCore() :: Exception : ", ex);
         // Get InnerException
         this.ControllerContext.RequestContext.HttpContext.Response.StatusCode = 500;
         JsonResult = new JsonRequestResult
                          {
                              ResultType = JsonRequestResultType.Error,
                              Message = CustomException.TranslateException(ex),
                              Description =
                                  String.Format("Detalhes: {0}", CustomException.GetInnerException(ex).Message)
                          };
         //throw new Exception(ex.Message, ex);
     }
 }
        /// <summary>
        /// Processes HTTP requests that fail authorization.
        /// </summary>
        /// <param name="filterContext">Encapsulates the information for using <see cref="T:System.Web.Mvc.AuthorizeAttribute"/>. The <paramref name="filterContext"/> object contains the controller, HTTP context, request context, action result, and route data.</param>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (Roles != null)
            {
                // Se não estiver autenticado - Irá matar a sessão e será redirecionado para a tela de Login;
                if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
                {
                    FormsAuthenticationUtil.SignOut();
                    if (IsAjaxRequest(filterContext))
                    {
                        var jsonResult = new JsonRequestResult
                        {
                            ResultType = JsonRequestResultType.Error,
                            Message = Constants._msgExpiredSession,
                            Description = Constants._msgExpiredSession
                        };
                        filterContext.Result = new JsonResult { Data = jsonResult };
                        return;
                    }
                    filterContext.Result = Roles == "0" ? null : new RedirectToRouteResult(new RouteValueDictionary(new { action = "AccessDenied", controller = "Home", area = "Admin" }));
                    //base.HandleUnauthorizedRequest(filterContext);
                    return;
                }

                if (filterContext.HttpContext.User.Identity.IsAuthenticated) // Sessão ainda existe
                {
                    filterContext.Result = Roles == "0" ? null : new RedirectToRouteResult(new RouteValueDictionary(new { action = "AccessDenied", controller = "Home", area = "Admin" }));
                }
            }
        }
        public ActionResult EnviarBandeira(Int32 idIdioma, String tempFile)
        {
            var jsonResult = new JsonRequestResult();
            try
            {
                // Verifica os Diretorios
                VerifyDirectories(TipoArquivo.Imagem);

                // Verifica se foi postado alguma coisa
                if (Request.Files.Count > 0)
                {
                    foreach (String file in Request.Files)
                    {
                        var postedFile = Request.Files[file];
                        if (postedFile != null && postedFile.ContentLength > 0)
                        {
                            // Verifica a extensão
                            if (!HasExtension(TipoArquivo.Imagem, postedFile.FileName))
                            {
                                jsonResult.Message = String.Format(Constants._msgUnauthorizedExtension, Path.GetExtension(postedFile.FileName), Settings.ImgAllowedExtensions);
                                jsonResult.ResultType = JsonRequestResultType.Alert;
                            }

                            // Verifica o Tamanho do Arquivo
                            if (!VerifyFileSize(postedFile.ContentLength))
                            {
                                jsonResult.Message = String.Format(Constants._msgFileSizeExceeded, Settings.MaxFileSize);
                                jsonResult.ResultType = JsonRequestResultType.Alert;
                            }

                            // Arquivo temporário
                            tempFile = Path.GetFileName(String.Format("imgFlag{0}{1}", Path.GetFileNameWithoutExtension(postedFile.FileName), Path.GetExtension(postedFile.FileName)));
                            var completePathFromServer = Path.Combine(Server.MapPath(Settings.UrlGalleryFlags), tempFile);

                            // Verificar se existe arquivo com mesmo Nome e o elimina
                            if (System.IO.File.Exists(completePathFromServer))
                            {
                                System.IO.File.Delete(completePathFromServer);
                            }

                            // Salva o arquivo no Disco do Servidor
                            postedFile.SaveAs(completePathFromServer);

                            // Atualiza Objeto
                            if (idIdioma != 0)
                            {
                                var tempObj = new IdiomaService().GetRecords(i => i.IdIdioma == idIdioma).FirstOrDefault();
                                if (tempObj != null)
                                {
                                    tempObj.CaminhoImagem = tempFile;
                                    new IdiomaService().UpdateIdioma(tempObj);
                                }
                            }
                        }
                        else
                        {
                            jsonResult.Message = Constants._msgFileNotFound;
                            jsonResult.ResultType = JsonRequestResultType.Alert;
                        }
                    }
                }
                else
                {
                    jsonResult.Message = Constants._msgFileNotFound;
                    jsonResult.ResultType = JsonRequestResultType.Alert;
                }
            }
            catch (Exception ex)
            {
                LogService.Log("UploadController.EnviarBandeira()", ex);

                jsonResult.Message = Constants._msgError;
                jsonResult.Description = CustomException.GetInnerException(ex).Message;
                jsonResult.ResultType = JsonRequestResultType.Error;
            }
            // Serializará o JsonResult para ser exibido em um Alert do sistema
            var dict = new JavaScriptSerializer().Serialize(jsonResult);
            return RedirectToAction("EnviarBandeira",
                                    new RouteValueDictionary(
                                        new
                                        {
                                            controller = "Upload",
                                            action = "EnviarBandeira",
                                            id = idIdioma,
                                            errorMessage = dict,
                                            fileName = tempFile
                                        }));
        }
        public ActionResult EnviarArquivo(Int32 idArquivo, String tempFile)
        {
            var jsonResult = new JsonRequestResult();

            var tipoArquivo = Request.Form["tipoArquivo"];

            try
            {
                // Verifica os Diretorios
                VerifyDirectories(TipoArquivo.Documento);
                VerifyDirectories(TipoArquivo.Imagem);
                VerifyDirectories(TipoArquivo.Video);


                // Verifica se foi postado alguma coisa
                if (Request.Files.Count > 0)
                {
                    foreach (String file in Request.Files)
                    {
                        var postedFile = Request.Files[file];
                        if (postedFile != null && postedFile.ContentLength > 0)
                        {
                            if (tipoArquivo == "")
                            {
                                jsonResult.Message = String.Format("Selecione um tipo de arquivo!", "", "");
                                jsonResult.ResultType = JsonRequestResultType.Alert;
                                break;
                            }

                            //Verifica se o arquivo enviado é igual oa selecionado na combobox
                            if (!HasExtension(TipoArquivo.Documento, postedFile.FileName) && tipoArquivo == "1")
                            {
                                jsonResult.Message = String.Format("O arquivo enviado não é um Documento!", Path.GetExtension(postedFile.FileName), "");
                                jsonResult.ResultType = JsonRequestResultType.Alert;
                                break;
                            }
                            else if (!HasExtension(TipoArquivo.Imagem, postedFile.FileName) && tipoArquivo == "2")
                            {
                                jsonResult.Message = String.Format("O arquivo enviado não é uma Imagem!", Path.GetExtension(postedFile.FileName), "");
                                jsonResult.ResultType = JsonRequestResultType.Alert;
                                break;
                            }
                            else if (!HasExtension(TipoArquivo.Video, postedFile.FileName) && tipoArquivo == "3")
                            {
                                jsonResult.Message = String.Format("O arquivo enviado não é um Vídeo!", Path.GetExtension(postedFile.FileName), "");
                                jsonResult.ResultType = JsonRequestResultType.Alert;
                                break;
                            }


                            // Verifica a extensão
                            if ((!HasExtension(TipoArquivo.Imagem, postedFile.FileName)) && (!HasExtension(TipoArquivo.Documento, postedFile.FileName)) && (!HasExtension(TipoArquivo.Video, postedFile.FileName)))
                            {
                                if (tipoArquivo == "1")
                                {
                                    jsonResult.Message = String.Format(Constants._msgUnauthorizedExtension, Path.GetExtension(postedFile.FileName), Settings.DocAllowedExtensions);
                                    jsonResult.ResultType = JsonRequestResultType.Alert;
                                    break;
                                }
                                else if (tipoArquivo == "2")
                                {
                                    jsonResult.Message = String.Format(Constants._msgUnauthorizedExtension, Path.GetExtension(postedFile.FileName), Settings.ImgAllowedExtensions);
                                    jsonResult.ResultType = JsonRequestResultType.Alert;
                                    break;
                                }
                                else if (tipoArquivo == "3")
                                {
                                    jsonResult.Message = String.Format(Constants._msgUnauthorizedExtension, Path.GetExtension(postedFile.FileName), Settings.VidAllowedExtensions);
                                    jsonResult.ResultType = JsonRequestResultType.Alert;
                                    break;
                                }
                                else
                                {
                                    jsonResult.Message = String.Format("A extensão enviada não é permitida!", Path.GetExtension(postedFile.FileName), "");
                                    jsonResult.ResultType = JsonRequestResultType.Alert;
                                    break;
                                }

                            }

                            // Verifica o Tamanho do Arquivo
                            if (!VerifyFileSize(postedFile.ContentLength))
                            {
                                jsonResult.Message = String.Format(Constants._msgFileSizeExceeded, Settings.MaxFileSize);
                                jsonResult.ResultType = JsonRequestResultType.Alert;
                            }

                            // Arquivo temporário
                            tempFile = Path.GetFileName(String.Format("imgArq{0}{1}", Path.GetFileNameWithoutExtension(postedFile.FileName), Path.GetExtension(postedFile.FileName)));
                            var pathProductFromServer = "";
                            if (HasExtension(TipoArquivo.Imagem, postedFile.FileName))
                            {
                                pathProductFromServer = Path.Combine(Server.MapPath(Settings.UrlGalleryImages), tempFile);
                            }
                            else if (HasExtension(TipoArquivo.Documento, postedFile.FileName))
                            {
                                pathProductFromServer = Path.Combine(Server.MapPath(Settings.UrlGalleryDocs), tempFile);
                            }
                            else if (HasExtension(TipoArquivo.Video, postedFile.FileName))
                            {
                                pathProductFromServer = Path.Combine(Server.MapPath(Settings.UrlGalleryVideos), tempFile);
                            }


                            // Verificar se existe arquivo com mesmo Nome e o elimina
                            if (System.IO.File.Exists(pathProductFromServer))
                            {
                                System.IO.File.Delete(pathProductFromServer);
                            }

                            // Salva o arquivo no Disco do Servidor
                            postedFile.SaveAs(pathProductFromServer);

                            if (HasExtension(TipoArquivo.Imagem, postedFile.FileName))
                            {

                                var pathDetailFromServer = Path.Combine(Server.MapPath(Settings.UrlGalleryProductsDetails), tempFile);
                                var pathThumbFromServer = Path.Combine(Server.MapPath(Settings.UrlGalleryProductsThumbs), tempFile);

                                // Resize da Imagem Details
                                GeneralHelpers.ResizeImage(pathProductFromServer,
                                                           pathDetailFromServer,
                                                           Settings.ImgWidthProductDetail,
                                                           Settings.ImgHeightProductDetail, true);

                                // Resize da Imagem Thumbs
                                GeneralHelpers.ResizeImage(pathProductFromServer,
                                                           pathThumbFromServer,
                                                           Settings.ImgWidthProductThumb,
                                                           Settings.ImgHeightProductThumb, true);
                            }


                            // Atualiza Objeto
                            if (idArquivo != 0)
                            {
                                var service = new GaleriaService();
                                var tempObj = service.GetArchive(idArquivo);
                                tempObj.CaminhoArquivo = tempFile;
                                new GaleriaService().UpdateArquivo(tempObj);
                            }
                        }
                        else
                        {
                            jsonResult.Message = Constants._msgFileNotFound;
                            jsonResult.ResultType = JsonRequestResultType.Alert;
                        }
                    }
                }
                else
                {
                    jsonResult.Message = Constants._msgFileNotFound;
                    jsonResult.ResultType = JsonRequestResultType.Alert;
                }
            }
            catch (Exception ex)
            {
                LogService.Log("UploadController.EnviarArquivo()", ex);

                jsonResult.Message = Constants._msgError;
                jsonResult.Description = CustomException.GetInnerException(ex).Message;
                jsonResult.ResultType = JsonRequestResultType.Error;
            }


            // Serializará o JsonResult para ser exibido em um Alert do sistema
            var dict = new JavaScriptSerializer().Serialize(jsonResult);
            return RedirectToAction("EnviarArquivo",
                                    new RouteValueDictionary(
                                        new
                                        {
                                            controller = "Upload",
                                            action = "EnviarArquivo",
                                            id = idArquivo,
                                            errorMessage = dict,
                                            fileName = tempFile
                                        }));
        }
 /// <summary>
 /// Method for delete an existing Product
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public JsonResult Remover(Int32 id)
 {
     try
     {
         new ProdutoService().DeleteObject(id);
     }
     catch (Exception ex)
     {
         return Json(JsonResult = new JsonRequestResult
         {
             ResultType = JsonRequestResultType.Error,
             Message = CustomException.TranslateException(ex),
             Description = String.Format("Detalhes: {0}", CustomException.GetInnerException(ex).Message)
         }, JsonRequestBehavior.AllowGet);
     }
     return Json(new JsonRequestResult { ResultType = JsonRequestResultType.Success, Message = Constants._msgDeleteSuccess, ReturnUrl = Url.Content("~/Admin/Produto/") }, JsonRequestBehavior.AllowGet);
 }
        /// <summary>
        /// Invokes the action in the current controller context.
        /// </summary>
        protected override void ExecuteCore()
        {
            try
            {
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("pt-br");
                Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("pt-br");
                base.ExecuteCore();
            }
            catch (HttpRequestValidationException ex)
            {
                LogService.Log("AdminController.ExecuteCore() :: HttpRequestValidationException : ", ex);
                // Get InnerException
                this.ControllerContext.RequestContext.HttpContext.Response.StatusCode = 500;
                JsonResult = new JsonRequestResult
                {
                    ResultType = JsonRequestResultType.Error,
                    Message = CustomException.TranslateException(ex),
                    Description = String.Format("Detalhes: {0}", CustomException.GetInnerException(ex).Message)
                };
                throw new Exception(ex.Message, ex);
            }
            catch (HttpException ex)
            {
                LogService.Log("AdminController.ExecuteCore() :: Exception : ", ex);
                // Get InnerException
                this.ControllerContext.RequestContext.HttpContext.Response.StatusCode = 500;
                JsonResult = new JsonRequestResult
                {
                    ResultType = JsonRequestResultType.Error,
                    Message = CustomException.TranslateException(ex),
                    Description = String.Format("Detalhes: {0}", CustomException.GetInnerException(ex).Message)
                };

                throw new Exception(ex.Message, ex);
            }
        }