quinta-feira, 23 de julho de 2015

Upload MVC

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Web.Helpers;
using Lapuinka.UploadExtratoMensal.ServiceUploadReference;
using System.Web.Configuration;
using Lapuinka.UploadExtratoMensal.Models;
using Lapuinka.Securities.Models;
using System.Collections;
using Telerik.Web.Mvc;
using Telerik.Web.Mvc.UI;

namespace Lapuinka.UploadExtratoMensal.Controllers
{
    [SessionState(System.Web.SessionState.SessionStateBehavior.Default)]
    public class UploadController : Controller
    {
        ServiceClient serviceClient = new ServiceClient("WSHttpBinding_IService");
        List listDocError = new List();
        List listFile = new List();
        public ActionResult Index()
        {
            return View();
           
        }
        public ActionResult Date()
        {
            return View("SetDate");
        }

        public ActionResult SetDate(DateTime data)
        {           
                Session["DATA"] = data;           
                return View("Index");
        }
       
        public DateTime GetReferenceData()
        {           
            if (Session["DATA"]!=null)
                return (DateTime)Session["DATA"];          
            else return DateTime.Today;
        }

        public List ListaStatusrelatorio
        {
            get { return (List)Session["DocError"]; }
            set { Session["DocError"] = value; }
        }

        public List ListaArquivorelatorio
        {
            get { return (List)Session["File"]; }
            set { Session["File"] = value; }
        }

        [GridAction]
        public ActionResult _SelectAjaxEditing()
        {
            return View(new GridModel(ListaStatusrelatorio));
        }    
      
        [GridAction]       
        public ActionResult _SaveAjaxEditing(string id)
        {
            List listDocConfig = new List();
            if (ListaStatusrelatorio != null)
            {
                listDocConfig = ListaStatusrelatorio;
                foreach (var client in listDocConfig)
                {
                    if (client.Name == id)
                    {
                        TryUpdateModel(client);
                    }
                }               
               
                ListaStatusrelatorio = listDocConfig;
            }
          
            return View(new GridModel(ListaStatusrelatorio));
        }

        [GridAction]
        public ActionResult _DeleteAjaxEditing(string id)
        {
            List listDocConfig = new List();
            if (ListaStatusrelatorio != null)
            {
                ResultUploadModel del = new ResultUploadModel();                               
                foreach (var client in ListaStatusrelatorio)
                {
                    if (client.Name == id)
                    {
                        del = client;
                    }
                }

                ListaStatusrelatorio.Remove(del);
            }
            return View(new GridModel(ListaStatusrelatorio));
        }

        public string Enviar(string x)
        {
            return x;
        }

        public ActionResult Save(IEnumerable attachments)
        {            
            foreach (var file in attachments)
            {               
                var fileName = Path.GetFileName(file.FileName);
                ConfigOperation(attachments);
            }           
            return Content("");
        }
       

        [GridAction]
        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public ActionResult GetListDocStatus(string x)
        {
            IEnumerable list= ListaStatusrelatorio;
            return PartialView("Grid", list);          
        }

        [GridAction]
        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public ActionResult ResultListDocStatus()
        {
            IEnumerable listResult = ListaStatusrelatorio;
            IEnumerable listArquivo = ListaArquivorelatorio;
            bool verdade = UploadDoc(listResult, listArquivo);

            return PartialView("resultUpload", ListaStatusrelatorio);
        }

        [GridAction]
        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public ActionResult _GetListDocStatus()
        {           
            return View(new GridModel
            {
                Data = ListaStatusrelatorio
            });
        }     
       
        private bool ConfigOperation(IEnumerable attachments)
        {
            if (attachments == null) return false;           
            var file = attachments.First();           
            var fileName = GetNameDoc(file);
            var result = Register(file, fileName);
         
            return true;
        }

        private bool Register(System.Web.HttpPostedFileBase file, string fileName)
        {

            List listDocConfig = new List();
            ResultUploadModel RegisterUploadMod = new ResultUploadModel();
            FilesRegister(fileName, file);
            RegisterUploadMod.Name = fileName;
            RegisterUploadMod.SaveDoc = true;
            RegisterUploadMod.SendEmail = true;
            Usuario usuario = new Usuario();
            Summary resultClient = serviceClient.getUsuarioTitularPorConta(out usuario, fileName);
            if (resultClient.EhErro == false)
            {
                RegisterUploadMod.Client = usuario.UsuarioPortal.Nome;
                RegisterUploadMod.Email = usuario.UsuarioPortal.Email;               
            }

            MemoryRegister(listDocConfig, RegisterUploadMod);
           
            return true;

        }

        public void FilesRegister(string fileName, System.Web.HttpPostedFileBase file)
        {
            ConfigUploadModel FileUploadMod = new ConfigUploadModel();           
            FileUploadMod.Arquivo = file;
            FileUploadMod.Name = fileName;
            MemoryFiliesRegister(FileUploadMod);
        }

        public void MemoryFiliesRegister(ConfigUploadModel UploadMod)
        {           
            if (ListaArquivorelatorio != null)
            {
                listFile = ListaArquivorelatorio;
                if (listFile.Count == 0)
                {
                    listFile.Add(UploadMod);
                    ListaArquivorelatorio = listFile;
                }
                else
                {                   
                     listFile.Add(UploadMod);
                     ListaArquivorelatorio = listFile;
                }
            }
            else
            {
                listFile.Add(UploadMod);
                ListaArquivorelatorio = listFile;
            }
        }

        private bool UploadDoc(IEnumerable ListResult, IEnumerable ListFile)
        {
            if (ListResult == null) return false;

            EmailRelatorioConfig emailobj = new EmailRelatorioConfig();
            emailobj.Config();
           
            foreach (var file in ListResult.ToList())
            {
                Documento documento = new Documento();              
                documento = SetDocument(GetFileByNmame(file.Name), documento, file.Name);               
                file.DataRef = GetReferenceData().ToShortDateString();
                file.TipoDoc = documento.TipoDocumento.Id;
                // Insere Documento (ExtratoMensal) na área restrita!!
                if (file.SaveDoc == true)
                {
                    Summary result = serviceClient.insereDocumentoExtratoMensal(documento);
                    OperationControl(listDocError, emailobj, file.Name, result, file, documento);
                }
                else
                {
                    StatusRegister(listDocError, file, "Não Foi Salvo");
                    StatusRegisterEmail(listDocError, file, "Não Enviado", file.Name, file.Email);
                }   
            }
            return true;
        }

        public System.Web.HttpPostedFileBase GetFileByNmame(string fileName)
        {
            System.Web.HttpPostedFileBase File = null;
            foreach (var file in ListaArquivorelatorio)
            {
                if (file.Name == fileName)
                {
                    File = file.Arquivo;              
                }
            }
            return File;
        }

        private void OperationControl(List listDocError, EmailRelatorioConfig emailobj, string fileName, Summary result, ResultUploadModel UploadMod, Documento documento)
        {
            bool var = false;

            if ((result.EhErro == false))
            {
                StatusRegister(listDocError, UploadMod, "SUCESSO");
                Usuario usuario = new Usuario();
                Summary resultClient = serviceClient.getUsuarioTitularPorConta(out usuario, documento.IdConta);
                if (resultClient.EhErro == false)
                {
                   //UploadMod.Client = usuario.UsuarioPortal.Nome;
                   //UploadMod.Email = usuario.UsuarioPortal.Email;
                   if (UploadMod.SendEmail == true)
                   {
                       //var = SedEmail(emailobj, fileName, UploadMod.Email, UploadMod.Client);
                       if ((var == true))
                       {
                           StatusRegisterEmail(listDocError, UploadMod, "Enviado", UploadMod.Name, UploadMod.Email);
                       }
                       else
                       {
                           StatusRegisterEmail(listDocError, UploadMod, "Não Enviado", UploadMod.Name, UploadMod.Email);
                       }
                   }
                   else
                   {
                       if (UploadMod.SendEmail == false)
                       {
                           StatusRegisterEmail(listDocError, UploadMod, "Não Enviado", UploadMod.Name, UploadMod.Email);
                       }
                   }
                }               
                               
            }
            else
            {
                StatusRegister(listDocError, UploadMod, "ERRO");
                StatusRegisterEmail(listDocError, UploadMod, "Não Enviado", UploadMod.Name, UploadMod.Email);
            }
        }       

        private static ResultUploadModel ModelDoc(Documento documento, ResultUploadModel UploadMod)
        {
            UploadMod.Name = documento.Nome;           
            return UploadMod;
        }

        private static ResultUploadModel GetModel()
        {
            ResultUploadModel UploadMod = new ResultUploadModel();
            return UploadMod;
        }
        private void MemoryRegister(List listDocError, ResultUploadModel UploadMod)
        {
           
            if (ListaStatusrelatorio != null)
            {
                listDocError = ListaStatusrelatorio;
                if (listDocError.Count == 0)
                {
                    listDocError.Add(UploadMod);
                    ListaStatusrelatorio = listDocError;
                }
                else
                {                 
                    listDocError.Add(UploadMod);
                    ListaStatusrelatorio = listDocError;                    
                }
            }
            else
            {              
                 listDocError.Add(UploadMod);
                 ListaStatusrelatorio = listDocError;            
            }
        }
        private void StatusRegister(List listDocError, ResultUploadModel UploadMod, string Status)
        {           
            if (ListaStatusrelatorio != null)
            {                
                foreach (var item in ListaStatusrelatorio.ToList())
                {
                    if (item.Name == UploadMod.Name)
                    {
                        item.Status = Status;
                    }
                }
            }
            else
            {
                listDocError.Add(UploadMod);
                ListaStatusrelatorio = listDocError;
            }                      
        }

        private void StatusRegisterEmail(List listDocError, ResultUploadModel UploadMod, string Status, string name, string Email)
        {
            UploadMod.EmailEnviado = Status;
            UploadMod.Email = Email;
            listDocError = ListaStatusrelatorio.ToList();
            foreach (var item in listDocError)
            {
                if(UploadMod.Name == name)
                    UploadMod.EmailEnviado = Status;
            }
            ListaStatusrelatorio = listDocError;
        }  

        private Documento SetDocument(System.Web.HttpPostedFileBase file, Documento documento, string fileName)
        {
            MemoryStream memoryStream = Tobyte(file);
            documento.Arquivo = memoryStream.ToArray();
            documento.TamanhoArquivo = memoryStream.Length;
            documento.ContentType = file.ContentType;
            documento.Nome = fileName;
            documento.DataReferencia = GetReferenceData();
            documento.IdConta = fileName;
            TipoDocumento tp = new TipoDocumento();
            tp.Id = 1;
            documento.TipoDocumento = tp;

            return documento;
        }

        private bool SedEmail(EmailRelatorioConfig emailobj, string fileName, string emailClient, string nameClient)
        {           
            try
            {
                WebMail.SmtpServer = emailobj.Smtp;
                WebMail.SmtpPort = emailobj.SmtpPort;
                WebMail.EnableSsl = emailobj.EnableSsl;
                WebMail.From = emailobj.EmailFrom;
                WebMail.UserName = emailobj.UserName;
                WebMail.Password = emailobj.Senha;
                WebMail.SmtpUseDefaultCredentials = true;

                WebMail.Send(to: "youremail@gmail.com",//emailClient,
                    subject: "TESTE",
                    body: "Olá " + nameClient + ", favor acessar sua área restrita no link abaixo:"
                    + "\n" + "www.arearestrita.com.br",
                     filesToAttach: null,
                    isBodyHtml: true
                    );
                return true;
            }
            catch (Exception ex)
            {              
                return false;
            }
        }

        private static MemoryStream Tobyte(System.Web.HttpPostedFileBase file)
        {
            using (Stream inputStream = file.InputStream)
            {
                MemoryStream memoryStream = inputStream as MemoryStream;
                if (memoryStream == null)
                {
                    memoryStream = new MemoryStream();
                    inputStream.CopyTo(memoryStream);
                }
                return memoryStream;
            }           
        }

        private static string GetNameDoc(HttpPostedFileBase file)
        {
            string[] nameclient = Path.GetFileName(file.FileName).Split('.');
            string NameClient = "";
            string tipoDoc = "";
            foreach(var client in nameclient)
            {
                if (client.StartsWith("APG"))
                    NameClient = client;
                else
                {
                    tipoDoc = client;
                }
            }

            return NameClient;
        }

        public ActionResult Remove(string[] fileNames)
        {
            // The parameter of the Remove action must be called "fileNames"
            foreach (var fullName in fileNames)
            {
                var fileName = Path.GetFileName(fullName);
                var physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);

                // TODO: Verify user permissions
                if (System.IO.File.Exists(physicalPath))
                {
                    // The files are not actually removed in this demo
                    // System.IO.File.Delete(physicalPath);
                }
            }
            // Return an empty string to signify success
            return Content("");
        }

    }
   

}
Postar um comentário