/// <summary>
        /// Función que revisa que el correo sea el de un colaborador válido, y trae sus datos.
        /// </summary>
        /// <param name="correo">Cuenta de correo a validar</param>
        /// <returns>Objeto Colaborador con los datos personales obtenidos por el correo electrónico</returns>
        public static Colaborador Obtiene(string correo)
        {
            Colaborador persona = null;

            /* Solo se permite el acceso a personas que tengan fuentas de correo terminadas en "@anahuac.mx" */
            database db = new database();

            /* Buscamos al colaborador para revisar que este registrado como un colaborador en el sorteo activo actual */
            ResultSet dbPersona = db.getTable(String.Format(@"
SELECT top 1 CA.PK1, C.CLAVE, C.NOMBRE, C.APATERNO, C.AMATERNO, C.CORREO_P, S.CUENTA, SE.PK_SORTEO
FROM COLABORADORES_ASIGNACION CA, 
SECTORES SE, 
SORTEOS S,
COLABORADORES C
WHERE CA.PK_SECTOR=SE.PK1 
AND SE.PK_SORTEO=S.PK1 
AND S.ACTIVO = 1
AND CA.PK_COLABORADOR=(SELECT TOP 1 PK1 FROM COLABORADORES C WHERE C.CORREO_P='{0}' AND C.CORREO_P LIKE '*****@*****.**')", correo));

            long sorteo_colab = -1;

            // Si existe la persona con correo anahuac, entonces extraemos sus datos
            if (dbPersona.Next())
            {
                persona = new Colaborador()
                {
                    clave               = dbPersona.GetLong("PK1"),
                    identificador       = dbPersona.Get("CLAVE"),
                    nombre              = dbPersona.Get("NOMBRE"),
                    apellido_paterno    = dbPersona.Get("APATERNO"),
                    apellido_materno    = dbPersona.Get("AMATERNO"),
                    correo              = dbPersona.Get("CORREO_P").ToLower(),
                    referencia_bancaria = dbPersona.Get("CUENTA")
                                          //referencia_bancaria = dbPersona.Get("REFBANCARIA")
                };
                sorteo_colab = dbPersona.GetLong("PK_SORTEO");
            }

            /* Si la persona existe, obtenemos los datos del estado de cuenta */
            if (persona != null)
            {
                ResultSet dbEdoCuenta = db.getTable(String.Format(@"
SELECT TOP 1 IMPORTE, ABONO, SALDO
FROM vESTADO_CUENTA_COLABORADOR edo
WHERE edo.PK_COLABORADOR = {0}", persona.clave));

                /* Si encontramos datos, entonces extraemos la información del estado de cuenta */
                if (dbEdoCuenta.Next())
                {
                    persona.monto_total   = dbEdoCuenta.GetDecimal("IMPORTE");
                    persona.monto_abonado = dbEdoCuenta.GetDecimal("ABONO");
                    persona.monto_deudor  = dbEdoCuenta.GetDecimal("SALDO");
                }
            }
            ;

            db.Close();

            return(persona);
        }
예제 #2
0
        public string getSearch(int max)
        {
            Dictionary <int, string> mostSearchDiseases = new Dictionary <int, string>();

            database        db    = new database(database.maindb);
            int             upLim = max * 4;
            MySqlDataReader rd    = db.ExecuteReader("select diseaseName, COUNT(diseaseName) as nr from viewHistory GROUP BY diseaseName Order by  nr DESC LIMIT " + upLim.ToString());

            int i = 0;

            while (rd.Read() && i < max)
            {
                //iei valorile rd.GetString("numele coloanei") sau rd.GetInt32("nume coloana");
                int    deaths = rd.GetInt32("nr");
                string code   = rd.GetString("diseaseName");


                if (mostSearchDiseases.ContainsValue(code) == false && mostSearchDiseases.ContainsKey(deaths) == false)
                {
                    mostSearchDiseases.Add(deaths, code);
                    i++;
                }
            }
            db.Close();

            return(JsonConvert.SerializeObject(mostSearchDiseases));
        }
예제 #3
0
        public string getMostCommonDiseases(int max)
        {
            Dictionary <int, string> mostSearchDiseases = new Dictionary <int, string>();

            database        db    = new database(database.maindb);
            int             upLim = max * 4;
            MySqlDataReader rd    = db.ExecuteReader("select code, SUM(deaths) as deathsno from diseasestatistics GROUP BY code Order by deathsno DESC LIMIT " + upLim.ToString());

            int i = 0;

            while (rd.Read() && i < max)
            {
                //iei valorile rd.GetString("numele coloanei") sau rd.GetInt32("nume coloana");
                int    deaths = rd.GetInt32("deathsno");
                string code   = rd.GetString("code");

                string diseaseName = getDiseaseNameFromCode(code);
                if (!mostSearchDiseases.ContainsValue(diseaseName))
                {
                    mostSearchDiseases.Add(deaths, diseaseName);
                    i++;
                }
            }
            db.Close();

            return(JsonConvert.SerializeObject(mostSearchDiseases));
        }
예제 #4
0
        public string getTopUsers(int max)
        {
            Dictionary <string, int> mostSearchDiseases = new Dictionary <string, int>();

            database        db    = new database(database.maindb);
            int             upLim = max * 4;
            MySqlDataReader rd    = db.ExecuteReader("select username, score from users Order by  score DESC LIMIT " + upLim.ToString());

            int i = 0;

            while (rd.Read() && i < max)
            {
                //iei valorile rd.GetString("numele coloanei") sau rd.GetInt32("nume coloana");
                int    deaths = rd.GetInt32("score");
                string code   = rd.GetString("username");


                if (mostSearchDiseases.ContainsKey(code) == false)
                {
                    mostSearchDiseases.Add(code, deaths);
                    i++;
                }
            }
            db.Close();

            return(JsonConvert.SerializeObject(mostSearchDiseases));
        }
예제 #5
0
        public IActionResult viewDisease(string diseaseName)
        {
            ViewBag.error         = "false";
            ViewBag.diseaseExists = "false";

            try
            {
                if ((Context.Session.GetInt32("on") != null && Context.Session.GetInt32("on") == 1))
                {
                    int    userid = (int)Context.Session.GetInt32("id");
                    string key    = diseaseName + userid.ToString();

                    Models.database db = new database(database.maindb);
                    MySqlDataReader rd = db.ExecuteReader("replace into viewHistory (id,diseaseName,ky) values(" + userid.ToString() + ", '" + diseaseName + "', '" + key + "');");
                    db.Close();
                }
            }
            catch { }
            try
            {
                ObjectResult obj = (ObjectResult) new MeAd.Raml.DiseaseDiseaseNameController().Get(diseaseName);
                Dictionary <string, string> apil = (Dictionary <string, string>)obj.Value;


                if (apil.Count != 0)
                {
                    ViewBag.diseaseExists = "true";
                    apil["name"]          = apil["name"].Replace("%20", " ");
                    ViewBag.api           = apil;

                    string url = "http://www.wikidoc.org/api.php?action=query&titles=" + diseaseName + "_(patient_information)&export&contentformat=text/plaino";



                    try
                    {
                        WebRequest wrGETURL;
                        wrGETURL = WebRequest.Create(url);
                        Stream objStream;
                        objStream = wrGETURL.GetResponse().GetResponseStream();

                        StreamReader objReader = new StreamReader(objStream);
                        string       content   = objReader.ReadToEnd();
                        string[]     split     = content.Split(new string[] { "==" }, StringSplitOptions.None);
                        string       symptoms  = split[4].Replace("\\n", "<br/>").Replace(":*", "").Replace("*", "").Replace("[[", "").Replace("]]", "");
                        ViewBag.symptoms = symptoms;
                    }
                    catch
                    { ViewBag.symptoms = "N.A."; }
                }
            }
            catch { ViewBag.error = "true"; }
            return(View());
        }
예제 #6
0
        /// <summary>
        /// Función que regresa la lista de estados y municipios disponibles para este Sorteo
        /// </summary>
        /// <returns></returns>
        public static Ubicaciones.Estado[] Estados()
        {
            /* Inicializamos un diccionario de estados */
            Dictionary <string, HashSet <string> > diccEstados = new Dictionary <string, HashSet <string> >();

            /* Abrimos conexión a base de datos para buscar los datos */
            database db = new database();

            ResultSet dbEntidades = db.getTable(String.Format(@"
SELECT DISTINCT d_estado, D_mnpio
FROM SEPOMEX
ORDER BY 1, 2;"));

            /* Generamos la estructura de datos de los estados y municpios */
            while (dbEntidades.Next())
            {
                string estado    = dbEntidades.Get("d_estado");
                string municipio = dbEntidades.Get("D_mnpio");
                if (!diccEstados.ContainsKey(estado))
                {
                    diccEstados[estado] = new HashSet <string>();
                }
                if (!diccEstados[estado].Contains(municipio))
                {
                    diccEstados[estado].Add(municipio);
                }
            }


            Ubicaciones.Estado[] estados = new Ubicaciones.Estado[diccEstados.Keys.Count];
            int indiceE = -1;

            /* Convertimos el diccionario a un arreglo */
            foreach (string estado in diccEstados.Keys)
            {
                estados[++indiceE] = new Ubicaciones.Estado()
                {
                    nombre     = estado,
                    municipios = diccEstados[estado].Select(m => new Ubicaciones.Municipio()
                    {
                        nombre = m
                    }).ToArray()
                };
            }
            ;

            /* Cerramos la conexión de base de datos */
            db.Close();

            /* Regresamos el listado de estados */
            return(estados);
        }
예제 #7
0
        public string Login(string username, string password)
        {
            //-1 username or email doesnt exist
            try
            {
                //if (!IsValidEmail(email)) return "-1";

                database db = new database(database.maindb);
                db.AddParam("?username", username);
                db.AddParam("?password", password);
                MySqlDataReader rd = db.ExecuteReader("select * from users where lower(username)=lower(?username) and password=?password");
                if (!rd.HasRows)
                {
                    Context.Session.SetInt32("on", 0);
                    // invalid user / pass
                    db.Close();
                    return("-1");
                }
                while (rd.Read())
                {
                    Context.Session.SetInt32("on", 1);
                    Context.Session.SetInt32("id", rd.GetInt32("id"));
                    Context.Session.SetString("email", rd.GetString("email"));
                    Context.Session.SetString("username", rd.GetString("username"));
                    Context.Session.SetInt32("score", rd.GetInt32("score"));
                    Context.Session.SetString("country", rd.GetString("country"));
                    Context.Session.SetInt32("gender", rd.GetInt32("gender"));
                    Context.Session.SetString("birthday", rd.GetString("birthday"));
                    break;
                }
                db.Close();
            }
            catch (Exception e)
            {
                //  HttpContext.Current.Session["on"] = 0;
                return(e.ToString());
            }
            return("1");
        }
예제 #8
0
        /// <summary>
        /// Función que revisa si hay compradores asignados para un colaborador.
        /// </summary>
        /// <param name="id">Identificador a validar</param>
        /// <param name="texto">Texto a validar</param>
        /// <returns>Objeto Comprador con los datos personales obtenidos de la busqueda</returns>
        public static List <Comprador> Obtiene(int id, string texto)
        {
            //Comprador persona = null;

            /* Solo se permite el acceso a personas que tengan fuentas de correo terminadas en "@anahuac.mx" */
            database db = new database();

            List <Comprador> compradores = new List <Comprador>(5);

            /* Buscamos al colaborador para revisar que este registrado como un colaborador en el sorteo activo actual */
            //            ResultSet dbComprador = db.getTable(String.Format(@"
            //select c.NOMBRE, c.APELLIDOS, c.TELEFONO_F, c.TELEFONO_M, c.CORREO, c.CALLE, c.NUMERO, c.COLONIA, c.ESTADO, c.MUNDEL, c.CP
            //from COMPRADORES c
            //inner join COMPRADORES_BOLETOS cmb on c.PK1 = cmb.PK_COMPRADOR
            //inner join COLABORADORES_BOLETOS clb on clb.PK_BOLETO = cmb.PK_BOLETO
            //where clb.PK_COLABORADOR = {0}
            //and (c.nombre like '%'+ '{1}' +'%' OR  c.APELLIDOS like '%'+ '{1}' +'%')", id, texto));

            ResultSet dbComprador = db.getTable(String.Format(@"SELECT * FROM COMPRADORES WHERE USUARIO = '{0}' AND NOMBRE LIKE '%{1}%' OR APELLIDOS LIKE '%{1}%';", id, texto));

            /* Por cada talonario, agregamos el folio a la lista*/
            while (dbComprador.Next())
            {
                compradores.Add(new Comprador()
                {
                    nombre    = dbComprador.Get("NOMBRE"),
                    apellidos = dbComprador.Get("APELLIDOS"),
                    correo    = dbComprador.Get("CORREO"),
                    direccion = new Direccion()
                    {
                        calle         = dbComprador.Get("CALLE"),
                        numero        = dbComprador.Get("NUMERO"),
                        colonia       = dbComprador.Get("COLONIA"),
                        estado        = dbComprador.Get("ESTADO"),
                        municipio     = dbComprador.Get("MUNDEL"),
                        telefono      = dbComprador.Get("TELEFONO_F"),
                        codigo_postal = dbComprador.Get("CP")
                    }
                });
            }

            /* Convertimos la lista a arreglo antes de ciclar sobre los talonarios y agregar losboletos*/
            //persona.compradores = compradores.ToArray();

            db.Close();

            return(compradores);
        }
        /// <summary>
        /// Función que permite marcar como aceptado un talonario por su folio
        /// </summary>
        /// <param name="folio">Folio público del talonario a aceptar</param>
        /// <param name="clave_persona">Clave de la persona dueña del talonario</param>
        public static void AceptarTalonario(string folio, long clave_persona)
        {
            /* Abrimos la conexión de base de datos */
            database db = new database();

            /* Actualizamos los registros de colaborador_talonario del colaborador, donde el talonario sea del sorteo activo, del folio ingresado y sea digital */
            db.execute(string.Format(@"
UPDATE [SORTEOS_COLABORADORES_TALONARIOS] 
SET FECHA_M = GETDATE(),
USUARIO = {0}
WHERE PK_SORTEO IN (SELECT PK1 FROM SORTEOS WHERE ACTIVO = 1)
AND PK_COLABORADOR = {0}
AND PK_TALONARIO IN (SELECT PK1 FROM TALONARIOS WHERE FOLIO = {1} AND DIGITAL = 1)", clave_persona, folio));

            /* Cerramos la conexión de base de datos */
            db.Close();
        }
        /// <summary>
        /// Función que obtiene los talonarios de un usuario
        /// </summary>
        /// <param name="usuario"></param>
        /// <returns></returns>
        public static Talonario[] ObtienePorUsuario(string usuario)
        {
            List <string>    folios     = new List <string>();
            List <Talonario> talonarios = new List <Talonario>();

            /* Traemos los datos del usuario del cual se quiere obtener los talonarios */
            Colaborador persona = ColaboradorService.Obtiene(usuario);

            /* Traemos los datos del sorteo activo */
            Sorteo sorteo_activo = SorteoService.ObtenerActivo();

            /* Si la persona existe y tenemos un sorteo activo, abrimos la conexión a la base de datos para obtener sus talonarios*/
            if (persona != null && sorteo_activo != null)
            {
                database db = new database();

                /* Traemos los folios de los talonarios digitales asignados a un colaborador en el sorteo activo */
                ResultSet dbTalonarios = db.getTable(String.Format(@"
SELECT tal.FOLIO
FROM TALONARIOS tal
INNER JOIN SORTEOS_COLABORADORES_TALONARIOS ctal
ON tal.PK1 = ctal.PK_TALONARIO
WHERE tal.DIGITAL = 1
AND ctal.PK_SORTEO = {0}
AND ctal.PK_COLABORADOR = {1}
ORDER BY tal.FOLIO", sorteo_activo.clave, persona.clave));

                /* Por cada talonario, agregamos el folio a la lista*/
                while (dbTalonarios.Next())
                {
                    folios.Add(dbTalonarios.Get("FOLIO"));
                }

                db.Close();

                /* Por cada folio obtenido, traemos los datos del talonario*/
                foreach (string folio in folios)
                {
                    /* Traemos los datos del talonario */
                    talonarios.Add(Obtiene(folio, persona.clave));
                }
                ;
            }

            return(talonarios.ToArray());
        }
예제 #11
0
        public string getCountriesDisease(string id)
        {
            Dictionary <string, int> diseaseCount = new Dictionary <string, int>();

            diseaseCount.Add(id, 10);

            database        db = new database(database.maindb);
            MySqlDataReader rd = db.ExecuteReader("select country, SUM(deaths) as deaths from diseasestatistics where code like '" + id + "%' GROUP BY country");

            while (rd.Read())
            {
                //iei valorile rd.GetString("numele coloanei") sau rd.GetInt32("nume coloana");
                string countryName = rd.GetString("country");
                int    nr          = rd.GetInt32("deaths");
                diseaseCount.Add(countryName, nr);
            }
            db.Close();

            return(JsonConvert.SerializeObject(diseaseCount));
        }
        //passow  75nW7naeKubWjJnkcbT1fiH

        // GET: /Login/Start
        public ActionResult Start()
        {
            database  db     = new database();
            SessionDB sesion = SessionDB.start(Request, Response, true, db);

            db.Close();
            ViewBag.TOKEN = Guid.NewGuid().ToString();
            // Si ya existe una sesion se redirecciona al Dashboard ...
            if (sesion != null)
            {
                if (sesion.tipouser == 'U')
                {
                    return(RedirectToAction("Start", "Dashboard"));
                }
                else
                {
                    return(RedirectToAction("Home", "EstadodeCuentaWeb"));
                }
            }

            return(View());
        }
예제 #13
0
        public string getCountriesDiseaseClimate(string id, string climate)
        {
            string js = getCountriesDisease(id);

            Dictionary <string, int> diseases  = JsonConvert.DeserializeObject <Dictionary <string, int> >(js);
            Dictionary <string, int> countries = new Dictionary <string, int>();

            database        db = new database(database.maindb);
            MySqlDataReader rd = db.ExecuteReader("select country, climate from countries where climate like '%" + climate + "%'");

            while (rd.Read())
            {
                //iei valorile rd.GetString("numele coloanei") sau rd.GetInt32("nume coloana");
                string countryName = rd.GetString("country");
                string climateDB   = rd.GetString("climate");
                if (diseases.ContainsKey(countryName))
                {
                    countries.Add(countryName, diseases[countryName]);
                }
            }
            db.Close();

            return(JsonConvert.SerializeObject(countries));
        }
예제 #14
0
        public string getCountriesDiseaseObesity(string id, int min, int max)
        {
            string js = getCountriesDisease(id);

            Dictionary <string, int> diseases  = JsonConvert.DeserializeObject <Dictionary <string, int> >(js);
            Dictionary <string, int> countries = new Dictionary <string, int>();

            database        db = new database(database.maindb);
            MySqlDataReader rd = db.ExecuteReader("select country, obesity from countries");

            while (rd.Read())
            {
                //iei valorile rd.GetString("numele coloanei") sau rd.GetInt32("nume coloana");
                string countryName = rd.GetString("country");
                int    nr          = rd.GetInt32("obesity");
                if (diseases.ContainsKey(countryName) && (diseases[countryName] >= min && diseases[countryName] <= max))
                {
                    countries.Add(countryName, diseases[countryName]);
                }
            }
            db.Close();

            return(JsonConvert.SerializeObject(countries));
        }
 public void Dispose()
 {
     db.Close();
     db     = null;
     sesion = null;
 }
        /// <summary>
        /// Función que permite marcar un boleto como vendido
        /// </summary>
        /// <param name="boleto">Boleto que va a ser marcado como vendido</param>
        /// <param name="clave_persona">Clave de la persona dueña del talonario</param>
        /// <returns>1 si el boleto es vendido. 2 si el boleto ya había sido vendido. 0 si el boleto no existe.</returns>
        public static int VenderBoleto(Boleto boleto, long clave_persona)
        {
            /* Traemos los datos del sorteo activo */
            //Sorteo sorteo_activo = SorteoService.ObtenerActivo();

            bool   vendido = false;
            int    resultado = 0;
            bool   boletoExiste = false;
            long   clave_boleto = -1;
            string clave_talonario = string.Empty, folio_talonario = string.Empty, folio_boleto = string.Empty;
            bool   esDigital = false, tieneComprador = false;

            /* Abrimos la conexión de base de datos */
            database db = new database();

            /* Buscamos el boleto por su folio, validando que el boleto pertenezca al colaborador que solicita la venta y que no tenga folio digital */
            ResultSet dbBoleto = db.getTable(String.Format(@"
SELECT TOP 1 bol.PK1,
bol.PK_TALONARIO,
tal.FOLIO as FolioTalon,
bol.FOLIO as FolioBoleto,
ISNULL(bol.FOLIODIGITAL,-1) digital,
ISNULL(com.PK1,-1) comprador
FROM BOLETOS bol
LEFT JOIN COMPRADORES_BOLETOS com
ON com.PK_BOLETO = bol.PK1
INNER JOIN TALONARIOS tal
ON tal.PK1 = bol.PK_TALONARIO
WHERE bol.FOLIO = '{0}'
AND EXISTS (
	SELECT 'X'
	FROM COLABORADORES_BOLETOS scb,
	SORTEOS sorteo
	INNER JOIN SECTORES sc
	ON sc.PK_SORTEO = sorteo.PK1
	WHERE sorteo.ACTIVO = 1
	AND scb.PK_SECTOR = sc.PK1
	AND scb.PK_COLABORADOR = {1}
	AND scb.PK_BOLETO = bol.PK1
)", boleto.folio, clave_persona));

            /* Validamos que el boleto exista y traemos sus datos*/
            if (dbBoleto.Next())
            {
                boletoExiste    = true;
                clave_boleto    = dbBoleto.GetLong("PK1");
                clave_talonario = dbBoleto.Get("PK_TALONARIO");
                folio_talonario = dbBoleto.Get("FolioTalon");
                folio_boleto    = dbBoleto.Get("FolioBoleto");
                esDigital       = dbBoleto.Get("digital") != "-1";
                tieneComprador  = dbBoleto.Get("comprador") != "-1";
            }

            /* Si el boleto existe, procedemos a hacer las validaciones para su venta */
            if (boletoExiste)
            {
                if (!esDigital)
                {
                    /* Actualizamos el folio digital y el estado del boleto para marcarlo como pendiente de pago*/
                    db.execute(string.Format(@"
UPDATE boletos
SET FOLIODIGITAL = (SELECT COUNT('x') + 1 FROM boletos WHERE NOT foliodigital IS NULL),
PK_ESTADO = 'P'
WHERE PK1 = {0}", clave_boleto));

                    /* Si el boleto no tiene comprador, le agregamos los datos del comprador actual */
                    if (!tieneComprador)
                    {
                        /* Traemos la clave del sorteo activo */
                        string    clave_sorteo = "NULL";
                        ResultSet dbSorteo     = db.getTable("SELECT TOP 1 PK1 FROM SORTEOS WHERE ACTIVO = 1");
                        if (dbSorteo.Next())
                        {
                            clave_sorteo = dbSorteo.Get("PK1");
                        }

                        /* Traemos el nicho y sector */
                        string    clave_nicho = "NULL", clave_sector = "NULL";
                        ResultSet dbColaborador = db.getTable(string.Format(@"
SELECT TOP 1 ISNULL(CAST(PK_NICHO as NVARCHAR(14)),'NULL') as PK_NICHO, ISNULL(CAST(PK_SECTOR as NVARCHAR(14)),'NULL') as PK_SECTOR
FROM COLABORADORES_ASIGNACION,
SECTORES SE
WHERE PK_COLABORADOR = {0}
AND SE.PK1 = COLABORADORES_ASIGNACION.PK_SECTOR
AND SE.PK_SORTEO = {1}", clave_persona, clave_sorteo));
                        if (dbColaborador.Next())
                        {
                            clave_nicho  = dbColaborador.Get("PK_NICHO");
                            clave_sector = dbColaborador.Get("PK_SECTOR");
                        }

                        /* Insertamos al comprador */
                        string clave_comprador = "NULL";
                        clave_comprador = db.executeId(String.Format(@"
INSERT INTO [COMPRADORES]
           ([NOMBRE],[APELLIDOS],[TELEFONO_F]
           ,[TELEFONO_M],[CORREO],[CALLE],[NUMERO],[COLONIA],[ESTADO],[MUNDEL]
           ,[USUARIO],[FECHA_R],[CP])
     VALUES
           ('{0}','{1}','{2}','{3}','{4}','{5}',{6},'{7}','{8}','{9}','{10}',GETDATE(),'{11}')",
                                                                     boleto.comprador.nombre, boleto.comprador.apellidos, boleto.comprador.direccion.telefono, boleto.comprador.celular,
                                                                     boleto.comprador.correo, boleto.comprador.direccion.calle, boleto.comprador.direccion.numero, boleto.comprador.direccion.colonia,
                                                                     boleto.comprador.direccion.estado, boleto.comprador.direccion.municipio, clave_persona.ToString(), boleto.comprador.direccion.codigo_postal));

                        db.execute(String.Format(@"
INSERT INTO [COMPRADORES_BOLETOS]
           ([PK_COMPRADOR],[PK_BOLETO],[FECHA_R])
     VALUES
           ({0},{1},GETDATE())",
                                                 clave_comprador, clave_boleto));
                    }
                    boleto.clave = clave_boleto;
                    vendido      = true;
                    resultado    = 1;
                }
                else
                {
                    /* En caso de que si exista con folio digital, cambiamos la salida para reflejar esta condición */
                    resultado = 2;
                }
            }

            /* Cerramos la base de datos */
            db.Close();

            if (vendido)
            {
                EnviarBoleto(boleto.clave, clave_persona);
            }

            return(resultado);
        }
        /// <summary>
        /// Función que obitene un talonaro en base a su folio
        /// </summary>
        /// <param name="folio">Folio del talonario</param>
        /// <param name="clave_persona">PK de la persona dueña del talonario</param>
        /// <returns>Talonario con sus boletos</returns>
        public static Talonario Obtiene(string folio, long clave_persona)
        {
            Talonario talonario = null;

            /* Traemos los datos del sorteo activo */
            Sorteo sorteo_activo = SorteoService.ObtenerActivo();

            /* Abrimos conexión a la base de datos */
            database db = new database();

            /* Traemos los folios de los talonarios digitales asignados a un colaborador en el sorteo activo */
            ResultSet dbTalonario = db.getTable(String.Format(@"
SELECT TOP 1 tal.PK1
FROM TALONARIOS tal
INNER JOIN SORTEOS_COLABORADORES_TALONARIOS ctal
ON tal.PK1 = ctal.PK_TALONARIO
WHERE tal.DIGITAL = 1
AND ctal.PK_SORTEO = {0}
AND ctal.PK_COLABORADOR = {1}
AND tal.FOLIO = '{2}'
ORDER BY tal.FOLIO", sorteo_activo.clave, clave_persona, folio));

            /* Si el talonario existe, traemos sus datos */
            if (dbTalonario.Next())
            {
                /* Traemos los datos del talonario */
                talonario = new Talonario()
                {
                    clave = dbTalonario.GetLong("PK1"),
                    folio = folio
                };
            }

            /* Si el talonario existe, traemos sus boletos */
            if (talonario != null)
            {
                ResultSet dbBoleto = db.getTable(String.Format(@"
SELECT
	boletos.PK1,
	boletos.FOLIO,
	boletos.FOLIODIGITAL
FROM SORTEOS_COLABORADORES_BOLETOS rel_boletos
INNER JOIN boletos
ON boletos.PK1 = rel_boletos.PK_BOLETO
WHERE rel_boletos.PK_SORTEO = {0}
AND rel_boletos.PK_COLABORADOR = {1}
AND rel_boletos.PK_TALONARIO = {2}", sorteo_activo.clave, clave_persona, talonario.clave));


                List <Boleto> boletos = new List <Boleto>();
                while (dbBoleto.Next())
                {
                    Boleto boleto = new Boleto(false)
                    {
                        clave         = dbBoleto.GetLong("PK1"),
                        folio         = dbBoleto.Get("FOLIO"),
                        folio_digital = dbBoleto.Get("FOLIODIGITAL")
                    };
                    if (boleto.folio_digital == "0")
                    {
                        boleto.folio_digital = null;
                    }
                    boleto.vendido = !String.IsNullOrEmpty(boleto.folio_digital);
                    boletos.Add(boleto);
                }

                talonario.boletos = boletos.ToArray();
            }

            db.Close();

            return(talonario);
        }
예제 #18
0
        public string FBLogin(string token)
        {
            try
            {
                WebClient wc = new WebClient();
                wc.Proxy = null;


                string res = wc.DownloadString("https://graph.facebook.com/me?fields=email,name,first_name,last_name,gender&access_token=" + token);
                Dictionary <string, string> response = JsonConvert.DeserializeObject <Dictionary <string, string> >(res);
                if (response.ContainsKey("name"))
                {
                    string   id    = response["id"];
                    string   email = response["email"];
                    database db    = new database(database.maindb);
                    db.AddParam("?fbid", id);
                    db.AddParam("?email", email);
                    db.AddParam("?username", response["first_name"] + response["last_name"]);

                    switch (response["gender"])
                    {
                    case "male":
                        db.AddParam("?gender", 1);
                        break;

                    case "female":
                        db.AddParam("?gender", 2);
                        break;

                    default:
                        db.AddParam("?gender", 0);
                        break;
                    }

                    MySqlDataReader rd;

                    rd = db.ExecuteReader("select * from users where facebookid = ?fbid or email = ?email");

                    if (rd.HasRows)
                    {
                        while (rd.Read())
                        {
                            Context.Session.SetInt32("on", 1);
                            Context.Session.SetString("email", rd.GetString("email"));
                            Context.Session.SetString("username", rd.GetString("username"));
                            Context.Session.SetInt32("id", rd.GetInt32("id"));
                            Context.Session.SetString("myname", rd.GetString("lastname") + " " + rd.GetString("firstname"));
                            break;
                            // return "2";
                        }
                    }
                    else
                    {
                        db.ExecuteNonQuery("insert into users (email,username,gender,facebookid) values (?email,?username,?gender,?fbid)");
                        rd = db.ExecuteReader("select * from users where facebookid = ?fbid or email = ?email");
                        while (rd.Read())
                        {
                            Context.Session.SetInt32("on", 1);
                            Context.Session.SetString("email", rd.GetString("email"));
                            Context.Session.SetInt32("id", rd.GetInt32("id"));
                            Context.Session.SetString("username", rd.GetString("username"));
                            Context.Session.SetInt32("gender", rd.GetInt32("gender"));
                        }
                        //return "3";
                    }

                    db.Close();

                    return("1");
                }
                else
                {
                    return("0");
                }
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
        }
        /// <summary>
        /// Función que permite obtener los datos de un boleto
        /// </summary>
        /// <param name="clave">Clave del boleto que se desea consutar</param>
        /// <param name="clave_persona">Clave de la persona dueña del talonario</param>
        public static Boleto ObtieneBoleto(long clave, long clave_persona)
        {
            Boleto boleto = null;

            /* Traemos los datos del sorteo activo */
            Sorteo sorteo_activo = SorteoService.ObtenerActivo();

            /* Abrimos la conexión de base de datos */
            database db = new database();

            /* Buscamos el boleto por su clave */
            ResultSet dbBoleto = db.getTable(String.Format(@"
SELECT TOP 1 bol.PK1, bol.FOLIO, CAST(bol.FOLIODIGITAL as NVARCHAR(16)) FOLIODIGITAL, tal.FOLIO AS TAL_FOLIO, scb.PK_COLABORADOR, tal.PK_SORTEO, ISNULL(comp.PK1,-1) tiene_comprador, com.NOMBRE, com.APELLIDOS, com.TELEFONO_M, com.CORREO, com.CALLE, com.NUMERO, com.COLONIA, com.ESTADO, com.MUNDEL, com.TELEFONO_F
FROM boletos bol
INNER JOIN TALONARIOS tal
ON tal.PK1 = bol.PK_TALONARIO
LEFT JOIN COLABORADORES_BOLETOS scb
ON scb.PK_BOLETO = bol.PK1
LEFT JOIN COMPRADORES_BOLETOS comp
ON comp.PK_BOLETO = bol.PK1
LEFT JOIN COMPRADORES com 
ON com.PK1 = comp.PK_COMPRADOR
WHERE bol.PK1 = {0}", clave));

            /* Si el boleto existe, procedemos a extraer sus datos */
            if (dbBoleto.Next())
            {
                boleto = new Boleto()
                {
                    clave             = dbBoleto.GetLong("PK1"),
                    folio             = dbBoleto.Get("FOLIO"),
                    folio_digital     = dbBoleto.Get("FOLIODIGITAL"),
                    vendido           = true,
                    folio_talonario   = dbBoleto.Get("TAL_FOLIO"),
                    clave_colaborador = dbBoleto.GetLong("PK_COLABORADOR"),
                    clave_sorteo      = dbBoleto.GetLong("PK_SORTEO")
                };

                /* Si el folio digital es un string vacío, significa que debe ser NULL y no ha sido vendido */
                if (string.IsNullOrEmpty(boleto.folio_digital))
                {
                    boleto.folio_digital = null;
                    boleto.vendido       = false;
                }

                /* Revisamos si tiene un comprador */
                if (dbBoleto.GetInt("tiene_comprador") > -1)
                {
                    /* Si tiene comprador agregamos los datos al objeto de salida */
                    boleto.comprador = new Comprador()
                    {
                        nombre    = dbBoleto.Get("NOMBRE"),
                        apellidos = dbBoleto.Get("APELLIDOS"),
                        celular   = dbBoleto.Get("TELEFONO_M"),
                        correo    = dbBoleto.Get("CORREO"),
                        direccion = new Direccion()
                        {
                            calle     = dbBoleto.Get("CALLE"),
                            numero    = dbBoleto.Get("NUMERO"),
                            colonia   = dbBoleto.Get("COLONIA"),
                            estado    = dbBoleto.Get("ESTADO"),
                            municipio = dbBoleto.Get("MUNDEL"),
                            telefono  = dbBoleto.Get("TELEFONO_F")
                        }
                    };
                }
            }


            /* Cerramos la conexión a base de datos */
            db.Close();

            return(boleto);
        }
예제 #20
0
        /// <summary>
        /// Search by country name - Country
        /// </summary>
        /// <param name="countryName"></param>
        public IActionResult Get(string countryName)
        {
            Dictionary <string, Countries.CountryDiseases> countrydiseases = new Dictionary <string, Countries.CountryDiseases>();
            string query = "";

            try
            {
                database        db = new database(database.maindb);
                MySqlDataReader rd;

                rd = db.ExecuteReader("SELECT code,sum(deaths) as nrDeaths FROM `diseasestatistics` where lower(country)=lower('" + countryName + "') group by code order by sum(deaths) desc limit 10");
                while (rd.Read())
                {
                    countrydiseases.Add(rd.GetString("code"), new Countries.CountryDiseases(rd.GetInt32("nrDeaths"), "", "", ""));
                }

                SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org");
                foreach (KeyValuePair <string, Countries.CountryDiseases> disease in countrydiseases)
                {
                    query = @"SELECT * WHERE {
                            ?url <http://dbpedia.org/ontology/icd10> ?ID.
                            ?url rdfs:label ?name.
                            ?url <http://dbpedia.org/ontology/abstract> ?description.
                            filter regex(str(lcase(?ID)), concat(lcase('" + disease.Key[0] + "'), '[" + disease.Key[1] + "][" + disease.Key[2] + "][.]?[0-9]?') )" +
                            "filter(langMatches(lang(?name), 'EN'))" +
                            "filter(langMatches(lang(?description), 'EN'))" +
                            "} limit 1";
                    SparqlResultSet results = endpoint.QueryWithResultSet(query);
                    if (results.Count > 0)
                    {
                        disease.Value.Description = results[0]["description"].ToString().Remove(results[0]["description"].ToString().Length - 3);
                        if (disease.Value.Description.Length > 300)
                        {
                            disease.Value.Description = disease.Value.Description.Remove(300) + " ...";
                        }
                        disease.Value.Disease = results[0]["name"].ToString().Remove(results[0]["name"].ToString().Length - 3);
                        disease.Value.Url     = disease.Value.Disease.Replace(" ", "_");
                    }
                    else
                    {
                        query = @"SELECT * WHERE {
                            ?url <http://dbpedia.org/ontology/icd10> ?ID.
                            ?url rdfs:label ?name.
                            ?url <http://dbpedia.org/ontology/abstract> ?description.
                            filter regex(str(lcase(?ID)), concat(lcase('" + disease.Key[0] + "'), '[" + disease.Key[1] + "][0-9][.]?[0-9]?') )" +
                                "filter(langMatches(lang(?name), 'EN'))" +
                                "filter(langMatches(lang(?description), 'EN'))" +
                                "} limit 1";
                        results = endpoint.QueryWithResultSet(query);
                        if (results.Count > 0)
                        {
                            disease.Value.Description = results[0]["description"].ToString().Remove(results[0]["description"].ToString().Length - 3);
                            if (disease.Value.Description.Length > 300)
                            {
                                disease.Value.Description = disease.Value.Description.Remove(300) + " ...";
                            }
                            disease.Value.Disease = results[0]["name"].ToString().Remove(results[0]["name"].ToString().Length - 3);
                        }
                    }
                }
                db.Close();
            }
            catch (Exception e) { return(new ObjectResult(countrydiseases)); }
            return(new ObjectResult(countrydiseases));
        }
예제 #21
0
        /// <summary>
        /// Función que obtiene los datos del sorteo activo
        /// </summary>
        /// <returns>Estructura con los datos del Sorteo Activo</returns>
        public static Sorteo ObtenerActivo()
        {
            Sorteo sorteo = null;

            /* Abrimos conexión a base de datos */
            database db = new database();

            /* Buscamos el sorteo */
            ResultSet dbSorteo = db.getTable(String.Format(@"
SELECT TOP 1 sorteo.PK1, sorteo.CLAVE, sorteo.SORTEO, sorteo.DESCRIPCION, sorteo.CUENTA, sorteo.FECHA_I, sorteo.FECHA_T, sorteo.URL_1, sorteo.URL_2, sorteo.URL_3, sorteo.URL_4, sorteo.URL_5, sorteo.URL_6, n.LIMITE_VENTA, n.LIMITE_DEPOSITO
FROM SORTEOS sorteo
LEFT JOIN SECTORES sc
ON sc.PK_SORTEO = sorteo.PK1
LEFT JOIN NICHOS n
ON n.PK_SECTOR = sc.PK1
WHERE sorteo.ACTIVO = 1
ORDER BY n.LIMITE_VENTA DESC"));//db.SORTEOS.Where(s => s.PK1 == clave).FirstOrDefault();

            /* En caso de existir ese sorteo, procedemos a traer sus datos */
            if (dbSorteo.Next())
            {
                /* Llenamos los datos que estan en la tabla de SORTEOS */
                sorteo = new Sorteo()
                {
                    clave               = dbSorteo.GetLong("PK1"),
                    identificador       = dbSorteo.Get("CLAVE"),
                    nombre              = dbSorteo.Get("SORTEO"),
                    descripcion         = dbSorteo.Get("DESCRIPCION"),
                    cuenta_bancaria     = dbSorteo.Get("CUENTA"),
                    fecha_inico         = dbSorteo.GetDateTime("FECHA_I"),
                    fecha_fin           = dbSorteo.GetDateTime("FECHA_T"),
                    url_politicas       = dbSorteo.Get("URL_1"),
                    url_condiciones     = dbSorteo.Get("URL_2"),
                    url_reglamento      = dbSorteo.Get("URL_3"),
                    url_aceptacion      = dbSorteo.Get("URL_4"),
                    url_conoce          = dbSorteo.Get("URL_5"),
                    url_lista_ganadores = dbSorteo.Get("URL_6")
                };

                sorteo.limite_venta = dbSorteo.GetDateTime("LIMITE_VENTA");
                sorteo.limite_abono = dbSorteo.GetDateTime("LIMITE_DEPOSITO");
            }

            // Si encontramos un sorteo válido, obtenemos su listado de ganadores
//            if (sorteo != null)
//            {
//                List<Ganador> ganadores = new List<Ganador>();

//                /* Traemos a los ganadores */
//                ResultSet dbGanadores = db.getTable(String.Format(@"
//SELECT boletos.FOLIO, premios.NUM_PREMIO
//FROM GANADORES gana
//INNER JOIN PREMIOS
//ON gana.PK_PREMIO = PREMIOS.PK1
//INNER JOIN COMPRADORES compra
//ON compra.PK1 = gana.PK_COMPRADOR
//INNER JOIN BOLETOS
//ON boletos.PK1 = compra.PK_BOLETO
//WHERE gana.PK_SORTEO = {0}
//AND premios.CLAVE_BENEFICIARIO = 1
//ORDER BY PREMIOS.CLASIFICACION, PREMIOS.NUM_PREMIO", sorteo.clave));
//                while (dbGanadores.Next())
//                {
//                    ganadores.Add(new Ganador()
//                    {
//                        folio = dbGanadores.Get("FOLIO"),
//                        lugar = dbGanadores.GetInt("NUM_PREMIO")
//                    });
//                };
//                sorteo.ganadores = ganadores.ToArray();
//            }

            db.Close();

            return(sorteo);
        }
예제 #22
0
        // GET: SSOffice365/Details/5
        public ActionResult VerifyToken()
        {
            database db = new database();

            sesion = SessionDB.start(Request, Response, true, db);

            string id_token         = Request.QueryString["id_token"];
            var    tokenString      = "Bearer " + id_token;
            var    jwtEncodedString = tokenString.Substring(7);

            try
            {
                // Si ya existe una sesion se redirecciona al Dashboard ...
                if (sesion != null)
                {
                    if (sesion.tipouser == 'U')
                    {
                        return(RedirectToAction("Start", "Dashboard"));
                    }
                    else
                    {
                        return(RedirectToAction("Home", "EstadodeCuentaWeb"));
                    }
                }
                else
                {
                    var token  = new JwtSecurityToken(jwtEncodedString: jwtEncodedString);
                    var correo = token.Claims.Where(c => c.Type == "unique_name");

                    var    nuevo       = correo.ToList();
                    var    valor       = nuevo[0].Value;
                    string client_user = valor;

                    db.Close();

                    LoginModel model = new LoginModel();

                    if (model.existeUsuario(client_user))
                    {
                        SessionDB.afterLogIn(client_user, db, Request, Response);
                        sesion = SessionDB.start(Request, Response, false, db);
                        //Log.write(this, "Validate", LOG.CONSULTA, "Detalle x", sesion);
                        return(RedirectToAction("Start", "Dashboard"));
                    }
                    else
                    {
                        //No cuenta con acceso como administrador al Sistema de Pago a Profesores
                        //Revisar si existe como profesor

                        if (model.existeProfesor(client_user))
                        {
                            string   strm_Tag  = ConfigurationManager.ConnectionStrings["GetToken"].ConnectionString;
                            string[] array_tag = strm_Tag.Split(';');
                            string   Key       = array_tag[0].Substring(4);
                            string   URL       = array_tag[1].Substring(5);

                            char   tipouser = '******';
                            string idsiu    = "";

                            sesion = SessionDB.afterLogIn(client_user, db, Request, Response, tipouser);
                            sesion = SessionDB.start(Request, Response, false, db);

                            string    sql = "SELECT IDSIU FROM PERSONAS WHERE ID_PERSONA = '" + sesion.pkUser + "'";
                            ResultSet res = db.getTable(sql);
                            if (res.Next())
                            {
                                idsiu = res.Get("IDSIU");
                            }

                            string data = "Periodo=&Nivel=&IDSIU=" + idsiu + "&NombreCompleto=" + sesion.completeName + "&Campus=UAN";

                            Response.Redirect(URL + "Token/GenerarToken?" + data);
                        }
                        else
                        {
                            //No cuenta con acceso  al Sistema de Pago a Profesores

                            return(RedirectToAction("AccesoDenegado", "SSOffice365"));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
                // Response.Redirect("https://login.microsoftonline.com/common/oauth2/authorize?response_type=id_token&client_id=09fa3fa2-106e-41b2-91f4-75026bdaa9ee&redirect_uri=http%3A%2F%2Flocalhost%3A58402%2F&state=00c2faab-e87f-47be-8a4a-f61448a10ea4&client-request-id=cad66ef3-92fc-4316-8bcb-5af6b1154683&x-client-SKU=Js&x-client-Ver=1.0.12&nonce=1a39aacd-f7fc-43ab-97f1-f0286ecea418");
            }

            return(null);
        }
        /// <summary>
        /// Función que revisa que el correo sea el de un colaborador válido, y trae sus datos incluyendo sus Talonarios.
        /// </summary>
        /// <param name="correo">Cuenta de correo a validar</param>
        /// <returns>Objeto Colaborador con los datos personales obtenidos por el correo electrónico</returns>
        public static Colaborador ObtieneConTalonarios(string correo)
        {
            Colaborador persona = null;

            /* Solo se permite el acceso a personas que tengan fuentas de correo terminadas en "@anahuac.mx" */
            database db = new database();

            /* Buscamos al colaborador para revisar que este registrado como un colaborador en el sorteo activo actual */
            ResultSet dbPersona = db.getTable(String.Format(@"
SELECT top 1 CA.PK1, C.CLAVE, C.NOMBRE, C.APATERNO, C.AMATERNO, S.CUENTA, SE.PK_SORTEO
FROM COLABORADORES_ASIGNACION CA, 
SECTORES SE, 
SORTEOS S,
COLABORADORES C
WHERE CA.PK_SECTOR=SE.PK1 
AND SE.PK_SORTEO=S.PK1 
AND S.ACTIVO = 1
AND CA.PK_COLABORADOR=(SELECT TOP 1 PK1 FROM COLABORADORES C WHERE C.CORREO_P='{0}' AND C.CORREO_P LIKE '*****@*****.**')", correo));

            long sorteo_colab  = -1;
            bool existePersona = false;

            // Si existe la persona con correo anahuac, entonces extraemos sus datos
            if (dbPersona.Next())
            {
                // Obtenemos los datos del nombre de la persona
                string nombre           = dbPersona.Get("NOMBRE"),
                       apellido_paterno = dbPersona.Get("APATERNO"),
                       apellido_materno = dbPersona.Get("AMATERNO");
                // Generamos el nombre completo
                string nombre_completo = string.Format("{0} {1} {2}", nombre, apellido_paterno, apellido_materno).Trim();

                persona = new Colaborador(false, nombre_completo)
                {
                    clave               = dbPersona.GetLong("PK1"),
                    identificador       = dbPersona.Get("CLAVE"),
                    nombre              = nombre,
                    apellido_paterno    = apellido_paterno,
                    apellido_materno    = apellido_materno,
                    correo              = correo.ToLower(),
                    referencia_bancaria = dbPersona.Get("CUENTA")
                                          //referencia_bancaria = dbPersona.Get("REFBANCARIA")
                };
                sorteo_colab  = dbPersona.GetLong("PK_SORTEO");
                existePersona = true;
            }

            /* Si la persona existe, obtenemos los datos del estado de cuenta */
            if (existePersona)
            {
                ResultSet dbEdoCuenta = db.getTable(String.Format(@"
SELECT TOP 1 IMPORTE, ABONO, SALDO
FROM vESTADO_CUENTA_COLABORADOR edo
WHERE edo.PK_COLABORADOR = {0}", persona.clave));

                /* Si encontramos datos, entonces extraemos la información del estado de cuenta */
                if (dbEdoCuenta.Next())
                {
                    persona.monto_total   = dbEdoCuenta.GetDecimal("IMPORTE");
                    persona.monto_abonado = dbEdoCuenta.GetDecimal("ABONO");
                    persona.monto_deudor  = dbEdoCuenta.GetDecimal("SALDO");
                }

                #region Talonarios y Boletos
                List <Talonario> talonarios = new List <Talonario>(5);

                /* Traemos los folios de los talonarios digitales asignados a un colaborador en el sorteo activo */
                ResultSet dbTalonarios = db.getTable(String.Format(@"
select distinct t.PK1, t.FOLIO
from COLABORADORES c
inner join COLABORADORES_BOLETOS cb ON c.pk1 = cb.PK_COLABORADOR
inner join BOLETOS b ON b.PK1 = cb.PK_BOLETO
inner join TALONARIOS t ON b.PK_TALONARIO = t.PK1
where t.DIGITAL = 1
and t.ASIGNADO = 1
and c.PK1 = {0}
and t.PK_SORTEO = {1}
ORDER BY t.FOLIO", persona.clave, sorteo_colab));

                /* Por cada talonario, agregamos el folio a la lista*/
                while (dbTalonarios.Next())
                {
                    talonarios.Add(new Talonario()
                    {
                        clave = dbTalonarios.GetLong("PK1"),
                        folio = dbTalonarios.Get("FOLIO")
                    });
                }

                /* Convertimos la lista a arreglo antes de ciclar sobre los talonarios y agregar losboletos*/
                persona.talonarios = talonarios.ToArray();

                /* Por cada folio obtenido, traemos los datos del talonario*/
                foreach (Talonario talonario in persona.talonarios)
                {
                    /* Traemos los datos del talonario */
                    ResultSet dbBoleto = db.getTable(String.Format(@"
SELECT
    boletos.PK1,
	boletos.FOLIO,
	boletos.FOLIODIGITAL,
    boletos.PK_ESTADO
FROM COLABORADORES_BOLETOS rel_boletos
INNER JOIN boletos
ON boletos.PK1 = rel_boletos.PK_BOLETO
inner join TALONARIOS t
ON boletos.PK_TALONARIO = t.PK1
inner join SORTEOS s
ON s.PK1 = t.PK_SORTEO
WHERE t.PK_SORTEO = {2}
AND rel_boletos.PK_COLABORADOR = {0}
AND boletos.PK_TALONARIO = {1}", persona.clave, talonario.clave, sorteo_colab));

                    List <Boleto> pendientes = new List <Boleto>(20);
                    List <Boleto> vendidos   = new List <Boleto>(20);
                    List <Boleto> asignados  = new List <Boleto>(20);

                    while (dbBoleto.Next())
                    {
                        Boleto boleto = new Boleto(false)
                        {
                            clave         = dbBoleto.GetLong("PK1"),
                            folio         = dbBoleto.Get("FOLIO"),
                            folio_digital = dbBoleto.Get("FOLIODIGITAL"),
                            estado_boleto = dbBoleto.Get("PK_ESTADO")
                        };
                        if (boleto.folio_digital == "0")
                        {
                            boleto.folio_digital = null;
                        }
                        boleto.vendido = !String.IsNullOrEmpty(boleto.folio_digital);
                        if (boleto.estado_boleto == "V")
                        {
                            vendidos.Add(boleto);
                        }
                        if (boleto.estado_boleto == "P")
                        {
                            asignados.Add(boleto);
                        }
                        if (boleto.estado_boleto == "NULL" || boleto.estado_boleto == String.Empty)
                        {
                            pendientes.Add(boleto);
                        }

                        /* Buscamos el boleto por su clave */
                        ResultSet dbBoletoComprador = db.getTable(String.Format(@"
SELECT TOP 1 bol.PK1, bol.FOLIO, CAST(bol.FOLIODIGITAL as NVARCHAR(16)) FOLIODIGITAL, tal.FOLIO AS TAL_FOLIO, scb.PK_COLABORADOR, tal.PK_SORTEO, ISNULL(comp.PK1,-1) tiene_comprador, com.NOMBRE, com.APELLIDOS, com.TELEFONO_M, com.CORREO, com.CALLE, com.NUMERO, com.COLONIA, com.ESTADO, com.MUNDEL, com.TELEFONO_F
FROM boletos bol
INNER JOIN TALONARIOS tal
ON tal.PK1 = bol.PK_TALONARIO
LEFT JOIN COLABORADORES_BOLETOS scb
ON scb.PK_BOLETO = bol.PK1
LEFT JOIN COMPRADORES_BOLETOS comp
ON comp.PK_BOLETO = bol.PK1
LEFT JOIN COMPRADORES com 
ON com.PK1 = comp.PK_COMPRADOR
WHERE bol.PK1 = {0}", boleto.clave));

                        /* Si el boleto existe, procedemos a extraer sus datos */
                        if (dbBoletoComprador.Next())
                        {
                            /* Revisamos si tiene un comprador */
                            if (dbBoletoComprador.GetInt("tiene_comprador") > -1)
                            {
                                /* Si tiene comprador agregamos los datos al objeto de salida */
                                boleto.comprador = new Comprador()
                                {
                                    nombre    = dbBoletoComprador.Get("NOMBRE"),
                                    apellidos = dbBoletoComprador.Get("APELLIDOS"),
                                    celular   = dbBoletoComprador.Get("TELEFONO_M"),
                                    correo    = dbBoletoComprador.Get("CORREO"),
                                    direccion = new Direccion()
                                    {
                                        calle     = dbBoletoComprador.Get("CALLE"),
                                        numero    = dbBoletoComprador.Get("NUMERO"),
                                        colonia   = dbBoletoComprador.Get("COLONIA"),
                                        estado    = dbBoletoComprador.Get("ESTADO"),
                                        municipio = dbBoletoComprador.Get("MUNDEL"),
                                        telefono  = dbBoletoComprador.Get("TELEFONO_F")
                                    }
                                };
                            }
                        }
                    }
                    //talonario.boletos = pendientes.ToArray();

                    talonario.Boletos.Add("pendientes", pendientes.ToArray());
                    talonario.Boletos.Add("vendidos", vendidos.ToArray());
                    talonario.Boletos.Add("asignados", asignados.ToArray());
                }
                ;

                #endregion
            }
            ;

            db.Close();

            persona.version = "1.0.2";

            return(persona);
        }
        /// <summary>
        /// Función que valida credeciales para regresar un colaborador activo
        /// </summary>
        /// <param name="correo">Correo del usuario que desea autenticarse</param>
        /// <param name="password">Contraseña del usuario a autenticar</param>
        /// <param name="ip_address">Dirección IP del usuario que se esta autenticando</param>
        /// <returns>Verdadero cuando el usuario y contraseña con correctos</returns>
        public static bool Auntenticar(string correo, string password, string ip_address)
        {
            /* Verificamos si la persona existe en la base de datos como colaborador */
            long clave = -1;

            if (correo.ToLowerInvariant().EndsWith("@anahuac.mx"))
            {
                database db = new database();
                /* Buscamos al colaborador para revisar que este registrado como un becario en el sorteo activo actual */
                /* Para saber que es becario, se busca que este registrado en un nicho con clave "0001" */
                ResultSet dbPersona = db.getTable(String.Format(@"
SELECT top 1 CA.PK1 
FROM COLABORADORES_ASIGNACION CA, 
SECTORES SE, 
SORTEOS S 
WHERE CA.PK_SECTOR=SE.PK1 
AND SE.PK_SORTEO=S.PK1 
AND S.ACTIVO = 1
AND CA.PK_COLABORADOR=(SELECT TOP 1 PK1 FROM COLABORADORES WHERE CORREO_P= '{0}')", correo));

                /* Buscamos a la persona */
                if (dbPersona.Next())
                {
                    clave = dbPersona.GetLong("PK1");

                    if (clave > -1)
                    {
                        System.Net.ServicePointManager.DefaultConnectionLimit = 5000;
                        System.Net.WebClient cliente = new System.Net.WebClient();
                        cliente.Credentials = new System.Net.NetworkCredential(correo, password);
                        try
                        {
                            string usuario = cliente.DownloadString("https://outlook.office365.com/api/v1.0/me/");
                        }
                        catch
                        {
                            clave = -1;
                        }
                    }

                    /* Si realizamos un login exitoso, registramos el acceso en la bitacora */
                    if (clave > -1)
                    {
                        Task.Run(() => {
                            db.execute(string.Format(@"
INSERT INTO [COLABORADORES_BITACORA_ACCESO] (
[PK_COLABORADOR],
[IP],
[FECHA_R])
VALUES(
{0},
'{1}',
GETDATE())", clave, ip_address));
                        });
                    }
                }

                db.Close();
            }



            return(clave > -1);
        }