Exemple #1
0
        public void AddLog(string evento, object key, object data)
        {
            int? eventoId;

            evento = string.IsNullOrEmpty(evento) ? GetControllerActionName() : evento;

            using (var db = new MMSContext())
                eventoId = db.Evento.FirstOrDefault(e => e.Nombre == evento && e.Activo)?.Id;

            if (eventoId == null)
                return;

            List<Log> logs;

            if (HttpContext.Items["__logs"] == null)
                logs = new List<Log>();
            else
                logs = (List<Log>)HttpContext.Items["__logs"];

            logs.Add(new Log()
            {
                Fecha = DateTime.Now,
                Usuario = Seguridadcll.Usuario.UsuarioId,
                Data = Fn.GetJsonString(data),
                Cliente = Request.Browser.Browser,
                EventoId = (int)eventoId,
                Key = key.ToString()
            });

            HttpContext.Items["__logs"] = logs;
        }
Exemple #2
0
        public static bool SendEmail(string to, string subject, string mensaje)
        {
            using (var db = new MMSContext())
            {
                var tbconfig = db.Database.SqlQuery <Configuracion>("SELECT TOP 1 * FROM Configuracion").First();
                var mail     = new MailMessage();
                var smtp     = new SmtpClient();

                try
                {
                    mail.From = new MailAddress(tbconfig.ConfigSmtpFrom);
                    mail.To.Add(new MailAddress(to));
                    mail.Subject     = subject;
                    mail.IsBodyHtml  = true;
                    mail.Body        = mensaje;
                    smtp.Host        = tbconfig.ConfigSmtpHost;
                    smtp.Port        = (int)tbconfig.ConfigSmtpPort;
                    smtp.Credentials = new NetworkCredential(tbconfig.ConfigSmtpUserName, tbconfig.ConfigSmtPassword);
                    smtp.EnableSsl   = true;
                    smtp.Send(mail);
                    return(true);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                    return(false);
                }
            }
        }
Exemple #3
0
        public static void SendHtmlEmail(string to, string toName, string subject, string msg, string app)
        {
            string body = string.Empty;

            using (var sr = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "/App_Data/Email_Base.html"))
                body = sr.ReadToEnd();

            body = body.Replace("{username}", toName);
            body = body.Replace("{message}", msg);

            using (var mail = new MailMessage())
            {
                using (var db = new MMSContext())
                {
                    var config = db.Configuracion.First();
                    body = body.Replace("{url}", $"http://{app}.{config.ConfigDominioWeb}");

                    mail.From = new MailAddress(config.ConfigSmtpFrom);
                    mail.To.Add(new MailAddress(to));
                    mail.Subject    = subject;
                    mail.Body       = body;
                    mail.IsBodyHtml = true;

                    var smtp = new SmtpClient()
                    {
                        Host = config.ConfigSmtpHost,
                        UseDefaultCredentials = config.configSmtpUseDefaultCredentials ?? true,
                        EnableSsl             = config.configSmtpUseDefaultCredentials ?? true,
                        Credentials           = (config.configSmtpUseDefaultCredentials ?? true) ? new NetworkCredential(config.ConfigSmtpUserName, config.ConfigSmtPassword) : null,
                        Port = (int)config.ConfigSmtpPort,
                    };
                    smtp.Send(mail);
                }
            }
        }
Exemple #4
0
        public static void AddLog(string usuario, string evento, string key, object data, string client)
        {
            try
            {
                using (var db = new MMSContext())
                {
                    int?eventoId = db.Evento.FirstOrDefault(e => e.Nombre == evento && e.Activo)?.Id;
                    if (eventoId == null)
                    {
                        return;
                    }

                    var log = new Log()
                    {
                        Fecha    = DateTime.Now,
                        Usuario  = string.IsNullOrWhiteSpace(usuario) ? "Anonymous" : usuario,
                        Data     = Fn.GetJsonString(data),
                        Cliente  = client,
                        EventoId = (int)eventoId,
                        Key      = key
                    };

                    db.Log.Add(log);
                    db.SaveChanges();
                }
            }
            catch { }
        }
Exemple #5
0
 public async Task <ActionResult> Eventos()
 {
     using (var db = new MMSContext())
     {
         string[] eventosOmitidos = { "Logs/Events" };
         return(PartialView("_Eventos", await db.Evento.Where(e => !eventosOmitidos.Contains(e.Nombre)).OrderBy(e => e.Id).ToListAsync()));
     }
 }
Exemple #6
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any())
            {
                return;
            }

            if (actionContext.Request.Headers.Authorization == null)
            {
                HandleUnauthorizedRequest(actionContext);
                return;
            }

            string scheme = actionContext.Request.Headers.Authorization.Scheme;
            string token  = actionContext.Request.Headers.Authorization.Parameter;

            if (string.IsNullOrWhiteSpace(scheme) || string.IsNullOrWhiteSpace(token) || scheme != "Bearer")
            {
                HandleUnauthorizedRequest(actionContext);
                return;
            }

            using (var db = new MMSContext())
            {
                var data = db.UsuarioToken
                           .Include(ut => ut.Usuario)
                           .Include(ut => ut.Usuario.RolUsuarioList)
                           .Where(ut => ut.Usuario.Usuarioactivo && ut.Token == token)
                           .Select(ut => new
                {
                    Usuario      = ut.Usuario,
                    UsuarioToken = ut,
                    RolesId      = ut.Usuario.RolUsuarioList.Select(ru => ru.RolId).ToList()
                })
                           .FirstOrDefault();

                if (data == null || !db.RolObjeto.Where(ro => data.RolesId.Contains(ro.RolId) && ro.ObjetoId == "PerfectStore").Any())
                {
                    HandleUnauthorizedRequest(actionContext);
                    return;
                }

                data.UsuarioToken.FechaUltimoUso = DateTime.Now;

                db.Entry(data.UsuarioToken).State = EntityState.Modified;
                db.SaveChanges();

                HttpContext.Current.Items["__usuario"] = data.Usuario;
            }
        }
Exemple #7
0
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);

            if (HttpContext.Current.Items["__logs"] == null)
            {
                return;
            }

            List <Log> logs = (List <Log>)HttpContext.Current.Items["__logs"];

            using (var db = new MMSContext())
            {
                db.Log.AddRange(logs);
                db.SaveChanges();
            }
        }
Exemple #8
0
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (HttpContext.Current.Items["__logs"] == null)
            {
                return;
            }

            List <Log> logs = (List <Log>)HttpContext.Current.Items["__logs"];

            if (logs.Count > 0)
            {
                using (var db = new MMSContext())
                {
                    db.Log.AddRange(logs);
                    db.SaveChanges();
                }
            }
        }
Exemple #9
0
        public void AddLog(string evento, object key, object data, string usuarioId = null)
        {
            if (string.IsNullOrEmpty(evento))
            {
                return;
            }

            int?eventoId;

            usuarioId = string.IsNullOrWhiteSpace(usuarioId) ? Usuario.UsuarioId : usuarioId;

            using (var db = new MMSContext())
                eventoId = db.Evento.FirstOrDefault(e => e.Nombre == evento && e.Activo)?.Id;

            if (eventoId == null)
            {
                return;
            }

            List <Log> logs;

            if (HttpContext.Current.Items["__logs"] == null)
            {
                logs = new List <Log>();
            }
            else
            {
                logs = (List <Log>)HttpContext.Current.Items["__logs"];
            }

            logs.Add(new Log()
            {
                Fecha    = DateTime.Now,
                Usuario  = usuarioId,
                Data     = Fn.GetJsonString(data),
                Cliente  = HttpContext.Current.Request.Browser.Browser,
                EventoId = (int)eventoId,
                Key      = key.ToString()
            });

            HttpContext.Current.Items["__logs"] = logs;
        }
Exemple #10
0
        public async Task <IHttpActionResult> EditAsesor(Asesor asesor)
        {
            try
            {
                Asesor actualAsesor;
                using (var db2 = new MMSContext())
                {
                    actualAsesor = await db2.Asesor.FindAsync(asesor.Id);

                    if (actualAsesor == null)
                    {
                        return(NotFound());
                    }
                }

                if (actualAsesor.Meta != asesor.Meta)
                {
                    var aprobaciones = await db.LiquidacionAprobacion
                                       .Include(la => la.Liquidacion)
                                       .Where(la => la.Liquidacion.Estado == EstadoLiquidacion.Open && la.AsesorId == asesor.Id)
                                       .ToListAsync();

                    if (aprobaciones.Count > 0)
                    {
                        db.LiquidacionAprobacion.RemoveRange(aprobaciones);
                    }
                }

                db.Entry(asesor).State = EntityState.Modified;
                await db.SaveChangesAsync();

                AddLog("", asesor.Id, asesor);

                return(Ok(true));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Exemple #11
0
        public void insertAuditoria(Auditoria modelo)
        {
            MMSContext db = new MMSContext();

            //SqlParameter[] parametters = new SqlParameter[9];
            //int cont = 0;
            try
            {
                System.Web.HttpContext context = HttpContext.Current;
                // System.Net.IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(context.Request.UserHostAddress);

                modelo.AuditoriaEquipo = "SERVER/HTCL0003";//hostEntry.HostName;

                db.Auditoria.Add(modelo);
                db.SaveChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                throw;
            }
        }
Exemple #12
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any())
            {
                return;
            }

            if (actionContext.RequestContext.Principal.Identity.IsAuthenticated)
            {
                Seguridadcll seguridadcll = (Seguridadcll)HttpContext.Current.Session["seguridad"];

                if (seguridadcll == null)
                {
                    using (var db = new MMSContext())
                    {
                        var usuario = db.Usuarios.FirstOrDefault(u => u.UsuarioId == actionContext.RequestContext.Principal.Identity.Name && u.Usuarioactivo);
                        new Controllers.Seguridad.UsuariosController().CargueSeguridad(usuario, HttpContext.Current);
                    }
                }
            }

            base.OnAuthorization(actionContext);
        }
Exemple #13
0
        //public bool CambioEstadoGasto(int GastoId = 0, int GastoLinea = 0, EstadoGasto Estado = EstadoGasto.Abierta)
        //public bool CambioEstadoGasto(int GastoId = 0, int GastoLinea = 0, EstadoGasto Estado = EstadoGasto.Abierta)
        //{
        //    bool result = false;
        //    var gasto = db.Gasto.Where(g => g.GastoId == GastoId && g.GastoLinea == GastoLinea).FirstOrDefault();

        //    if (gasto != null)
        //    {
        //        gasto.GastoEstado = Estado;
        //        db.Entry(gasto).State = EntityState.Modified;
        //        db.SaveChanges();
        //        result = true;

        //        #region auditoria
        //        Seguridad.Seguridad seguridad = new Seguridad.Seguridad();
        //        Auditoria auditoria = new Auditoria();
        //        Seguridadcll seguridadcll = (Seguridadcll)Session["seguridad"];

        //        auditoria.AuditoriaFecha = System.DateTime.Now;
        //        auditoria.AuditoriaHora = System.DateTime.Now.TimeOfDay;
        //        auditoria.usuarioId = seguridadcll.Usuario.UsuarioId;
        //        auditoria.AuditoriaEvento = "CambioEstadoGasto";
        //        auditoria.AuditoriaDesc = "Se cambio el estado del gasto: " + GastoId + " Linea: " + GastoLinea + " Estado: " + Estado.ToString();
        //        auditoria.ObjetoId = "Gastos/CambioEstadoGasto";

        //        seguridad.insertAuditoria(auditoria);
        //        #endregion auditoria
        //    }
        //    else
        //    {
        //        result = false;
        //    }

        //    return result;

        //}

        /// <summary>
        /// Steps:
        /// 1. Devuelve lo gastado(aun no ha guarado el gasto)
        /// 2. Afecta el gasto(el gasto ya fue guardado)
        /// </summary>
        /// <param name="gasto"></param>
        /// <param name="step"></param>
        /// <returns></returns>
        public void AfectaPresupuestoXGasto(int gastoId = 0, int step = 0)
        {
            // bool result = true;
            using (var Context = new MMSContext())
            {
                var gastoTemp = Context.Gasto
                                .Include(g => g.actividad)
                                .Where(g => g.GastoId == gastoId && (g.GastoEstado == EstadoGasto.Ejecutado || g.GastoEstado == EstadoGasto.Pagado))
                                .FirstOrDefault();
                decimal ValorGasto = 0;


                if (gastoTemp != null)
                {
                    //var actividad = Context.Actividad.Where(a => a.ActividadId == gastoTemp.ActividadId).FirstOrDefault();
                    ValorGasto = gastoTemp.GastoValor * gastoTemp.GastoCant;
                    //Buscar Prespuesto a Afectar
                    DateTime Date = gastoTemp.actividad.ActividadFecha;

                    int Year     = Date.Year;
                    int Month    = Date.Month;
                    int quartile = 0;

                    if (Month >= 1 && Month <= 3)//Q1
                    {
                        quartile = 1;
                    }
                    else if (Month >= 4 && Month <= 6)//Q2
                    {
                        quartile = 2;
                    }
                    else if (Month >= 7 && Month <= 9)//Q3
                    {
                        quartile = 3;
                    }
                    else if (Month >= 10 && Month <= 12)//Q4
                    {
                        quartile = 4;
                    }//if (Month >= 1 && Month <= 3)

                    var prespuesto = db.PresupuestoVendedor.Where(p => p.PlantaID == gastoTemp.actividad.ClienteID && p.CentroCostoID == gastoTemp.CentroCostoID &&
                                                                  p.PresupuestoVendedorAno == Year).FirstOrDefault();

                    switch (step)
                    {
                    case 1:    //1. Devuelve lo gastado(aun no ha guarado el gasto)
                        if (prespuesto != null)
                        {
                            prespuesto.PresupuestoGasto    -= ValorGasto;
                            Context.Entry(prespuesto).State = EntityState.Modified;
                            Context.SaveChanges();
                        }    //if (prespuesto != null)
                        break;

                    case 2:    //2. Afecta el gasto(el gasto ya fue guardado)
                        if (prespuesto != null)
                        {
                            prespuesto.PresupuestoGasto    += ValorGasto;
                            Context.Entry(prespuesto).State = EntityState.Modified;
                            Context.SaveChanges();
                        }    //if (prespuesto != null)
                        break;
                    }
                }
                else
                {
                }
            }// using (var Context = new MMSContext())
             //return result;
        }
Exemple #14
0
 public MachinesController(MMSContext context)
 {
     _context = context;
 }
Exemple #15
0
 public StockBasicDAO(MMSContext context) : base(context)
 {
 }
Exemple #16
0
 public MonthReportDAO(MMSContext context) : base(context)
 {
 }
Exemple #17
0
 public MMSCommonDAO(MMSContext context)
 {
     _context = context;
 }
 public MMSContext Init()
 {
     return(dbContext ?? (dbContext = new MMSContext()));
 }
Exemple #19
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), false).Any())
            {
                return;
            }

            if (filterContext.HttpContext.Request.IsAuthenticated)
            {
                Seguridadcll seguridadcll = (Seguridadcll)filterContext.HttpContext.Session["seguridad"];

                if (seguridadcll == null)
                {
                    using (var db = new MMSContext())
                    {
                        var usuario = db.Usuarios.FirstOrDefault(u => u.UsuarioId == filterContext.HttpContext.User.Identity.Name && u.Usuarioactivo);
                        seguridadcll = new UsuariosController().CargueSeguridad(usuario, HttpContext.Current);
                    }
                }

                string host    = filterContext.HttpContext.Request.Url.Host;
                string appName = host.Substring(0, host.IndexOf('.'));

                seguridadcll.Aplicacion = seguridadcll.Aplicaciones.FirstOrDefault(a => a.Link == appName);

                if (seguridadcll.Aplicacion == null) // no tiene permiso para la app
                {
                    base.HandleUnauthorizedRequest(filterContext);
                    return;
                }

                HttpContext.Current.Session["seguridad"] = seguridadcll;

                if (!filterContext.HttpContext.Request.IsAjaxRequest()) // no crear menu cuando sea una peticion Ajax
                {
                    var menus = seguridadcll.ObjetosMenuList
                                .Concat(seguridadcll.ObjetosMenuDirectorioList)
                                .Where(o => o.AplicacionObjetos.Any(ao => ao.AplicacionId == seguridadcll.Aplicacion.Id))
                                .Select(o => new Menu()
                    {
                        Objeto = o,
                        Active = false
                    })
                                .ToList();

                    var    sbMenu  = new StringBuilder();
                    string urlMenu = filterContext.HttpContext.Request.Url.AbsolutePath;

                    if (urlMenu.StartsWith("/"))
                    {
                        urlMenu = urlMenu.Remove(0, 1);
                    }

                    if (urlMenu.EndsWith("/"))
                    {
                        urlMenu = urlMenu.Remove(urlMenu.LastIndexOf('/'));
                    }

                    if (!urlMenu.ToLower().EndsWith("/index") && filterContext.HttpContext.Request.Url.Segments.Length == 2)
                    {
                        urlMenu += "/Index";
                    }

                    var menu = menus.Where(m => m.Objeto.ObjetoId == urlMenu).FirstOrDefault();

                    if (menu == null && filterContext.HttpContext.Request.Url.Segments.Length > 2)
                    {
                        for (int i = 2; i < filterContext.HttpContext.Request.Url.Segments.Length; i++)
                        {
                            urlMenu = urlMenu.Remove(urlMenu.LastIndexOf('/'));
                        }
                    }

                    if (!urlMenu.ToLower().EndsWith("/index"))
                    {
                        urlMenu += "/Index";
                    }

                    menu = menus.Where(m => m.Objeto.ObjetoId.ToLower() == urlMenu.ToLower()).FirstOrDefault();

                    while (menu != null)
                    {
                        menu.Active = true;
                        menu        = menus.Where(m => m.Objeto.ObjetoId == menu.Objeto.ObjetoIdPadre).FirstOrDefault();
                    }

                    var menusProcesar = menus.Where(m => m.Objeto.ObjetoIdPadre == null).OrderBy(m => m.Objeto.ObjetoOrden).ToList();
                    GenerarMenu(menusProcesar, menus, sbMenu);

                    filterContext.Controller.ViewBag.SidebarMenuHtml = sbMenu.ToString();
                }
            }

            base.OnAuthorization(filterContext);
        }