예제 #1
0
 public static Boolean EditSesnor(TblSensors sensor)
 {
     try
     {
         using (var db = new DBContextModel())
         {
             var old = db.TblSensors.Find(sensor.ID);
             if (old.RoomFK != sensor.RoomFK)
             {
                 var oldroom = db.TblRooms.Find(old.RoomFK);
                 if (db.TblSensors.Where(x => x.RoomFK == oldroom.ID).Count() <= 1)
                 {
                     oldroom.HasSensor       = false;
                     db.Entry(oldroom).State = EntityState.Modified;
                     db.SaveChanges();
                 }
                 var room = db.TblRooms.Find(sensor.RoomFK);
                 room.HasSensor       = true;
                 db.Entry(room).State = EntityState.Modified;
                 db.SaveChanges();
             }
             db.Entry(sensor).State = EntityState.Modified;
             db.SaveChanges();
             return(true);
         }
     }
     catch (Exception) { return(false); }
 }
예제 #2
0
        public static Boolean SendNotificationToUser(NotificationUser notification, int userID)
        {
            try
            {
                using (var db = new DBContextModel())
                {
                    TblNotifications notif = new TblNotifications
                    {
                        Description = notification.Description,
                        Hour        = DateTime.Now,
                        Subject     = notification.Subject,
                        Urgency     = notification.Urgency,
                        Approval    = notification.Approval,
                        UserFK      = notification.SenderFK
                    };
                    db.TblNotifications.Add(notif);
                    db.SaveChanges();

                    TblValidations valid = new TblValidations
                    {
                        NotificationFK = notif.ID,
                        ReceiverFK     = notification.ReceiverFK,
                        Accepted       = false,
                        Read           = false,
                        StudentFK      = notification.StudentFK
                    };
                    db.TblValidations.Add(valid);
                    db.SaveChanges();

                    BAction.SetActionToUser(String.Format("enviou uma notificação ao utilizador '{0}'", db.TblUsers.Find(notification.ReceiverFK).Name), userID);
                    return(true);
                }
            }
            catch (Exception) { return(false); }
        }
예제 #3
0
        public IActionResult Add(int Id, string Name)
        {
            var depart = context.Department
                         .Where(d => d.DepartmentId == Id)
                         .Select(d => new { DepartId = d.DepartmentId, DepartHier = d.Hierarchy, DepartParent = d.Parent }).FirstOrDefault();

            var department = context.Set <Department>();

            department.Add(new Department {
                Name = Name, Hierarchy = depart.DepartHier + 1, Parent = depart.DepartId
            });
            context.SaveChanges();
            return(RedirectToAction("Index", "Department"));
        }
예제 #4
0
        public categoria ActualizarCategoria(categoria item)
        {
            var obj = db.categoria.Find(item.id_categoria);

            if (obj == null)
            {
                return(null);
            }
            obj.img             = item.img;
            obj.nombre          = item.nombre;
            db.Entry(obj).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();
            return(obj);
        }
예제 #5
0
        /// <summary>
        /// Metodo que verifica si es posible actualizar datos
        /// </summary>
        /// <param name="id"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Put(int id, visita_busqueda item)
        {
            using (var db = new DBContextModel())
            {
                db.Configuration.ProxyCreationEnabled = false;
                visita_busqueda dbitem = db.visita_busqueda.Find(id);
                if (dbitem == null)
                {
                    return(false);
                }
                //Intercambio los atributos del objeto viejo con los del nuevo}
                dbitem.id_userquebusco   = item.id_userquebusco;
                dbitem.id_perfilvisitado = item.id_perfilvisitado;
                dbitem.fecha             = item.fecha;

                //guardo cambios
                try
                {
                    db.Entry(dbitem).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
        }
예제 #6
0
        public static Object DeleteDocument(int documentID, int userID)
        {
            try
            {
                using (var db = new DBContextModel())
                {
                    var document = db.TblDocuments.Find(documentID);
                    if (document.UserFK != userID)
                    {
                        return(new { result = false, info = "Não Autorizado, não foi o utilizador a submeter o documento." });
                    }
                    if (!BClass.GetActivity(document.ClassFK ?? 0))
                    {
                        return(new { result = false, info = "A turma enconstra-se inativa, já não é possível eliminar o documento." });
                    }
                    db.TblDocuments.Remove(document);
                    db.SaveChanges();

                    var cla = db.TblClasses.Find(document.ClassFK);
                    BAction.SetActionToUser(String.Format("Eliminou o documento '{0}' da turma '{1}' da escola '{2}'", document.File.Split('.')[1] + document.File.Split('.')[2], cla.Year + cla.ClassDesc, db.TblSchools.Find(cla.SchoolFK).Name), userID);
                    return(new { result = true });
                }
            }
            catch (Exception) { return(new { result = false, info = "Não foi possível eliminar o documento." }); }
        }
예제 #7
0
        /// <summary>
        /// Metodo que verifica si es posible actualizar datos
        /// </summary>
        /// <param name="id"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Put(int id, seguidores item)
        {
            using (var db = new DBContextModel())
            {
                db.Configuration.ProxyCreationEnabled = false;
                seguidores dbitem = db.seguidores.Find(id);
                if (dbitem == null)
                {
                    return(false);
                }
                //Intercambio los atributos del objeto viejo con los del nuevo}
                dbitem.seguidor_id = item.seguidor_id;
                dbitem.id_seguido  = item.id_seguido;
                dbitem.accepted    = item.accepted;
                dbitem.fecha       = item.fecha;

                //guardo cambios
                try
                {
                    db.Entry(dbitem).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
        }
예제 #8
0
        /// <summary>
        /// Metodo que verifica si es posible actualizar datos
        /// </summary>
        /// <param name="id"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Put(int id, publicaciones item)
        {
            using (var db = new DBContextModel())
            {
                db.Configuration.ProxyCreationEnabled = false;
                publicaciones dbitem = db.publicaciones.Find(id);
                if (dbitem == null)
                {
                    return(false);
                }
                //Intercambio los atributos del objeto viejo con los del nuevo}
                dbitem.id_user             = item.id_user;
                dbitem.descripcion         = item.descripcion;
                dbitem.fecha_creacion      = item.fecha_creacion;
                dbitem.fecha_actualizacion = item.fecha_actualizacion;
                dbitem.isDeleted           = item.isDeleted;

                //guardo cambios
                try
                {
                    db.Entry(dbitem).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
        }
예제 #9
0
        public HttpResponseMessage ChangePassWord(string oldPassWord, users itemNew)
        {
            var data = r.GetById(itemNew.id_user);

            if (data == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, $"No existe en la base de datos sobre el user a actualizar"));
            }
            try
            {
                if (data.pass == oldPassWord)
                {
                    data.pass = itemNew.pass;
                    using (var db = new DBContextModel())
                    {
                        db.Entry(data).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                    return(Request.CreateResponse(HttpStatusCode.OK, $"Contraseña cambiada"));
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotModified, $"Contraseña incorrecta"));
                }
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
            }
            return(Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, $"No fue posible actualizar la contraseña"));
        }
예제 #10
0
        public HttpResponseMessage logout(int id, users item)
        {
            if (id == item.id_user)
            {
                var data = r.GetById(id);
                if (data == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, $"No existe en la base de datos sobre el usuario a actualizar"));
                }
                try
                {
                    data.Phone_OS  = "";
                    data.Device_id = "";
                    using (var db = new DBContextModel())
                    {
                        db.Entry(data).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                    return(Request.CreateResponse(HttpStatusCode.OK, $"Sesión finalizada"));
                }
                catch (Exception ex)
                {
                    Debug.Print(ex.Message);
                }
            }

            return(Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, $"No fue posible actualizar la contraseña"));
        }
예제 #11
0
        public HttpResponseMessage deviceRegisterAgain(users item)
        {
            try
            {
                using (var db = new DBContextModel())
                {
                    var userObtenido = db.users.Find(item.id_user);
                    if (userObtenido != null)
                    {
                        userObtenido.Device_id = item.Device_id;
                        userObtenido.Phone_OS  = item.Phone_OS;

                        db.Entry(userObtenido).State = EntityState.Modified;
                        db.SaveChanges();

                        return(Request.CreateResponse(HttpStatusCode.OK, "Notificaciones Push configuradas"));
                    }
                    else
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Contraseña incorrecta"));
                    }
                }
            }
            catch (Exception) { }
            return(Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "No es posible comparar los datos proporcionados"));
        }
예제 #12
0
        /// <summary>
        /// Metodo que verifica si es posible actualizar datos
        /// </summary>
        /// <param name="id"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Put(int id, like_comentario item)
        {
            using (var db = new DBContextModel())
            {
                db.Configuration.ProxyCreationEnabled = false;
                like_comentario dbitem = db.like_comentario.Find(id);
                if (dbitem == null)
                {
                    return(false);
                }
                //Intercambio los atributos del objeto viejo con los del nuevo}
                dbitem.id_user       = item.id_user;
                dbitem.id_comentario = item.id_comentario;
                dbitem.fecha         = item.fecha;

                //guardo cambios
                try
                {
                    db.Entry(dbitem).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
        }
예제 #13
0
        public static Boolean EditUser(User editedUser, int userID)
        {
            try
            {
                using (var db = new DBContextModel())
                {
                    var user = db.TblUsers.Find(editedUser.ID);

                    user.Name         = editedUser.Name;
                    user.Email        = editedUser.Email;
                    user.Address      = editedUser.Address;
                    user.CitizenCard  = editedUser.CitizenCard;
                    user.Curriculum   = editedUser.Curriculum;
                    user.FiscalNumber = editedUser.FiscalNumber;
                    user.PhoneNumber  = editedUser.PhoneNumber;
                    user.Photo        = editedUser.Photo;
                    user.Function     = editedUser.Function;
                    user.DateOfBirth  = editedUser.DateOfBirth;

                    db.Entry(user).State = EntityState.Modified;
                    db.SaveChanges();


                    BAction.SetActionToUser(String.Format("Editou os dados do utilizador '{0}'", editedUser.Name), userID);
                    return(true);
                }
            }
            catch (Exception) { return(false); }
        }
예제 #14
0
 public static Boolean CreateSesnor(TblSensors sensor)
 {
     try
     {
         using (var db = new DBContextModel())
         {
             db.TblSensors.Add(sensor);
             db.SaveChanges();
             var room = db.TblRooms.Find(sensor.RoomFK);
             room.HasSensor       = true;
             db.Entry(room).State = EntityState.Modified;
             db.SaveChanges();
             return(true);
         }
     }
     catch (Exception) { return(false); }
 }
예제 #15
0
        public static Object CreateUser(User newUser, int userID)
        {
            try
            {
                using (var db = new DBContextModel())
                {
                    if (_VerifyUser(newUser.CitizenCard))
                    {
                        return(new { result = false, info = "Utilizador já se encontra registado." });
                    }

                    TblUsers user = new TblUsers
                    {
                        Address      = newUser.Address,
                        CitizenCard  = newUser.CitizenCard,
                        Curriculum   = newUser.Curriculum,
                        Email        = newUser.Email,
                        FiscalNumber = newUser.FiscalNumber,
                        Name         = newUser.Name,
                        Password     = new PasswordHasher().HashPassword(newUser.Password),
                        PhoneNumber  = newUser.PhoneNumber,
                        Photo        = newUser.Photo,
                        IsActive     = true,
                        Function     = newUser.Function,
                        DateOfBirth  = newUser.DateOfBirth,
                        RegisterDate = DateTime.Now
                    };
                    db.TblUsers.Add(user);
                    db.SaveChanges();

                    TblUserRoles userRoles = new TblUserRoles {
                        UserFK = user.ID, RoleFK = newUser.RoleID
                    };
                    db.TblUserRoles.Add(userRoles);
                    db.SaveChanges();

                    /*ActiveDirectory.CreateUser(user.Email, user.Password);
                    *  ActiveDirectory.AddRole(user.Email, userRoles.RoleFK);*/

                    //BAction.SetActionToUser(String.Format("Registou o utilizador '{0}'", newUser.Name), userID);
                    return(new { result = true, data = user.ID });
                }
            }
            catch (Exception) { return(new { result = false, info = "Não foi possível registar utilizador." }); }
        }
예제 #16
0
        public HttpResponseMessage login(users item)
        {
            //Retorno objeto con id
            if (item == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "No es posible analizar los datos proporcionados"));
            }
            try
            {
                using (var db = new DBContextModel())
                {
                    var userObtenido = db.users.Where(u => u.username == item.username || u.email == item.username).ToList();
                    if (userObtenido.Count <= 0)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "No se encontro el usuario o correo proporcionado"));
                    }
                    var usuarioDB = userObtenido.First();
                    if (usuarioDB.pass == item.pass)
                    {
                        usuarioDB.isDeleted = false;
                        usuarioDB.Device_id = item.Device_id;
                        usuarioDB.Phone_OS  = item.Phone_OS;

                        db.Entry(usuarioDB).State = EntityState.Modified;
                        db.SaveChanges();

                        userModel usuario = new userModel()
                        {
                            apellido     = usuarioDB.apellido,
                            descripcion  = usuarioDB.descripcion,
                            email        = usuarioDB.email,
                            id_user      = usuarioDB.id_user,
                            isVendor     = usuarioDB.isVendor,
                            nombre       = usuarioDB.nombre,
                            pass         = usuarioDB.pass,
                            puntaje      = usuarioDB.puntaje,
                            username     = usuarioDB.username,
                            img          = usuarioDB.img,
                            puesto_name  = usuarioDB.puesto_name,
                            isActive     = usuarioDB.isActive,
                            dui          = usuarioDB.dui,
                            isDeleted    = usuarioDB.isDeleted,
                            num_telefono = usuarioDB.num_telefono,
                            xlat         = usuarioDB.xlat,
                            ylon         = usuarioDB.ylon
                        };
                        return(Request.CreateResponse(HttpStatusCode.OK, usuario));
                    }
                    else
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Contraseña incorrecta"));
                    }
                }
            }
            catch (Exception) { }
            return(Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "No es posible comparar los datos proporcionados"));
        }
예제 #17
0
        public static Object CreateGuardian(Guardian guardian, int userID)
        {
            try
            {
                using (var db = new DBContextModel())
                {
                    if (_VerifyUser(guardian.CitizenCard))
                    {
                        return(new { result = false, info = "Utilizador já se encontra registado." });
                    }

                    TblUsers user = new TblUsers
                    {
                        Address      = guardian.Address,
                        CitizenCard  = guardian.CitizenCard,
                        Email        = guardian.Email,
                        FiscalNumber = guardian.FiscalNumber,
                        Name         = guardian.Name,
                        Password     = new PasswordHasher().HashPassword(guardian.Password),
                        PhoneNumber  = guardian.PhoneNumber,
                        IsActive     = true,
                        Function     = guardian.Function,
                        DateOfBirth  = guardian.DateOfBirth,
                        RegisterDate = DateTime.Now
                    };
                    db.TblUsers.Add(user);
                    db.SaveChanges();

                    TblUserRoles userRoles = new TblUserRoles {
                        UserFK = user.ID, RoleFK = 5
                    };
                    db.TblUserRoles.Add(userRoles);
                    db.SaveChanges();

                    if (!AddParenting(user.ID, guardian.ChildrenID, userID))
                    {
                        return(new { result = false, info = "Não foi possível relacionar Enc.Educação com o Estudante." });
                    }

                    return(new { result = true });
                }
            }
            catch (Exception) { return(new { result = false, info = "Não foi possível registar utilizador." }); }
        }
예제 #18
0
 public static Boolean RemoveSensor(int sensorID)
 {
     try
     {
         using (var db = new DBContextModel())
         {
             var sensor = db.TblSensors.Find(sensorID);
             var room   = db.TblRooms.Find(sensor.RoomFK);
             if (db.TblSensors.Where(x => x.RoomFK == room.ID).Count() <= 1)
             {
                 room.HasSensor       = false;
                 db.Entry(room).State = EntityState.Modified;
                 db.SaveChanges();
             }
             db.TblSensors.Remove(sensor);
             db.SaveChanges();
             return(true);
         }
     }
     catch { return(false); }
 }
예제 #19
0
 public static bool CreateSubject(TblSubjects subject)
 {
     try
     {
         using (var db = new DBContextModel())
         {
             db.TblSubjects.Add(subject);
             db.SaveChanges();
             return(true);
         }
     }
     catch (Exception) { return(false); }
 }
예제 #20
0
 public static bool EditTime(TblTimes time)
 {
     try
     {
         using (var db = new DBContextModel())
         {
             db.Entry(time).State = EntityState.Modified;
             db.SaveChanges();
             return(true);
         }
     }
     catch (Exception) { return(false); }
 }
예제 #21
0
        public static Boolean SendNotificationToClass(NotificationClass notification, int userID)
        {
            try
            {
                using (var db = new DBContextModel())
                {
                    TblNotifications notif = new TblNotifications
                    {
                        Description = notification.Description,
                        Hour        = DateTime.Now,
                        Subject     = notification.Subject,
                        Urgency     = notification.Urgency,
                        Approval    = notification.Approval,
                        UserFK      = notification.SenderFK
                    };
                    db.TblNotifications.Add(notif);
                    db.SaveChanges();

                    var students = BClass.GetStudentsByClass(notification.ClassFK);
                    foreach (var student in students)
                    {
                        TblValidations valid = new TblValidations
                        {
                            ReceiverFK = BParenting.GetGuardians(student).FirstOrDefault(),
                            StudentFK  = student,
                            Accepted   = false,
                            Read       = false
                        };
                        db.TblValidations.Add(valid);
                        db.SaveChanges();
                    }

                    var cla = db.TblClasses.Find(notification.ClassFK);
                    BAction.SetActionToUser(String.Format("enviou uma notificação a turma '{0}'", cla.Year + cla.ClassDesc), userID);
                    return(true);
                }
            }
            catch (Exception) { return(false); }
        }
예제 #22
0
 public static Object EditGrade(TblEvaluationStudents grade)
 {
     try
     {
         using (var db = new DBContextModel())
         {
             db.Entry(grade).State = EntityState.Modified;
             db.SaveChanges();
             return(new { result = true });
         }
     }
     catch (Exception) { return(new { result = false, info = "Não foi possível alterar a nota da avaliação" }); }
 }
예제 #23
0
 public static Object CreateSchool(TblSchools school)
 {
     try
     {
         using (var db = new DBContextModel())
         {
             db.TblSchools.Add(school);
             db.SaveChanges();
             return(new { result = true, data = school.ID });
         }
     }
     catch (Exception) { return(new { result = false, info = "Não foi possível registar escola" }); }
 }
예제 #24
0
 public static Boolean EditFaults(TblLessonStudents lesson)
 {
     try
     {
         using (var db = new DBContextModel())
         {
             db.Entry(lesson).State = EntityState.Modified;
             db.SaveChanges();
             return(true);
         }
     }
     catch (Exception) { return(false); }
 }
예제 #25
0
        public void Configuration(IAppBuilder app)
        {
            Database.SetInitializer(new CreateDatabaseIfNotExists <DBContextModel>());
            DBContextModel context = new DBContextModel();

            TblUsers admin = new TblUsers
            {
                Email        = "[email protected]",
                IsActive     = true,
                Password     = "******",
                RegisterDate = DateTime.Now
            };

            if (!context.TblUsers.Any(x => x.Email == admin.Email))
            {
                context.TblUsers.Add(admin);
                context.SaveChanges();
            }

            String[] roles = { "student", "teacher", "secretary", "assistant", "guardian", "admin" };
            Array.ForEach(roles, role =>
            {
                if (!context.TblRoles.Any(x => x.Name == role))
                {
                    var newRole = new TblRoles {
                        Name = role
                    };
                    context.TblRoles.Add(newRole);
                    context.SaveChanges();
                    if (role == "admin")
                    {
                        context.TblUserRoles.Add(new TblUserRoles {
                            RoleFK = newRole.ID, UserFK = admin.ID
                        });
                        context.SaveChanges();
                    }
                }
            });
        }
예제 #26
0
        // This method is posting Registation to the Server
        public IActionResult Registration(User user)
        {
            if (ModelState.IsValid)
            {
                _context.User.Add(user);
                _context.SaveChanges();


                ModelState.Clear();
                ViewBag.Message = "Welcome " + user.FirstName + " " + user.LastName;
            }
            return(View());
        }
예제 #27
0
 public static Boolean CreateFloor(TblFloors floor)
 {
     try
     {
         using (var db = new DBContextModel())
         {
             db.TblFloors.Add(floor);
             db.SaveChanges();
             return(true);
         }
     }
     catch (Exception) { return(false); }
 }
예제 #28
0
 public static Boolean CreateRoom(TblRooms room)
 {
     try
     {
         using (var db = new DBContextModel())
         {
             db.TblRooms.Add(room);
             db.SaveChanges();
             return(true);
         }
     }
     catch (Exception) { return(false); }
 }
예제 #29
0
 public static Boolean EditFloor(TblFloors floor)
 {
     try
     {
         using (var db = new DBContextModel())
         {
             db.Entry(floor).State = EntityState.Modified;
             db.SaveChanges();
             return(true);
         }
     }
     catch (Exception) { return(false); }
 }
예제 #30
0
 public static bool EditSubject(TblSubjects subject)
 {
     try
     {
         using (var db = new DBContextModel())
         {
             db.Entry(subject).State = EntityState.Modified;
             db.SaveChanges();
             return(true);
         }
     }
     catch (Exception) { return(false); }
 }