public ClientResponse InsertLogPromo(LogPromo objeto)
        {
            try
            {
                XElement root = new XElement("ROOT");
                foreach (LogPromoDet detalle in objeto.LogPromoDet)
                {
                    XElement element = new XElement("Detalle",
                                                    new XElement("id_grupo_correo", detalle.id_grupo_correo),
                                                    new XElement("destinatario", detalle.destinatario)
                                                    );
                    root.Add(element);
                }
                string xml = root.ToString();

                using (conexion = new SqlConnection(ConexionDAO.cnx))
                {
                    using (comando = new SqlCommand("usp_ins_LogPromo", conexion))
                    {
                        comando.Parameters.AddWithValue("@xml", xml);
                        comando.Parameters.AddWithValue("@remitente", objeto.remitente);
                        comando.Parameters.AddWithValue("@asunto", objeto.asunto);
                        comando.Parameters.AddWithValue("@plantillaID", objeto.PlantillaID);
                        comando.Parameters.Add("@Ind", SqlDbType.Int).Direction = ParameterDirection.Output;
                        comando.Parameters.Add("@Mensaje", SqlDbType.VarChar, 200).Direction = ParameterDirection.Output;
                        comando.CommandType = CommandType.StoredProcedure;
                        conexion.Open();
                        comando.ExecuteNonQuery();
                        int    ind     = Convert.ToInt32(comando.Parameters["@Ind"].Value);
                        string mensaje = Convert.ToString(comando.Parameters["@Mensaje"].Value);

                        if (ind > 0)
                        {
                            clientResponse.Mensaje = mensaje;
                            clientResponse.Status  = "Ok";
                        }
                        else
                        {
                            clientResponse.Mensaje = mensaje;
                            clientResponse.Status  = "ERROR";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                clientResponse.Mensaje = ex.Message;
                clientResponse.Status  = "ERROR";
            }
            finally {
                conexion.Close();
                conexion.Dispose();
                comando.Dispose();
            }
            return(clientResponse);
        }
        public ClientResponse getLstRemitente()
        {
            try
            {
                using (conexion = new SqlConnection(ConexionDAO.cnx))
                {
                    using (comando = new SqlCommand("usp_lst_remitente_promo", conexion))
                    {
                        comando.CommandType = CommandType.StoredProcedure;
                        conexion.Open();
                        using (reader = comando.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                entidad = new LogPromoDet();

                                LogPromo logpromo = new LogPromo();
                                logpromo.remitente = Convert.ToString(reader["remitente"] == DBNull.Value ? "" : reader["remitente"]);
                                entidad.LogPromo   = logpromo;

                                listLogPromoDet.Add(entidad);
                            }
                        }
                        clientResponse.DataJson = JsonConvert.SerializeObject(listLogPromoDet).ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                clientResponse.Mensaje = ex.Message;
                clientResponse.Status  = "ERROR";
            }
            finally
            {
                conexion.Close();
                conexion.Dispose();
                comando.Dispose();
                reader.Dispose();
            }

            return(clientResponse);
        }
        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));
            }
        }
        public ClientResponse getLstLogPromo(string remitente, DateTime?FechaInicial, DateTime?FechaFinal, int paginaActual, int RegistroXPagina)
        {
            try
            {
                int recordCount = 0;
                using (conexion = new SqlConnection(ConexionDAO.cnx))
                {
                    using (comando = new SqlCommand("usp_lista_logpromo", conexion))
                    {
                        comando.Parameters.AddWithValue("@remitente", remitente);
                        comando.Parameters.AddWithValue("@StartDate", FechaInicial);
                        comando.Parameters.AddWithValue("@EndDate", FechaFinal);
                        comando.Parameters.AddWithValue("@vi_Pagina", paginaActual);
                        comando.Parameters.AddWithValue("@vi_RegistrosporPagina", RegistroXPagina);
                        comando.Parameters.Add("@vi_RecordCount", SqlDbType.Int).Direction = ParameterDirection.Output;
                        comando.CommandType = CommandType.StoredProcedure;
                        conexion.Open();
                        using (reader = comando.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                entidad = new LogPromoDet();
                                GrupoCorreo grupocorreo = new GrupoCorreo();
                                grupocorreo.id          = Convert.ToInt32(reader["id_grupo_correo"] == DBNull.Value ? 0 : reader["id_grupo_correo"]);
                                grupocorreo.descripcion = Convert.ToString(reader["ds_grupo_correo"] == DBNull.Value ? "" : reader["ds_grupo_correo"]);
                                entidad.Cantidad        = Convert.ToInt32(reader["cantidad"] == DBNull.Value ? 0 : reader["cantidad"]);

                                entidad.GrupoCorreo = grupocorreo;

                                LogPromo logpromo = new LogPromo();
                                logpromo.ID     = Convert.ToInt32(reader["logPromoId"] == DBNull.Value ? 0 : reader["logPromoId"]);
                                logpromo.asunto = Convert.ToString(reader["asunto"] == DBNull.Value ? "" : reader["asunto"]);
                                logpromo.fecha  = Convert.ToString(reader["fecha"] == DBNull.Value ? "" : reader["fecha"]);

                                Plantilla plantilla = new Plantilla();
                                plantilla.id          = Convert.ToInt32(reader["plantillaID"] == DBNull.Value ? 0 : reader["plantillaID"]);
                                plantilla.descripcion = Convert.ToString(reader["plantillads"] == DBNull.Value ? "" : reader["plantillads"]);
                                logpromo.Plantilla    = plantilla;

                                Users users = new Users();
                                users.UserName        = Convert.ToString(reader["remitente"] == DBNull.Value ? "" : reader["remitente"]);
                                users.Nombre          = Convert.ToString(reader["Nombre"] == DBNull.Value ? "" : reader["Nombre"]);
                                users.ApellidoPaterno = Convert.ToString(reader["apellidopaterno"] == DBNull.Value ? "" : reader["apellidopaterno"]);
                                users.ApellidoMaterno = Convert.ToString(reader["apellidoMaterno"] == DBNull.Value ? "" : reader["apellidoMaterno"]);
                                logpromo.Users        = users;

                                entidad.LogPromo = logpromo;

                                listLogPromoDet.Add(entidad);
                            }
                        }

                        recordCount = Convert.ToInt32(comando.Parameters["@vi_RecordCount"].Value);
                        Pagination responsepaginacion = new Pagination()
                        {
                            TotalItems = recordCount,
                            TotalPages = (int)Math.Ceiling((double)recordCount / 10)
                        };
                        clientResponse.paginacion = JsonConvert.SerializeObject(responsepaginacion).ToString();
                        clientResponse.DataJson   = JsonConvert.SerializeObject(listLogPromoDet).ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                clientResponse.Mensaje = ex.Message;
                clientResponse.Status  = "ERROR";
            }
            finally
            {
                conexion.Close();
                conexion.Dispose();
                comando.Dispose();
                reader.Dispose();
            }

            return(clientResponse);
        }