//User like to be in your RVK (id)
        public ActionResult RequestBelong(int id)
        {
            if (!(AspNetUsersRoles.IsUserInRole("Administrator", User.Identity.Name) || AspNetUsersRoles.IsUserInRole("Maestro", User.Identity.Name) || AspNetUsersRoles.IsUserInRole("Estudiante", User.Identity.Name)))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            try
            {
                Guid             userid = new Guid(AspNetUsers.GetUserId(User.Identity.Name));
                investicEntities db     = new investicEntities();

                tbNetVirtualUserGroup tbnetVirtualUserGroup = new tbNetVirtualUserGroup();
                tbnetVirtualUserGroup.idNetVirtualUser    = userid;
                tbnetVirtualUserGroup.idNetVirtualGroup   = id;
                tbnetVirtualUserGroup.isOwner             = false;
                tbnetVirtualUserGroup.StateUserAceptGroup = 4;
                db.tbNetVirtualUserGroup.Add(tbnetVirtualUserGroup);
                db.SaveChanges();
                return(Json(new { rta = "Su solicitud ha sido enviada al creador de esta red." }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception)
            {
                return(Json(new { rta = "Wrong" }, JsonRequestBehavior.AllowGet));
            }
        }
        public ActionResult ResetPassword(string code)
        {
            investicEntities db = new investicEntities();
            var user            = (from q in db.AspNetUsers where q.Id == code select new { q.Id }).FirstOrDefault();

            return(user == null?View("Error") : View());
        }
        public ActionResult Datos(string Id_Contratista)
        {
            var usuario         = AspNetUsers.Find(Id_Contratista);
            investicEntities db = new investicEntities();

            var currentUser = User.Identity.GetUserId();
            var equip       = db.tblEquiposTrabajo.Where(x => x.Id_Coordinador.Equals(currentUser));
            var carge       = db.tblCargos.ToList();
            var usuarios    = db.AspNetUsers.ToList();


            ViewBag.Equipo = new SelectList(equip, "Id_Equipo", "Nombre_Equipo");
            ViewBag.Cargo  = new SelectList(carge, "Id_Cargo", "Nombre_Cargo");

            if (AspNetUsersRoles.IsUserInRole("Coordinador", User.Identity.Name))
            {
                investicEntities db2 = new investicEntities();

                var currentUser2 = User.Identity.GetUserId();
                var algo         = db2.tblEquiposTrabajo.Where(x => x.Id_Coordinador.Equals(currentUser2));
                var carg         = db2.tblCargos.ToList();
                var usuarios2    = db2.AspNetUsers.ToList();


                ViewBag.Equipo = new SelectList(algo, "Id_Equipo", "Nombre_Equipo");
                ViewBag.Cargo  = new SelectList(carg, "Id_Cargo", "Nombre_Cargo");
            }
            return(View(usuario));
        }
        public async Task <ActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            investicEntities db = new investicEntities();
            var user            = (from q in db.AspNetUsers where q.PersonalID == model.PersonalID select new { q.Email, q.Id }).FirstOrDefault();

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(RedirectToAction("ResetPasswordConfirmation", "Usuario"));
            }
            var result = await UserManager.RemovePasswordAsync(user.Id);

            if (result.Succeeded)
            {
                UserManager.AddPassword(user.Id, model.Password);
                return(RedirectToAction("ResetPasswordConfirmation", "Usuario"));
            }
            else
            {
                return(View());
            }
        }
        //Editor aprove your RVK(id) request
        public ActionResult ChangeState(int id = 0)
        {
            if (!(AspNetUsersRoles.IsUserInRole("Administrator", User.Identity.Name) || AspNetUsersRoles.IsUserInRole("Editor", User.Identity.Name)))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            investicEntities db = new investicEntities();

            try
            {
                var rvc = db.tbNetVirtualGroup.Find(id);
                if (rvc == null)
                {
                    return(Json(new { rta = "Ocurrio un error inesperado" }, JsonRequestBehavior.AllowGet));
                }
                rvc.state = true;
                var rvcug = rvc.tbNetVirtualUserGroup.Where(m => m.isOwner = true).FirstOrDefault();
                if (rvcug == null)
                {
                    return(Json(new { rta = "Ocurrio un error inesperado" }, JsonRequestBehavior.AllowGet));
                }
                rvcug.StateUserAceptGroup = 1;
                db.Entry(rvc).State       = System.Data.Entity.EntityState.Modified;
                db.Entry(rvcug).State     = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
                return(Json(new { rta = "La red ha sido aprobada." }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception)
            {
                return(Json(new { rta = "Ocurrio un error inesperado" }, JsonRequestBehavior.AllowGet));
            }
        }
        public static int GetRoleMiembro(string userId)
        {
            investicEntities db = new investicEntities();
            var q = (from u in db.tblMiembroGrupo
                     where u.idUsuario.Equals(userId)
                     select u).First();

            return(q.idRol);
        }
        public static int GetIdInstitucion(string userId)
        {
            investicEntities db = new investicEntities();
            var q = (from u in db.tblMaestroCoInvestigador
                     where u.idUsuario.Equals(userId)
                     select u).FirstOrDefault();

            return(q.idInstitucion);
        }
        public static bool Exist(string userId)
        {
            investicEntities db = new investicEntities();
            var q = (from u in db.tblMaestroCoInvestigador
                     where u.idUsuario.Equals(userId)
                     select u).FirstOrDefault();

            return(q != null);
        }
        public static int ResearchGroupIdByUser(string UserId)
        {
            investicEntities cxt = new investicEntities();
            var q = (from m in cxt.tblGrupoInvestigacion
                     where m.idUsuario == UserId
                     select m.id).SingleOrDefault();

            return(q);
        }
        public static bool ExistGroup(string UserId)
        {
            investicEntities cxt = new investicEntities();
            var q = (from m in cxt.tblGrupoInvestigacion
                     where m.idUsuario == UserId
                     select m).SingleOrDefault();

            return(q != null);
        }
        public static tblGrupoInvestigacion FindByUserId(string userId)
        {
            investicEntities cxt = new investicEntities();
            var q = (from m in cxt.tblGrupoInvestigacion
                     where m.idUsuario.Equals(userId)
                     select m).SingleOrDefault();

            return(q);
        }
        public static tblGrupoInvestigacion Find(int id)
        {
            investicEntities cxt = new investicEntities();
            var q = (from m in cxt.tblGrupoInvestigacion
                     where m.id == id
                     select m).SingleOrDefault();

            return(q);
        }
        public static string GetMunicipalityInstitucion(string userId)
        {
            investicEntities db = new investicEntities();
            var q = (from u in db.tblMaestroCoInvestigador
                     where u.AspNetUsers.Id.Equals(userId)
                     select u).FirstOrDefault();

            return(q.tblInstitucion.tblMunicipios.NombreMunicipio);
        }
        public static string GetRoleId(string roleName)
        {
            investicEntities db = new investicEntities();

            var q = (from r in db.AspNetRoles
                     where r.Name.Equals(roleName)
                     select r).FirstOrDefault();

            return(q.Id);
        }
        public static bool IsUserInRole(string roleName, string userName)
        {
            investicEntities db = new investicEntities();

            var userId = AspNetUsers.GetUserId(userName);
            var roleId = AspNetRoles.GetRoleId(roleName);
            var r      = (from l in db.AspNetUserRoles
                          where l.UserId.Equals(userId) && l.RoleId.Equals(roleId)
                          select l).FirstOrDefault();

            return(r != null);
        }
        public ActionResult OffLine(int code = 0)
        {
            investicEntities db = new investicEntities();
            var cadenaxml       = db.GeneradorConsultaSQLAXML("16306").ToList();

            string rutaXML = @"D:\SQLAXML.xml";

            System.IO.File.WriteAllText(rutaXML, (cadenaxml[0] != null && cadenaxml[0].ToString() != string.Empty) ? cadenaxml[0].ToString() : "No tiene Registro XML");

            ViewBag.Mensaje = dl.ErrorCodes.ErrorCodeToString(code);
            return(View());
        }
        public static AspNetUsers Find(string UserId)
        {
            investicEntities db = new investicEntities();
            var q = (from u in db.AspNetUsers
                     where u.Id.Equals(UserId)
                     select u).FirstOrDefault();

            if (q != null)
            {
                return(q);
            }
            return(null);
        }
        public static int GetRoleMiembro(string userId, int idGrupo)
        {
            investicEntities db = new investicEntities();

            var q = (from u in db.tblMiembroGrupo
                     where u.idUsuario.Equals(userId) && u.idGrupoInvestigacion.Equals(idGrupo)
                     select u).First();

            //var q = (from u in db.tblMiembroGrupo
            //         where u.idUsuario.Equals(userId) && u.idGrupoInvestigacion.Equals(idGrupo)
            //         select u).First();
            return(q.idRol);
        }
        public static string GetName(string userName)
        {
            investicEntities db = new investicEntities();
            var q = (from u in db.AspNetUsers
                     where u.UserName.Equals(userName)
                     select u).FirstOrDefault();

            if (q != null)
            {
                return(string.Format("{0} {1}", q.Name, q.SureName));
            }
            return("");
        }
        public static string GetUserId(string userName)
        {
            investicEntities db = new investicEntities();
            var q = (from u in db.AspNetUsers
                     where u.UserName.Equals(userName)
                     select new { u.Id }).FirstOrDefault();

            if (q != null)
            {
                return(q.Id);
            }
            return("");
        }
        public static string GetNameById(Guid id)
        {
            investicEntities db  = new investicEntities();
            string           ids = id.ToString();
            var q = (from u in db.AspNetUsers
                     where u.Id == ids
                     select new { u.Name, u.SureName }).FirstOrDefault();

            if (q != null)
            {
                return(string.Format("{0} {1}", q.Name, q.SureName));
            }
            return("");
        }
        public static List <AspNetUsers> GetUsersInRole(string rol)
        {
            investicEntities   db    = new investicEntities();
            List <AspNetUsers> users = new List <AspNetUsers>();

            var idRol    = AspNetRoles.GetRoleId(rol);
            var usuarios = db.AspNetUserRoles.Where(m => m.RoleId.Equals(idRol)).Select(m => m.UserId).Take(10);

            foreach (string item in usuarios)
            {
                users.Add(AspNetUsers.Find(item));
            }
            return(users);
        }
        public static List <string> GetRoles(string Iduser)
        {
            investicEntities db = new investicEntities();

            var r = (from l in db.AspNetUserRoles
                     where l.UserId.Equals(Iduser)
                     select l.AspNetRoles.Name);

            return(r.ToList());
            //var q = (from u in db.AspNetUsers
            //         where u.UserName.Equals(userName)
            //         select u).First();
            //return q.Id;
        }
        public ActionResult Salir()
        {
            investicEntities db = new investicEntities();
            var idUser          = User.Identity.Name;

            tblLogAcceso tbllogAcceso = (from m in db.tblLogAcceso where m.Usuario == idUser orderby m.FechaInicioSesion descending select m).Take(1).FirstOrDefault();

            tbllogAcceso.FechaCierreSesion = System.DateTime.Now;

            db.Entry(tbllogAcceso).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();

            AuthenticationManager.SignOut();
            return(Redirect("http://investic.udenar.edu.co/chamilolms/closessn.php?logout=logout&uid=0"));
        }
        public static List <AspNetUsers> UserNotInGroup(long id)
        {
            investicEntities cxt = new investicEntities();

            var UsuariosEnGrupo = cxt.tblIntegrantesGrupoInv.Where(m => m.tblGruposInvestigacion_ID == id);

            var UsuariosMaestros = AspNetUsers.GetUsersInRole("Maestro");

            var Usuarios = from u in UsuariosMaestros
                           where !(from ug in UsuariosEnGrupo
                                   select ug.tblUsuarioPlataforma_ID).Contains(u.Id)
                           select u;

            return(Usuarios.ToList());
        }
        public static List <AspNetUsers> UserStudentNotInGroup(int id)
        {
            investicEntities cxt = new investicEntities();

            //List<AspNetUsers> Usuarios = new List<AspNetUsers>();

            var UsuariosEnGrupo = cxt.tblMiembroGrupo.Where(m => m.idGrupoInvestigacion == id);

            var UsuariosMaestros = AspNetUsers.GetUsersInRole("Estudiante");

            var Usuarios = from u in UsuariosMaestros
                           where !(from ug in UsuariosEnGrupo
                                   select ug.idUsuario).Contains(u.Id)
                           select u;

            return(Usuarios.ToList());
        }
        // GET: RVC
        public ActionResult Index()
        {
            if (!(AspNetUsersRoles.IsUserInRole("Administrator", User.Identity.Name) || AspNetUsersRoles.IsUserInRole("Maestro", User.Identity.Name) || AspNetUsersRoles.IsUserInRole("Estudiante", User.Identity.Name)))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            investicEntities db     = new investicEntities();
            Guid             userid = new Guid(AspNetUsers.GetUserId(User.Identity.Name));
            int n = db.tbNetVirtualUserGroup.Where(m => m.idNetVirtualUser == userid && (m.StateUserAceptGroup == 1 || m.StateUserAceptGroup == 2)).Count();

            if (n == 0)
            {
                return(View());
            }
            else
            {
                return(RedirectToAction("Index", "tbNetVirtualGroups"));
            }
        }
        public ActionResult Aprobar()
        {
            if (!(AspNetUsersRoles.IsUserInRole("Administrator", User.Identity.Name) || AspNetUsersRoles.IsUserInRole("Editor", User.Identity.Name)))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            investicEntities db = new investicEntities();
            var Peticionrvc     = from q in db.tbNetVirtualUserGroup
                                  where q.isOwner == true && q.tbNetVirtualGroup.state == false
                                  select new RedVirtualGrupoOwner
            {
                id         = q.idNetVirtualGroup,
                Name       = q.tbNetVirtualGroup.name,
                State      = q.tbNetVirtualGroup.state,
                IsOwner    = q.isOwner,
                CreateDate = q.tbNetVirtualGroup.createDate.Value
            };

            return(View(Peticionrvc));
        }
        public ActionResult AttachmentUser()
        {
            if (!(AspNetUsersRoles.IsUserInRole("Administrator", User.Identity.Name) || AspNetUsersRoles.IsUserInRole("Maestro", User.Identity.Name) || AspNetUsersRoles.IsUserInRole("Estudiante", User.Identity.Name)))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            investicEntities db     = new investicEntities();
            Guid             userid = new Guid(AspNetUsers.GetUserId(User.Identity.Name));
            int nu = db.tbNetVirtualUser.Where(m => m.id == userid).Count();

            if (nu == 0)
            {
                db.tbNetVirtualUser.Add(new tbNetVirtualUser()
                {
                    id = userid, state = true
                });
                db.SaveChanges();
            }
            return(RedirectToAction("Index", "tbNetVirtualGroups"));
        }
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                //var user = await UserManager.FindByEmailAsync(model.Email);

                investicEntities db = new investicEntities();
                var user            = (from q in db.AspNetUsers where q.PersonalID == model.PersonalID select new { q.Email, q.Id }).FirstOrDefault();

                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(View("IniciarSesion"));
                }

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link

                var callbackUrl = Url.Action("ResetPassword", "Usuario", new { code = user.Id }, protocol: Request.Url.Scheme);


                var m = new MailMessage(
                    new MailAddress("*****@*****.**", "Registro Plataforma Investic"),
                    new MailAddress(user.Email));
                m.Subject = "Plataforma Investic - Cambiar contraseña";
                m.Body    =
                    string.Format("Para cambiar contraseña haga click <a href='{0}'>aquí!</a>", callbackUrl);
                m.IsBodyHtml = true;
                var smtp = new SmtpClient("smtp.gmail.com");
                smtp.Credentials = new NetworkCredential("*****@*****.**", "Investic666");
                smtp.EnableSsl   = true;
                smtp.Send(m);


                return(RedirectToAction("ForgotPasswordConfirmation", "Usuario"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }