Exemple #1
0
        public string[] GenerateUser(string TypeUser)
        {
            int    consecutivo  = 0;
            string folioPadLeft = string.Empty;
            var    Types        = (from t in _context.types.ToList()
                                   join g in _context.groupTypes.Where(x => x.Name == "Usuarios").ToList()
                                   on t.GroupTypeId equals g.GroupTypeID
                                   select t).Where(x => x.Name == TypeUser).ToList();

            if (Types.Count == 0)
            {
                return(null);
            }
            var folio = _context.FoliosControls.Where(x => x.Type == Types.FirstOrDefault().TypeId).FirstOrDefault();

            try
            {
                if (folio != null)
                {
                    using (var scope = _context.Database.BeginTransaction())
                    {
                        consecutivo                 = folio.Secuencial + 1;
                        folio.Secuencial            = consecutivo;
                        folioPadLeft                = consecutivo.ToString().PadLeft(3, '0');
                        _context.Entry(folio).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
                        _context.SaveChanges();
                        scope.Commit();
                    }
                    return(new string[] { string.Format("{0}{1}{2}", folio.Prefix, folioPadLeft, folio.Sufix), Types.FirstOrDefault().TypeId });
                }

                return(null);
            }
            catch (Exception e)
            {
                SystemLog systemLog = new SystemLog();
                systemLog.Description = e.ToMessageAndCompleteStacktrace();
                systemLog.DateLog     = DateTime.UtcNow.ToLocalTime();
                systemLog.Controller  = GetType().Name;
                systemLog.Action      = UtilitiesAIO.GetCallerMemberName();
                systemLog.Parameter   = JsonConvert.SerializeObject(new { Type = TypeUser });
                _customSystemLog.AddLog(systemLog);
                return(null);
            }
        }
Exemple #2
0
 public async Task <bool> SaveAllAsync(TypeEmergency typeEmergency)
 {
     try
     {
         return(await this.context.SaveChangesAsync() > 0);
     }
     catch (Exception ex)
     {
         SystemLog systemLog = new SystemLog();
         systemLog.Description = ex.ToMessageAndCompleteStacktrace();
         systemLog.DateLog     = DateTime.UtcNow.ToLocalTime();
         systemLog.Controller  = GetType().Name;
         systemLog.Action      = UtilitiesAIO.GetCallerMemberName();
         systemLog.Parameter   = JsonConvert.SerializeObject(typeEmergency);
         _customSystemLog.AddLog(systemLog);
         return(false);
     }
 }
Exemple #3
0
 public async Task <bool> SaveAllAsync(Address address)
 {
     try
     {
         return(await _context.SaveChangesAsync() > 0);
     }
     catch (Exception ex)
     {
         //var response = new StatusResponse<string>();
         SystemLog systemLog = new SystemLog();
         systemLog.Description = ex.ToMessageAndCompleteStacktrace();
         systemLog.DateLog     = DateTime.UtcNow.ToLocalTime();
         systemLog.Controller  = GetType().Name;
         systemLog.Action      = UtilitiesAIO.GetCallerMemberName();
         systemLog.Parameter   = JsonConvert.SerializeObject(address);
         _customSystemLog.AddLog(systemLog);
         //response.StatusCode = HttpStatusCode.InternalServerError;
         //response.Message = "Error al intentar hacer el registro";
         //response.Value = null;
         return(false);
     }
 }
Exemple #4
0
        public async Task <IActionResult> PreRegister([FromBody] PreRegisterDAO pre)
        {
            try
            {
                var response = await _registerRepository.FirstRegister(pre);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var html = await _viewRenderService.RenderToStringAsync("Register/Emailtemplate", response.Value);

                    await _emailService.SendEmailAsync(pre.Email, html, "Email Verification");

                    return(Ok(new Response {
                        Status = "OK", Message = "Se ha enviado un correo electrónico favor de verificar para poder contitnuar con el registro "
                    }));
                }
                else
                {
                    return(StatusCode((int)response.StatusCode, new Response {
                        Status = "Error", Message = response.Message
                    }));
                }
            }
            catch (Exception e)
            {
                SystemLog systemLog = new SystemLog
                {
                    Description = e.ToMessageAndCompleteStacktrace(),
                    DateLog     = DateTime.UtcNow.ToLocalTime(),
                    Controller  = GetType().Name,
                    Action      = UtilitiesAIO.GetCallerMemberName(),
                    Parameter   = JsonConvert.SerializeObject(pre)
                };
                _customSystemLog.AddLog(systemLog);
                return(StatusCode(500, new Response {
                    Status = "Error", Message = systemLog.Description
                }));
            }
        }
Exemple #5
0
        public IList <LocationResponse> GetAll()
        {
            DateTime fecha          = DateTime.Now;
            string   day            = fecha.ToShortDateString().Substring(0, 2);
            string   mont           = fecha.ToShortDateString().Substring(3, 2);
            string   year           = fecha.ToShortDateString().Substring(6, 4);
            var      client         = new MongoClient("mongodb://192.168.11.201:27018"); //127.0.0.1:27017
            var      database       = client.GetDatabase("gpsreal_" + year + "" + mont);
            var      collectionDate = database.GetCollection <GpsTracker>("gps_" + day); ///.Find(d=> true).Filter();

            try
            {
                #region querys
                //var deviceActive = collectionDate.AsQueryable()
                //            .GroupBy(g => g.Tid)
                //            .Select(s => new GpsTracker
                //            {
                //                Id = s.First().Id,
                //                Tid = s.Key,
                //            })
                //            .Count();//Device active
                //var listDevices = collectionDate.AsQueryable()
                //    .OrderByDescending(d => d.Tm)
                //    .Take(deviceActive).ToList();
                //var veicleDevice = _mySQLContext.vehicleDevices.
                //    Join(_mySQLContext.groupInfos,
                //    vd => vd.GroupID,
                //    gi => gi.Id,
                //    (vd, gi) => new { vd, gi }).
                //    Where(w => w.vd.GroupID == w.gi.Id).
                //    Select(s => new
                //    {
                //        s.vd.DeviceID,
                //        s.vd.CarLicence,
                //        s.vd.EconomicNumber,
                //        s.gi.GroupName,
                //        s.gi.Remark,
                //        s.gi.Id
                //    }).ToList();

                //var simpleResponse = listDevices.AsQueryable().Join(veicleDevice.AsQueryable(),
                //    ld => ld.Tid,
                //    vd => vd.DeviceID,
                //    (ld, vd) => new { ld, vd })
                //    .Where(w => w.ld.Tid == w.vd.DeviceID)
                //    .Select(s => new
                //    {
                //        s.vd.DeviceID,
                //        s.vd.CarLicence,
                //        s.vd.EconomicNumber,
                //        s.vd.GroupName,
                //        s.vd.Remark,
                //        s.vd.Id,
                //        s.ld.GeoLocation.Lat,
                //        s.ld.GeoLocation.Long
                //    })
                //    .ToList();
                #endregion
                var simpleResponse = collectionDate.AsQueryable()
                                     .OrderByDescending(d => d.Tm)
                                     .Take(collectionDate.AsQueryable()
                                           .GroupBy(g => g.Tid)
                                           .Select(s => new GpsTracker
                {
                    Id  = s.First().Id,
                    Tid = s.Key,
                })
                                           .Count()).ToList()
                                     .Join(_mySQLContext.vehicleDevices.
                                           Join(_mySQLContext.groupInfos,
                                                vd => vd.GroupID,
                                                gi => gi.Id,
                                                (vd, gi) => new { vd, gi }).
                                           Where(w => w.vd.GroupID == w.gi.Id).
                                           Select(s => new
                {
                    s.vd.DeviceID,
                    s.vd.CarLicence,
                    s.vd.EconomicNumber,
                    s.gi.GroupName,
                    s.gi.Remark,
                    s.gi.Id
                }).ToList(),
                                           ld => ld.Tid,
                                           vd => vd.DeviceID,
                                           (ld, vd) => new { ld, vd })
                                     .Where(w => w.ld.Tid == w.vd.DeviceID)
                                     .Select(s => new
                {
                    s.vd.DeviceID,
                    s.vd.CarLicence,
                    s.vd.EconomicNumber,
                    s.vd.GroupName,
                    s.vd.Remark,
                    s.vd.Id,
                    s.ld.GeoLocation.Lat,
                    s.ld.GeoLocation.Long
                })
                                     .ToList();

                List <LocationResponse> locationResponses = new List <LocationResponse>();

                foreach (var item in simpleResponse)
                {
                    locationResponses.Add(new LocationResponse
                    {
                        Id             = item.Id,
                        CarLicence     = item.CarLicence,
                        EconomicNumber = item.EconomicNumber,
                        GroupName      = item.GroupName,
                        Remark         = item.Remark,
                        DeviceID       = item.DeviceID,
                        Lat            = item.Lat,
                        Long           = item.Long
                    });
                }
                return(locationResponses);
            }
            catch (Exception ex)
            {
                SystemLog systemLog = new SystemLog();
                systemLog.Description = ex.ToMessageAndCompleteStacktrace();
                systemLog.DateLog     = DateTime.UtcNow.ToLocalTime();
                systemLog.Controller  = GetType().Name;
                systemLog.Action      = UtilitiesAIO.GetCallerMemberName();
                systemLog.Parameter   = JsonConvert.SerializeObject(ex.Message);
                _customSystemLog.AddLog(systemLog);
                return(null);
            }
        }
Exemple #6
0
        public async Task <StatusResponse <AppUser> > FirstRegister(PreRegisterDAO registerDAO)
        {
            var response = new StatusResponse <AppUser>();

            try
            {
                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    AppUser user = new AppUser()
                    {
                        Email              = registerDAO.Email,
                        Type               = "TU004",
                        UserName           = registerDAO.Email,
                        PhoneNumber        = registerDAO.PhoneNumber,
                        Name               = "PRE-REGISTER",
                        MiddleName         = "PRE-REGISTER",
                        LastName           = "PRE-REGISTER",
                        AuthValidationCode = KeyGenerator.GetUniqueKey(10),
                        IsActive           = true
                    };

                    IdentityResult result = await _userManager.CreateAsync(user, registerDAO.Password);

                    if (result.Succeeded)
                    {
                        MobileDeviceRegistrationTemp registrationTemp = new MobileDeviceRegistrationTemp()
                        {
                            AppUserId       = user.Id,
                            CellComapny     = registerDAO.CellCompany,
                            DateRegister    = DateTime.Now,
                            DeviceId        = registerDAO.DeviceId,
                            MakeModel       = registerDAO.MakeModel,
                            NumberPhone     = registerDAO.PhoneNumber,
                            LatLangRegister = string.Format("{0},{1}", registerDAO.Latitude, registerDAO.Longitude),
                            Platform        = registerDAO.Platform,
                            VersionOS       = registerDAO.VersionOS
                        };
                        _context.MobileDeviceRegistrationTemps.Add(registrationTemp);


                        _context.SaveChanges();

                        response.StatusCode = HttpStatusCode.OK;
                        response.Message    = "Usuario agregado satisfactoriamente";
                        response.Value      = user;
                    }
                    else
                    {
                        response.StatusCode = HttpStatusCode.BadRequest;
                        response.Message    = string.Join(",", UtilitiesAIO.AddErrors(result));
                        response.Value      = null;
                    }

                    scope.Complete();
                }
            }
            catch (Exception e)
            {
                SystemLog systemLog = new SystemLog();
                systemLog.Description = e.ToMessageAndCompleteStacktrace();
                systemLog.DateLog     = DateTime.UtcNow.ToLocalTime();
                systemLog.Controller  = GetType().Name;
                systemLog.Action      = UtilitiesAIO.GetCallerMemberName();
                systemLog.Parameter   = JsonConvert.SerializeObject(registerDAO);
                _customSystemLog.AddLog(systemLog);
                response.StatusCode = HttpStatusCode.InternalServerError;
                response.Message    = "Error al intentar hacer el registro";
                response.Value      = null;
            }


            return(response);
        }
Exemple #7
0
        public async Task <StatusResponse> Login(string UserName, string Password)
        {
            StatusResponse response = new StatusResponse();
            AppUser        user     = null;

            try
            {
                user = await _userManager.FindByNameAsync(UserName);

                if (user == null)
                {
                    response.StatusCode = System.Net.HttpStatusCode.BadRequest;
                    response.Message    = "Usuario o contraseña incorrectos. Favor de verificar";
                    return(response);
                }
                else
                {
                    if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user))
                    {
                        var LockEnd = await _userManager.GetLockoutEndDateAsync(user);

                        response.StatusCode = System.Net.HttpStatusCode.Conflict;
                        response.Message    = string.Format("La cuenta se bloqueó temporalmente por seguridad. Intente dentro de {0} minutos", Math.Round((LockEnd.Value - DateTimeOffset.Now).TotalMinutes));
                        return(response);
                    }
                    if (await _userManager.CheckPasswordAsync(user, Password))
                    {
                        if (!user.IsActive)
                        {
                            response.StatusCode = System.Net.HttpStatusCode.Conflict;
                            response.Message    = "Su cuenta ha sido bloqueada permanentemente. Favor de comunicarse a servicios de Cuatlancingo";
                            return(response);
                        }
                        if (_userManager.SupportsUserLockout && await _userManager.GetAccessFailedCountAsync(user) > 0)
                        {
                            await _userManager.ResetAccessFailedCountAsync(user);
                        }
                        //TODO: ver respuesta
                        var Entitykey = await _context.ApiKeyUsers.Where(x => x.AppUserId == user.Id).FirstOrDefaultAsync();

                        Entitykey.IsActive = true;
                        _context.Entry(Entitykey).State = EntityState.Modified;
                        _context.SaveChanges();

                        response.StatusCode = System.Net.HttpStatusCode.OK;
                        response.Message    = "Inicio de sesión exitoso";
                        return(response);
                    }
                    else
                    {
                        if (_userManager.SupportsUserLockout && await _userManager.GetLockoutEnabledAsync(user))
                        {
                            var contador = await _userManager.GetAccessFailedCountAsync(user);

                            if (await _userManager.GetAccessFailedCountAsync(user) >= 4)
                            {
                                await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.Now.AddMinutes(_identitySettings.Lockout.DefaultLockoutTimeSpanInMins));

                                await _userManager.ResetAccessFailedCountAsync(user);

                                response.StatusCode = System.Net.HttpStatusCode.Conflict;
                                response.Message    = string.Format("Su cuenta ha sido bloqueada termporalmente. Intente despues de {0} minutos", _identitySettings.Lockout.DefaultLockoutTimeSpanInMins);
                                return(response);
                            }
                            else
                            {
                                await _userManager.AccessFailedAsync(user);

                                response.StatusCode = System.Net.HttpStatusCode.Conflict;
                                response.Message    = string.Format("Solo quedan {0} intentos antes de bloquear la cuenta", (_identitySettings.Lockout.MaxFailedAccessAttempts - await _userManager.GetAccessFailedCountAsync(user)));
                                return(response);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                SystemLog systemLog = new SystemLog();
                systemLog.Description = e.ToMessageAndCompleteStacktrace();
                systemLog.DateLog     = DateTime.UtcNow.ToLocalTime();
                systemLog.Controller  = GetType().Name;
                systemLog.Action      = UtilitiesAIO.GetCallerMemberName();
                systemLog.Parameter   = JsonConvert.SerializeObject(new { UserName = UserName, Password = Password });
                _customSystemLog.AddLog(systemLog);
                response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
                response.Message    = "Error al intentar ingresar en la aplicación";
            }

            return(response);
        }