public static ClientResponse Preview(int plantilla)
        {
            ClientResponse response;

            try
            {
                using (PlantillaDAO dbPlanilla = new PlantillaDAO())
                {
                    response = dbPlanilla.getPlantillaXId(plantilla);
                }
                Plantilla objetoplantilla = Newtonsoft.Json.JsonConvert.DeserializeObject <Plantilla>(response.DataJson);

                string body = string.Empty;
                using (StreamReader reader = new StreamReader(objetoplantilla.ruta_plantilla_html))
                {
                    body = reader.ReadToEnd();
                }
                response.ViewResult = body;
            }
            catch (Exception exception)
            {
                throw exception;
            }
            return(response);
        }
        public static ClientResponse AnularPlantilla(int plantilla)
        {
            ClientResponse response;

            try
            {
                using (PlantillaDAO dbPlanilla = new PlantillaDAO())
                {
                    //response = dbPlanilla.getPlantillaXId_Anulacion(plantilla);

                    //Plantilla desafiliacion = Newtonsoft.Json.JsonConvert.DeserializeObject<Plantilla>(response.DataJson);
                    ////Eliminamos las el html adjuntado
                    //Char delimiter = '\\';
                    //string[] arrayruta_plantilla = desafiliacion.ruta_plantilla_html.Split(delimiter);
                    //List<string> listStr = arrayruta_plantilla.ToList();
                    //int index = 0;
                    //string ruta = string.Empty;

                    //if (listStr.Count() > 0) {
                    //    index = listStr.Count() - 1;
                    //    listStr.RemoveAt(index);
                    //    ruta = string.Empty;
                    //    listStr.ForEach(delegate (string cadena)
                    //    {
                    //        ruta += cadena + "\\";

                    //    });
                    //    Directory.Delete(ruta, true);
                    //}

                    ////Eliminamos las imagenes adjuntadas
                    //arrayruta_plantilla = desafiliacion.list_plantilla_detalle[0].ruta_imagen.Split(delimiter);
                    //listStr = arrayruta_plantilla.ToList();
                    //if (listStr.Count() > 0) {
                    //    index = listStr.Count() - 1;
                    //    listStr.RemoveAt(index);
                    //    ruta = string.Empty;
                    //    listStr.ForEach(delegate (string cadena)
                    //    {
                    //        ruta += cadena + "\\";

                    //    });
                    //    Directory.Delete(ruta, true);
                    //}
                    response = dbPlanilla.AnularPlantilla(plantilla);
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
            return(response);
        }
        public static ClientResponse getPlanilla()
        {
            ClientResponse response;

            try
            {
                using (PlantillaDAO dbPlanilla = new PlantillaDAO())
                {
                    response = dbPlanilla.getPlantilla();
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
            return(response);
        }
        public static ClientResponse listarImagenBD(int id_plantilla)
        {
            ClientResponse response = new ClientResponse();

            try
            {
                using (PlantillaDAO dbPlanilla = new PlantillaDAO())
                {
                    List <Plantilla_Detalle> list = dbPlanilla.getPlantillaDetalle(id_plantilla);
                    response.Id       = id_plantilla;
                    response.DataJson = JsonConvert.SerializeObject(list).ToString();
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
            return(response);
        }
        public static ClientResponse EliminarImagenBD(int id_plantilla, int id_det_plantilla)
        {
            ClientResponse response;

            try
            {
                using (PlantillaDAO dbPlanilla = new PlantillaDAO())
                {
                    Plantilla_Detalle oCheque = dbPlanilla.getPlantillaDetalle(id_plantilla).Where(p => p.id == id_det_plantilla).FirstOrDefault();
                    FileInfo          fi      = new FileInfo(oCheque.ruta_imagen);
                    fi.Delete();
                    response = dbPlanilla.EliminarImgen_DetallePlantilla(id_plantilla, id_det_plantilla);
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
            return(response);
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Expires     = -1;
            //string ruta_hota_name = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
            try

            {
                string hora             = DateTime.Now.ToString("yyyyMMddhhmmss");
                string tempPath         = "";
                string txt_descripcion  = context.Request["txt_descripcion"];
                int    txt_codigo       = Convert.ToInt32(context.Request["txt_codigo"]);
                string FiledataHTMLName = context.Request["FiledataHTMLName"];

                HttpFileCollection uploadFiles = context.Request.Files;

                plantilla.id          = txt_codigo;
                plantilla.descripcion = txt_descripcion;

                //string FolderPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"];

                ClientResponse responserutahtml;
                using (ParametrosMaestrosDAO dbParametrosMaestro = new ParametrosMaestrosDAO())
                {
                    responserutahtml = dbParametrosMaestro.getObjParametroMaestro("RUTA_CARGAHTMLPLANTILLACORREOS");
                }
                ParametrosMaestros rutahtml = Newtonsoft.Json.JsonConvert.DeserializeObject <ParametrosMaestros>(responserutahtml.DataJson);


                ClientResponse responserutaimage;
                using (ParametrosMaestrosDAO dbParametrosMaestro = new ParametrosMaestrosDAO())
                {
                    responserutaimage = dbParametrosMaestro.getObjParametroMaestro("RUTA_CARGAIMAGENPLANTILLACORREOS");
                }
                ParametrosMaestros rutaimage = Newtonsoft.Json.JsonConvert.DeserializeObject <ParametrosMaestros>(responserutaimage.DataJson);

                ClientResponse responserutasiteimage;
                using (ParametrosMaestrosDAO dbParametrosMaestro = new ParametrosMaestrosDAO())
                {
                    responserutasiteimage = dbParametrosMaestro.getObjParametroMaestro("RUTA_SITE_CARGAIMAGENPLANTILLACORREOS");
                }
                ParametrosMaestros rutasiteimage = Newtonsoft.Json.JsonConvert.DeserializeObject <ParametrosMaestros>(responserutasiteimage.DataJson);



                for (int i = 0; i < uploadFiles.Count; i++)
                {
                    HttpPostedFile postedFile = uploadFiles[i];
                    if (postedFile.FileName.Equals(FiledataHTMLName))
                    {
                        tempPath = rutahtml.valor + hora;
                        string savepath = "";
                        // savepath = context.Server.MapPath(tempPath);
                        savepath = tempPath;// context.Server.MapPath(tempPath);
                        if (!Directory.Exists(savepath))
                        {
                            Directory.CreateDirectory(savepath);
                        }

                        string filename = postedFile.FileName;
                        string files    = savepath + @"/" + filename;
                        postedFile.SaveAs(files);
                        plantilla.NombreArchivoHtml   = filename;
                        plantilla.id_estado           = 1;
                        plantilla.ruta_plantilla_html = files;
                    }
                    else
                    {
                        plantilla_detalle = new Plantilla_Detalle();
                        tempPath          = rutaimage.valor + hora;
                        string savepath = "";
                        //savepath = context.Server.MapPath(tempPath);
                        savepath = tempPath;// context.Server.MapPath(tempPath);
                        if (!Directory.Exists(savepath))
                        {
                            Directory.CreateDirectory(savepath);
                        }

                        string filename = postedFile.FileName;
                        string files    = savepath + @"/" + filename;
                        postedFile.SaveAs(files);
                        plantilla_detalle.NombreArchivoImagen = filename;
                        plantilla_detalle.ruta_imagen         = files;
                        plantilla_detalle.id_estado           = 1;
                        // plantilla_detalle.ruta_site_imagen = ruta_hota_name + "/" + FolderPath + rutaimage.valor + hora + "/" + filename;
                        plantilla_detalle.ruta_site_imagen = rutasiteimage.valor + hora + "/" + filename;
                        list_plantilla_detalle.Add(plantilla_detalle);
                    }
                }

                plantilla.list_plantilla_detalle = list_plantilla_detalle;

                //Replace SRC  plantilla html
                HtmlDocument document = new HtmlDocument();
                if (plantilla.ruta_plantilla_html != null)
                {
                    document.Load(plantilla.ruta_plantilla_html);
                    document.DocumentNode.Descendants("img")
                    .Where(e =>
                    {
                        string src = e.GetAttributeValue("src", null) ?? "";
                        return(!string.IsNullOrEmpty(src));           // && src.StartsWith("data:image");
                    })
                    .ToList()
                    .ForEach(x =>
                    {
                        string currentSrcValue   = string.Empty;
                        currentSrcValue          = x.GetAttributeValue("src", null);
                        Plantilla_Detalle objeto = plantilla.list_plantilla_detalle.Where(i => i.NombreArchivoImagen.ToUpper().Equals(currentSrcValue.ToUpper())).FirstOrDefault();
                        if (objeto != null)
                        {
                            x.SetAttributeValue("src", objeto.ruta_site_imagen);
                        }
                    });
                    document.Save(plantilla.ruta_plantilla_html);

                    document.DocumentNode.Descendants("a")
                    .Where(e =>
                    {
                        string src = e.GetAttributeValue("href", null) ?? "";
                        return(!string.IsNullOrEmpty(src));           // && src.StartsWith("data:image");
                    })
                    .ToList()
                    .ForEach(x =>
                    {
                        string currentSrcValue = string.Empty;
                        currentSrcValue        = x.GetAttributeValue("href", null);

                        if (currentSrcValue != "{linkdardebaja}" && !currentSrcValue.Contains("http"))
                        {
                            Plantilla_Detalle objeto = plantilla.list_plantilla_detalle.Where(i => i.NombreArchivoImagen.ToUpper().Equals(currentSrcValue.ToUpper())).FirstOrDefault();
                            if (objeto != null)
                            {
                                x.SetAttributeValue("href", objeto.ruta_site_imagen);
                            }
                        }
                    });
                    document.Save(plantilla.ruta_plantilla_html);

                    HtmlDocument document1 = new HtmlDocument();
                    document1.Load(plantilla.ruta_plantilla_html);
                    plantilla.fl_parrafo = 0;
                    try
                    {
                        //List<HtmlNode> list = document1.DocumentNode.SelectNodes("p").ToList();
                        //plantilla.fl_parrafo = list.Count > 0 ? 1 : 0;
                        document.DocumentNode.Descendants("p")
                        .Where(e =>
                        {
                            string src = e.GetAttributeValue("type", null) ?? "";
                            return(!string.IsNullOrEmpty(src));
                        })
                        .ToList()
                        .ForEach(x =>
                        {
                            string currentSrcValue = string.Empty;
                            currentSrcValue        = x.GetAttributeValue("type", null);

                            if (currentSrcValue == "por ingresar")
                            {
                                plantilla.fl_parrafo = 1;
                            }
                        });
                    }
                    catch (Exception)
                    {
                        plantilla.fl_parrafo = 0;
                    }
                }


                ClientResponse response;

                using (PlantillaDAO dbPlanilla = new PlantillaDAO())
                {
                    if (txt_codigo == 0)
                    {
                        response = dbPlanilla.InsertPantilla(plantilla);
                    }
                    else
                    {
                        if (plantilla.ruta_plantilla_html != null) //si adjunto html se elminar el existente
                        {
                            ClientResponse responseplantilla = dbPlanilla.getPlantillaXId(plantilla.id);
                            Plantilla      objetoplantilla   = Newtonsoft.Json.JsonConvert.DeserializeObject <Plantilla>(responseplantilla.DataJson);
                            FileInfo       fi = new FileInfo(objetoplantilla.ruta_plantilla_html);
                            fi.Delete();
                        }
                        response = dbPlanilla.UpdatePantilla(plantilla);
                    }
                }
                var result = new
                {
                    Result  = response.Status,
                    Mensaje = response.Mensaje
                };
                context.Response.Write(JsonConvert.SerializeObject(result));
            }

            catch (Exception ex)

            {
                var result = new
                {
                    Result  = "Error",
                    Mensaje = ex.Message
                };
                context.Response.Write(JsonConvert.SerializeObject(result));
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Expires     = -1;
            try

            {
                string hora          = DateTime.Now.ToString("yyyyMMddhhmmss");
                string tempPath      = "";
                string savepath      = "";
                int    cbo_origen    = 0;
                int    cbo_plantilla = 0;
                int.TryParse(context.Request["cbo_origen"], out cbo_origen);
                int.TryParse(context.Request["cbo_plantilla"], out cbo_plantilla);
                string             txt_prompt      = context.Request["txt_prompt"];
                string             txt_asunto      = context.Request["txt_asunto"];
                string             id_grupo_correo = context.Request.Form.Get("list");
                string             usuarioSession  = context.Request.Form.Get("txt_UserSession");
                HttpFileCollection uploadFiles     = context.Request.Files;
                List <string>      listrutas       = new List <string>();
                List <LogPromoDet> lstLogPromoDet  = new List <LogPromoDet>();

                ClientResponse responseruta;
                using (ParametrosMaestrosDAO dbParametrosMaestro = new ParametrosMaestrosDAO())
                {
                    responseruta = dbParametrosMaestro.getObjParametroMaestro("RUTA_ADJUNTO_ENVIO_CORREOS");
                }
                ParametrosMaestros rutaadjunto = Newtonsoft.Json.JsonConvert.DeserializeObject <ParametrosMaestros>(responseruta.DataJson);



                for (int i = 0; i < uploadFiles.Count; i++)
                {
                    HttpPostedFile postedFile = uploadFiles[i];
                    //tempPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"] + rutaadjunto.valor + hora;
                    tempPath = rutaadjunto.valor + hora;

                    savepath = tempPath;
                    if (!Directory.Exists(savepath))
                    {
                        Directory.CreateDirectory(savepath);
                    }

                    string filename = postedFile.FileName;
                    string files    = savepath + @"\" + filename;
                    postedFile.SaveAs(files);
                    listrutas.Add(files);
                }

                ClientResponse response;
                string         usuario = cUtil.ObtenerValorParametro("CORREOPROMO", "USER");
                string         clave   = cUtil.ObtenerValorParametro("CORREOPROMO", "CLAVE");
                string         smtp    = cUtil.ObtenerValorParametro("CORREOPROMO", "SMTP");
                int            puerto  = Convert.ToInt32(cUtil.ObtenerValorParametro("CORREOPROMO", "PUERTO"));

                ClientResponse responsedesafiliacion;
                using (ParametrosMaestrosDAO dbParametrosMaestro = new ParametrosMaestrosDAO())
                {
                    responsedesafiliacion = dbParametrosMaestro.getObjParametroMaestro("DESAFILACIONPROMOCIONES");
                }
                ParametrosMaestros desafiliacion = Newtonsoft.Json.JsonConvert.DeserializeObject <ParametrosMaestros>(responsedesafiliacion.DataJson);



                ClientResponse responseplantilla;
                using (PlantillaDAO dbPlanilla = new PlantillaDAO())
                {
                    responseplantilla = dbPlanilla.getPlantillaXId(cbo_plantilla);
                }
                Plantilla objetoplantilla = Newtonsoft.Json.JsonConvert.DeserializeObject <Plantilla>(responseplantilla.DataJson);

                string body = string.Empty;
                using (StreamReader reader = new StreamReader(objetoplantilla.ruta_plantilla_html))
                {
                    body = reader.ReadToEnd();
                }
                body = "<div style='padding: 0px 2px; '>" + body + "</div>";
                using (GestionCorreoDAO dbGestionCorreoDAO = new GestionCorreoDAO())
                {
                    response = dbGestionCorreoDAO.getLstGestionCorreoXGrupo(id_grupo_correo);
                }
                List <GestionCorreo> liscorreos = Newtonsoft.Json.JsonConvert.DeserializeObject <List <GestionCorreo> >(response.DataJson);
                string bodyaux = string.Empty;

                LogPromo oLogPromo = new LogPromo();
                oLogPromo.remitente   = usuarioSession;
                oLogPromo.asunto      = txt_asunto;
                oLogPromo.PlantillaID = objetoplantilla.id;

                foreach (GestionCorreo item in liscorreos)
                {
                    bodyaux = body;
                    if (objetoplantilla.fl_parrafo == 1)
                    {
                        bodyaux = bodyaux.Replace("{parrafo}", txt_prompt);
                    }
                    bodyaux = bodyaux.Replace("{NombreUsuario}", item.Nombre1 + " " + item.Nombre2);
                    bodyaux = bodyaux.Replace("{Codigo}", item.codigo.Trim());
                    bodyaux = bodyaux.Replace("{linkdardebaja}", desafiliacion.valor + "?tokens=" + item.Tokens);
                    bodyaux = HttpUtility.HtmlDecode(bodyaux);
                    cUtil.EnvioMailSegundo(txt_asunto, item.Email, bodyaux, listrutas, usuario, clave, smtp, puerto);

                    LogPromoDet oLogPromoDet = new LogPromoDet();
                    oLogPromoDet.id_grupo_correo = item.grupocorreo.id;// Convert.ToInt32(id_grupo_correo);
                    oLogPromoDet.destinatario    = item.Email.ToString();
                    lstLogPromoDet.Add(oLogPromoDet);
                }
                oLogPromo.LogPromoDet = lstLogPromoDet;

                ClientResponse responseLogPromo;
                using (LogPromoDAO dbLogPromo = new LogPromoDAO())
                {
                    responseLogPromo = dbLogPromo.InsertLogPromo(oLogPromo);
                }

                //Directory.Delete(savepath, true);

                //plantilla.list_plantilla_detalle = list_plantilla_detalle;
                //ClientResponse response;
                //using (PlantillaDAO dbPlanilla = new PlantillaDAO())
                //{
                //    response = dbPlanilla.InsertPantilla(plantilla);
                //}

                //if ((System.IO.File.Exists(files)))
                //{
                //    System.IO.File.Delete(files);
                //}

                var result = new
                {
                    Result  = "Ok",
                    Mensaje = "Se envio correo"
                };
                context.Response.Write(JsonConvert.SerializeObject(result));
            }

            catch (Exception ex)

            {
                var result = new
                {
                    Result  = "Error",
                    Mensaje = ex.Message
                };
                context.Response.Write(JsonConvert.SerializeObject(result));
            }
        }